diff --git a/.clang-format b/.clang-format index b6bcb71ce..dae9439c4 100644 --- a/.clang-format +++ b/.clang-format @@ -2,5 +2,5 @@ BasedOnStyle: LLVM IndentWidth: 4 UseTab: Never -ColumnLimit: 0 +ColumnLimit: 80 AlignConsecutiveAssignments: false \ No newline at end of file diff --git a/.clang-tidy b/.clang-tidy index 7c2775daf..c17204eae 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,5 +1,23 @@ --- -Checks: '*, -google-runtime-references, -hicpp-no-array-decay, -cppcoreguidelines-pro-bounds-array-to-pointer-decay, -cppcoreguidelines-pro-bounds-pointer-arithmetic, -fuchsia*,-readability-else-after-return,-readability-avoid-const-params-in-decls,-hicpp-signed-bitwise,-cppcoreguidelines-pro-bounds-constant-array-index,-llvm-header-guard,-readability-static-accessed-through-instance,-google-readability-todo' +Checks: '*, + -android-cloexec-fopen, + -cppcoreguidelines-pro-bounds-array-to-pointer-decay, + -cppcoreguidelines-pro-bounds-pointer-arithmetic, + -fuchsia*, + -readability-else-after-return, + -readability-avoid-const-params-in-decls, + -cppcoreguidelines-pro-bounds-constant-array-index, + -cppcoreguidelines-pro-type-reinterpret-cast, + -llvm-header-guard, + -readability-static-accessed-through-instance, + -readability-braces-around-statements, + -hicpp-signed-bitwise, + -hicpp-no-array-decay, + -hicpp-braces-around-statements, + -google-runtime-references, + -google-readability-todo, + -google-readability-braces-around-statements' + WarningsAsErrors: '*' HeaderFilterRegex: '.*' AnalyzeTemporaryDtors: false diff --git a/.gitignore b/.gitignore index 4ef28dd50..fb8df8cb6 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,13 @@ bin/ *.log *.out *.toc +*.o +.* build docs/ RELEASE.txt + + +*.pyc +*/__pycache__/* + diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..9b655d9cc --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "python/pybind11"] + path = python/pybind11 + url = https://github.com/pybind/pybind11.git diff --git a/.travis.yml b/.travis.yml index 3348a8b60..a3774de07 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,10 +2,13 @@ sudo: false language: cpp -matrix: - include: - - os: linux - env: CONDA_PY=3.6 +os: linux + +env: + matrix: + - CONDA_PY=3.6 + - CONDA_PY=3.7 + dist: trusty @@ -23,6 +26,7 @@ install: - conda update conda - conda update --all - conda install conda-build anaconda-client + - conda install conda-verify # Useful for debugging any issues with conda - conda info -a @@ -34,12 +38,12 @@ install: - conda-build . script: - - echo "No test scripts to be run!" + - CTEST_OUTPUT_ON_FAILURE=1 ctest -j 2 deploy: provider: script script: find $HOME/miniconda/conda-bld/${TRAVIS_OS_NAME}-64 -name "*.tar.bz2" -exec anaconda -t $CONDA_TOKEN upload --force {} \; on: - branch: developer + branch: refactor diff --git a/CMakeLists.txt b/CMakeLists.txt old mode 100644 new mode 100755 index 68b2b010b..858528c56 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,76 +1,174 @@ -cmake_minimum_required(VERSION 2.8) +cmake_minimum_required(VERSION 3.9) +project(slsDetectorPackage) +set(PROJECT_VERSION 5.0.0) + +include(CheckIPOSupported) + + + + +include(cmake/project_version.cmake) + +# Include additional modules that are used unconditionally +include(GNUInstallDirs) + +# If conda build, always set lib dir to 'lib' +if($ENV{CONDA_BUILD}) + set(CMAKE_INSTALL_LIBDIR "lib") +endif() + +# Set lower / upper case project names +string(TOUPPER "${PROJECT_NAME}" PROJECT_NAME_UPPER) +string(TOLOWER "${PROJECT_NAME}" PROJECT_NAME_LOWER) + +# Set targets export name (used by slsDetectorPackage and dependencies) +set(TARGETS_EXPORT_NAME "${PROJECT_NAME_LOWER}-targets") +#set(namespace "${PROJECT_NAME}::") + set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH}) -set (CALIBRATE OFF) + # Check if project is being used directly or via add_subdirectory set(SLS_MASTER_PROJECT OFF) if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) - set(SLS_MASTER_PROJECT ON) + set(SLS_MASTER_PROJECT ON) endif() option (SLS_USE_HDF5 "HDF5 File format" OFF) option (SLS_USE_TEXTCLIENT "Text Client" OFF) option (SLS_USE_RECEIVER "Receiver" OFF) option (SLS_USE_GUI "GUI" OFF) +option (SLS_USE_TESTS "TESTS" ON) +option (SLS_USE_INTEGRATION_TESTS "Integration Tests" ON) +option(SLS_USE_SANITIZER "Sanitizers for debugging" OFF) +option(SLS_USE_PYTHON "Python bindings" OFF) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) - -#Flags to always be used -# -Wno-unused-parameter should eventually be removes -# -Wno-overloaded-virtual TODO! remove warnings in refactor -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wno-overloaded-virtual -Wno-unused-parameter -std=c++98") - -if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") - # clang does not support -Wno-misleading-indentation - # add any special clang flags -elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") - if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 6.0) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-misleading-indentation") - endif () +if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + message(STATUS "No build type selected, default to Release") + set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Build type (default Release)" FORCE) endif() -find_package(Qt4) -find_package(Qwt 6) -find_package(CBF) -find_package(Doxygen) -# find_package(PNG REQUIRED) +#Add two fake libraries to manage options +add_library(slsProjectOptions INTERFACE) +add_library(slsProjectWarnings INTERFACE) +target_compile_features(slsProjectOptions INTERFACE cxx_std_11) +target_compile_options(slsProjectWarnings INTERFACE + -Wall + -Wextra + -Wno-unused-parameter #Needs to be slowly mitigated + # -Wold-style-cast + -Wnon-virtual-dtor + -Woverloaded-virtual + -Wdouble-promotion + -Wformat=2 + -Wredundant-decls + # -Wconversion + -Wdouble-promotion -if (SLS_USE_HDF5) - find_package(HDF5 1.10 COMPONENTS CXX) -endif (SLS_USE_HDF5) + ) + + +#Testing for minimum version for compilers +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") + if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.2) + message(FATAL_ERROR "Clang version must be at least 3.2!") + endif() + target_compile_options(slsProjectWarnings INTERFACE -Wshadow) #Clag does not warn on constructor +elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.8) + message(FATAL_ERROR "GCC version must be at least 4.8!") + endif() + target_compile_options(slsProjectWarnings INTERFACE + + ) + if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 6.0) + target_compile_options(slsProjectWarnings INTERFACE + -Wno-misleading-indentation # mostly in rapidjson remove using clang format + -Wduplicated-cond + -Wnull-dereference ) + + endif() + if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 8.0) + target_compile_options(slsProjectWarnings INTERFACE + -Wno-class-memaccess ) + + endif() +endif() + + +if(SLS_USE_SANITIZER) + target_compile_options(slsProjectOptions INTERFACE -fsanitize=address,undefined) + target_link_libraries(slsProjectOptions INTERFACE -fsanitize=address,undefined) +endif() + + +# Install fake the library +install(TARGETS slsProjectOptions slsProjectWarnings + EXPORT "${TARGETS_EXPORT_NAME}" + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} +) set(CMAKE_POSITION_INDEPENDENT_CODE ON) - set(CMAKE_INSTALL_RPATH "$ORIGIN") set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE) + +find_package(Doxygen) +find_package(ZeroMQ 4 REQUIRED) + +if (SLS_USE_TESTS) + enable_testing() + add_subdirectory(tests) +endif(SLS_USE_TESTS) + +# Support library containing functionallity common to +# detector and receiver +add_subdirectory(slsSupportLib) + if (SLS_USE_TEXTCLIENT) - add_subdirectory(slsDetectorSoftware) + add_subdirectory(slsDetectorSoftware) endif (SLS_USE_TEXTCLIENT) if (SLS_USE_RECEIVER) - add_subdirectory(slsReceiverSoftware) - add_subdirectory(manual/manual-api) + if (SLS_USE_HDF5) + find_package(HDF5 1.10 COMPONENTS CXX REQUIRED) + endif (SLS_USE_HDF5) + add_subdirectory(slsReceiverSoftware) + add_subdirectory(manual/manual-api) endif (SLS_USE_RECEIVER) - - + if (SLS_USE_GUI) - if (QT4_FOUND AND QWT_FOUND) - add_subdirectory(slsDetectorGui) - endif() + find_package(Qt4 REQUIRED) + find_package(Qwt 6 REQUIRED) + if (QT4_FOUND AND QWT_FOUND) + add_subdirectory(slsDetectorGui) + endif() endif (SLS_USE_GUI) -if (SLS_MASTER_PROJECT) - # Set targets export name (otherwise set by upstream project) - set(TARGETS_EXPORT_NAME "slsdetector-targets") -endif (SLS_MASTER_PROJECT) -if (CALIBRATE) - if (DEFINED ENV{ROOTSYS}) - find_package(ROOT) - if (ROOT_FOUND) - add_subdirectory(calibrationWizards) - endif() - endif() -endif(CALIBRATE) + +if (SLS_USE_INTEGRATION_TESTS) + add_subdirectory(integrationTests) +endif (SLS_USE_INTEGRATION_TESTS) + +if (SLS_USE_PYTHON) + add_subdirectory(python) +endif(SLS_USE_PYTHON) + +configure_file( .clang-tidy + ${CMAKE_BINARY_DIR}/.clang-tidy ) + +if(SLS_MASTER_PROJECT) + # Set install dir CMake packages + set(CMAKE_INSTALL_DIR ${CMAKE_INSTALL_DATADIR}/cmake/sls) + # Set the list of exported targets + set(PROJECT_LIBRARIES slsSupportLib slsDetectorShared slsReceiverShared) + # Generate and install package config file and version + include(cmake/package_config.cmake) +endif() + diff --git a/Makefile b/Makefile deleted file mode 100755 index 8d4849b75..000000000 --- a/Makefile +++ /dev/null @@ -1,235 +0,0 @@ -# do not change below this line# - -# Include common definitions -include Makefile.include - -INSTALLROOT ?= $(PWD) -BINDIR ?= $(INSTALLROOT)/bin -DOCDIR ?= $(INSTALLROOT)/manual/docs -LIBDIR ?= $(INSTALLROOT)/bin -INCDIR ?= $(INSTALLROOT)/include -DETAILDOC ?= $(INSTALLROOT)/docs - -WD = $(shell pwd) -LIBRARYDIR = $(WD)/slsDetectorSoftware -LIBRARYRXRDIR = $(WD)/slsReceiverSoftware -CLIENTDIR = $(LIBRARYDIR)/slsDetectorClient -GUIDIR = $(WD)/slsDetectorGui -RECEIVERDIR = $(LIBRARYRXRDIR) -CALWIZDIR = $(WD)/calibrationWizards -MANDIR = $(WD)/manual -CALIBDIR = $(WD)/slsDetectorCalibration -MANAPIDIR = $(MANDIR)/manual-api - -TABSPACE := "\t" - - -INCLUDES=-I. -I$(LIBRARYDIR)/commonFiles -I$(LIBRARYDIR)/slsDetector -I$(LIBRARYDIR)/usersFunctions -I$(LIBRARYDIR)/multiSlsDetector -I$(LIBRARYDIR)/slsDetectorUtils -I$(LIBRARYDIR)/slsDetectorCommand -I$(LIBRARYDIR)/slsDetectorAnalysis -I$(LIBRARYDIR)/slsReceiverInterface -I$(LIBRARYRXRDIR)/include -I$(LIBRARYDIR)/threadFiles -I$(LIBRARYDIR)/sharedMemory -I$(ASM) - -INCLUDESRXR += -I. -I$(LIBRARYRXRDIR)/include -I$(CALIBDIR) -I$(ASM) -#LIBFLAGRXR += - -$(info ) -$(info #######################################) -$(info # In slsDetectorsPackage Makefile #) -$(info #######################################) -$(info ) - - -.PHONY: all nonstatic static lib libreceiver textclient receiver gui stextclient sreceiver - -#all: lib textclient receiver gui -all: textclient receiver gui - -nonstatic: lib libreceiver textclient receiver gui - -static: lib libreceiver stextclient sreceiver gui - - -lib: - cd $(LIBRARYDIR) && $(MAKE) FLAGS='$(FLAGS)' DESTDIR='$(LIBDIR)' LIBRARYDIR='$(LIBRARYDIR)' LIBS='$(LDFLAGDET)' INCLUDES='$(INCLUDES)' LIBDIR='$(LIBDIR)' - -libreceiver: - cd $(LIBRARYRXRDIR) && $(MAKE) FLAGS='$(FLAGS)' DESTDIR='$(LIBDIR)' LIBS='$(LDFLAGRXR)' INCLUDES='$(INCLUDESRXR)' LIBDIR='$(LIBDIR)' - - -stextclient: slsDetectorClient_static - -slsDetectorClient: textclient - -slsDetectorClient_static: #lib - cd $(CLIENTDIR) && $(MAKE) static_clients FLAGS='$(FLAGS)' DESTDIR='$(BINDIR)' LIBRARYDIR='$(LIBRARYDIR)' LIBS='$(LDFLAGDET)' INCLUDES='$(INCLUDES)' LIBDIR='$(LIBDIR)' - @echo "" - @echo "#######################################" - @echo "# Back in slsDetectorPackage Makefile #" - @echo "#######################################" - @echo "" - -textclient: #lib - cd $(CLIENTDIR) && $(MAKE) FLAGS='$(FLAGS)' DESTDIR='$(BINDIR)' LIBRARYDIR='$(LIBRARYDIR)' LIBS='$(LDFLAGDET)' INCLUDES='$(INCLUDES)' LIBDIR='$(LIBDIR)' - @echo "" - @echo "#######################################" - @echo "# Back in slsDetectorPackage Makefile #" - @echo "#######################################" - @echo "" - -slsReceiver: receiver - -slsReceiver_static: receiver - -receiver: #libreceiver -# cd $(RECEIVERDIR) && $(MAKE) receiver FLAGS='$(FLAGS)' DESTDIR='$(BINDIR)' LIBS='$(LDFLAGRXR)' INCLUDES='$(INCLUDESRXR)' LIBDIR='$(LIBDIR)' - cd $(RECEIVERDIR) && $(MAKE) FLAGS='$(FLAGS)' DESTDIR='$(BINDIR)' LIBS='$(LDFLAGRXR)' INCLUDES='$(INCLUDESRXR)' LIBDIR='$(LIBDIR)' - cd $(MANAPIDIR) && $(MAKE) slsMultiReceiver - @echo "" - @echo "#######################################" - @echo "# Back in slsDetectorPackage Makefile #" - @echo "#######################################" - @echo "" - -sreceiver: #libreceiver - cd $(RECEIVERDIR) && $(MAKE) static_receiver FLAGS='$(FLAGS)' DESTDIR='$(BINDIR)' LIBS='$(LDFLAGRXR)' INCLUDES='$(INCLUDESRXR)' LIBDIR='$(LIBDIR)' - @echo "" - @echo "#######################################" - @echo "# Back in slsDetectorPackage Makefile #" - @echo "#######################################" - @echo "" - -slsDetectorGUI: #lib - cd $(GUIDIR) && $(MAKE) DESTDIR='$(BINDIR)' LIBRARYDIR='$(LIBRARYDIR)' INCLUDES='$(INCLUDES)' LDFLAGDET='$(LDFLAGDETONLY)' LIBDIR='$(LIBDIR)' - @echo "" - @echo "#######################################" - @echo "# Back in slsDetectorPackage Makefile #" - @echo "#######################################" - @echo "" - -calWiz: - cd $(CALWIZDIR) && $(MAKE) DESTDIR=$(BINDIR) #FLAGS=$(FLAGS) LDFLAGDET=$(LDFLAGDET) INCLUDES=$(INCLUDES) - - - -gui: slsDetectorGUI - - -doc: - $(shell test -d $(DOCDIR) || mkdir -p $(DOCDIR)) - cd manual && make all DESTDIR=$(DOCDIR) - -htmldoc: - make doc - $(shell test -d $(DOCDIR) || mkdir -p $(DOCDIR)) - cd manual && make html DESTDIR=$(DOCDIR) - -detaildoc: createdocs docspdf docshtml removedocs - -createdocs: $(LIBRARYDIR)/doxy.config - doxygen $(LIBRARYDIR)/doxy.config - -docspdf: - cd slsDetectorPackageDocs/latex && make - $(shell test -d $(DETAILDOC) || mkdir -p $(DETAILDOC)) - $(shell test -d $(DETAILDOC)/pdf || mkdir -p $(DETAILDOC)/pdf) - mv slsDetectorPackageDocs/latex/refman.pdf $(DETAILDOC)/pdf/slsDetectorPackageDocs.pdf - -docshtml: - $(shell test -d $(DETAILDOC) || mkdir -p $(DETAILDOC)) - $(shell test -d $(DETAILDOC)/html || mkdir -p $(DETAILDOC)/html) - $(shell test -d $(DETAILDOC)/html/slsDetectorPackageDocs && rm -r $(DETAILDOC)/html/slsDetectorPackageDocs) - mv slsDetectorPackageDocs/html $(DETAILDOC)/html/slsDetectorPackageDocs - -removedocs: - rm -rf slsDetectorPackageDocs; - - -clean: - cd $(BINDIR) && rm -rf sls_detector_* slsDetectorGui slsReceiver angularCalibrationWizard energyCalibrationWizard - cd $(LIBDIR) && rm -rf libSlsDetector.so libSlsDetector.a libSlsReceiver.so libSlsReceiver.a - cd $(LIBRARYDIR) && $(MAKE) clean - cd $(LIBRARYRXRDIR) && $(MAKE) clean - cd $(CLIENTDIR) && $(MAKE) clean - cd $(GUIDIR) && $(MAKE) clean - cd $(CALWIZDIR) && $(MAKE) clean - cd manual && $(MAKE) clean - cd $(DOCDIR) && rm -rf * - rm -rf slsDetectorPackageDocs; - rm -rf $(DETAILDOC) - rm -rf $(MANAPIDIR)/slsMultiReceiver - - -#install_lib: -# cd $(LIBRARYDIR) && $(MAKE) install DESTDIR=$(LIBDIR) INCLUDES=$(INCLUDES) -# cd $(LIBRARYDIR) && $(MAKE) install_inc DESTDIR=$(INCDIR) - -mythen_virtual: - cd $(LIBRARYDIR) && $(MAKE) mythenVirtualServer DESTDIR=$(BINDIR) - - -gotthard_virtual: - cd $(LIBRARYDIR) && $(MAKE) gotthardVirtualServer DESTDIR=$(BINDIR) - - -install_client: textclient slsReceiver - -install_gui: gui - -confinstall: - make conf;\ - make install - -install_lib: - make lib;\ - make libreceiver; \ - make textclient; \ - make slsReceiver; \ - make doc; \ - make htmldoc; \ - cd $(LIBRARYDIR) && $(MAKE) install_inc DESTDIR=$(INCDIR); \ - cd $(LIBRARYRXRDIR) && $(MAKE) install_inc DESTDIR=$(INCDIR); - -install: - make install_lib; \ - make gui; \ - make calWiz; \ - cd $(LIBRARYDIR) && $(MAKE) install_inc DESTDIR=$(INCDIR);\ - cd $(LIBRARYRXRDIR) && $(MAKE) install_inc DESTDIR=$(INCDIR); - -conf: - set -e; \ - . ./configure; \ - @echo "INSTALLROOT is $(INSTALLROOT)" - @echo "BINDIR is $(BINDIR)" - @echo "LIBDIR is $(LIBDIR)" - @echo "INCDIR is $(INCDIR)" - @echo "DOCDIR is $(DOCDIR)" - - -help: - @echo "Targets:" - @echo "make all compile library, text clients, data reciever" - @echo "make lib compile library" - @echo "make libreceiver compile receiver library" - @echo "make textclient compile the slsDetectorClient dynamically linking the libraries" - @echo "make stextclient compile slsDetectorClient statically linking the libraries" - @echo "make receiver compile the slsReciever dynamically linking the libraries" - @echo "make sreceiver compile the slsReciever statically linking the libraries" - @echo "make gui compile slsDetectorGUI - requires a working Qt4 and Qwt installation" - @echo "make calWiz compile the calibration wizards - requires a working Root installation" - @echo "make doc compile pdf documentation" - @echo "make htmldoc compile html (and pdf) documentation" - @echo "make install_lib installs the libraries, the text clients, the documentation and the includes for the API" - @echo "make install installs all software, including the gui, the cal wizards and the includes for the API" - @echo "make confinstall installs all software, including the gui, the cal wizards and the includes for the API, prompting for the install paths" - @echo "make clean remove object files and executables" - @echo "make help lists possible targets" - @echo "" - @echo "" - @echo "Makefile variables" - @echo "DEBUG=1,2 set debug level to 1 (VERBOSE) or 2 (VERYVERBOSE)" - @echo "" - @echo "" - @echo "Variables - to change them run :" - @echo "INSTALLROOT=: installation root di r, default $PWD" - @echo "BINDIR=: binary installation dir below INSTALLROOT, default bin" - @echo "LIBDIR=: library installation dir below INSTALLROOT, default lib" - @echo "INCDIR=: header installation dir below INSTALLROOT, default include" - @echo "DOCDIR=: documentation installation dir below INSTALLROOT, default doc" diff --git a/Makefile.include b/Makefile.include deleted file mode 100755 index 71dba3160..000000000 --- a/Makefile.include +++ /dev/null @@ -1,58 +0,0 @@ -############################################################## -# Generic -############################################################## - -CC = g++ -CXX = $(CC) -ASM=$(shell echo "/lib/modules/`uname -r`/build/include") -LDFLAGDETONLY = -L$(LIBDIR) -Wl,-rpath=$(LIBDIR) -lSlsDetector -LDFLAGDET = -L$(LIBDIR) -Wl,-rpath=$(LIBDIR) -lSlsDetector -L/usr/lib64/ -pthread -LDFLAGRXR = -L$(LIBDIR) -Wl,-rpath=$(LIBDIR) -lSlsReceiver -L/usr/lib64/ -pthread -FLAGS= -Wall -pthread #-DEIGER_DEBUG2 -# -DVERBOSE - -# Setting up the verbose flags -ifeq ($(DEBUG),1) - FLAGS = -Wall -DVERBOSE -endif -ifeq ($(DEBUG),2) - FLAGS = -Wall -DVERYVERBOSE -endif - -############################################################## -# HDF5 specific. Set this to yes, if you want to compile -# HDF5 code: in this case, you need HDF5 libraries -############################################################## - -HDF5 = no -HDF5_DIR = /opt/hdf5v1.10.0 - -ifeq ($(HDF5),yes) - LDFLAGRXR = -L$(LIBDIR) -Wl,-rpath=$(LIBDIR) -lSlsReceiver -L$(HDF5_DIR)/lib -Wl,-rpath=$(HDF5_DIR)/lib -lhdf5 -lhdf5_cpp -lsz -lz -DHDF5C -L/usr/lib64/ -pthread - INCLUDESRXR = -I$(HDF5_DIR)/include -endif - - -############################################################## -# ROOTSLS specific. Set this to yes, if you want to compile -# ROOTSLS code: in this case, you need also root libraries -############################################################## - -ROOTSLS = no - -ROOTFLAGS = $(shell root-config --cflags --glibs) -DMYROOT1 #-DALLFILE_DEBUG #-DMYROOT1 - -ifeq ($(ROOTSLS),yes) - LDFLAGRXR = -L$(LIBDIR) -lSlsReceiver $(ROOTFLAGS) -DROOTSLS -endif - - -define colorecho - @tput setaf 6 - @echo $1 - @tput sgr0 -endef - - - - diff --git a/README.md b/README.md old mode 100644 new mode 100755 diff --git a/RELEASE.txt b/RELEASE.txt old mode 100644 new mode 100755 index 74e9ca8c6..e69de29bb --- a/RELEASE.txt +++ b/RELEASE.txt @@ -1,205 +0,0 @@ -SLS Detector Package 4.0.1 released on 08.02.2018 (Bug Fix Release) -=================================================================== - - -This document describes the differences between 4.0.1 and 4.0.0 releases. - - CONTENTS - -------- - 1. Topics Concerning - 2. Resolved Issues - 3. Known Issues - 4. Firmware Requirements - 5. Download, Documentation & Support - - - -1. Topics Concerning -==================== - - - Jungfrau server (new firmware mapped) - - Eiger server (measuredPeriod, reg) - - Gotthard server(ADC channel shift, ROI, 25um slave packets) - - Receiver (padding, releasing resources segfault, gappixels) - - Users class (detectorSize, ROI, versions, status) - - API (config error, ROI) - - Compile (Options prefix, static libraries, Makefile for API) - - Gui (multi module) - - - -2. Resolved Issues -================== - - Detector Server - --------------- - - 1. (Jungfrau): Latest Jungfrau firmware release mapped. - - 2. (Eiger): Measured subperiod initially wrapped around 4.29s. Now, upto 42.9s. - - Advanced command "reg" was writing only to right FPGA. - - 3. (Gotthard 25/50um): Since Gotthard only sends packet numbers, one had to - remember to take even number of images in ROI mode, if they wanted to - switch back to non ROI mode. - This is fixed now, but temporary fix involves sending an image during - configuration, which will not be captured by the receiver. Hence, it takes - longer to configure. Permanent fix will require a firmware update. - - The detector output is shifted by 1 for every 32 channels. This is fixed now. - - - Receiver - -------- - - 1. Receiver padding was enabled only if deactivated padding was also enabled. - Receiver padding enable and receiver deactivated padding enable are independent now. - - 2. Starting and stopping receiver without listening resulted in seg faults. - - 3. Gappixels in receiver bug fix. - - - Client - ------ - - 1. (Users class): DetectorSize modified to set/get ROI if ROI is only 1 in number. - - Allowed setting/getting ROI at single detector level via API. - (ROI for Gotthard only). Added them to the users class as setROI and getROI. - - Retrieving versions at module level is possible now. - - Added "stopped" as status in getRunStatus list. - - 2. (API): Incorrect mac address in config file will set error flag in API and not just - print the error. - - ROI possible at module level. - - - Compile - ------- - - 1. CMake options now have a prefix 'SLS_'. - - 2. Static libraries removed. - - 2. slsDetectorPackage/manual/manual-api/Makefile modified to use libraries - from slsDetectorPackage/bin as the main Makefile copies the libraries there. - No effect when using CMakeFiles. - - - Gui - --- - - 1. Adding multiple detectors in x and y direction incremented number of detectors - in y direction incorrectly. Effect seen only in GUI (segfault) if - detsizechan has multi detectors in both direction. Fixed. - - - -3. Known Issues -=============== - - Detector Specific - ----------------- - - 1. (Gotthard 25 um): Slave misses or captures an extra frame. Occurs irregularly. - - 2. (Gotthard 25/50um): Using ROI (2 chips, 256 channels) missses last pixel - of that ADC. - - - -4. Firmware Requirements -======================== - - Gotthard - ======== - Minimum compatible version : 11.01.2013 - Latest compatible version : 08.02.2018 (50um and 25um Master) - 09.02.2018 (25 um Slave) - Eiger - ===== - Minimum compatible version : 22 - Latest compatible version : 22 - - Jungfrau - ======== - Minimum compatible version : 26.02.2018 - Latest compatible version : 06.12.2018 - - - Detector Upgrade - ================ - Gotthard Cannot be upgraded remotely. Requires programming via USB blaster - Eiger Can be upgraded remotely via bit files - Jungfrau Can be upgraded remotely using sls_detector_put programfpga - - Instructions available at - https://www.psi.ch/detectors/installation-instructions - under Detector Upgrade -> [Detector Type] -> Firmware. - - - Please refer to the link below for more details on the firmware versions. - https://www.psi.ch/detectors/firmware. - - - -5. Download, Documentation & Support -==================================== - - Download - -------- - - The Source Code (Default C++ API): - https://github.com/slsdetectorgroup/slsDetectorPackage - - The Conda Lib Package: - https://github.com/slsdetectorgroup/sls_detector_lib - - The Conda GUI Package: - https://github.com/slsdetectorgroup/sls_detector_gui - - The Python Interface (including the package): - https://github.com/slsdetectorgroup/sls_detector - - - Documentation - ------------- - - Manual (HTML & PDF): - https://www.psi.ch/detectors/documentation - slsDetectorPackage/manual/docs/ - - Command Line Documentation: - manual/docs/html/slsDetectorClientDocs/index.html - manual/docs/pdf/slsDetectorClientDocs.pdf - - C++ API Documentation: - manual/docs/html/slsDetectorUsersDocs/index.html - manual/docs/pdf/slsDetectorUsersDocs.pdf - - C++ API Example: - manual/manual-api/mainClient.cpp - manual/manual-api/mainReceiver.cpp - - Python API Documentation: - https://slsdetectorgroup.github.io/sls_detector/ - - Further Documentation: - https://www.psi.ch/detectors/users-support - - - Support - ------- - - General Software related: - dhanya.thattil@psi.ch - anna.bergamaschi@psi.ch - - Python related: - erik.frojdh@psi.ch - diff --git a/catch/catch.hpp b/catch/catch.hpp new file mode 100755 index 000000000..1850fff12 --- /dev/null +++ b/catch/catch.hpp @@ -0,0 +1,14934 @@ +/* + * Catch v2.7.0 + * Generated: 2019-03-07 21:34:30.252164 + * ---------------------------------------------------------- + * This file has been merged from multiple headers. Please don't edit it directly + * Copyright (c) 2019 Two Blue Cubes Ltd. All rights reserved. + * + * Distributed under the Boost Software License, Version 1.0. (See accompanying + * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + */ +#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED +#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED +// start catch.hpp + + +#define CATCH_VERSION_MAJOR 2 +#define CATCH_VERSION_MINOR 7 +#define CATCH_VERSION_PATCH 0 + +#ifdef __clang__ +# pragma clang system_header +#elif defined __GNUC__ +# pragma GCC system_header +#endif + +// start catch_suppress_warnings.h + +#ifdef __clang__ +# ifdef __ICC // icpc defines the __clang__ macro +# pragma warning(push) +# pragma warning(disable: 161 1682) +# else // __ICC +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wpadded" +# pragma clang diagnostic ignored "-Wswitch-enum" +# pragma clang diagnostic ignored "-Wcovered-switch-default" +# endif +#elif defined __GNUC__ + // Because REQUIREs trigger GCC's -Wparentheses, and because still + // supported version of g++ have only buggy support for _Pragmas, + // Wparentheses have to be suppressed globally. +# pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details + +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wunused-variable" +# pragma GCC diagnostic ignored "-Wpadded" +#endif +// end catch_suppress_warnings.h +#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER) +# define CATCH_IMPL +# define CATCH_CONFIG_ALL_PARTS +#endif + +// In the impl file, we want to have access to all parts of the headers +// Can also be used to sanely support PCHs +#if defined(CATCH_CONFIG_ALL_PARTS) +# define CATCH_CONFIG_EXTERNAL_INTERFACES +# if defined(CATCH_CONFIG_DISABLE_MATCHERS) +# undef CATCH_CONFIG_DISABLE_MATCHERS +# endif +# if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) +# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER +# endif +#endif + +#if !defined(CATCH_CONFIG_IMPL_ONLY) +// start catch_platform.h + +#ifdef __APPLE__ +# include +# if TARGET_OS_OSX == 1 +# define CATCH_PLATFORM_MAC +# elif TARGET_OS_IPHONE == 1 +# define CATCH_PLATFORM_IPHONE +# endif + +#elif defined(linux) || defined(__linux) || defined(__linux__) +# define CATCH_PLATFORM_LINUX + +#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__) +# define CATCH_PLATFORM_WINDOWS +#endif + +// end catch_platform.h + +#ifdef CATCH_IMPL +# ifndef CLARA_CONFIG_MAIN +# define CLARA_CONFIG_MAIN_NOT_DEFINED +# define CLARA_CONFIG_MAIN +# endif +#endif + +// start catch_user_interfaces.h + +namespace Catch { + unsigned int rngSeed(); +} + +// end catch_user_interfaces.h +// start catch_tag_alias_autoregistrar.h + +// start catch_common.h + +// start catch_compiler_capabilities.h + +// Detect a number of compiler features - by compiler +// The following features are defined: +// +// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? +// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported? +// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported? +// CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled? +// **************** +// Note to maintainers: if new toggles are added please document them +// in configuration.md, too +// **************** + +// In general each macro has a _NO_ form +// (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature. +// Many features, at point of detection, define an _INTERNAL_ macro, so they +// can be combined, en-mass, with the _NO_ forms later. + +#ifdef __cplusplus + +# if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L) +# define CATCH_CPP14_OR_GREATER +# endif + +# if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) +# define CATCH_CPP17_OR_GREATER +# endif + +#endif + +#if defined(CATCH_CPP17_OR_GREATER) +# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS +#endif + +#ifdef __clang__ + +# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + _Pragma( "clang diagnostic push" ) \ + _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \ + _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"") +# define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ + _Pragma( "clang diagnostic pop" ) + +# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ + _Pragma( "clang diagnostic push" ) \ + _Pragma( "clang diagnostic ignored \"-Wparentheses\"" ) +# define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ + _Pragma( "clang diagnostic pop" ) + +# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ + _Pragma( "clang diagnostic push" ) \ + _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" ) +# define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS \ + _Pragma( "clang diagnostic pop" ) + +#endif // __clang__ + +//////////////////////////////////////////////////////////////////////////////// +// Assume that non-Windows platforms support posix signals by default +#if !defined(CATCH_PLATFORM_WINDOWS) + #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS +#endif + +//////////////////////////////////////////////////////////////////////////////// +// We know some environments not to support full POSIX signals +#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__) + #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +#endif + +#ifdef __OS400__ +# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS +# define CATCH_CONFIG_COLOUR_NONE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Android somehow still does not support std::to_string +#if defined(__ANDROID__) +# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Not all Windows environments support SEH properly +#if defined(__MINGW32__) +# define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH +#endif + +//////////////////////////////////////////////////////////////////////////////// +// PS4 +#if defined(__ORBIS__) +# define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Cygwin +#ifdef __CYGWIN__ + +// Required for some versions of Cygwin to declare gettimeofday +// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin +# define _BSD_SOURCE +// some versions of cygwin (most) do not support std::to_string. Use the libstd check. +// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813 +# if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \ + && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF)) + +# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING + +# endif +#endif // __CYGWIN__ + +//////////////////////////////////////////////////////////////////////////////// +// Visual C++ +#ifdef _MSC_VER + +# if _MSC_VER >= 1900 // Visual Studio 2015 or newer +# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS +# endif + +// Universal Windows platform does not support SEH +// Or console colours (or console at all...) +# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) +# define CATCH_CONFIG_COLOUR_NONE +# else +# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH +# endif + +// MSVC traditional preprocessor needs some workaround for __VA_ARGS__ +// _MSVC_TRADITIONAL == 0 means new conformant preprocessor +// _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor +# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL) +# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +# endif + +#endif // _MSC_VER + +//////////////////////////////////////////////////////////////////////////////// +// Check if we are compiled with -fno-exceptions or equivalent +#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND) +# define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED +#endif + +//////////////////////////////////////////////////////////////////////////////// +// DJGPP +#ifdef __DJGPP__ +# define CATCH_INTERNAL_CONFIG_NO_WCHAR +#endif // __DJGPP__ + +//////////////////////////////////////////////////////////////////////////////// +// Embarcadero C++Build +#if defined(__BORLANDC__) + #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN +#endif + +//////////////////////////////////////////////////////////////////////////////// + +// Use of __COUNTER__ is suppressed during code analysis in +// CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly +// handled by it. +// Otherwise all supported compilers support COUNTER macro, +// but user still might want to turn it off +#if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L ) + #define CATCH_INTERNAL_CONFIG_COUNTER +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Check if string_view is available and usable +// The check is split apart to work around v140 (VS2015) preprocessor issue... +#if defined(__has_include) +#if __has_include() && defined(CATCH_CPP17_OR_GREATER) +# define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW +#endif +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Check if optional is available and usable +#if defined(__has_include) +# if __has_include() && defined(CATCH_CPP17_OR_GREATER) +# define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL +# endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) +#endif // __has_include + +//////////////////////////////////////////////////////////////////////////////// +// Check if variant is available and usable +#if defined(__has_include) +# if __has_include() && defined(CATCH_CPP17_OR_GREATER) +# if defined(__clang__) && (__clang_major__ < 8) + // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852 + // fix should be in clang 8, workaround in libstdc++ 8.2 +# include +# if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) +# define CATCH_CONFIG_NO_CPP17_VARIANT +# else +# define CATCH_INTERNAL_CONFIG_CPP17_VARIANT +# endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9) +# else +# define CATCH_INTERNAL_CONFIG_CPP17_VARIANT +# endif // defined(__clang__) && (__clang_major__ < 8) +# endif // __has_include() && defined(CATCH_CPP17_OR_GREATER) +#endif // __has_include + +#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) +# define CATCH_CONFIG_COUNTER +#endif +#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH) +# define CATCH_CONFIG_WINDOWS_SEH +#endif +// This is set by default, because we assume that unix compilers are posix-signal-compatible by default. +#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS) +# define CATCH_CONFIG_POSIX_SIGNALS +#endif +// This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions. +#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR) +# define CATCH_CONFIG_WCHAR +#endif + +#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING) +# define CATCH_CONFIG_CPP11_TO_STRING +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL) +# define CATCH_CONFIG_CPP17_OPTIONAL +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) +# define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW) +# define CATCH_CONFIG_CPP17_STRING_VIEW +#endif + +#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT) +# define CATCH_CONFIG_CPP17_VARIANT +#endif + +#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) +# define CATCH_INTERNAL_CONFIG_NEW_CAPTURE +#endif + +#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE) +# define CATCH_CONFIG_NEW_CAPTURE +#endif + +#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) +# define CATCH_CONFIG_DISABLE_EXCEPTIONS +#endif + +#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN) +# define CATCH_CONFIG_POLYFILL_ISNAN +#endif + +#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS +# define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS +# define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS +#endif +#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS) +# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS +# define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS +#endif + +#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) +#define CATCH_TRY if ((true)) +#define CATCH_CATCH_ALL if ((false)) +#define CATCH_CATCH_ANON(type) if ((false)) +#else +#define CATCH_TRY try +#define CATCH_CATCH_ALL catch (...) +#define CATCH_CATCH_ANON(type) catch (type) +#endif + +#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) +#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#endif + +// end catch_compiler_capabilities.h +#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line +#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) +#ifdef CATCH_CONFIG_COUNTER +# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ ) +#else +# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ ) +#endif + +#include +#include +#include + +// We need a dummy global operator<< so we can bring it into Catch namespace later +struct Catch_global_namespace_dummy {}; +std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy); + +namespace Catch { + + struct CaseSensitive { enum Choice { + Yes, + No + }; }; + + class NonCopyable { + NonCopyable( NonCopyable const& ) = delete; + NonCopyable( NonCopyable && ) = delete; + NonCopyable& operator = ( NonCopyable const& ) = delete; + NonCopyable& operator = ( NonCopyable && ) = delete; + + protected: + NonCopyable(); + virtual ~NonCopyable(); + }; + + struct SourceLineInfo { + + SourceLineInfo() = delete; + SourceLineInfo( char const* _file, std::size_t _line ) noexcept + : file( _file ), + line( _line ) + {} + + SourceLineInfo( SourceLineInfo const& other ) = default; + SourceLineInfo& operator = ( SourceLineInfo const& ) = default; + SourceLineInfo( SourceLineInfo&& ) noexcept = default; + SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default; + + bool empty() const noexcept; + bool operator == ( SourceLineInfo const& other ) const noexcept; + bool operator < ( SourceLineInfo const& other ) const noexcept; + + char const* file; + std::size_t line; + }; + + std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); + + // Bring in operator<< from global namespace into Catch namespace + // This is necessary because the overload of operator<< above makes + // lookup stop at namespace Catch + using ::operator<<; + + // Use this in variadic streaming macros to allow + // >> +StreamEndStop + // as well as + // >> stuff +StreamEndStop + struct StreamEndStop { + std::string operator+() const; + }; + template + T const& operator + ( T const& value, StreamEndStop ) { + return value; + } +} + +#define CATCH_INTERNAL_LINEINFO \ + ::Catch::SourceLineInfo( __FILE__, static_cast( __LINE__ ) ) + +// end catch_common.h +namespace Catch { + + struct RegistrarForTagAliases { + RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); + }; + +} // end namespace Catch + +#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \ + CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS + +// end catch_tag_alias_autoregistrar.h +// start catch_test_registry.h + +// start catch_interfaces_testcase.h + +#include + +namespace Catch { + + class TestSpec; + + struct ITestInvoker { + virtual void invoke () const = 0; + virtual ~ITestInvoker(); + }; + + class TestCase; + struct IConfig; + + struct ITestCaseRegistry { + virtual ~ITestCaseRegistry(); + virtual std::vector const& getAllTests() const = 0; + virtual std::vector const& getAllTestsSorted( IConfig const& config ) const = 0; + }; + + bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); + std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ); + std::vector const& getAllTestCasesSorted( IConfig const& config ); + +} + +// end catch_interfaces_testcase.h +// start catch_stringref.h + +#include +#include +#include + +namespace Catch { + + /// A non-owning string class (similar to the forthcoming std::string_view) + /// Note that, because a StringRef may be a substring of another string, + /// it may not be null terminated. c_str() must return a null terminated + /// string, however, and so the StringRef will internally take ownership + /// (taking a copy), if necessary. In theory this ownership is not externally + /// visible - but it does mean (substring) StringRefs should not be shared between + /// threads. + class StringRef { + public: + using size_type = std::size_t; + + private: + friend struct StringRefTestAccess; + + char const* m_start; + size_type m_size; + + char* m_data = nullptr; + + void takeOwnership(); + + static constexpr char const* const s_empty = ""; + + public: // construction/ assignment + StringRef() noexcept + : StringRef( s_empty, 0 ) + {} + + StringRef( StringRef const& other ) noexcept + : m_start( other.m_start ), + m_size( other.m_size ) + {} + + StringRef( StringRef&& other ) noexcept + : m_start( other.m_start ), + m_size( other.m_size ), + m_data( other.m_data ) + { + other.m_data = nullptr; + } + + StringRef( char const* rawChars ) noexcept; + + StringRef( char const* rawChars, size_type size ) noexcept + : m_start( rawChars ), + m_size( size ) + {} + + StringRef( std::string const& stdString ) noexcept + : m_start( stdString.c_str() ), + m_size( stdString.size() ) + {} + + ~StringRef() noexcept { + delete[] m_data; + } + + auto operator = ( StringRef const &other ) noexcept -> StringRef& { + delete[] m_data; + m_data = nullptr; + m_start = other.m_start; + m_size = other.m_size; + return *this; + } + + operator std::string() const; + + void swap( StringRef& other ) noexcept; + + public: // operators + auto operator == ( StringRef const& other ) const noexcept -> bool; + auto operator != ( StringRef const& other ) const noexcept -> bool; + + auto operator[] ( size_type index ) const noexcept -> char; + + public: // named queries + auto empty() const noexcept -> bool { + return m_size == 0; + } + auto size() const noexcept -> size_type { + return m_size; + } + + auto numberOfCharacters() const noexcept -> size_type; + auto c_str() const -> char const*; + + public: // substrings and searches + auto substr( size_type start, size_type size ) const noexcept -> StringRef; + + // Returns the current start pointer. + // Note that the pointer can change when if the StringRef is a substring + auto currentData() const noexcept -> char const*; + + private: // ownership queries - may not be consistent between calls + auto isOwned() const noexcept -> bool; + auto isSubstring() const noexcept -> bool; + }; + + auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string; + auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string; + auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string; + + auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&; + auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&; + + inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef { + return StringRef( rawChars, size ); + } + +} // namespace Catch + +inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef { + return Catch::StringRef( rawChars, size ); +} + +// end catch_stringref.h +// start catch_type_traits.hpp + + +#include + +namespace Catch{ + +#ifdef CATCH_CPP17_OR_GREATER + template + inline constexpr auto is_unique = std::true_type{}; + + template + inline constexpr auto is_unique = std::bool_constant< + (!std::is_same_v && ...) && is_unique + >{}; +#else + +template +struct is_unique : std::true_type{}; + +template +struct is_unique : std::integral_constant +::value + && is_unique::value + && is_unique::value +>{}; + +#endif +} + +// end catch_type_traits.hpp +// start catch_preprocessor.hpp + + +#define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__ +#define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__))) +#define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__))) + +#ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__ +// MSVC needs more evaluations +#define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__))) +#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__)) +#else +#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__) +#endif + +#define CATCH_REC_END(...) +#define CATCH_REC_OUT + +#define CATCH_EMPTY() +#define CATCH_DEFER(id) id CATCH_EMPTY() + +#define CATCH_REC_GET_END2() 0, CATCH_REC_END +#define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2 +#define CATCH_REC_GET_END(...) CATCH_REC_GET_END1 +#define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT +#define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0) +#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next) + +#define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ ) + +#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ ) +#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ ) + +// Applies the function macro `f` to each of the remaining parameters, inserts commas between the results, +// and passes userdata as the first parameter to each invocation, +// e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c) +#define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) + +#define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0)) + +#define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param) +#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__ +#define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__ +#define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF +#define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__) +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__ +#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) +#else +// MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF +#define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__) +#define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__ +#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1) +#endif + +#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__) + +#define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name, __VA_ARGS__) +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name,...) Name " - " #__VA_ARGS__ +#define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME(Name,...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)) +#else +// MSVC is adding extra space and needs more calls to properly remove () +#define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME3(Name,...) Name " -" #__VA_ARGS__ +#define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME1(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME2(Name, __VA_ARGS__) +#define INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME(Name, ...) INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME1(Name, INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))) +#endif + +#define INTERNAL_CATCH_MAKE_TYPE_LIST(types) Catch::TypeList + +#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(types)\ + CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,INTERNAL_CATCH_REMOVE_PARENS(types)) + +// end catch_preprocessor.hpp +// start catch_meta.hpp + + +#include + +namespace Catch { +template< typename... > +struct TypeList {}; + +template< typename... > +struct append; + +template< template class L1 + , typename...E1 + , template class L2 + , typename...E2 +> +struct append< L1, L2 > { + using type = L1; +}; + +template< template class L1 + , typename...E1 + , template class L2 + , typename...E2 + , typename...Rest +> +struct append< L1, L2, Rest...> { + using type = typename append< L1, Rest... >::type; +}; + +template< template class + , typename... +> +struct rewrap; + +template< template class Container + , template class List + , typename...elems +> +struct rewrap> { + using type = TypeList< Container< elems... > >; +}; + +template< template class Container + , template class List + , class...Elems + , typename...Elements> + struct rewrap, Elements...> { + using type = typename append>, typename rewrap::type>::type; +}; + +template< template class...Containers > +struct combine { + template< typename...Types > + struct with_types { + template< template class Final > + struct into { + using type = typename append, typename rewrap::type...>::type; + }; + }; +}; + +template +struct always_false : std::false_type {}; + +} // namespace Catch + +// end catch_meta.hpp +namespace Catch { + +template +class TestInvokerAsMethod : public ITestInvoker { + void (C::*m_testAsMethod)(); +public: + TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {} + + void invoke() const override { + C obj; + (obj.*m_testAsMethod)(); + } +}; + +auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*; + +template +auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* { + return new(std::nothrow) TestInvokerAsMethod( testAsMethod ); +} + +struct NameAndTags { + NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept; + StringRef name; + StringRef tags; +}; + +struct AutoReg : NonCopyable { + AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept; + ~AutoReg(); +}; + +} // end namespace Catch + +#if defined(CATCH_CONFIG_DISABLE) + #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \ + static void TestName() + #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \ + namespace{ \ + struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ + void test(); \ + }; \ + } \ + void TestName::test() + #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION( TestName, ... ) \ + template \ + static void TestName() + #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \ + namespace{ \ + template \ + struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName ) { \ + void test(); \ + }; \ + } \ + template \ + void TestName::test() +#endif + + /////////////////////////////////////////////////////////////////////////////// + #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \ + static void TestName(); \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \ + CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ + static void TestName() + #define INTERNAL_CATCH_TESTCASE( ... ) \ + INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ ) + + /////////////////////////////////////////////////////////////////////////////// + #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \ + CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS + + /////////////////////////////////////////////////////////////////////////////// + #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace{ \ + struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \ + void test(); \ + }; \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \ + } \ + CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ + void TestName::test() + #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ + INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ ) + + /////////////////////////////////////////////////////////////////////////////// + #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \ + CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS + + /////////////////////////////////////////////////////////////////////////////// + #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, ... )\ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + template \ + static void TestFunc();\ + namespace {\ + template \ + struct TestName{\ + template \ + TestName(Ts...names){\ + CATCH_INTERNAL_CHECK_UNIQUE_TYPES(CATCH_REC_LIST(INTERNAL_CATCH_REMOVE_PARENS, __VA_ARGS__)) \ + using expander = int[];\ + (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ names, Tags } ), 0)... };/* NOLINT */ \ + }\ + };\ + INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestName, Name, __VA_ARGS__) \ + }\ + CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ + template \ + static void TestFunc() + +#if defined(CATCH_CPP17_OR_GREATER) +#define CATCH_INTERNAL_CHECK_UNIQUE_TYPES(...) static_assert(Catch::is_unique<__VA_ARGS__>,"Duplicate type detected in declaration of template test case"); +#else +#define CATCH_INTERNAL_CHECK_UNIQUE_TYPES(...) static_assert(Catch::is_unique<__VA_ARGS__>::value,"Duplicate type detected in declaration of template test case"); +#endif + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR + #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, __VA_ARGS__ ) +#else + #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \ + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, __VA_ARGS__ ) ) +#endif + + #define INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestName, Name, ...)\ + static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ + TestName(CATCH_REC_LIST_UD(INTERNAL_CATCH_TEMPLATE_UNIQUE_NAME,Name, __VA_ARGS__));\ + return 0;\ + }(); + + #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, TmplTypes, TypesList) \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + template static void TestFuncName(); \ + namespace { \ + template \ + struct TestName { \ + TestName() { \ + CATCH_INTERNAL_CHECK_UNIQUE_TYPES(Types...) \ + int index = 0; \ + using expander = int[]; \ + constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ + constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ + constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ + (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++, 0)... };/* NOLINT */\ + } \ + }; \ + static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \ + using TestInit = Catch::combine \ + ::with_types::into::type; \ + TestInit(); \ + return 0; \ + }(); \ + } \ + CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ + template \ + static void TestFuncName() + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR + #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ),Name,Tags,__VA_ARGS__) +#else + #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\ + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), Name, Tags, __VA_ARGS__ ) ) +#endif + + #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, ... ) \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace{ \ + template \ + struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName ) { \ + void test();\ + };\ + template \ + struct TestNameClass{\ + template \ + TestNameClass(Ts...names){\ + CATCH_INTERNAL_CHECK_UNIQUE_TYPES(CATCH_REC_LIST(INTERNAL_CATCH_REMOVE_PARENS, __VA_ARGS__)) \ + using expander = int[];\ + (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ names, Tags } ), 0)... };/* NOLINT */ \ + }\ + };\ + INTERNAL_CATCH_TEMPLATE_REGISTRY_INITIATE(TestNameClass, Name, __VA_ARGS__)\ + }\ + CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS\ + template \ + void TestName::test() + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR + #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ + INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, __VA_ARGS__ ) +#else + #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \ + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____C_L_A_S_S____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) , ClassName, Name, Tags, __VA_ARGS__ ) ) +#endif + + #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, TmplTypes, TypesList)\ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + template \ + struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName ) { \ + void test();\ + };\ + namespace {\ + template\ + struct TestNameClass{\ + TestNameClass(){\ + CATCH_INTERNAL_CHECK_UNIQUE_TYPES(Types...)\ + int index = 0;\ + using expander = int[];\ + constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\ + constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\ + constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\ + (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++, 0)... };/* NOLINT */ \ + }\ + };\ + static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\ + using TestInit = Catch::combine\ + ::with_types::into::type;\ + TestInit();\ + return 0;\ + }(); \ + }\ + CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ + template \ + void TestName::test() + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR + #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ + INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, __VA_ARGS__ ) +#else + #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\ + INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____F_U_N_C____ ), ClassName, Name, Tags, __VA_ARGS__ ) ) +#endif + +// end catch_test_registry.h +// start catch_capture.hpp + +// start catch_assertionhandler.h + +// start catch_assertioninfo.h + +// start catch_result_type.h + +namespace Catch { + + // ResultWas::OfType enum + struct ResultWas { enum OfType { + Unknown = -1, + Ok = 0, + Info = 1, + Warning = 2, + + FailureBit = 0x10, + + ExpressionFailed = FailureBit | 1, + ExplicitFailure = FailureBit | 2, + + Exception = 0x100 | FailureBit, + + ThrewException = Exception | 1, + DidntThrowException = Exception | 2, + + FatalErrorCondition = 0x200 | FailureBit + + }; }; + + bool isOk( ResultWas::OfType resultType ); + bool isJustInfo( int flags ); + + // ResultDisposition::Flags enum + struct ResultDisposition { enum Flags { + Normal = 0x01, + + ContinueOnFailure = 0x02, // Failures fail test, but execution continues + FalseTest = 0x04, // Prefix expression with ! + SuppressFail = 0x08 // Failures are reported but do not fail the test + }; }; + + ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ); + + bool shouldContinueOnFailure( int flags ); + inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; } + bool shouldSuppressFailure( int flags ); + +} // end namespace Catch + +// end catch_result_type.h +namespace Catch { + + struct AssertionInfo + { + StringRef macroName; + SourceLineInfo lineInfo; + StringRef capturedExpression; + ResultDisposition::Flags resultDisposition; + + // We want to delete this constructor but a compiler bug in 4.8 means + // the struct is then treated as non-aggregate + //AssertionInfo() = delete; + }; + +} // end namespace Catch + +// end catch_assertioninfo.h +// start catch_decomposer.h + +// start catch_tostring.h + +#include +#include +#include +#include +// start catch_stream.h + +#include +#include +#include + +namespace Catch { + + std::ostream& cout(); + std::ostream& cerr(); + std::ostream& clog(); + + class StringRef; + + struct IStream { + virtual ~IStream(); + virtual std::ostream& stream() const = 0; + }; + + auto makeStream( StringRef const &filename ) -> IStream const*; + + class ReusableStringStream { + std::size_t m_index; + std::ostream* m_oss; + public: + ReusableStringStream(); + ~ReusableStringStream(); + + auto str() const -> std::string; + + template + auto operator << ( T const& value ) -> ReusableStringStream& { + *m_oss << value; + return *this; + } + auto get() -> std::ostream& { return *m_oss; } + }; +} + +// end catch_stream.h + +#ifdef CATCH_CONFIG_CPP17_STRING_VIEW +#include +#endif + +#ifdef __OBJC__ +// start catch_objc_arc.hpp + +#import + +#ifdef __has_feature +#define CATCH_ARC_ENABLED __has_feature(objc_arc) +#else +#define CATCH_ARC_ENABLED 0 +#endif + +void arcSafeRelease( NSObject* obj ); +id performOptionalSelector( id obj, SEL sel ); + +#if !CATCH_ARC_ENABLED +inline void arcSafeRelease( NSObject* obj ) { + [obj release]; +} +inline id performOptionalSelector( id obj, SEL sel ) { + if( [obj respondsToSelector: sel] ) + return [obj performSelector: sel]; + return nil; +} +#define CATCH_UNSAFE_UNRETAINED +#define CATCH_ARC_STRONG +#else +inline void arcSafeRelease( NSObject* ){} +inline id performOptionalSelector( id obj, SEL sel ) { +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" +#endif + if( [obj respondsToSelector: sel] ) + return [obj performSelector: sel]; +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + return nil; +} +#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained +#define CATCH_ARC_STRONG __strong +#endif + +// end catch_objc_arc.hpp +#endif + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless +#endif + +namespace Catch { + namespace Detail { + + extern const std::string unprintableString; + + std::string rawMemoryToString( const void *object, std::size_t size ); + + template + std::string rawMemoryToString( const T& object ) { + return rawMemoryToString( &object, sizeof(object) ); + } + + template + class IsStreamInsertable { + template + static auto test(int) + -> decltype(std::declval() << std::declval(), std::true_type()); + + template + static auto test(...)->std::false_type; + + public: + static const bool value = decltype(test(0))::value; + }; + + template + std::string convertUnknownEnumToString( E e ); + + template + typename std::enable_if< + !std::is_enum::value && !std::is_base_of::value, + std::string>::type convertUnstreamable( T const& ) { + return Detail::unprintableString; + } + template + typename std::enable_if< + !std::is_enum::value && std::is_base_of::value, + std::string>::type convertUnstreamable(T const& ex) { + return ex.what(); + } + + template + typename std::enable_if< + std::is_enum::value + , std::string>::type convertUnstreamable( T const& value ) { + return convertUnknownEnumToString( value ); + } + +#if defined(_MANAGED) + //! Convert a CLR string to a utf8 std::string + template + std::string clrReferenceToString( T^ ref ) { + if (ref == nullptr) + return std::string("null"); + auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString()); + cli::pin_ptr p = &bytes[0]; + return std::string(reinterpret_cast(p), bytes->Length); + } +#endif + + } // namespace Detail + + // If we decide for C++14, change these to enable_if_ts + template + struct StringMaker { + template + static + typename std::enable_if<::Catch::Detail::IsStreamInsertable::value, std::string>::type + convert(const Fake& value) { + ReusableStringStream rss; + // NB: call using the function-like syntax to avoid ambiguity with + // user-defined templated operator<< under clang. + rss.operator<<(value); + return rss.str(); + } + + template + static + typename std::enable_if::value, std::string>::type + convert( const Fake& value ) { +#if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER) + return Detail::convertUnstreamable(value); +#else + return CATCH_CONFIG_FALLBACK_STRINGIFIER(value); +#endif + } + }; + + namespace Detail { + + // This function dispatches all stringification requests inside of Catch. + // Should be preferably called fully qualified, like ::Catch::Detail::stringify + template + std::string stringify(const T& e) { + return ::Catch::StringMaker::type>::type>::convert(e); + } + + template + std::string convertUnknownEnumToString( E e ) { + return ::Catch::Detail::stringify(static_cast::type>(e)); + } + +#if defined(_MANAGED) + template + std::string stringify( T^ e ) { + return ::Catch::StringMaker::convert(e); + } +#endif + + } // namespace Detail + + // Some predefined specializations + + template<> + struct StringMaker { + static std::string convert(const std::string& str); + }; + +#ifdef CATCH_CONFIG_CPP17_STRING_VIEW + template<> + struct StringMaker { + static std::string convert(std::string_view str); + }; +#endif + + template<> + struct StringMaker { + static std::string convert(char const * str); + }; + template<> + struct StringMaker { + static std::string convert(char * str); + }; + +#ifdef CATCH_CONFIG_WCHAR + template<> + struct StringMaker { + static std::string convert(const std::wstring& wstr); + }; + +# ifdef CATCH_CONFIG_CPP17_STRING_VIEW + template<> + struct StringMaker { + static std::string convert(std::wstring_view str); + }; +# endif + + template<> + struct StringMaker { + static std::string convert(wchar_t const * str); + }; + template<> + struct StringMaker { + static std::string convert(wchar_t * str); + }; +#endif + + // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer, + // while keeping string semantics? + template + struct StringMaker { + static std::string convert(char const* str) { + return ::Catch::Detail::stringify(std::string{ str }); + } + }; + template + struct StringMaker { + static std::string convert(signed char const* str) { + return ::Catch::Detail::stringify(std::string{ reinterpret_cast(str) }); + } + }; + template + struct StringMaker { + static std::string convert(unsigned char const* str) { + return ::Catch::Detail::stringify(std::string{ reinterpret_cast(str) }); + } + }; + + template<> + struct StringMaker { + static std::string convert(int value); + }; + template<> + struct StringMaker { + static std::string convert(long value); + }; + template<> + struct StringMaker { + static std::string convert(long long value); + }; + template<> + struct StringMaker { + static std::string convert(unsigned int value); + }; + template<> + struct StringMaker { + static std::string convert(unsigned long value); + }; + template<> + struct StringMaker { + static std::string convert(unsigned long long value); + }; + + template<> + struct StringMaker { + static std::string convert(bool b); + }; + + template<> + struct StringMaker { + static std::string convert(char c); + }; + template<> + struct StringMaker { + static std::string convert(signed char c); + }; + template<> + struct StringMaker { + static std::string convert(unsigned char c); + }; + + template<> + struct StringMaker { + static std::string convert(std::nullptr_t); + }; + + template<> + struct StringMaker { + static std::string convert(float value); + }; + template<> + struct StringMaker { + static std::string convert(double value); + }; + + template + struct StringMaker { + template + static std::string convert(U* p) { + if (p) { + return ::Catch::Detail::rawMemoryToString(p); + } else { + return "nullptr"; + } + } + }; + + template + struct StringMaker { + static std::string convert(R C::* p) { + if (p) { + return ::Catch::Detail::rawMemoryToString(p); + } else { + return "nullptr"; + } + } + }; + +#if defined(_MANAGED) + template + struct StringMaker { + static std::string convert( T^ ref ) { + return ::Catch::Detail::clrReferenceToString(ref); + } + }; +#endif + + namespace Detail { + template + std::string rangeToString(InputIterator first, InputIterator last) { + ReusableStringStream rss; + rss << "{ "; + if (first != last) { + rss << ::Catch::Detail::stringify(*first); + for (++first; first != last; ++first) + rss << ", " << ::Catch::Detail::stringify(*first); + } + rss << " }"; + return rss.str(); + } + } + +#ifdef __OBJC__ + template<> + struct StringMaker { + static std::string convert(NSString * nsstring) { + if (!nsstring) + return "nil"; + return std::string("@") + [nsstring UTF8String]; + } + }; + template<> + struct StringMaker { + static std::string convert(NSObject* nsObject) { + return ::Catch::Detail::stringify([nsObject description]); + } + + }; + namespace Detail { + inline std::string stringify( NSString* nsstring ) { + return StringMaker::convert( nsstring ); + } + + } // namespace Detail +#endif // __OBJC__ + +} // namespace Catch + +////////////////////////////////////////////////////// +// Separate std-lib types stringification, so it can be selectively enabled +// This means that we do not bring in + +#if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS) +# define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER +# define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER +# define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER +# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER +# define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER +#endif + +// Separate std::pair specialization +#if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER) +#include +namespace Catch { + template + struct StringMaker > { + static std::string convert(const std::pair& pair) { + ReusableStringStream rss; + rss << "{ " + << ::Catch::Detail::stringify(pair.first) + << ", " + << ::Catch::Detail::stringify(pair.second) + << " }"; + return rss.str(); + } + }; +} +#endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER + +#if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL) +#include +namespace Catch { + template + struct StringMaker > { + static std::string convert(const std::optional& optional) { + ReusableStringStream rss; + if (optional.has_value()) { + rss << ::Catch::Detail::stringify(*optional); + } else { + rss << "{ }"; + } + return rss.str(); + } + }; +} +#endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER + +// Separate std::tuple specialization +#if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER) +#include +namespace Catch { + namespace Detail { + template< + typename Tuple, + std::size_t N = 0, + bool = (N < std::tuple_size::value) + > + struct TupleElementPrinter { + static void print(const Tuple& tuple, std::ostream& os) { + os << (N ? ", " : " ") + << ::Catch::Detail::stringify(std::get(tuple)); + TupleElementPrinter::print(tuple, os); + } + }; + + template< + typename Tuple, + std::size_t N + > + struct TupleElementPrinter { + static void print(const Tuple&, std::ostream&) {} + }; + + } + + template + struct StringMaker> { + static std::string convert(const std::tuple& tuple) { + ReusableStringStream rss; + rss << '{'; + Detail::TupleElementPrinter>::print(tuple, rss.get()); + rss << " }"; + return rss.str(); + } + }; +} +#endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER + +#if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT) +#include +namespace Catch { + template<> + struct StringMaker { + static std::string convert(const std::monostate&) { + return "{ }"; + } + }; + + template + struct StringMaker> { + static std::string convert(const std::variant& variant) { + if (variant.valueless_by_exception()) { + return "{valueless variant}"; + } else { + return std::visit( + [](const auto& value) { + return ::Catch::Detail::stringify(value); + }, + variant + ); + } + } + }; +} +#endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER + +namespace Catch { + struct not_this_one {}; // Tag type for detecting which begin/ end are being selected + + // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace + using std::begin; + using std::end; + + not_this_one begin( ... ); + not_this_one end( ... ); + + template + struct is_range { + static const bool value = + !std::is_same())), not_this_one>::value && + !std::is_same())), not_this_one>::value; + }; + +#if defined(_MANAGED) // Managed types are never ranges + template + struct is_range { + static const bool value = false; + }; +#endif + + template + std::string rangeToString( Range const& range ) { + return ::Catch::Detail::rangeToString( begin( range ), end( range ) ); + } + + // Handle vector specially + template + std::string rangeToString( std::vector const& v ) { + ReusableStringStream rss; + rss << "{ "; + bool first = true; + for( bool b : v ) { + if( first ) + first = false; + else + rss << ", "; + rss << ::Catch::Detail::stringify( b ); + } + rss << " }"; + return rss.str(); + } + + template + struct StringMaker::value && !::Catch::Detail::IsStreamInsertable::value>::type> { + static std::string convert( R const& range ) { + return rangeToString( range ); + } + }; + + template + struct StringMaker { + static std::string convert(T const(&arr)[SZ]) { + return rangeToString(arr); + } + }; + +} // namespace Catch + +// Separate std::chrono::duration specialization +#if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) +#include +#include +#include + +namespace Catch { + +template +struct ratio_string { + static std::string symbol(); +}; + +template +std::string ratio_string::symbol() { + Catch::ReusableStringStream rss; + rss << '[' << Ratio::num << '/' + << Ratio::den << ']'; + return rss.str(); +} +template <> +struct ratio_string { + static std::string symbol(); +}; +template <> +struct ratio_string { + static std::string symbol(); +}; +template <> +struct ratio_string { + static std::string symbol(); +}; +template <> +struct ratio_string { + static std::string symbol(); +}; +template <> +struct ratio_string { + static std::string symbol(); +}; +template <> +struct ratio_string { + static std::string symbol(); +}; + + //////////// + // std::chrono::duration specializations + template + struct StringMaker> { + static std::string convert(std::chrono::duration const& duration) { + ReusableStringStream rss; + rss << duration.count() << ' ' << ratio_string::symbol() << 's'; + return rss.str(); + } + }; + template + struct StringMaker>> { + static std::string convert(std::chrono::duration> const& duration) { + ReusableStringStream rss; + rss << duration.count() << " s"; + return rss.str(); + } + }; + template + struct StringMaker>> { + static std::string convert(std::chrono::duration> const& duration) { + ReusableStringStream rss; + rss << duration.count() << " m"; + return rss.str(); + } + }; + template + struct StringMaker>> { + static std::string convert(std::chrono::duration> const& duration) { + ReusableStringStream rss; + rss << duration.count() << " h"; + return rss.str(); + } + }; + + //////////// + // std::chrono::time_point specialization + // Generic time_point cannot be specialized, only std::chrono::time_point + template + struct StringMaker> { + static std::string convert(std::chrono::time_point const& time_point) { + return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch"; + } + }; + // std::chrono::time_point specialization + template + struct StringMaker> { + static std::string convert(std::chrono::time_point const& time_point) { + auto converted = std::chrono::system_clock::to_time_t(time_point); + +#ifdef _MSC_VER + std::tm timeInfo = {}; + gmtime_s(&timeInfo, &converted); +#else + std::tm* timeInfo = std::gmtime(&converted); +#endif + + auto const timeStampSize = sizeof("2017-01-16T17:06:45Z"); + char timeStamp[timeStampSize]; + const char * const fmt = "%Y-%m-%dT%H:%M:%SZ"; + +#ifdef _MSC_VER + std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); +#else + std::strftime(timeStamp, timeStampSize, fmt, timeInfo); +#endif + return std::string(timeStamp); + } + }; +} +#endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +// end catch_tostring.h +#include + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable:4389) // '==' : signed/unsigned mismatch +#pragma warning(disable:4018) // more "signed/unsigned mismatch" +#pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform) +#pragma warning(disable:4180) // qualifier applied to function type has no meaning +#pragma warning(disable:4800) // Forcing result to true or false +#endif + +namespace Catch { + + struct ITransientExpression { + auto isBinaryExpression() const -> bool { return m_isBinaryExpression; } + auto getResult() const -> bool { return m_result; } + virtual void streamReconstructedExpression( std::ostream &os ) const = 0; + + ITransientExpression( bool isBinaryExpression, bool result ) + : m_isBinaryExpression( isBinaryExpression ), + m_result( result ) + {} + + // We don't actually need a virtual destructor, but many static analysers + // complain if it's not here :-( + virtual ~ITransientExpression(); + + bool m_isBinaryExpression; + bool m_result; + + }; + + void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ); + + template + class BinaryExpr : public ITransientExpression { + LhsT m_lhs; + StringRef m_op; + RhsT m_rhs; + + void streamReconstructedExpression( std::ostream &os ) const override { + formatReconstructedExpression + ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) ); + } + + public: + BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs ) + : ITransientExpression{ true, comparisonResult }, + m_lhs( lhs ), + m_op( op ), + m_rhs( rhs ) + {} + + template + auto operator && ( T ) const -> BinaryExpr const { + static_assert(always_false::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); + } + + template + auto operator || ( T ) const -> BinaryExpr const { + static_assert(always_false::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); + } + + template + auto operator == ( T ) const -> BinaryExpr const { + static_assert(always_false::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); + } + + template + auto operator != ( T ) const -> BinaryExpr const { + static_assert(always_false::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); + } + + template + auto operator > ( T ) const -> BinaryExpr const { + static_assert(always_false::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); + } + + template + auto operator < ( T ) const -> BinaryExpr const { + static_assert(always_false::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); + } + + template + auto operator >= ( T ) const -> BinaryExpr const { + static_assert(always_false::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); + } + + template + auto operator <= ( T ) const -> BinaryExpr const { + static_assert(always_false::value, + "chained comparisons are not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); + } + }; + + template + class UnaryExpr : public ITransientExpression { + LhsT m_lhs; + + void streamReconstructedExpression( std::ostream &os ) const override { + os << Catch::Detail::stringify( m_lhs ); + } + + public: + explicit UnaryExpr( LhsT lhs ) + : ITransientExpression{ false, static_cast(lhs) }, + m_lhs( lhs ) + {} + }; + + // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int) + template + auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast(lhs == rhs); } + template + auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast( rhs ); } + template + auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast( rhs ); } + template + auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast( lhs ) == rhs; } + template + auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast( lhs ) == rhs; } + + template + auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast(lhs != rhs); } + template + auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast( rhs ); } + template + auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast( rhs ); } + template + auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast( lhs ) != rhs; } + template + auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast( lhs ) != rhs; } + + template + class ExprLhs { + LhsT m_lhs; + public: + explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {} + + template + auto operator == ( RhsT const& rhs ) -> BinaryExpr const { + return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs }; + } + auto operator == ( bool rhs ) -> BinaryExpr const { + return { m_lhs == rhs, m_lhs, "==", rhs }; + } + + template + auto operator != ( RhsT const& rhs ) -> BinaryExpr const { + return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs }; + } + auto operator != ( bool rhs ) -> BinaryExpr const { + return { m_lhs != rhs, m_lhs, "!=", rhs }; + } + + template + auto operator > ( RhsT const& rhs ) -> BinaryExpr const { + return { static_cast(m_lhs > rhs), m_lhs, ">", rhs }; + } + template + auto operator < ( RhsT const& rhs ) -> BinaryExpr const { + return { static_cast(m_lhs < rhs), m_lhs, "<", rhs }; + } + template + auto operator >= ( RhsT const& rhs ) -> BinaryExpr const { + return { static_cast(m_lhs >= rhs), m_lhs, ">=", rhs }; + } + template + auto operator <= ( RhsT const& rhs ) -> BinaryExpr const { + return { static_cast(m_lhs <= rhs), m_lhs, "<=", rhs }; + } + + template + auto operator && ( RhsT const& ) -> BinaryExpr const { + static_assert(always_false::value, + "operator&& is not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); + } + + template + auto operator || ( RhsT const& ) -> BinaryExpr const { + static_assert(always_false::value, + "operator|| is not supported inside assertions, " + "wrap the expression inside parentheses, or decompose it"); + } + + auto makeUnaryExpr() const -> UnaryExpr { + return UnaryExpr{ m_lhs }; + } + }; + + void handleExpression( ITransientExpression const& expr ); + + template + void handleExpression( ExprLhs const& expr ) { + handleExpression( expr.makeUnaryExpr() ); + } + + struct Decomposer { + template + auto operator <= ( T const& lhs ) -> ExprLhs { + return ExprLhs{ lhs }; + } + + auto operator <=( bool value ) -> ExprLhs { + return ExprLhs{ value }; + } + }; + +} // end namespace Catch + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +// end catch_decomposer.h +// start catch_interfaces_capture.h + +#include + +namespace Catch { + + class AssertionResult; + struct AssertionInfo; + struct SectionInfo; + struct SectionEndInfo; + struct MessageInfo; + struct MessageBuilder; + struct Counts; + struct BenchmarkInfo; + struct BenchmarkStats; + struct AssertionReaction; + struct SourceLineInfo; + + struct ITransientExpression; + struct IGeneratorTracker; + + struct IResultCapture { + + virtual ~IResultCapture(); + + virtual bool sectionStarted( SectionInfo const& sectionInfo, + Counts& assertions ) = 0; + virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0; + virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0; + + virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0; + + virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0; + virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0; + + virtual void pushScopedMessage( MessageInfo const& message ) = 0; + virtual void popScopedMessage( MessageInfo const& message ) = 0; + + virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0; + + virtual void handleFatalErrorCondition( StringRef message ) = 0; + + virtual void handleExpr + ( AssertionInfo const& info, + ITransientExpression const& expr, + AssertionReaction& reaction ) = 0; + virtual void handleMessage + ( AssertionInfo const& info, + ResultWas::OfType resultType, + StringRef const& message, + AssertionReaction& reaction ) = 0; + virtual void handleUnexpectedExceptionNotThrown + ( AssertionInfo const& info, + AssertionReaction& reaction ) = 0; + virtual void handleUnexpectedInflightException + ( AssertionInfo const& info, + std::string const& message, + AssertionReaction& reaction ) = 0; + virtual void handleIncomplete + ( AssertionInfo const& info ) = 0; + virtual void handleNonExpr + ( AssertionInfo const &info, + ResultWas::OfType resultType, + AssertionReaction &reaction ) = 0; + + virtual bool lastAssertionPassed() = 0; + virtual void assertionPassed() = 0; + + // Deprecated, do not use: + virtual std::string getCurrentTestName() const = 0; + virtual const AssertionResult* getLastResult() const = 0; + virtual void exceptionEarlyReported() = 0; + }; + + IResultCapture& getResultCapture(); +} + +// end catch_interfaces_capture.h +namespace Catch { + + struct TestFailureException{}; + struct AssertionResultData; + struct IResultCapture; + class RunContext; + + class LazyExpression { + friend class AssertionHandler; + friend struct AssertionStats; + friend class RunContext; + + ITransientExpression const* m_transientExpression = nullptr; + bool m_isNegated; + public: + LazyExpression( bool isNegated ); + LazyExpression( LazyExpression const& other ); + LazyExpression& operator = ( LazyExpression const& ) = delete; + + explicit operator bool() const; + + friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&; + }; + + struct AssertionReaction { + bool shouldDebugBreak = false; + bool shouldThrow = false; + }; + + class AssertionHandler { + AssertionInfo m_assertionInfo; + AssertionReaction m_reaction; + bool m_completed = false; + IResultCapture& m_resultCapture; + + public: + AssertionHandler + ( StringRef const& macroName, + SourceLineInfo const& lineInfo, + StringRef capturedExpression, + ResultDisposition::Flags resultDisposition ); + ~AssertionHandler() { + if ( !m_completed ) { + m_resultCapture.handleIncomplete( m_assertionInfo ); + } + } + + template + void handleExpr( ExprLhs const& expr ) { + handleExpr( expr.makeUnaryExpr() ); + } + void handleExpr( ITransientExpression const& expr ); + + void handleMessage(ResultWas::OfType resultType, StringRef const& message); + + void handleExceptionThrownAsExpected(); + void handleUnexpectedExceptionNotThrown(); + void handleExceptionNotThrownAsExpected(); + void handleThrowingCallSkipped(); + void handleUnexpectedInflightException(); + + void complete(); + void setCompleted(); + + // query + auto allowThrows() const -> bool; + }; + + void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ); + +} // namespace Catch + +// end catch_assertionhandler.h +// start catch_message.h + +#include +#include + +namespace Catch { + + struct MessageInfo { + MessageInfo( StringRef const& _macroName, + SourceLineInfo const& _lineInfo, + ResultWas::OfType _type ); + + StringRef macroName; + std::string message; + SourceLineInfo lineInfo; + ResultWas::OfType type; + unsigned int sequence; + + bool operator == ( MessageInfo const& other ) const; + bool operator < ( MessageInfo const& other ) const; + private: + static unsigned int globalCount; + }; + + struct MessageStream { + + template + MessageStream& operator << ( T const& value ) { + m_stream << value; + return *this; + } + + ReusableStringStream m_stream; + }; + + struct MessageBuilder : MessageStream { + MessageBuilder( StringRef const& macroName, + SourceLineInfo const& lineInfo, + ResultWas::OfType type ); + + template + MessageBuilder& operator << ( T const& value ) { + m_stream << value; + return *this; + } + + MessageInfo m_info; + }; + + class ScopedMessage { + public: + explicit ScopedMessage( MessageBuilder const& builder ); + ScopedMessage( ScopedMessage& duplicate ) = delete; + ScopedMessage( ScopedMessage&& old ); + ~ScopedMessage(); + + MessageInfo m_info; + bool m_moved; + }; + + class Capturer { + std::vector m_messages; + IResultCapture& m_resultCapture = getResultCapture(); + size_t m_captured = 0; + public: + Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ); + ~Capturer(); + + void captureValue( size_t index, std::string const& value ); + + template + void captureValues( size_t index, T const& value ) { + captureValue( index, Catch::Detail::stringify( value ) ); + } + + template + void captureValues( size_t index, T const& value, Ts const&... values ) { + captureValue( index, Catch::Detail::stringify(value) ); + captureValues( index+1, values... ); + } + }; + +} // end namespace Catch + +// end catch_message.h +#if !defined(CATCH_CONFIG_DISABLE) + +#if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION) + #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__ +#else + #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION" +#endif + +#if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) + +/////////////////////////////////////////////////////////////////////////////// +// Another way to speed-up compilation is to omit local try-catch for REQUIRE* +// macros. +#define INTERNAL_CATCH_TRY +#define INTERNAL_CATCH_CATCH( capturer ) + +#else // CATCH_CONFIG_FAST_COMPILE + +#define INTERNAL_CATCH_TRY try +#define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); } + +#endif + +#define INTERNAL_CATCH_REACT( handler ) handler.complete(); + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \ + do { \ + Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ + INTERNAL_CATCH_TRY { \ + CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ + catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \ + CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \ + } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ + INTERNAL_CATCH_REACT( catchAssertionHandler ) \ + } while( (void)0, (false) && static_cast( !!(__VA_ARGS__) ) ) // the expression here is never evaluated at runtime but it forces the compiler to give it a look + // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&. + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \ + INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ + if( Catch::getResultCapture().lastAssertionPassed() ) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \ + INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \ + if( !Catch::getResultCapture().lastAssertionPassed() ) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \ + do { \ + Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \ + try { \ + static_cast(__VA_ARGS__); \ + catchAssertionHandler.handleExceptionNotThrownAsExpected(); \ + } \ + catch( ... ) { \ + catchAssertionHandler.handleUnexpectedInflightException(); \ + } \ + INTERNAL_CATCH_REACT( catchAssertionHandler ) \ + } while( false ) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \ + do { \ + Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \ + if( catchAssertionHandler.allowThrows() ) \ + try { \ + static_cast(__VA_ARGS__); \ + catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ + } \ + catch( ... ) { \ + catchAssertionHandler.handleExceptionThrownAsExpected(); \ + } \ + else \ + catchAssertionHandler.handleThrowingCallSkipped(); \ + INTERNAL_CATCH_REACT( catchAssertionHandler ) \ + } while( false ) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \ + do { \ + Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \ + if( catchAssertionHandler.allowThrows() ) \ + try { \ + static_cast(expr); \ + catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ + } \ + catch( exceptionType const& ) { \ + catchAssertionHandler.handleExceptionThrownAsExpected(); \ + } \ + catch( ... ) { \ + catchAssertionHandler.handleUnexpectedInflightException(); \ + } \ + else \ + catchAssertionHandler.handleThrowingCallSkipped(); \ + INTERNAL_CATCH_REACT( catchAssertionHandler ) \ + } while( false ) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \ + do { \ + Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \ + catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \ + INTERNAL_CATCH_REACT( catchAssertionHandler ) \ + } while( false ) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \ + auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \ + varName.captureValues( 0, __VA_ARGS__ ) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_INFO( macroName, log ) \ + Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ); + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \ + Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log ) + +/////////////////////////////////////////////////////////////////////////////// +// Although this is matcher-based, it can be used with just a string +#define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \ + do { \ + Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ + if( catchAssertionHandler.allowThrows() ) \ + try { \ + static_cast(__VA_ARGS__); \ + catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ + } \ + catch( ... ) { \ + Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \ + } \ + else \ + catchAssertionHandler.handleThrowingCallSkipped(); \ + INTERNAL_CATCH_REACT( catchAssertionHandler ) \ + } while( false ) + +#endif // CATCH_CONFIG_DISABLE + +// end catch_capture.hpp +// start catch_section.h + +// start catch_section_info.h + +// start catch_totals.h + +#include + +namespace Catch { + + struct Counts { + Counts operator - ( Counts const& other ) const; + Counts& operator += ( Counts const& other ); + + std::size_t total() const; + bool allPassed() const; + bool allOk() const; + + std::size_t passed = 0; + std::size_t failed = 0; + std::size_t failedButOk = 0; + }; + + struct Totals { + + Totals operator - ( Totals const& other ) const; + Totals& operator += ( Totals const& other ); + + Totals delta( Totals const& prevTotals ) const; + + int error = 0; + Counts assertions; + Counts testCases; + }; +} + +// end catch_totals.h +#include + +namespace Catch { + + struct SectionInfo { + SectionInfo + ( SourceLineInfo const& _lineInfo, + std::string const& _name ); + + // Deprecated + SectionInfo + ( SourceLineInfo const& _lineInfo, + std::string const& _name, + std::string const& ) : SectionInfo( _lineInfo, _name ) {} + + std::string name; + std::string description; // !Deprecated: this will always be empty + SourceLineInfo lineInfo; + }; + + struct SectionEndInfo { + SectionInfo sectionInfo; + Counts prevAssertions; + double durationInSeconds; + }; + +} // end namespace Catch + +// end catch_section_info.h +// start catch_timer.h + +#include + +namespace Catch { + + auto getCurrentNanosecondsSinceEpoch() -> uint64_t; + auto getEstimatedClockResolution() -> uint64_t; + + class Timer { + uint64_t m_nanoseconds = 0; + public: + void start(); + auto getElapsedNanoseconds() const -> uint64_t; + auto getElapsedMicroseconds() const -> uint64_t; + auto getElapsedMilliseconds() const -> unsigned int; + auto getElapsedSeconds() const -> double; + }; + +} // namespace Catch + +// end catch_timer.h +#include + +namespace Catch { + + class Section : NonCopyable { + public: + Section( SectionInfo const& info ); + ~Section(); + + // This indicates whether the section should be executed or not + explicit operator bool() const; + + private: + SectionInfo m_info; + + std::string m_name; + Counts m_assertions; + bool m_sectionIncluded; + Timer m_timer; + }; + +} // end namespace Catch + +#define INTERNAL_CATCH_SECTION( ... ) \ + CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ + if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \ + CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS + +#define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \ + CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \ + if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \ + CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS + +// end catch_section.h +// start catch_benchmark.h + +#include +#include + +namespace Catch { + + class BenchmarkLooper { + + std::string m_name; + std::size_t m_count = 0; + std::size_t m_iterationsToRun = 1; + uint64_t m_resolution; + Timer m_timer; + + static auto getResolution() -> uint64_t; + public: + // Keep most of this inline as it's on the code path that is being timed + BenchmarkLooper( StringRef name ) + : m_name( name ), + m_resolution( getResolution() ) + { + reportStart(); + m_timer.start(); + } + + explicit operator bool() { + if( m_count < m_iterationsToRun ) + return true; + return needsMoreIterations(); + } + + void increment() { + ++m_count; + } + + void reportStart(); + auto needsMoreIterations() -> bool; + }; + +} // end namespace Catch + +#define BENCHMARK( name ) \ + for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() ) + +// end catch_benchmark.h +// start catch_interfaces_exception.h + +// start catch_interfaces_registry_hub.h + +#include +#include + +namespace Catch { + + class TestCase; + struct ITestCaseRegistry; + struct IExceptionTranslatorRegistry; + struct IExceptionTranslator; + struct IReporterRegistry; + struct IReporterFactory; + struct ITagAliasRegistry; + class StartupExceptionRegistry; + + using IReporterFactoryPtr = std::shared_ptr; + + struct IRegistryHub { + virtual ~IRegistryHub(); + + virtual IReporterRegistry const& getReporterRegistry() const = 0; + virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; + virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0; + + virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0; + + virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0; + }; + + struct IMutableRegistryHub { + virtual ~IMutableRegistryHub(); + virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0; + virtual void registerListener( IReporterFactoryPtr const& factory ) = 0; + virtual void registerTest( TestCase const& testInfo ) = 0; + virtual void registerTranslator( const IExceptionTranslator* translator ) = 0; + virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0; + virtual void registerStartupException() noexcept = 0; + }; + + IRegistryHub const& getRegistryHub(); + IMutableRegistryHub& getMutableRegistryHub(); + void cleanUp(); + std::string translateActiveException(); + +} + +// end catch_interfaces_registry_hub.h +#if defined(CATCH_CONFIG_DISABLE) + #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \ + static std::string translatorName( signature ) +#endif + +#include +#include +#include + +namespace Catch { + using exceptionTranslateFunction = std::string(*)(); + + struct IExceptionTranslator; + using ExceptionTranslators = std::vector>; + + struct IExceptionTranslator { + virtual ~IExceptionTranslator(); + virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0; + }; + + struct IExceptionTranslatorRegistry { + virtual ~IExceptionTranslatorRegistry(); + + virtual std::string translateActiveException() const = 0; + }; + + class ExceptionTranslatorRegistrar { + template + class ExceptionTranslator : public IExceptionTranslator { + public: + + ExceptionTranslator( std::string(*translateFunction)( T& ) ) + : m_translateFunction( translateFunction ) + {} + + std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override { + try { + if( it == itEnd ) + std::rethrow_exception(std::current_exception()); + else + return (*it)->translate( it+1, itEnd ); + } + catch( T& ex ) { + return m_translateFunction( ex ); + } + } + + protected: + std::string(*m_translateFunction)( T& ); + }; + + public: + template + ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) { + getMutableRegistryHub().registerTranslator + ( new ExceptionTranslator( translateFunction ) ); + } + }; +} + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \ + static std::string translatorName( signature ); \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \ + CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \ + static std::string translatorName( signature ) + +#define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) + +// end catch_interfaces_exception.h +// start catch_approx.h + +#include + +namespace Catch { +namespace Detail { + + class Approx { + private: + bool equalityComparisonImpl(double other) const; + // Validates the new margin (margin >= 0) + // out-of-line to avoid including stdexcept in the header + void setMargin(double margin); + // Validates the new epsilon (0 < epsilon < 1) + // out-of-line to avoid including stdexcept in the header + void setEpsilon(double epsilon); + + public: + explicit Approx ( double value ); + + static Approx custom(); + + Approx operator-() const; + + template ::value>::type> + Approx operator()( T const& value ) { + Approx approx( static_cast(value) ); + approx.m_epsilon = m_epsilon; + approx.m_margin = m_margin; + approx.m_scale = m_scale; + return approx; + } + + template ::value>::type> + explicit Approx( T const& value ): Approx(static_cast(value)) + {} + + template ::value>::type> + friend bool operator == ( const T& lhs, Approx const& rhs ) { + auto lhs_v = static_cast(lhs); + return rhs.equalityComparisonImpl(lhs_v); + } + + template ::value>::type> + friend bool operator == ( Approx const& lhs, const T& rhs ) { + return operator==( rhs, lhs ); + } + + template ::value>::type> + friend bool operator != ( T const& lhs, Approx const& rhs ) { + return !operator==( lhs, rhs ); + } + + template ::value>::type> + friend bool operator != ( Approx const& lhs, T const& rhs ) { + return !operator==( rhs, lhs ); + } + + template ::value>::type> + friend bool operator <= ( T const& lhs, Approx const& rhs ) { + return static_cast(lhs) < rhs.m_value || lhs == rhs; + } + + template ::value>::type> + friend bool operator <= ( Approx const& lhs, T const& rhs ) { + return lhs.m_value < static_cast(rhs) || lhs == rhs; + } + + template ::value>::type> + friend bool operator >= ( T const& lhs, Approx const& rhs ) { + return static_cast(lhs) > rhs.m_value || lhs == rhs; + } + + template ::value>::type> + friend bool operator >= ( Approx const& lhs, T const& rhs ) { + return lhs.m_value > static_cast(rhs) || lhs == rhs; + } + + template ::value>::type> + Approx& epsilon( T const& newEpsilon ) { + double epsilonAsDouble = static_cast(newEpsilon); + setEpsilon(epsilonAsDouble); + return *this; + } + + template ::value>::type> + Approx& margin( T const& newMargin ) { + double marginAsDouble = static_cast(newMargin); + setMargin(marginAsDouble); + return *this; + } + + template ::value>::type> + Approx& scale( T const& newScale ) { + m_scale = static_cast(newScale); + return *this; + } + + std::string toString() const; + + private: + double m_epsilon; + double m_margin; + double m_scale; + double m_value; + }; +} // end namespace Detail + +namespace literals { + Detail::Approx operator "" _a(long double val); + Detail::Approx operator "" _a(unsigned long long val); +} // end namespace literals + +template<> +struct StringMaker { + static std::string convert(Catch::Detail::Approx const& value); +}; + +} // end namespace Catch + +// end catch_approx.h +// start catch_string_manip.h + +#include +#include + +namespace Catch { + + bool startsWith( std::string const& s, std::string const& prefix ); + bool startsWith( std::string const& s, char prefix ); + bool endsWith( std::string const& s, std::string const& suffix ); + bool endsWith( std::string const& s, char suffix ); + bool contains( std::string const& s, std::string const& infix ); + void toLowerInPlace( std::string& s ); + std::string toLower( std::string const& s ); + std::string trim( std::string const& str ); + bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ); + + struct pluralise { + pluralise( std::size_t count, std::string const& label ); + + friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ); + + std::size_t m_count; + std::string m_label; + }; +} + +// end catch_string_manip.h +#ifndef CATCH_CONFIG_DISABLE_MATCHERS +// start catch_capture_matchers.h + +// start catch_matchers.h + +#include +#include + +namespace Catch { +namespace Matchers { + namespace Impl { + + template struct MatchAllOf; + template struct MatchAnyOf; + template struct MatchNotOf; + + class MatcherUntypedBase { + public: + MatcherUntypedBase() = default; + MatcherUntypedBase ( MatcherUntypedBase const& ) = default; + MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete; + std::string toString() const; + + protected: + virtual ~MatcherUntypedBase(); + virtual std::string describe() const = 0; + mutable std::string m_cachedToString; + }; + +#ifdef __clang__ +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wnon-virtual-dtor" +#endif + + template + struct MatcherMethod { + virtual bool match( ObjectT const& arg ) const = 0; + }; + +#ifdef __clang__ +# pragma clang diagnostic pop +#endif + + template + struct MatcherBase : MatcherUntypedBase, MatcherMethod { + + MatchAllOf operator && ( MatcherBase const& other ) const; + MatchAnyOf operator || ( MatcherBase const& other ) const; + MatchNotOf operator ! () const; + }; + + template + struct MatchAllOf : MatcherBase { + bool match( ArgT const& arg ) const override { + for( auto matcher : m_matchers ) { + if (!matcher->match(arg)) + return false; + } + return true; + } + std::string describe() const override { + std::string description; + description.reserve( 4 + m_matchers.size()*32 ); + description += "( "; + bool first = true; + for( auto matcher : m_matchers ) { + if( first ) + first = false; + else + description += " and "; + description += matcher->toString(); + } + description += " )"; + return description; + } + + MatchAllOf& operator && ( MatcherBase const& other ) { + m_matchers.push_back( &other ); + return *this; + } + + std::vector const*> m_matchers; + }; + template + struct MatchAnyOf : MatcherBase { + + bool match( ArgT const& arg ) const override { + for( auto matcher : m_matchers ) { + if (matcher->match(arg)) + return true; + } + return false; + } + std::string describe() const override { + std::string description; + description.reserve( 4 + m_matchers.size()*32 ); + description += "( "; + bool first = true; + for( auto matcher : m_matchers ) { + if( first ) + first = false; + else + description += " or "; + description += matcher->toString(); + } + description += " )"; + return description; + } + + MatchAnyOf& operator || ( MatcherBase const& other ) { + m_matchers.push_back( &other ); + return *this; + } + + std::vector const*> m_matchers; + }; + + template + struct MatchNotOf : MatcherBase { + + MatchNotOf( MatcherBase const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {} + + bool match( ArgT const& arg ) const override { + return !m_underlyingMatcher.match( arg ); + } + + std::string describe() const override { + return "not " + m_underlyingMatcher.toString(); + } + MatcherBase const& m_underlyingMatcher; + }; + + template + MatchAllOf MatcherBase::operator && ( MatcherBase const& other ) const { + return MatchAllOf() && *this && other; + } + template + MatchAnyOf MatcherBase::operator || ( MatcherBase const& other ) const { + return MatchAnyOf() || *this || other; + } + template + MatchNotOf MatcherBase::operator ! () const { + return MatchNotOf( *this ); + } + + } // namespace Impl + +} // namespace Matchers + +using namespace Matchers; +using Matchers::Impl::MatcherBase; + +} // namespace Catch + +// end catch_matchers.h +// start catch_matchers_floating.h + +#include +#include + +namespace Catch { +namespace Matchers { + + namespace Floating { + + enum class FloatingPointKind : uint8_t; + + struct WithinAbsMatcher : MatcherBase { + WithinAbsMatcher(double target, double margin); + bool match(double const& matchee) const override; + std::string describe() const override; + private: + double m_target; + double m_margin; + }; + + struct WithinUlpsMatcher : MatcherBase { + WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType); + bool match(double const& matchee) const override; + std::string describe() const override; + private: + double m_target; + int m_ulps; + FloatingPointKind m_type; + }; + + } // namespace Floating + + // The following functions create the actual matcher objects. + // This allows the types to be inferred + Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff); + Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff); + Floating::WithinAbsMatcher WithinAbs(double target, double margin); + +} // namespace Matchers +} // namespace Catch + +// end catch_matchers_floating.h +// start catch_matchers_generic.hpp + +#include +#include + +namespace Catch { +namespace Matchers { +namespace Generic { + +namespace Detail { + std::string finalizeDescription(const std::string& desc); +} + +template +class PredicateMatcher : public MatcherBase { + std::function m_predicate; + std::string m_description; +public: + + PredicateMatcher(std::function const& elem, std::string const& descr) + :m_predicate(std::move(elem)), + m_description(Detail::finalizeDescription(descr)) + {} + + bool match( T const& item ) const override { + return m_predicate(item); + } + + std::string describe() const override { + return m_description; + } +}; + +} // namespace Generic + + // The following functions create the actual matcher objects. + // The user has to explicitly specify type to the function, because + // infering std::function is hard (but possible) and + // requires a lot of TMP. + template + Generic::PredicateMatcher Predicate(std::function const& predicate, std::string const& description = "") { + return Generic::PredicateMatcher(predicate, description); + } + +} // namespace Matchers +} // namespace Catch + +// end catch_matchers_generic.hpp +// start catch_matchers_string.h + +#include + +namespace Catch { +namespace Matchers { + + namespace StdString { + + struct CasedString + { + CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ); + std::string adjustString( std::string const& str ) const; + std::string caseSensitivitySuffix() const; + + CaseSensitive::Choice m_caseSensitivity; + std::string m_str; + }; + + struct StringMatcherBase : MatcherBase { + StringMatcherBase( std::string const& operation, CasedString const& comparator ); + std::string describe() const override; + + CasedString m_comparator; + std::string m_operation; + }; + + struct EqualsMatcher : StringMatcherBase { + EqualsMatcher( CasedString const& comparator ); + bool match( std::string const& source ) const override; + }; + struct ContainsMatcher : StringMatcherBase { + ContainsMatcher( CasedString const& comparator ); + bool match( std::string const& source ) const override; + }; + struct StartsWithMatcher : StringMatcherBase { + StartsWithMatcher( CasedString const& comparator ); + bool match( std::string const& source ) const override; + }; + struct EndsWithMatcher : StringMatcherBase { + EndsWithMatcher( CasedString const& comparator ); + bool match( std::string const& source ) const override; + }; + + struct RegexMatcher : MatcherBase { + RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity ); + bool match( std::string const& matchee ) const override; + std::string describe() const override; + + private: + std::string m_regex; + CaseSensitive::Choice m_caseSensitivity; + }; + + } // namespace StdString + + // The following functions create the actual matcher objects. + // This allows the types to be inferred + + StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); + StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); + StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); + StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); + StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ); + +} // namespace Matchers +} // namespace Catch + +// end catch_matchers_string.h +// start catch_matchers_vector.h + +#include + +namespace Catch { +namespace Matchers { + + namespace Vector { + namespace Detail { + template + size_t count(InputIterator first, InputIterator last, T const& item) { + size_t cnt = 0; + for (; first != last; ++first) { + if (*first == item) { + ++cnt; + } + } + return cnt; + } + template + bool contains(InputIterator first, InputIterator last, T const& item) { + for (; first != last; ++first) { + if (*first == item) { + return true; + } + } + return false; + } + } + + template + struct ContainsElementMatcher : MatcherBase> { + + ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {} + + bool match(std::vector const &v) const override { + for (auto const& el : v) { + if (el == m_comparator) { + return true; + } + } + return false; + } + + std::string describe() const override { + return "Contains: " + ::Catch::Detail::stringify( m_comparator ); + } + + T const& m_comparator; + }; + + template + struct ContainsMatcher : MatcherBase> { + + ContainsMatcher(std::vector const &comparator) : m_comparator( comparator ) {} + + bool match(std::vector const &v) const override { + // !TBD: see note in EqualsMatcher + if (m_comparator.size() > v.size()) + return false; + for (auto const& comparator : m_comparator) { + auto present = false; + for (const auto& el : v) { + if (el == comparator) { + present = true; + break; + } + } + if (!present) { + return false; + } + } + return true; + } + std::string describe() const override { + return "Contains: " + ::Catch::Detail::stringify( m_comparator ); + } + + std::vector const& m_comparator; + }; + + template + struct EqualsMatcher : MatcherBase> { + + EqualsMatcher(std::vector const &comparator) : m_comparator( comparator ) {} + + bool match(std::vector const &v) const override { + // !TBD: This currently works if all elements can be compared using != + // - a more general approach would be via a compare template that defaults + // to using !=. but could be specialised for, e.g. std::vector etc + // - then just call that directly + if (m_comparator.size() != v.size()) + return false; + for (std::size_t i = 0; i < v.size(); ++i) + if (m_comparator[i] != v[i]) + return false; + return true; + } + std::string describe() const override { + return "Equals: " + ::Catch::Detail::stringify( m_comparator ); + } + std::vector const& m_comparator; + }; + + template + struct UnorderedEqualsMatcher : MatcherBase> { + UnorderedEqualsMatcher(std::vector const& target) : m_target(target) {} + bool match(std::vector const& vec) const override { + // Note: This is a reimplementation of std::is_permutation, + // because I don't want to include inside the common path + if (m_target.size() != vec.size()) { + return false; + } + auto lfirst = m_target.begin(), llast = m_target.end(); + auto rfirst = vec.begin(), rlast = vec.end(); + // Cut common prefix to optimize checking of permuted parts + while (lfirst != llast && *lfirst == *rfirst) { + ++lfirst; ++rfirst; + } + if (lfirst == llast) { + return true; + } + + for (auto mid = lfirst; mid != llast; ++mid) { + // Skip already counted items + if (Detail::contains(lfirst, mid, *mid)) { + continue; + } + size_t num_vec = Detail::count(rfirst, rlast, *mid); + if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) { + return false; + } + } + + return true; + } + + std::string describe() const override { + return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target); + } + private: + std::vector const& m_target; + }; + + } // namespace Vector + + // The following functions create the actual matcher objects. + // This allows the types to be inferred + + template + Vector::ContainsMatcher Contains( std::vector const& comparator ) { + return Vector::ContainsMatcher( comparator ); + } + + template + Vector::ContainsElementMatcher VectorContains( T const& comparator ) { + return Vector::ContainsElementMatcher( comparator ); + } + + template + Vector::EqualsMatcher Equals( std::vector const& comparator ) { + return Vector::EqualsMatcher( comparator ); + } + + template + Vector::UnorderedEqualsMatcher UnorderedEquals(std::vector const& target) { + return Vector::UnorderedEqualsMatcher(target); + } + +} // namespace Matchers +} // namespace Catch + +// end catch_matchers_vector.h +namespace Catch { + + template + class MatchExpr : public ITransientExpression { + ArgT const& m_arg; + MatcherT m_matcher; + StringRef m_matcherString; + public: + MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) + : ITransientExpression{ true, matcher.match( arg ) }, + m_arg( arg ), + m_matcher( matcher ), + m_matcherString( matcherString ) + {} + + void streamReconstructedExpression( std::ostream &os ) const override { + auto matcherAsString = m_matcher.toString(); + os << Catch::Detail::stringify( m_arg ) << ' '; + if( matcherAsString == Detail::unprintableString ) + os << m_matcherString; + else + os << matcherAsString; + } + }; + + using StringMatcher = Matchers::Impl::MatcherBase; + + void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ); + + template + auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr { + return MatchExpr( arg, matcher, matcherString ); + } + +} // namespace Catch + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \ + do { \ + Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ + INTERNAL_CATCH_TRY { \ + catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \ + } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \ + INTERNAL_CATCH_REACT( catchAssertionHandler ) \ + } while( false ) + +/////////////////////////////////////////////////////////////////////////////// +#define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \ + do { \ + Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \ + if( catchAssertionHandler.allowThrows() ) \ + try { \ + static_cast(__VA_ARGS__ ); \ + catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \ + } \ + catch( exceptionType const& ex ) { \ + catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \ + } \ + catch( ... ) { \ + catchAssertionHandler.handleUnexpectedInflightException(); \ + } \ + else \ + catchAssertionHandler.handleThrowingCallSkipped(); \ + INTERNAL_CATCH_REACT( catchAssertionHandler ) \ + } while( false ) + +// end catch_capture_matchers.h +#endif +// start catch_generators.hpp + +// start catch_interfaces_generatortracker.h + + +#include + +namespace Catch { + + namespace Generators { + class GeneratorUntypedBase { + public: + GeneratorUntypedBase() = default; + virtual ~GeneratorUntypedBase(); + // Attempts to move the generator to the next element + // + // Returns true iff the move succeeded (and a valid element + // can be retrieved). + virtual bool next() = 0; + }; + using GeneratorBasePtr = std::unique_ptr; + + } // namespace Generators + + struct IGeneratorTracker { + virtual ~IGeneratorTracker(); + virtual auto hasGenerator() const -> bool = 0; + virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0; + virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0; + }; + +} // namespace Catch + +// end catch_interfaces_generatortracker.h +// start catch_enforce.h + +#include + +namespace Catch { +#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) + template + [[noreturn]] + void throw_exception(Ex const& e) { + throw e; + } +#else // ^^ Exceptions are enabled // Exceptions are disabled vv + [[noreturn]] + void throw_exception(std::exception const& e); +#endif +} // namespace Catch; + +#define CATCH_PREPARE_EXCEPTION( type, msg ) \ + type( ( Catch::ReusableStringStream() << msg ).str() ) +#define CATCH_INTERNAL_ERROR( msg ) \ + Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg)) +#define CATCH_ERROR( msg ) \ + Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::domain_error, msg )) +#define CATCH_RUNTIME_ERROR( msg ) \ + Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::runtime_error, msg )) +#define CATCH_ENFORCE( condition, msg ) \ + do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false) + +// end catch_enforce.h +#include +#include +#include + +#include +#include + +namespace Catch { + +class GeneratorException : public std::exception { + const char* const m_msg = ""; + +public: + GeneratorException(const char* msg): + m_msg(msg) + {} + + const char* what() const noexcept override final; +}; + +namespace Generators { + + // !TBD move this into its own location? + namespace pf{ + template + std::unique_ptr make_unique( Args&&... args ) { + return std::unique_ptr(new T(std::forward(args)...)); + } + } + + template + struct IGenerator : GeneratorUntypedBase { + virtual ~IGenerator() = default; + + // Returns the current element of the generator + // + // \Precondition The generator is either freshly constructed, + // or the last call to `next()` returned true + virtual T const& get() const = 0; + using type = T; + }; + + template + class SingleValueGenerator final : public IGenerator { + T m_value; + public: + SingleValueGenerator(T const& value) : m_value( value ) {} + SingleValueGenerator(T&& value) : m_value(std::move(value)) {} + + T const& get() const override { + return m_value; + } + bool next() override { + return false; + } + }; + + template + class FixedValuesGenerator final : public IGenerator { + std::vector m_values; + size_t m_idx = 0; + public: + FixedValuesGenerator( std::initializer_list values ) : m_values( values ) {} + + T const& get() const override { + return m_values[m_idx]; + } + bool next() override { + ++m_idx; + return m_idx < m_values.size(); + } + }; + + template + class GeneratorWrapper final { + std::unique_ptr> m_generator; + public: + GeneratorWrapper(std::unique_ptr> generator): + m_generator(std::move(generator)) + {} + T const& get() const { + return m_generator->get(); + } + bool next() { + return m_generator->next(); + } + }; + + template + GeneratorWrapper value(T&& value) { + return GeneratorWrapper(pf::make_unique>(std::forward(value))); + } + template + GeneratorWrapper values(std::initializer_list values) { + return GeneratorWrapper(pf::make_unique>(values)); + } + + template + class Generators : public IGenerator { + std::vector> m_generators; + size_t m_current = 0; + + void populate(GeneratorWrapper&& generator) { + m_generators.emplace_back(std::move(generator)); + } + void populate(T&& val) { + m_generators.emplace_back(value(std::move(val))); + } + template + void populate(U&& val) { + populate(T(std::move(val))); + } + template + void populate(U&& valueOrGenerator, Gs... moreGenerators) { + populate(std::forward(valueOrGenerator)); + populate(std::forward(moreGenerators)...); + } + + public: + template + Generators(Gs... moreGenerators) { + m_generators.reserve(sizeof...(Gs)); + populate(std::forward(moreGenerators)...); + } + + T const& get() const override { + return m_generators[m_current].get(); + } + + bool next() override { + if (m_current >= m_generators.size()) { + return false; + } + const bool current_status = m_generators[m_current].next(); + if (!current_status) { + ++m_current; + } + return m_current < m_generators.size(); + } + }; + + template + GeneratorWrapper> table( std::initializer_list::type...>> tuples ) { + return values>( tuples ); + } + + // Tag type to signal that a generator sequence should convert arguments to a specific type + template + struct as {}; + + template + auto makeGenerators( GeneratorWrapper&& generator, Gs... moreGenerators ) -> Generators { + return Generators(std::move(generator), std::forward(moreGenerators)...); + } + template + auto makeGenerators( GeneratorWrapper&& generator ) -> Generators { + return Generators(std::move(generator)); + } + template + auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators { + return makeGenerators( value( std::forward( val ) ), std::forward( moreGenerators )... ); + } + template + auto makeGenerators( as, U&& val, Gs... moreGenerators ) -> Generators { + return makeGenerators( value( T( std::forward( val ) ) ), std::forward( moreGenerators )... ); + } + + auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&; + + template + // Note: The type after -> is weird, because VS2015 cannot parse + // the expression used in the typedef inside, when it is in + // return type. Yeah. + auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval().get()) { + using UnderlyingType = typename decltype(generatorExpression())::type; + + IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo ); + if (!tracker.hasGenerator()) { + tracker.setGenerator(pf::make_unique>(generatorExpression())); + } + + auto const& generator = static_cast const&>( *tracker.getGenerator() ); + return generator.get(); + } + +} // namespace Generators +} // namespace Catch + +#define GENERATE( ... ) \ + Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, []{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) + +// end catch_generators.hpp +// start catch_generators_generic.hpp + +namespace Catch { +namespace Generators { + + template + class TakeGenerator : public IGenerator { + GeneratorWrapper m_generator; + size_t m_returned = 0; + size_t m_target; + public: + TakeGenerator(size_t target, GeneratorWrapper&& generator): + m_generator(std::move(generator)), + m_target(target) + { + assert(target != 0 && "Empty generators are not allowed"); + } + T const& get() const override { + return m_generator.get(); + } + bool next() override { + ++m_returned; + if (m_returned >= m_target) { + return false; + } + + const auto success = m_generator.next(); + // If the underlying generator does not contain enough values + // then we cut short as well + if (!success) { + m_returned = m_target; + } + return success; + } + }; + + template + GeneratorWrapper take(size_t target, GeneratorWrapper&& generator) { + return GeneratorWrapper(pf::make_unique>(target, std::move(generator))); + } + + template + class FilterGenerator : public IGenerator { + GeneratorWrapper m_generator; + Predicate m_predicate; + public: + template + FilterGenerator(P&& pred, GeneratorWrapper&& generator): + m_generator(std::move(generator)), + m_predicate(std::forward

(pred)) + { + if (!m_predicate(m_generator.get())) { + // It might happen that there are no values that pass the + // filter. In that case we throw an exception. + auto has_initial_value = next(); + if (!has_initial_value) { + Catch::throw_exception(GeneratorException("No valid value found in filtered generator")); + } + } + } + + T const& get() const override { + return m_generator.get(); + } + + bool next() override { + bool success = m_generator.next(); + if (!success) { + return false; + } + while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true); + return success; + } + }; + + template + GeneratorWrapper filter(Predicate&& pred, GeneratorWrapper&& generator) { + return GeneratorWrapper(std::unique_ptr>(pf::make_unique>(std::forward(pred), std::move(generator)))); + } + + template + class RepeatGenerator : public IGenerator { + GeneratorWrapper m_generator; + mutable std::vector m_returned; + size_t m_target_repeats; + size_t m_current_repeat = 0; + size_t m_repeat_index = 0; + public: + RepeatGenerator(size_t repeats, GeneratorWrapper&& generator): + m_generator(std::move(generator)), + m_target_repeats(repeats) + { + assert(m_target_repeats > 0 && "Repeat generator must repeat at least once"); + } + + T const& get() const override { + if (m_current_repeat == 0) { + m_returned.push_back(m_generator.get()); + return m_returned.back(); + } + return m_returned[m_repeat_index]; + } + + bool next() override { + // There are 2 basic cases: + // 1) We are still reading the generator + // 2) We are reading our own cache + + // In the first case, we need to poke the underlying generator. + // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache + if (m_current_repeat == 0) { + const auto success = m_generator.next(); + if (!success) { + ++m_current_repeat; + } + return m_current_repeat < m_target_repeats; + } + + // In the second case, we need to move indices forward and check that we haven't run up against the end + ++m_repeat_index; + if (m_repeat_index == m_returned.size()) { + m_repeat_index = 0; + ++m_current_repeat; + } + return m_current_repeat < m_target_repeats; + } + }; + + template + GeneratorWrapper repeat(size_t repeats, GeneratorWrapper&& generator) { + return GeneratorWrapper(pf::make_unique>(repeats, std::move(generator))); + } + + template + class MapGenerator : public IGenerator { + // TBD: provide static assert for mapping function, for friendly error message + GeneratorWrapper m_generator; + Func m_function; + // To avoid returning dangling reference, we have to save the values + T m_cache; + public: + template + MapGenerator(F2&& function, GeneratorWrapper&& generator) : + m_generator(std::move(generator)), + m_function(std::forward(function)), + m_cache(m_function(m_generator.get())) + {} + + T const& get() const override { + return m_cache; + } + bool next() override { + const auto success = m_generator.next(); + if (success) { + m_cache = m_function(m_generator.get()); + } + return success; + } + }; + + template + GeneratorWrapper map(Func&& function, GeneratorWrapper&& generator) { + return GeneratorWrapper( + pf::make_unique>(std::forward(function), std::move(generator)) + ); + } + template + GeneratorWrapper map(Func&& function, GeneratorWrapper&& generator) { + return GeneratorWrapper( + pf::make_unique>(std::forward(function), std::move(generator)) + ); + } + + template + class ChunkGenerator final : public IGenerator> { + std::vector m_chunk; + size_t m_chunk_size; + GeneratorWrapper m_generator; + bool m_used_up = false; + public: + ChunkGenerator(size_t size, GeneratorWrapper generator) : + m_chunk_size(size), m_generator(std::move(generator)) + { + m_chunk.reserve(m_chunk_size); + m_chunk.push_back(m_generator.get()); + for (size_t i = 1; i < m_chunk_size; ++i) { + if (!m_generator.next()) { + Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk")); + } + m_chunk.push_back(m_generator.get()); + } + } + std::vector const& get() const override { + return m_chunk; + } + bool next() override { + m_chunk.clear(); + for (size_t idx = 0; idx < m_chunk_size; ++idx) { + if (!m_generator.next()) { + return false; + } + m_chunk.push_back(m_generator.get()); + } + return true; + } + }; + + template + GeneratorWrapper> chunk(size_t size, GeneratorWrapper&& generator) { + return GeneratorWrapper>( + pf::make_unique>(size, std::move(generator)) + ); + } + +} // namespace Generators +} // namespace Catch + +// end catch_generators_generic.hpp +// start catch_generators_specific.hpp + +// start catch_context.h + +#include + +namespace Catch { + + struct IResultCapture; + struct IRunner; + struct IConfig; + struct IMutableContext; + + using IConfigPtr = std::shared_ptr; + + struct IContext + { + virtual ~IContext(); + + virtual IResultCapture* getResultCapture() = 0; + virtual IRunner* getRunner() = 0; + virtual IConfigPtr const& getConfig() const = 0; + }; + + struct IMutableContext : IContext + { + virtual ~IMutableContext(); + virtual void setResultCapture( IResultCapture* resultCapture ) = 0; + virtual void setRunner( IRunner* runner ) = 0; + virtual void setConfig( IConfigPtr const& config ) = 0; + + private: + static IMutableContext *currentContext; + friend IMutableContext& getCurrentMutableContext(); + friend void cleanUpContext(); + static void createContext(); + }; + + inline IMutableContext& getCurrentMutableContext() + { + if( !IMutableContext::currentContext ) + IMutableContext::createContext(); + return *IMutableContext::currentContext; + } + + inline IContext& getCurrentContext() + { + return getCurrentMutableContext(); + } + + void cleanUpContext(); +} + +// end catch_context.h +// start catch_interfaces_config.h + +#include +#include +#include +#include + +namespace Catch { + + enum class Verbosity { + Quiet = 0, + Normal, + High + }; + + struct WarnAbout { enum What { + Nothing = 0x00, + NoAssertions = 0x01, + NoTests = 0x02 + }; }; + + struct ShowDurations { enum OrNot { + DefaultForReporter, + Always, + Never + }; }; + struct RunTests { enum InWhatOrder { + InDeclarationOrder, + InLexicographicalOrder, + InRandomOrder + }; }; + struct UseColour { enum YesOrNo { + Auto, + Yes, + No + }; }; + struct WaitForKeypress { enum When { + Never, + BeforeStart = 1, + BeforeExit = 2, + BeforeStartAndExit = BeforeStart | BeforeExit + }; }; + + class TestSpec; + + struct IConfig : NonCopyable { + + virtual ~IConfig(); + + virtual bool allowThrows() const = 0; + virtual std::ostream& stream() const = 0; + virtual std::string name() const = 0; + virtual bool includeSuccessfulResults() const = 0; + virtual bool shouldDebugBreak() const = 0; + virtual bool warnAboutMissingAssertions() const = 0; + virtual bool warnAboutNoTests() const = 0; + virtual int abortAfter() const = 0; + virtual bool showInvisibles() const = 0; + virtual ShowDurations::OrNot showDurations() const = 0; + virtual TestSpec const& testSpec() const = 0; + virtual bool hasTestFilters() const = 0; + virtual RunTests::InWhatOrder runOrder() const = 0; + virtual unsigned int rngSeed() const = 0; + virtual int benchmarkResolutionMultiple() const = 0; + virtual UseColour::YesOrNo useColour() const = 0; + virtual std::vector const& getSectionsToRun() const = 0; + virtual Verbosity verbosity() const = 0; + }; + + using IConfigPtr = std::shared_ptr; +} + +// end catch_interfaces_config.h +#include + +namespace Catch { +namespace Generators { + +template +class RandomFloatingGenerator final : public IGenerator { + // FIXME: What is the right seed? + std::minstd_rand m_rand; + std::uniform_real_distribution m_dist; + Float m_current_number; +public: + + RandomFloatingGenerator(Float a, Float b): + m_rand(getCurrentContext().getConfig()->rngSeed()), + m_dist(a, b) { + static_cast(next()); + } + + Float const& get() const override { + return m_current_number; + } + bool next() override { + m_current_number = m_dist(m_rand); + return true; + } +}; + +template +class RandomIntegerGenerator final : public IGenerator { + std::minstd_rand m_rand; + std::uniform_int_distribution m_dist; + Integer m_current_number; +public: + + RandomIntegerGenerator(Integer a, Integer b): + m_rand(getCurrentContext().getConfig()->rngSeed()), + m_dist(a, b) { + static_cast(next()); + } + + Integer const& get() const override { + return m_current_number; + } + bool next() override { + m_current_number = m_dist(m_rand); + return true; + } +}; + +// TODO: Ideally this would be also constrained against the various char types, +// but I don't expect users to run into that in practice. +template +typename std::enable_if::value && !std::is_same::value, +GeneratorWrapper>::type +random(T a, T b) { + return GeneratorWrapper( + pf::make_unique>(a, b) + ); +} + +template +typename std::enable_if::value, +GeneratorWrapper>::type +random(T a, T b) { + return GeneratorWrapper( + pf::make_unique>(a, b) + ); +} + +template +class RangeGenerator final : public IGenerator { + T m_current; + T m_end; + T m_step; + bool m_positive; + +public: + RangeGenerator(T const& start, T const& end, T const& step): + m_current(start), + m_end(end), + m_step(step), + m_positive(m_step > T(0)) + { + assert(m_current != m_end && "Range start and end cannot be equal"); + assert(m_step != T(0) && "Step size cannot be zero"); + assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end"); + } + + RangeGenerator(T const& start, T const& end): + RangeGenerator(start, end, (start < end) ? T(1) : T(-1)) + {} + + T const& get() const override { + return m_current; + } + + bool next() override { + m_current += m_step; + return (m_positive) ? (m_current < m_end) : (m_current > m_end); + } +}; + +template +GeneratorWrapper range(T const& start, T const& end, T const& step) { + static_assert(std::is_integral::value && !std::is_same::value, "Type must be an integer"); + return GeneratorWrapper(pf::make_unique>(start, end, step)); +} + +template +GeneratorWrapper range(T const& start, T const& end) { + static_assert(std::is_integral::value && !std::is_same::value, "Type must be an integer"); + return GeneratorWrapper(pf::make_unique>(start, end)); +} + +} // namespace Generators +} // namespace Catch + +// end catch_generators_specific.hpp + +// These files are included here so the single_include script doesn't put them +// in the conditionally compiled sections +// start catch_test_case_info.h + +#include +#include +#include + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpadded" +#endif + +namespace Catch { + + struct ITestInvoker; + + struct TestCaseInfo { + enum SpecialProperties{ + None = 0, + IsHidden = 1 << 1, + ShouldFail = 1 << 2, + MayFail = 1 << 3, + Throws = 1 << 4, + NonPortable = 1 << 5, + Benchmark = 1 << 6 + }; + + TestCaseInfo( std::string const& _name, + std::string const& _className, + std::string const& _description, + std::vector const& _tags, + SourceLineInfo const& _lineInfo ); + + friend void setTags( TestCaseInfo& testCaseInfo, std::vector tags ); + + bool isHidden() const; + bool throws() const; + bool okToFail() const; + bool expectedToFail() const; + + std::string tagsAsString() const; + + std::string name; + std::string className; + std::string description; + std::vector tags; + std::vector lcaseTags; + SourceLineInfo lineInfo; + SpecialProperties properties; + }; + + class TestCase : public TestCaseInfo { + public: + + TestCase( ITestInvoker* testCase, TestCaseInfo&& info ); + + TestCase withName( std::string const& _newName ) const; + + void invoke() const; + + TestCaseInfo const& getTestCaseInfo() const; + + bool operator == ( TestCase const& other ) const; + bool operator < ( TestCase const& other ) const; + + private: + std::shared_ptr test; + }; + + TestCase makeTestCase( ITestInvoker* testCase, + std::string const& className, + NameAndTags const& nameAndTags, + SourceLineInfo const& lineInfo ); +} + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +// end catch_test_case_info.h +// start catch_interfaces_runner.h + +namespace Catch { + + struct IRunner { + virtual ~IRunner(); + virtual bool aborting() const = 0; + }; +} + +// end catch_interfaces_runner.h + +#ifdef __OBJC__ +// start catch_objc.hpp + +#import + +#include + +// NB. Any general catch headers included here must be included +// in catch.hpp first to make sure they are included by the single +// header for non obj-usage + +/////////////////////////////////////////////////////////////////////////////// +// This protocol is really only here for (self) documenting purposes, since +// all its methods are optional. +@protocol OcFixture + +@optional + +-(void) setUp; +-(void) tearDown; + +@end + +namespace Catch { + + class OcMethod : public ITestInvoker { + + public: + OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {} + + virtual void invoke() const { + id obj = [[m_cls alloc] init]; + + performOptionalSelector( obj, @selector(setUp) ); + performOptionalSelector( obj, m_sel ); + performOptionalSelector( obj, @selector(tearDown) ); + + arcSafeRelease( obj ); + } + private: + virtual ~OcMethod() {} + + Class m_cls; + SEL m_sel; + }; + + namespace Detail{ + + inline std::string getAnnotation( Class cls, + std::string const& annotationName, + std::string const& testCaseName ) { + NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()]; + SEL sel = NSSelectorFromString( selStr ); + arcSafeRelease( selStr ); + id value = performOptionalSelector( cls, sel ); + if( value ) + return [(NSString*)value UTF8String]; + return ""; + } + } + + inline std::size_t registerTestMethods() { + std::size_t noTestMethods = 0; + int noClasses = objc_getClassList( nullptr, 0 ); + + Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses); + objc_getClassList( classes, noClasses ); + + for( int c = 0; c < noClasses; c++ ) { + Class cls = classes[c]; + { + u_int count; + Method* methods = class_copyMethodList( cls, &count ); + for( u_int m = 0; m < count ; m++ ) { + SEL selector = method_getName(methods[m]); + std::string methodName = sel_getName(selector); + if( startsWith( methodName, "Catch_TestCase_" ) ) { + std::string testCaseName = methodName.substr( 15 ); + std::string name = Detail::getAnnotation( cls, "Name", testCaseName ); + std::string desc = Detail::getAnnotation( cls, "Description", testCaseName ); + const char* className = class_getName( cls ); + + getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) ); + noTestMethods++; + } + } + free(methods); + } + } + return noTestMethods; + } + +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) + + namespace Matchers { + namespace Impl { + namespace NSStringMatchers { + + struct StringHolder : MatcherBase{ + StringHolder( NSString* substr ) : m_substr( [substr copy] ){} + StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){} + StringHolder() { + arcSafeRelease( m_substr ); + } + + bool match( NSString* arg ) const override { + return false; + } + + NSString* CATCH_ARC_STRONG m_substr; + }; + + struct Equals : StringHolder { + Equals( NSString* substr ) : StringHolder( substr ){} + + bool match( NSString* str ) const override { + return (str != nil || m_substr == nil ) && + [str isEqualToString:m_substr]; + } + + std::string describe() const override { + return "equals string: " + Catch::Detail::stringify( m_substr ); + } + }; + + struct Contains : StringHolder { + Contains( NSString* substr ) : StringHolder( substr ){} + + bool match( NSString* str ) const { + return (str != nil || m_substr == nil ) && + [str rangeOfString:m_substr].location != NSNotFound; + } + + std::string describe() const override { + return "contains string: " + Catch::Detail::stringify( m_substr ); + } + }; + + struct StartsWith : StringHolder { + StartsWith( NSString* substr ) : StringHolder( substr ){} + + bool match( NSString* str ) const override { + return (str != nil || m_substr == nil ) && + [str rangeOfString:m_substr].location == 0; + } + + std::string describe() const override { + return "starts with: " + Catch::Detail::stringify( m_substr ); + } + }; + struct EndsWith : StringHolder { + EndsWith( NSString* substr ) : StringHolder( substr ){} + + bool match( NSString* str ) const override { + return (str != nil || m_substr == nil ) && + [str rangeOfString:m_substr].location == [str length] - [m_substr length]; + } + + std::string describe() const override { + return "ends with: " + Catch::Detail::stringify( m_substr ); + } + }; + + } // namespace NSStringMatchers + } // namespace Impl + + inline Impl::NSStringMatchers::Equals + Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); } + + inline Impl::NSStringMatchers::Contains + Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); } + + inline Impl::NSStringMatchers::StartsWith + StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); } + + inline Impl::NSStringMatchers::EndsWith + EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); } + + } // namespace Matchers + + using namespace Matchers; + +#endif // CATCH_CONFIG_DISABLE_MATCHERS + +} // namespace Catch + +/////////////////////////////////////////////////////////////////////////////// +#define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix +#define OC_TEST_CASE2( name, desc, uniqueSuffix ) \ ++(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \ +{ \ +return @ name; \ +} \ ++(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \ +{ \ +return @ desc; \ +} \ +-(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix ) + +#define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ ) + +// end catch_objc.hpp +#endif + +#ifdef CATCH_CONFIG_EXTERNAL_INTERFACES +// start catch_external_interfaces.h + +// start catch_reporter_bases.hpp + +// start catch_interfaces_reporter.h + +// start catch_config.hpp + +// start catch_test_spec_parser.h + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpadded" +#endif + +// start catch_test_spec.h + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpadded" +#endif + +// start catch_wildcard_pattern.h + +namespace Catch +{ + class WildcardPattern { + enum WildcardPosition { + NoWildcard = 0, + WildcardAtStart = 1, + WildcardAtEnd = 2, + WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd + }; + + public: + + WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity ); + virtual ~WildcardPattern() = default; + virtual bool matches( std::string const& str ) const; + + private: + std::string adjustCase( std::string const& str ) const; + CaseSensitive::Choice m_caseSensitivity; + WildcardPosition m_wildcard = NoWildcard; + std::string m_pattern; + }; +} + +// end catch_wildcard_pattern.h +#include +#include +#include + +namespace Catch { + + class TestSpec { + struct Pattern { + virtual ~Pattern(); + virtual bool matches( TestCaseInfo const& testCase ) const = 0; + }; + using PatternPtr = std::shared_ptr; + + class NamePattern : public Pattern { + public: + NamePattern( std::string const& name ); + virtual ~NamePattern(); + virtual bool matches( TestCaseInfo const& testCase ) const override; + private: + WildcardPattern m_wildcardPattern; + }; + + class TagPattern : public Pattern { + public: + TagPattern( std::string const& tag ); + virtual ~TagPattern(); + virtual bool matches( TestCaseInfo const& testCase ) const override; + private: + std::string m_tag; + }; + + class ExcludedPattern : public Pattern { + public: + ExcludedPattern( PatternPtr const& underlyingPattern ); + virtual ~ExcludedPattern(); + virtual bool matches( TestCaseInfo const& testCase ) const override; + private: + PatternPtr m_underlyingPattern; + }; + + struct Filter { + std::vector m_patterns; + + bool matches( TestCaseInfo const& testCase ) const; + }; + + public: + bool hasFilters() const; + bool matches( TestCaseInfo const& testCase ) const; + + private: + std::vector m_filters; + + friend class TestSpecParser; + }; +} + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +// end catch_test_spec.h +// start catch_interfaces_tag_alias_registry.h + +#include + +namespace Catch { + + struct TagAlias; + + struct ITagAliasRegistry { + virtual ~ITagAliasRegistry(); + // Nullptr if not present + virtual TagAlias const* find( std::string const& alias ) const = 0; + virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0; + + static ITagAliasRegistry const& get(); + }; + +} // end namespace Catch + +// end catch_interfaces_tag_alias_registry.h +namespace Catch { + + class TestSpecParser { + enum Mode{ None, Name, QuotedName, Tag, EscapedName }; + Mode m_mode = None; + bool m_exclusion = false; + std::size_t m_start = std::string::npos, m_pos = 0; + std::string m_arg; + std::vector m_escapeChars; + TestSpec::Filter m_currentFilter; + TestSpec m_testSpec; + ITagAliasRegistry const* m_tagAliases = nullptr; + + public: + TestSpecParser( ITagAliasRegistry const& tagAliases ); + + TestSpecParser& parse( std::string const& arg ); + TestSpec testSpec(); + + private: + void visitChar( char c ); + void startNewMode( Mode mode, std::size_t start ); + void escape(); + std::string subString() const; + + template + void addPattern() { + std::string token = subString(); + for( std::size_t i = 0; i < m_escapeChars.size(); ++i ) + token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 ); + m_escapeChars.clear(); + if( startsWith( token, "exclude:" ) ) { + m_exclusion = true; + token = token.substr( 8 ); + } + if( !token.empty() ) { + TestSpec::PatternPtr pattern = std::make_shared( token ); + if( m_exclusion ) + pattern = std::make_shared( pattern ); + m_currentFilter.m_patterns.push_back( pattern ); + } + m_exclusion = false; + m_mode = None; + } + + void addFilter(); + }; + TestSpec parseTestSpec( std::string const& arg ); + +} // namespace Catch + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +// end catch_test_spec_parser.h +// Libstdc++ doesn't like incomplete classes for unique_ptr + +#include +#include +#include + +#ifndef CATCH_CONFIG_CONSOLE_WIDTH +#define CATCH_CONFIG_CONSOLE_WIDTH 80 +#endif + +namespace Catch { + + struct IStream; + + struct ConfigData { + bool listTests = false; + bool listTags = false; + bool listReporters = false; + bool listTestNamesOnly = false; + + bool showSuccessfulTests = false; + bool shouldDebugBreak = false; + bool noThrow = false; + bool showHelp = false; + bool showInvisibles = false; + bool filenamesAsTags = false; + bool libIdentify = false; + + int abortAfter = -1; + unsigned int rngSeed = 0; + int benchmarkResolutionMultiple = 100; + + Verbosity verbosity = Verbosity::Normal; + WarnAbout::What warnings = WarnAbout::Nothing; + ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter; + RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder; + UseColour::YesOrNo useColour = UseColour::Auto; + WaitForKeypress::When waitForKeypress = WaitForKeypress::Never; + + std::string outputFilename; + std::string name; + std::string processName; +#ifndef CATCH_CONFIG_DEFAULT_REPORTER +#define CATCH_CONFIG_DEFAULT_REPORTER "console" +#endif + std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER; +#undef CATCH_CONFIG_DEFAULT_REPORTER + + std::vector testsOrTags; + std::vector sectionsToRun; + }; + + class Config : public IConfig { + public: + + Config() = default; + Config( ConfigData const& data ); + virtual ~Config() = default; + + std::string const& getFilename() const; + + bool listTests() const; + bool listTestNamesOnly() const; + bool listTags() const; + bool listReporters() const; + + std::string getProcessName() const; + std::string const& getReporterName() const; + + std::vector const& getTestsOrTags() const; + std::vector const& getSectionsToRun() const override; + + virtual TestSpec const& testSpec() const override; + bool hasTestFilters() const override; + + bool showHelp() const; + + // IConfig interface + bool allowThrows() const override; + std::ostream& stream() const override; + std::string name() const override; + bool includeSuccessfulResults() const override; + bool warnAboutMissingAssertions() const override; + bool warnAboutNoTests() const override; + ShowDurations::OrNot showDurations() const override; + RunTests::InWhatOrder runOrder() const override; + unsigned int rngSeed() const override; + int benchmarkResolutionMultiple() const override; + UseColour::YesOrNo useColour() const override; + bool shouldDebugBreak() const override; + int abortAfter() const override; + bool showInvisibles() const override; + Verbosity verbosity() const override; + + private: + + IStream const* openStream(); + ConfigData m_data; + + std::unique_ptr m_stream; + TestSpec m_testSpec; + bool m_hasTestFilters = false; + }; + +} // end namespace Catch + +// end catch_config.hpp +// start catch_assertionresult.h + +#include + +namespace Catch { + + struct AssertionResultData + { + AssertionResultData() = delete; + + AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression ); + + std::string message; + mutable std::string reconstructedExpression; + LazyExpression lazyExpression; + ResultWas::OfType resultType; + + std::string reconstructExpression() const; + }; + + class AssertionResult { + public: + AssertionResult() = delete; + AssertionResult( AssertionInfo const& info, AssertionResultData const& data ); + + bool isOk() const; + bool succeeded() const; + ResultWas::OfType getResultType() const; + bool hasExpression() const; + bool hasMessage() const; + std::string getExpression() const; + std::string getExpressionInMacro() const; + bool hasExpandedExpression() const; + std::string getExpandedExpression() const; + std::string getMessage() const; + SourceLineInfo getSourceInfo() const; + StringRef getTestMacroName() const; + + //protected: + AssertionInfo m_info; + AssertionResultData m_resultData; + }; + +} // end namespace Catch + +// end catch_assertionresult.h +// start catch_option.hpp + +namespace Catch { + + // An optional type + template + class Option { + public: + Option() : nullableValue( nullptr ) {} + Option( T const& _value ) + : nullableValue( new( storage ) T( _value ) ) + {} + Option( Option const& _other ) + : nullableValue( _other ? new( storage ) T( *_other ) : nullptr ) + {} + + ~Option() { + reset(); + } + + Option& operator= ( Option const& _other ) { + if( &_other != this ) { + reset(); + if( _other ) + nullableValue = new( storage ) T( *_other ); + } + return *this; + } + Option& operator = ( T const& _value ) { + reset(); + nullableValue = new( storage ) T( _value ); + return *this; + } + + void reset() { + if( nullableValue ) + nullableValue->~T(); + nullableValue = nullptr; + } + + T& operator*() { return *nullableValue; } + T const& operator*() const { return *nullableValue; } + T* operator->() { return nullableValue; } + const T* operator->() const { return nullableValue; } + + T valueOr( T const& defaultValue ) const { + return nullableValue ? *nullableValue : defaultValue; + } + + bool some() const { return nullableValue != nullptr; } + bool none() const { return nullableValue == nullptr; } + + bool operator !() const { return nullableValue == nullptr; } + explicit operator bool() const { + return some(); + } + + private: + T *nullableValue; + alignas(alignof(T)) char storage[sizeof(T)]; + }; + +} // end namespace Catch + +// end catch_option.hpp +#include +#include +#include +#include +#include + +namespace Catch { + + struct ReporterConfig { + explicit ReporterConfig( IConfigPtr const& _fullConfig ); + + ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream ); + + std::ostream& stream() const; + IConfigPtr fullConfig() const; + + private: + std::ostream* m_stream; + IConfigPtr m_fullConfig; + }; + + struct ReporterPreferences { + bool shouldRedirectStdOut = false; + bool shouldReportAllAssertions = false; + }; + + template + struct LazyStat : Option { + LazyStat& operator=( T const& _value ) { + Option::operator=( _value ); + used = false; + return *this; + } + void reset() { + Option::reset(); + used = false; + } + bool used = false; + }; + + struct TestRunInfo { + TestRunInfo( std::string const& _name ); + std::string name; + }; + struct GroupInfo { + GroupInfo( std::string const& _name, + std::size_t _groupIndex, + std::size_t _groupsCount ); + + std::string name; + std::size_t groupIndex; + std::size_t groupsCounts; + }; + + struct AssertionStats { + AssertionStats( AssertionResult const& _assertionResult, + std::vector const& _infoMessages, + Totals const& _totals ); + + AssertionStats( AssertionStats const& ) = default; + AssertionStats( AssertionStats && ) = default; + AssertionStats& operator = ( AssertionStats const& ) = delete; + AssertionStats& operator = ( AssertionStats && ) = delete; + virtual ~AssertionStats(); + + AssertionResult assertionResult; + std::vector infoMessages; + Totals totals; + }; + + struct SectionStats { + SectionStats( SectionInfo const& _sectionInfo, + Counts const& _assertions, + double _durationInSeconds, + bool _missingAssertions ); + SectionStats( SectionStats const& ) = default; + SectionStats( SectionStats && ) = default; + SectionStats& operator = ( SectionStats const& ) = default; + SectionStats& operator = ( SectionStats && ) = default; + virtual ~SectionStats(); + + SectionInfo sectionInfo; + Counts assertions; + double durationInSeconds; + bool missingAssertions; + }; + + struct TestCaseStats { + TestCaseStats( TestCaseInfo const& _testInfo, + Totals const& _totals, + std::string const& _stdOut, + std::string const& _stdErr, + bool _aborting ); + + TestCaseStats( TestCaseStats const& ) = default; + TestCaseStats( TestCaseStats && ) = default; + TestCaseStats& operator = ( TestCaseStats const& ) = default; + TestCaseStats& operator = ( TestCaseStats && ) = default; + virtual ~TestCaseStats(); + + TestCaseInfo testInfo; + Totals totals; + std::string stdOut; + std::string stdErr; + bool aborting; + }; + + struct TestGroupStats { + TestGroupStats( GroupInfo const& _groupInfo, + Totals const& _totals, + bool _aborting ); + TestGroupStats( GroupInfo const& _groupInfo ); + + TestGroupStats( TestGroupStats const& ) = default; + TestGroupStats( TestGroupStats && ) = default; + TestGroupStats& operator = ( TestGroupStats const& ) = default; + TestGroupStats& operator = ( TestGroupStats && ) = default; + virtual ~TestGroupStats(); + + GroupInfo groupInfo; + Totals totals; + bool aborting; + }; + + struct TestRunStats { + TestRunStats( TestRunInfo const& _runInfo, + Totals const& _totals, + bool _aborting ); + + TestRunStats( TestRunStats const& ) = default; + TestRunStats( TestRunStats && ) = default; + TestRunStats& operator = ( TestRunStats const& ) = default; + TestRunStats& operator = ( TestRunStats && ) = default; + virtual ~TestRunStats(); + + TestRunInfo runInfo; + Totals totals; + bool aborting; + }; + + struct BenchmarkInfo { + std::string name; + }; + struct BenchmarkStats { + BenchmarkInfo info; + std::size_t iterations; + uint64_t elapsedTimeInNanoseconds; + }; + + struct IStreamingReporter { + virtual ~IStreamingReporter() = default; + + // Implementing class must also provide the following static methods: + // static std::string getDescription(); + // static std::set getSupportedVerbosities() + + virtual ReporterPreferences getPreferences() const = 0; + + virtual void noMatchingTestCases( std::string const& spec ) = 0; + + virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0; + virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0; + + virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0; + virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0; + + // *** experimental *** + virtual void benchmarkStarting( BenchmarkInfo const& ) {} + + virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0; + + // The return value indicates if the messages buffer should be cleared: + virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0; + + // *** experimental *** + virtual void benchmarkEnded( BenchmarkStats const& ) {} + + virtual void sectionEnded( SectionStats const& sectionStats ) = 0; + virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0; + virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0; + virtual void testRunEnded( TestRunStats const& testRunStats ) = 0; + + virtual void skipTest( TestCaseInfo const& testInfo ) = 0; + + // Default empty implementation provided + virtual void fatalErrorEncountered( StringRef name ); + + virtual bool isMulti() const; + }; + using IStreamingReporterPtr = std::unique_ptr; + + struct IReporterFactory { + virtual ~IReporterFactory(); + virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0; + virtual std::string getDescription() const = 0; + }; + using IReporterFactoryPtr = std::shared_ptr; + + struct IReporterRegistry { + using FactoryMap = std::map; + using Listeners = std::vector; + + virtual ~IReporterRegistry(); + virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0; + virtual FactoryMap const& getFactories() const = 0; + virtual Listeners const& getListeners() const = 0; + }; + +} // end namespace Catch + +// end catch_interfaces_reporter.h +#include +#include +#include +#include +#include +#include +#include + +namespace Catch { + void prepareExpandedExpression(AssertionResult& result); + + // Returns double formatted as %.3f (format expected on output) + std::string getFormattedDuration( double duration ); + + template + struct StreamingReporterBase : IStreamingReporter { + + StreamingReporterBase( ReporterConfig const& _config ) + : m_config( _config.fullConfig() ), + stream( _config.stream() ) + { + m_reporterPrefs.shouldRedirectStdOut = false; + if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) ) + CATCH_ERROR( "Verbosity level not supported by this reporter" ); + } + + ReporterPreferences getPreferences() const override { + return m_reporterPrefs; + } + + static std::set getSupportedVerbosities() { + return { Verbosity::Normal }; + } + + ~StreamingReporterBase() override = default; + + void noMatchingTestCases(std::string const&) override {} + + void testRunStarting(TestRunInfo const& _testRunInfo) override { + currentTestRunInfo = _testRunInfo; + } + void testGroupStarting(GroupInfo const& _groupInfo) override { + currentGroupInfo = _groupInfo; + } + + void testCaseStarting(TestCaseInfo const& _testInfo) override { + currentTestCaseInfo = _testInfo; + } + void sectionStarting(SectionInfo const& _sectionInfo) override { + m_sectionStack.push_back(_sectionInfo); + } + + void sectionEnded(SectionStats const& /* _sectionStats */) override { + m_sectionStack.pop_back(); + } + void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override { + currentTestCaseInfo.reset(); + } + void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override { + currentGroupInfo.reset(); + } + void testRunEnded(TestRunStats const& /* _testRunStats */) override { + currentTestCaseInfo.reset(); + currentGroupInfo.reset(); + currentTestRunInfo.reset(); + } + + void skipTest(TestCaseInfo const&) override { + // Don't do anything with this by default. + // It can optionally be overridden in the derived class. + } + + IConfigPtr m_config; + std::ostream& stream; + + LazyStat currentTestRunInfo; + LazyStat currentGroupInfo; + LazyStat currentTestCaseInfo; + + std::vector m_sectionStack; + ReporterPreferences m_reporterPrefs; + }; + + template + struct CumulativeReporterBase : IStreamingReporter { + template + struct Node { + explicit Node( T const& _value ) : value( _value ) {} + virtual ~Node() {} + + using ChildNodes = std::vector>; + T value; + ChildNodes children; + }; + struct SectionNode { + explicit SectionNode(SectionStats const& _stats) : stats(_stats) {} + virtual ~SectionNode() = default; + + bool operator == (SectionNode const& other) const { + return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo; + } + bool operator == (std::shared_ptr const& other) const { + return operator==(*other); + } + + SectionStats stats; + using ChildSections = std::vector>; + using Assertions = std::vector; + ChildSections childSections; + Assertions assertions; + std::string stdOut; + std::string stdErr; + }; + + struct BySectionInfo { + BySectionInfo( SectionInfo const& other ) : m_other( other ) {} + BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {} + bool operator() (std::shared_ptr const& node) const { + return ((node->stats.sectionInfo.name == m_other.name) && + (node->stats.sectionInfo.lineInfo == m_other.lineInfo)); + } + void operator=(BySectionInfo const&) = delete; + + private: + SectionInfo const& m_other; + }; + + using TestCaseNode = Node; + using TestGroupNode = Node; + using TestRunNode = Node; + + CumulativeReporterBase( ReporterConfig const& _config ) + : m_config( _config.fullConfig() ), + stream( _config.stream() ) + { + m_reporterPrefs.shouldRedirectStdOut = false; + if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) ) + CATCH_ERROR( "Verbosity level not supported by this reporter" ); + } + ~CumulativeReporterBase() override = default; + + ReporterPreferences getPreferences() const override { + return m_reporterPrefs; + } + + static std::set getSupportedVerbosities() { + return { Verbosity::Normal }; + } + + void testRunStarting( TestRunInfo const& ) override {} + void testGroupStarting( GroupInfo const& ) override {} + + void testCaseStarting( TestCaseInfo const& ) override {} + + void sectionStarting( SectionInfo const& sectionInfo ) override { + SectionStats incompleteStats( sectionInfo, Counts(), 0, false ); + std::shared_ptr node; + if( m_sectionStack.empty() ) { + if( !m_rootSection ) + m_rootSection = std::make_shared( incompleteStats ); + node = m_rootSection; + } + else { + SectionNode& parentNode = *m_sectionStack.back(); + auto it = + std::find_if( parentNode.childSections.begin(), + parentNode.childSections.end(), + BySectionInfo( sectionInfo ) ); + if( it == parentNode.childSections.end() ) { + node = std::make_shared( incompleteStats ); + parentNode.childSections.push_back( node ); + } + else + node = *it; + } + m_sectionStack.push_back( node ); + m_deepestSection = std::move(node); + } + + void assertionStarting(AssertionInfo const&) override {} + + bool assertionEnded(AssertionStats const& assertionStats) override { + assert(!m_sectionStack.empty()); + // AssertionResult holds a pointer to a temporary DecomposedExpression, + // which getExpandedExpression() calls to build the expression string. + // Our section stack copy of the assertionResult will likely outlive the + // temporary, so it must be expanded or discarded now to avoid calling + // a destroyed object later. + prepareExpandedExpression(const_cast( assertionStats.assertionResult ) ); + SectionNode& sectionNode = *m_sectionStack.back(); + sectionNode.assertions.push_back(assertionStats); + return true; + } + void sectionEnded(SectionStats const& sectionStats) override { + assert(!m_sectionStack.empty()); + SectionNode& node = *m_sectionStack.back(); + node.stats = sectionStats; + m_sectionStack.pop_back(); + } + void testCaseEnded(TestCaseStats const& testCaseStats) override { + auto node = std::make_shared(testCaseStats); + assert(m_sectionStack.size() == 0); + node->children.push_back(m_rootSection); + m_testCases.push_back(node); + m_rootSection.reset(); + + assert(m_deepestSection); + m_deepestSection->stdOut = testCaseStats.stdOut; + m_deepestSection->stdErr = testCaseStats.stdErr; + } + void testGroupEnded(TestGroupStats const& testGroupStats) override { + auto node = std::make_shared(testGroupStats); + node->children.swap(m_testCases); + m_testGroups.push_back(node); + } + void testRunEnded(TestRunStats const& testRunStats) override { + auto node = std::make_shared(testRunStats); + node->children.swap(m_testGroups); + m_testRuns.push_back(node); + testRunEndedCumulative(); + } + virtual void testRunEndedCumulative() = 0; + + void skipTest(TestCaseInfo const&) override {} + + IConfigPtr m_config; + std::ostream& stream; + std::vector m_assertions; + std::vector>> m_sections; + std::vector> m_testCases; + std::vector> m_testGroups; + + std::vector> m_testRuns; + + std::shared_ptr m_rootSection; + std::shared_ptr m_deepestSection; + std::vector> m_sectionStack; + ReporterPreferences m_reporterPrefs; + }; + + template + char const* getLineOfChars() { + static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0}; + if( !*line ) { + std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 ); + line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0; + } + return line; + } + + struct TestEventListenerBase : StreamingReporterBase { + TestEventListenerBase( ReporterConfig const& _config ); + + static std::set getSupportedVerbosities(); + + void assertionStarting(AssertionInfo const&) override; + bool assertionEnded(AssertionStats const&) override; + }; + +} // end namespace Catch + +// end catch_reporter_bases.hpp +// start catch_console_colour.h + +namespace Catch { + + struct Colour { + enum Code { + None = 0, + + White, + Red, + Green, + Blue, + Cyan, + Yellow, + Grey, + + Bright = 0x10, + + BrightRed = Bright | Red, + BrightGreen = Bright | Green, + LightGrey = Bright | Grey, + BrightWhite = Bright | White, + BrightYellow = Bright | Yellow, + + // By intention + FileName = LightGrey, + Warning = BrightYellow, + ResultError = BrightRed, + ResultSuccess = BrightGreen, + ResultExpectedFailure = Warning, + + Error = BrightRed, + Success = Green, + + OriginalExpression = Cyan, + ReconstructedExpression = BrightYellow, + + SecondaryText = LightGrey, + Headers = White + }; + + // Use constructed object for RAII guard + Colour( Code _colourCode ); + Colour( Colour&& other ) noexcept; + Colour& operator=( Colour&& other ) noexcept; + ~Colour(); + + // Use static method for one-shot changes + static void use( Code _colourCode ); + + private: + bool m_moved = false; + }; + + std::ostream& operator << ( std::ostream& os, Colour const& ); + +} // end namespace Catch + +// end catch_console_colour.h +// start catch_reporter_registrars.hpp + + +namespace Catch { + + template + class ReporterRegistrar { + + class ReporterFactory : public IReporterFactory { + + virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override { + return std::unique_ptr( new T( config ) ); + } + + virtual std::string getDescription() const override { + return T::getDescription(); + } + }; + + public: + + explicit ReporterRegistrar( std::string const& name ) { + getMutableRegistryHub().registerReporter( name, std::make_shared() ); + } + }; + + template + class ListenerRegistrar { + + class ListenerFactory : public IReporterFactory { + + virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override { + return std::unique_ptr( new T( config ) ); + } + virtual std::string getDescription() const override { + return std::string(); + } + }; + + public: + + ListenerRegistrar() { + getMutableRegistryHub().registerListener( std::make_shared() ); + } + }; +} + +#if !defined(CATCH_CONFIG_DISABLE) + +#define CATCH_REGISTER_REPORTER( name, reporterType ) \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace{ Catch::ReporterRegistrar catch_internal_RegistrarFor##reporterType( name ); } \ + CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS + +#define CATCH_REGISTER_LISTENER( listenerType ) \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \ + namespace{ Catch::ListenerRegistrar catch_internal_RegistrarFor##listenerType; } \ + CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS +#else // CATCH_CONFIG_DISABLE + +#define CATCH_REGISTER_REPORTER(name, reporterType) +#define CATCH_REGISTER_LISTENER(listenerType) + +#endif // CATCH_CONFIG_DISABLE + +// end catch_reporter_registrars.hpp +// Allow users to base their work off existing reporters +// start catch_reporter_compact.h + +namespace Catch { + + struct CompactReporter : StreamingReporterBase { + + using StreamingReporterBase::StreamingReporterBase; + + ~CompactReporter() override; + + static std::string getDescription(); + + ReporterPreferences getPreferences() const override; + + void noMatchingTestCases(std::string const& spec) override; + + void assertionStarting(AssertionInfo const&) override; + + bool assertionEnded(AssertionStats const& _assertionStats) override; + + void sectionEnded(SectionStats const& _sectionStats) override; + + void testRunEnded(TestRunStats const& _testRunStats) override; + + }; + +} // end namespace Catch + +// end catch_reporter_compact.h +// start catch_reporter_console.h + +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch + // Note that 4062 (not all labels are handled + // and default is missing) is enabled +#endif + +namespace Catch { + // Fwd decls + struct SummaryColumn; + class TablePrinter; + + struct ConsoleReporter : StreamingReporterBase { + std::unique_ptr m_tablePrinter; + + ConsoleReporter(ReporterConfig const& config); + ~ConsoleReporter() override; + static std::string getDescription(); + + void noMatchingTestCases(std::string const& spec) override; + + void assertionStarting(AssertionInfo const&) override; + + bool assertionEnded(AssertionStats const& _assertionStats) override; + + void sectionStarting(SectionInfo const& _sectionInfo) override; + void sectionEnded(SectionStats const& _sectionStats) override; + + void benchmarkStarting(BenchmarkInfo const& info) override; + void benchmarkEnded(BenchmarkStats const& stats) override; + + void testCaseEnded(TestCaseStats const& _testCaseStats) override; + void testGroupEnded(TestGroupStats const& _testGroupStats) override; + void testRunEnded(TestRunStats const& _testRunStats) override; + + private: + + void lazyPrint(); + + void lazyPrintWithoutClosingBenchmarkTable(); + void lazyPrintRunInfo(); + void lazyPrintGroupInfo(); + void printTestCaseAndSectionHeader(); + + void printClosedHeader(std::string const& _name); + void printOpenHeader(std::string const& _name); + + // if string has a : in first line will set indent to follow it on + // subsequent lines + void printHeaderString(std::string const& _string, std::size_t indent = 0); + + void printTotals(Totals const& totals); + void printSummaryRow(std::string const& label, std::vector const& cols, std::size_t row); + + void printTotalsDivider(Totals const& totals); + void printSummaryDivider(); + + private: + bool m_headerPrinted = false; + }; + +} // end namespace Catch + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif + +// end catch_reporter_console.h +// start catch_reporter_junit.h + +// start catch_xmlwriter.h + +#include + +namespace Catch { + + class XmlEncode { + public: + enum ForWhat { ForTextNodes, ForAttributes }; + + XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ); + + void encodeTo( std::ostream& os ) const; + + friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ); + + private: + std::string m_str; + ForWhat m_forWhat; + }; + + class XmlWriter { + public: + + class ScopedElement { + public: + ScopedElement( XmlWriter* writer ); + + ScopedElement( ScopedElement&& other ) noexcept; + ScopedElement& operator=( ScopedElement&& other ) noexcept; + + ~ScopedElement(); + + ScopedElement& writeText( std::string const& text, bool indent = true ); + + template + ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { + m_writer->writeAttribute( name, attribute ); + return *this; + } + + private: + mutable XmlWriter* m_writer = nullptr; + }; + + XmlWriter( std::ostream& os = Catch::cout() ); + ~XmlWriter(); + + XmlWriter( XmlWriter const& ) = delete; + XmlWriter& operator=( XmlWriter const& ) = delete; + + XmlWriter& startElement( std::string const& name ); + + ScopedElement scopedElement( std::string const& name ); + + XmlWriter& endElement(); + + XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ); + + XmlWriter& writeAttribute( std::string const& name, bool attribute ); + + template + XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { + ReusableStringStream rss; + rss << attribute; + return writeAttribute( name, rss.str() ); + } + + XmlWriter& writeText( std::string const& text, bool indent = true ); + + XmlWriter& writeComment( std::string const& text ); + + void writeStylesheetRef( std::string const& url ); + + XmlWriter& writeBlankLine(); + + void ensureTagClosed(); + + private: + + void writeDeclaration(); + + void newlineIfNecessary(); + + bool m_tagIsOpen = false; + bool m_needsNewline = false; + std::vector m_tags; + std::string m_indent; + std::ostream& m_os; + }; + +} + +// end catch_xmlwriter.h +namespace Catch { + + class JunitReporter : public CumulativeReporterBase { + public: + JunitReporter(ReporterConfig const& _config); + + ~JunitReporter() override; + + static std::string getDescription(); + + void noMatchingTestCases(std::string const& /*spec*/) override; + + void testRunStarting(TestRunInfo const& runInfo) override; + + void testGroupStarting(GroupInfo const& groupInfo) override; + + void testCaseStarting(TestCaseInfo const& testCaseInfo) override; + bool assertionEnded(AssertionStats const& assertionStats) override; + + void testCaseEnded(TestCaseStats const& testCaseStats) override; + + void testGroupEnded(TestGroupStats const& testGroupStats) override; + + void testRunEndedCumulative() override; + + void writeGroup(TestGroupNode const& groupNode, double suiteTime); + + void writeTestCase(TestCaseNode const& testCaseNode); + + void writeSection(std::string const& className, + std::string const& rootName, + SectionNode const& sectionNode); + + void writeAssertions(SectionNode const& sectionNode); + void writeAssertion(AssertionStats const& stats); + + XmlWriter xml; + Timer suiteTimer; + std::string stdOutForSuite; + std::string stdErrForSuite; + unsigned int unexpectedExceptions = 0; + bool m_okToFail = false; + }; + +} // end namespace Catch + +// end catch_reporter_junit.h +// start catch_reporter_xml.h + +namespace Catch { + class XmlReporter : public StreamingReporterBase { + public: + XmlReporter(ReporterConfig const& _config); + + ~XmlReporter() override; + + static std::string getDescription(); + + virtual std::string getStylesheetRef() const; + + void writeSourceInfo(SourceLineInfo const& sourceInfo); + + public: // StreamingReporterBase + + void noMatchingTestCases(std::string const& s) override; + + void testRunStarting(TestRunInfo const& testInfo) override; + + void testGroupStarting(GroupInfo const& groupInfo) override; + + void testCaseStarting(TestCaseInfo const& testInfo) override; + + void sectionStarting(SectionInfo const& sectionInfo) override; + + void assertionStarting(AssertionInfo const&) override; + + bool assertionEnded(AssertionStats const& assertionStats) override; + + void sectionEnded(SectionStats const& sectionStats) override; + + void testCaseEnded(TestCaseStats const& testCaseStats) override; + + void testGroupEnded(TestGroupStats const& testGroupStats) override; + + void testRunEnded(TestRunStats const& testRunStats) override; + + private: + Timer m_testCaseTimer; + XmlWriter m_xml; + int m_sectionDepth = 0; + }; + +} // end namespace Catch + +// end catch_reporter_xml.h + +// end catch_external_interfaces.h +#endif + +#endif // ! CATCH_CONFIG_IMPL_ONLY + +#ifdef CATCH_IMPL +// start catch_impl.hpp + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wweak-vtables" +#endif + +// Keep these here for external reporters +// start catch_test_case_tracker.h + +#include +#include +#include + +namespace Catch { +namespace TestCaseTracking { + + struct NameAndLocation { + std::string name; + SourceLineInfo location; + + NameAndLocation( std::string const& _name, SourceLineInfo const& _location ); + }; + + struct ITracker; + + using ITrackerPtr = std::shared_ptr; + + struct ITracker { + virtual ~ITracker(); + + // static queries + virtual NameAndLocation const& nameAndLocation() const = 0; + + // dynamic queries + virtual bool isComplete() const = 0; // Successfully completed or failed + virtual bool isSuccessfullyCompleted() const = 0; + virtual bool isOpen() const = 0; // Started but not complete + virtual bool hasChildren() const = 0; + + virtual ITracker& parent() = 0; + + // actions + virtual void close() = 0; // Successfully complete + virtual void fail() = 0; + virtual void markAsNeedingAnotherRun() = 0; + + virtual void addChild( ITrackerPtr const& child ) = 0; + virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0; + virtual void openChild() = 0; + + // Debug/ checking + virtual bool isSectionTracker() const = 0; + virtual bool isGeneratorTracker() const = 0; + }; + + class TrackerContext { + + enum RunState { + NotStarted, + Executing, + CompletedCycle + }; + + ITrackerPtr m_rootTracker; + ITracker* m_currentTracker = nullptr; + RunState m_runState = NotStarted; + + public: + + static TrackerContext& instance(); + + ITracker& startRun(); + void endRun(); + + void startCycle(); + void completeCycle(); + + bool completedCycle() const; + ITracker& currentTracker(); + void setCurrentTracker( ITracker* tracker ); + }; + + class TrackerBase : public ITracker { + protected: + enum CycleState { + NotStarted, + Executing, + ExecutingChildren, + NeedsAnotherRun, + CompletedSuccessfully, + Failed + }; + + using Children = std::vector; + NameAndLocation m_nameAndLocation; + TrackerContext& m_ctx; + ITracker* m_parent; + Children m_children; + CycleState m_runState = NotStarted; + + public: + TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ); + + NameAndLocation const& nameAndLocation() const override; + bool isComplete() const override; + bool isSuccessfullyCompleted() const override; + bool isOpen() const override; + bool hasChildren() const override; + + void addChild( ITrackerPtr const& child ) override; + + ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override; + ITracker& parent() override; + + void openChild() override; + + bool isSectionTracker() const override; + bool isGeneratorTracker() const override; + + void open(); + + void close() override; + void fail() override; + void markAsNeedingAnotherRun() override; + + private: + void moveToParent(); + void moveToThis(); + }; + + class SectionTracker : public TrackerBase { + std::vector m_filters; + public: + SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ); + + bool isSectionTracker() const override; + + bool isComplete() const override; + + static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ); + + void tryOpen(); + + void addInitialFilters( std::vector const& filters ); + void addNextFilters( std::vector const& filters ); + }; + +} // namespace TestCaseTracking + +using TestCaseTracking::ITracker; +using TestCaseTracking::TrackerContext; +using TestCaseTracking::SectionTracker; + +} // namespace Catch + +// end catch_test_case_tracker.h + +// start catch_leak_detector.h + +namespace Catch { + + struct LeakDetector { + LeakDetector(); + ~LeakDetector(); + }; + +} +// end catch_leak_detector.h +// Cpp files will be included in the single-header file here +// start catch_approx.cpp + +#include +#include + +namespace { + +// Performs equivalent check of std::fabs(lhs - rhs) <= margin +// But without the subtraction to allow for INFINITY in comparison +bool marginComparison(double lhs, double rhs, double margin) { + return (lhs + margin >= rhs) && (rhs + margin >= lhs); +} + +} + +namespace Catch { +namespace Detail { + + Approx::Approx ( double value ) + : m_epsilon( std::numeric_limits::epsilon()*100 ), + m_margin( 0.0 ), + m_scale( 0.0 ), + m_value( value ) + {} + + Approx Approx::custom() { + return Approx( 0 ); + } + + Approx Approx::operator-() const { + auto temp(*this); + temp.m_value = -temp.m_value; + return temp; + } + + std::string Approx::toString() const { + ReusableStringStream rss; + rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )"; + return rss.str(); + } + + bool Approx::equalityComparisonImpl(const double other) const { + // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value + // Thanks to Richard Harris for his help refining the scaled margin value + return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value))); + } + + void Approx::setMargin(double margin) { + CATCH_ENFORCE(margin >= 0, + "Invalid Approx::margin: " << margin << '.' + << " Approx::Margin has to be non-negative."); + m_margin = margin; + } + + void Approx::setEpsilon(double epsilon) { + CATCH_ENFORCE(epsilon >= 0 && epsilon <= 1.0, + "Invalid Approx::epsilon: " << epsilon << '.' + << " Approx::epsilon has to be in [0, 1]"); + m_epsilon = epsilon; + } + +} // end namespace Detail + +namespace literals { + Detail::Approx operator "" _a(long double val) { + return Detail::Approx(val); + } + Detail::Approx operator "" _a(unsigned long long val) { + return Detail::Approx(val); + } +} // end namespace literals + +std::string StringMaker::convert(Catch::Detail::Approx const& value) { + return value.toString(); +} + +} // end namespace Catch +// end catch_approx.cpp +// start catch_assertionhandler.cpp + +// start catch_debugger.h + +namespace Catch { + bool isDebuggerActive(); +} + +#ifdef CATCH_PLATFORM_MAC + + #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */ + +#elif defined(CATCH_PLATFORM_LINUX) + // If we can use inline assembler, do it because this allows us to break + // directly at the location of the failing check instead of breaking inside + // raise() called from it, i.e. one stack frame below. + #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64)) + #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */ + #else // Fall back to the generic way. + #include + + #define CATCH_TRAP() raise(SIGTRAP) + #endif +#elif defined(_MSC_VER) + #define CATCH_TRAP() __debugbreak() +#elif defined(__MINGW32__) + extern "C" __declspec(dllimport) void __stdcall DebugBreak(); + #define CATCH_TRAP() DebugBreak() +#endif + +#ifdef CATCH_TRAP + #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }() +#else + #define CATCH_BREAK_INTO_DEBUGGER() []{}() +#endif + +// end catch_debugger.h +// start catch_run_context.h + +// start catch_fatal_condition.h + +// start catch_windows_h_proxy.h + + +#if defined(CATCH_PLATFORM_WINDOWS) + +#if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX) +# define CATCH_DEFINED_NOMINMAX +# define NOMINMAX +#endif +#if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN) +# define CATCH_DEFINED_WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +#endif + +#ifdef __AFXDLL +#include +#else +#include +#endif + +#ifdef CATCH_DEFINED_NOMINMAX +# undef NOMINMAX +#endif +#ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN +# undef WIN32_LEAN_AND_MEAN +#endif + +#endif // defined(CATCH_PLATFORM_WINDOWS) + +// end catch_windows_h_proxy.h +#if defined( CATCH_CONFIG_WINDOWS_SEH ) + +namespace Catch { + + struct FatalConditionHandler { + + static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo); + FatalConditionHandler(); + static void reset(); + ~FatalConditionHandler(); + + private: + static bool isSet; + static ULONG guaranteeSize; + static PVOID exceptionHandlerHandle; + }; + +} // namespace Catch + +#elif defined ( CATCH_CONFIG_POSIX_SIGNALS ) + +#include + +namespace Catch { + + struct FatalConditionHandler { + + static bool isSet; + static struct sigaction oldSigActions[]; + static stack_t oldSigStack; + static char altStackMem[]; + + static void handleSignal( int sig ); + + FatalConditionHandler(); + ~FatalConditionHandler(); + static void reset(); + }; + +} // namespace Catch + +#else + +namespace Catch { + struct FatalConditionHandler { + void reset(); + }; +} + +#endif + +// end catch_fatal_condition.h +#include + +namespace Catch { + + struct IMutableContext; + + /////////////////////////////////////////////////////////////////////////// + + class RunContext : public IResultCapture, public IRunner { + + public: + RunContext( RunContext const& ) = delete; + RunContext& operator =( RunContext const& ) = delete; + + explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter ); + + ~RunContext() override; + + void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ); + void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ); + + Totals runTest(TestCase const& testCase); + + IConfigPtr config() const; + IStreamingReporter& reporter() const; + + public: // IResultCapture + + // Assertion handlers + void handleExpr + ( AssertionInfo const& info, + ITransientExpression const& expr, + AssertionReaction& reaction ) override; + void handleMessage + ( AssertionInfo const& info, + ResultWas::OfType resultType, + StringRef const& message, + AssertionReaction& reaction ) override; + void handleUnexpectedExceptionNotThrown + ( AssertionInfo const& info, + AssertionReaction& reaction ) override; + void handleUnexpectedInflightException + ( AssertionInfo const& info, + std::string const& message, + AssertionReaction& reaction ) override; + void handleIncomplete + ( AssertionInfo const& info ) override; + void handleNonExpr + ( AssertionInfo const &info, + ResultWas::OfType resultType, + AssertionReaction &reaction ) override; + + bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override; + + void sectionEnded( SectionEndInfo const& endInfo ) override; + void sectionEndedEarly( SectionEndInfo const& endInfo ) override; + + auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override; + + void benchmarkStarting( BenchmarkInfo const& info ) override; + void benchmarkEnded( BenchmarkStats const& stats ) override; + + void pushScopedMessage( MessageInfo const& message ) override; + void popScopedMessage( MessageInfo const& message ) override; + + void emplaceUnscopedMessage( MessageBuilder const& builder ) override; + + std::string getCurrentTestName() const override; + + const AssertionResult* getLastResult() const override; + + void exceptionEarlyReported() override; + + void handleFatalErrorCondition( StringRef message ) override; + + bool lastAssertionPassed() override; + + void assertionPassed() override; + + public: + // !TBD We need to do this another way! + bool aborting() const final; + + private: + + void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ); + void invokeActiveTestCase(); + + void resetAssertionInfo(); + bool testForMissingAssertions( Counts& assertions ); + + void assertionEnded( AssertionResult const& result ); + void reportExpr + ( AssertionInfo const &info, + ResultWas::OfType resultType, + ITransientExpression const *expr, + bool negated ); + + void populateReaction( AssertionReaction& reaction ); + + private: + + void handleUnfinishedSections(); + + TestRunInfo m_runInfo; + IMutableContext& m_context; + TestCase const* m_activeTestCase = nullptr; + ITracker* m_testCaseTracker = nullptr; + Option m_lastResult; + + IConfigPtr m_config; + Totals m_totals; + IStreamingReporterPtr m_reporter; + std::vector m_messages; + std::vector m_messageScopes; /* Keeps owners of so-called unscoped messages. */ + AssertionInfo m_lastAssertionInfo; + std::vector m_unfinishedSections; + std::vector m_activeSections; + TrackerContext m_trackerContext; + bool m_lastAssertionPassed = false; + bool m_shouldReportUnexpected = true; + bool m_includeSuccessfulResults; + }; + +} // end namespace Catch + +// end catch_run_context.h +namespace Catch { + + namespace { + auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& { + expr.streamReconstructedExpression( os ); + return os; + } + } + + LazyExpression::LazyExpression( bool isNegated ) + : m_isNegated( isNegated ) + {} + + LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {} + + LazyExpression::operator bool() const { + return m_transientExpression != nullptr; + } + + auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& { + if( lazyExpr.m_isNegated ) + os << "!"; + + if( lazyExpr ) { + if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() ) + os << "(" << *lazyExpr.m_transientExpression << ")"; + else + os << *lazyExpr.m_transientExpression; + } + else { + os << "{** error - unchecked empty expression requested **}"; + } + return os; + } + + AssertionHandler::AssertionHandler + ( StringRef const& macroName, + SourceLineInfo const& lineInfo, + StringRef capturedExpression, + ResultDisposition::Flags resultDisposition ) + : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition }, + m_resultCapture( getResultCapture() ) + {} + + void AssertionHandler::handleExpr( ITransientExpression const& expr ) { + m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction ); + } + void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) { + m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction ); + } + + auto AssertionHandler::allowThrows() const -> bool { + return getCurrentContext().getConfig()->allowThrows(); + } + + void AssertionHandler::complete() { + setCompleted(); + if( m_reaction.shouldDebugBreak ) { + + // If you find your debugger stopping you here then go one level up on the + // call-stack for the code that caused it (typically a failed assertion) + + // (To go back to the test and change execution, jump over the throw, next) + CATCH_BREAK_INTO_DEBUGGER(); + } + if (m_reaction.shouldThrow) { +#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) + throw Catch::TestFailureException(); +#else + CATCH_ERROR( "Test failure requires aborting test!" ); +#endif + } + } + void AssertionHandler::setCompleted() { + m_completed = true; + } + + void AssertionHandler::handleUnexpectedInflightException() { + m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction ); + } + + void AssertionHandler::handleExceptionThrownAsExpected() { + m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); + } + void AssertionHandler::handleExceptionNotThrownAsExpected() { + m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); + } + + void AssertionHandler::handleUnexpectedExceptionNotThrown() { + m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction ); + } + + void AssertionHandler::handleThrowingCallSkipped() { + m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction); + } + + // This is the overload that takes a string and infers the Equals matcher from it + // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp + void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) { + handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString ); + } + +} // namespace Catch +// end catch_assertionhandler.cpp +// start catch_assertionresult.cpp + +namespace Catch { + AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression): + lazyExpression(_lazyExpression), + resultType(_resultType) {} + + std::string AssertionResultData::reconstructExpression() const { + + if( reconstructedExpression.empty() ) { + if( lazyExpression ) { + ReusableStringStream rss; + rss << lazyExpression; + reconstructedExpression = rss.str(); + } + } + return reconstructedExpression; + } + + AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data ) + : m_info( info ), + m_resultData( data ) + {} + + // Result was a success + bool AssertionResult::succeeded() const { + return Catch::isOk( m_resultData.resultType ); + } + + // Result was a success, or failure is suppressed + bool AssertionResult::isOk() const { + return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition ); + } + + ResultWas::OfType AssertionResult::getResultType() const { + return m_resultData.resultType; + } + + bool AssertionResult::hasExpression() const { + return m_info.capturedExpression[0] != 0; + } + + bool AssertionResult::hasMessage() const { + return !m_resultData.message.empty(); + } + + std::string AssertionResult::getExpression() const { + if( isFalseTest( m_info.resultDisposition ) ) + return "!(" + m_info.capturedExpression + ")"; + else + return m_info.capturedExpression; + } + + std::string AssertionResult::getExpressionInMacro() const { + std::string expr; + if( m_info.macroName[0] == 0 ) + expr = m_info.capturedExpression; + else { + expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 ); + expr += m_info.macroName; + expr += "( "; + expr += m_info.capturedExpression; + expr += " )"; + } + return expr; + } + + bool AssertionResult::hasExpandedExpression() const { + return hasExpression() && getExpandedExpression() != getExpression(); + } + + std::string AssertionResult::getExpandedExpression() const { + std::string expr = m_resultData.reconstructExpression(); + return expr.empty() + ? getExpression() + : expr; + } + + std::string AssertionResult::getMessage() const { + return m_resultData.message; + } + SourceLineInfo AssertionResult::getSourceInfo() const { + return m_info.lineInfo; + } + + StringRef AssertionResult::getTestMacroName() const { + return m_info.macroName; + } + +} // end namespace Catch +// end catch_assertionresult.cpp +// start catch_benchmark.cpp + +namespace Catch { + + auto BenchmarkLooper::getResolution() -> uint64_t { + return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple(); + } + + void BenchmarkLooper::reportStart() { + getResultCapture().benchmarkStarting( { m_name } ); + } + auto BenchmarkLooper::needsMoreIterations() -> bool { + auto elapsed = m_timer.getElapsedNanoseconds(); + + // Exponentially increasing iterations until we're confident in our timer resolution + if( elapsed < m_resolution ) { + m_iterationsToRun *= 10; + return true; + } + + getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } ); + return false; + } + +} // end namespace Catch +// end catch_benchmark.cpp +// start catch_capture_matchers.cpp + +namespace Catch { + + using StringMatcher = Matchers::Impl::MatcherBase; + + // This is the general overload that takes a any string matcher + // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers + // the Equals matcher (so the header does not mention matchers) + void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) { + std::string exceptionMessage = Catch::translateActiveException(); + MatchExpr expr( exceptionMessage, matcher, matcherString ); + handler.handleExpr( expr ); + } + +} // namespace Catch +// end catch_capture_matchers.cpp +// start catch_commandline.cpp + +// start catch_commandline.h + +// start catch_clara.h + +// Use Catch's value for console width (store Clara's off to the side, if present) +#ifdef CLARA_CONFIG_CONSOLE_WIDTH +#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH +#undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH +#endif +#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1 + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wweak-vtables" +#pragma clang diagnostic ignored "-Wexit-time-destructors" +#pragma clang diagnostic ignored "-Wshadow" +#endif + +// start clara.hpp +// Copyright 2017 Two Blue Cubes Ltd. All rights reserved. +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See https://github.com/philsquared/Clara for more details + +// Clara v1.1.5 + + +#ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH +#define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80 +#endif + +#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH +#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH +#endif + +#ifndef CLARA_CONFIG_OPTIONAL_TYPE +#ifdef __has_include +#if __has_include() && __cplusplus >= 201703L +#include +#define CLARA_CONFIG_OPTIONAL_TYPE std::optional +#endif +#endif +#endif + +// ----------- #included from clara_textflow.hpp ----------- + +// TextFlowCpp +// +// A single-header library for wrapping and laying out basic text, by Phil Nash +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// This project is hosted at https://github.com/philsquared/textflowcpp + + +#include +#include +#include +#include + +#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH +#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80 +#endif + +namespace Catch { +namespace clara { +namespace TextFlow { + +inline auto isWhitespace(char c) -> bool { + static std::string chars = " \t\n\r"; + return chars.find(c) != std::string::npos; +} +inline auto isBreakableBefore(char c) -> bool { + static std::string chars = "[({<|"; + return chars.find(c) != std::string::npos; +} +inline auto isBreakableAfter(char c) -> bool { + static std::string chars = "])}>.,:;*+-=&/\\"; + return chars.find(c) != std::string::npos; +} + +class Columns; + +class Column { + std::vector m_strings; + size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH; + size_t m_indent = 0; + size_t m_initialIndent = std::string::npos; + +public: + class iterator { + friend Column; + + Column const& m_column; + size_t m_stringIndex = 0; + size_t m_pos = 0; + + size_t m_len = 0; + size_t m_end = 0; + bool m_suffix = false; + + iterator(Column const& column, size_t stringIndex) + : m_column(column), + m_stringIndex(stringIndex) {} + + auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; } + + auto isBoundary(size_t at) const -> bool { + assert(at > 0); + assert(at <= line().size()); + + return at == line().size() || + (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) || + isBreakableBefore(line()[at]) || + isBreakableAfter(line()[at - 1]); + } + + void calcLength() { + assert(m_stringIndex < m_column.m_strings.size()); + + m_suffix = false; + auto width = m_column.m_width - indent(); + m_end = m_pos; + while (m_end < line().size() && line()[m_end] != '\n') + ++m_end; + + if (m_end < m_pos + width) { + m_len = m_end - m_pos; + } else { + size_t len = width; + while (len > 0 && !isBoundary(m_pos + len)) + --len; + while (len > 0 && isWhitespace(line()[m_pos + len - 1])) + --len; + + if (len > 0) { + m_len = len; + } else { + m_suffix = true; + m_len = width - 1; + } + } + } + + auto indent() const -> size_t { + auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos; + return initial == std::string::npos ? m_column.m_indent : initial; + } + + auto addIndentAndSuffix(std::string const &plain) const -> std::string { + return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain); + } + + public: + using difference_type = std::ptrdiff_t; + using value_type = std::string; + using pointer = value_type * ; + using reference = value_type & ; + using iterator_category = std::forward_iterator_tag; + + explicit iterator(Column const& column) : m_column(column) { + assert(m_column.m_width > m_column.m_indent); + assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent); + calcLength(); + if (m_len == 0) + m_stringIndex++; // Empty string + } + + auto operator *() const -> std::string { + assert(m_stringIndex < m_column.m_strings.size()); + assert(m_pos <= m_end); + return addIndentAndSuffix(line().substr(m_pos, m_len)); + } + + auto operator ++() -> iterator& { + m_pos += m_len; + if (m_pos < line().size() && line()[m_pos] == '\n') + m_pos += 1; + else + while (m_pos < line().size() && isWhitespace(line()[m_pos])) + ++m_pos; + + if (m_pos == line().size()) { + m_pos = 0; + ++m_stringIndex; + } + if (m_stringIndex < m_column.m_strings.size()) + calcLength(); + return *this; + } + auto operator ++(int) -> iterator { + iterator prev(*this); + operator++(); + return prev; + } + + auto operator ==(iterator const& other) const -> bool { + return + m_pos == other.m_pos && + m_stringIndex == other.m_stringIndex && + &m_column == &other.m_column; + } + auto operator !=(iterator const& other) const -> bool { + return !operator==(other); + } + }; + using const_iterator = iterator; + + explicit Column(std::string const& text) { m_strings.push_back(text); } + + auto width(size_t newWidth) -> Column& { + assert(newWidth > 0); + m_width = newWidth; + return *this; + } + auto indent(size_t newIndent) -> Column& { + m_indent = newIndent; + return *this; + } + auto initialIndent(size_t newIndent) -> Column& { + m_initialIndent = newIndent; + return *this; + } + + auto width() const -> size_t { return m_width; } + auto begin() const -> iterator { return iterator(*this); } + auto end() const -> iterator { return { *this, m_strings.size() }; } + + inline friend std::ostream& operator << (std::ostream& os, Column const& col) { + bool first = true; + for (auto line : col) { + if (first) + first = false; + else + os << "\n"; + os << line; + } + return os; + } + + auto operator + (Column const& other)->Columns; + + auto toString() const -> std::string { + std::ostringstream oss; + oss << *this; + return oss.str(); + } +}; + +class Spacer : public Column { + +public: + explicit Spacer(size_t spaceWidth) : Column("") { + width(spaceWidth); + } +}; + +class Columns { + std::vector m_columns; + +public: + + class iterator { + friend Columns; + struct EndTag {}; + + std::vector const& m_columns; + std::vector m_iterators; + size_t m_activeIterators; + + iterator(Columns const& columns, EndTag) + : m_columns(columns.m_columns), + m_activeIterators(0) { + m_iterators.reserve(m_columns.size()); + + for (auto const& col : m_columns) + m_iterators.push_back(col.end()); + } + + public: + using difference_type = std::ptrdiff_t; + using value_type = std::string; + using pointer = value_type * ; + using reference = value_type & ; + using iterator_category = std::forward_iterator_tag; + + explicit iterator(Columns const& columns) + : m_columns(columns.m_columns), + m_activeIterators(m_columns.size()) { + m_iterators.reserve(m_columns.size()); + + for (auto const& col : m_columns) + m_iterators.push_back(col.begin()); + } + + auto operator ==(iterator const& other) const -> bool { + return m_iterators == other.m_iterators; + } + auto operator !=(iterator const& other) const -> bool { + return m_iterators != other.m_iterators; + } + auto operator *() const -> std::string { + std::string row, padding; + + for (size_t i = 0; i < m_columns.size(); ++i) { + auto width = m_columns[i].width(); + if (m_iterators[i] != m_columns[i].end()) { + std::string col = *m_iterators[i]; + row += padding + col; + if (col.size() < width) + padding = std::string(width - col.size(), ' '); + else + padding = ""; + } else { + padding += std::string(width, ' '); + } + } + return row; + } + auto operator ++() -> iterator& { + for (size_t i = 0; i < m_columns.size(); ++i) { + if (m_iterators[i] != m_columns[i].end()) + ++m_iterators[i]; + } + return *this; + } + auto operator ++(int) -> iterator { + iterator prev(*this); + operator++(); + return prev; + } + }; + using const_iterator = iterator; + + auto begin() const -> iterator { return iterator(*this); } + auto end() const -> iterator { return { *this, iterator::EndTag() }; } + + auto operator += (Column const& col) -> Columns& { + m_columns.push_back(col); + return *this; + } + auto operator + (Column const& col) -> Columns { + Columns combined = *this; + combined += col; + return combined; + } + + inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) { + + bool first = true; + for (auto line : cols) { + if (first) + first = false; + else + os << "\n"; + os << line; + } + return os; + } + + auto toString() const -> std::string { + std::ostringstream oss; + oss << *this; + return oss.str(); + } +}; + +inline auto Column::operator + (Column const& other) -> Columns { + Columns cols; + cols += *this; + cols += other; + return cols; +} +} + +} +} + +// ----------- end of #include from clara_textflow.hpp ----------- +// ........... back in clara.hpp + +#include +#include +#include +#include +#include + +#if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) ) +#define CATCH_PLATFORM_WINDOWS +#endif + +namespace Catch { namespace clara { +namespace detail { + + // Traits for extracting arg and return type of lambdas (for single argument lambdas) + template + struct UnaryLambdaTraits : UnaryLambdaTraits {}; + + template + struct UnaryLambdaTraits { + static const bool isValid = false; + }; + + template + struct UnaryLambdaTraits { + static const bool isValid = true; + using ArgType = typename std::remove_const::type>::type; + using ReturnType = ReturnT; + }; + + class TokenStream; + + // Transport for raw args (copied from main args, or supplied via init list for testing) + class Args { + friend TokenStream; + std::string m_exeName; + std::vector m_args; + + public: + Args( int argc, char const* const* argv ) + : m_exeName(argv[0]), + m_args(argv + 1, argv + argc) {} + + Args( std::initializer_list args ) + : m_exeName( *args.begin() ), + m_args( args.begin()+1, args.end() ) + {} + + auto exeName() const -> std::string { + return m_exeName; + } + }; + + // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string + // may encode an option + its argument if the : or = form is used + enum class TokenType { + Option, Argument + }; + struct Token { + TokenType type; + std::string token; + }; + + inline auto isOptPrefix( char c ) -> bool { + return c == '-' +#ifdef CATCH_PLATFORM_WINDOWS + || c == '/' +#endif + ; + } + + // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled + class TokenStream { + using Iterator = std::vector::const_iterator; + Iterator it; + Iterator itEnd; + std::vector m_tokenBuffer; + + void loadBuffer() { + m_tokenBuffer.resize( 0 ); + + // Skip any empty strings + while( it != itEnd && it->empty() ) + ++it; + + if( it != itEnd ) { + auto const &next = *it; + if( isOptPrefix( next[0] ) ) { + auto delimiterPos = next.find_first_of( " :=" ); + if( delimiterPos != std::string::npos ) { + m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } ); + m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } ); + } else { + if( next[1] != '-' && next.size() > 2 ) { + std::string opt = "- "; + for( size_t i = 1; i < next.size(); ++i ) { + opt[1] = next[i]; + m_tokenBuffer.push_back( { TokenType::Option, opt } ); + } + } else { + m_tokenBuffer.push_back( { TokenType::Option, next } ); + } + } + } else { + m_tokenBuffer.push_back( { TokenType::Argument, next } ); + } + } + } + + public: + explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {} + + TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) { + loadBuffer(); + } + + explicit operator bool() const { + return !m_tokenBuffer.empty() || it != itEnd; + } + + auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); } + + auto operator*() const -> Token { + assert( !m_tokenBuffer.empty() ); + return m_tokenBuffer.front(); + } + + auto operator->() const -> Token const * { + assert( !m_tokenBuffer.empty() ); + return &m_tokenBuffer.front(); + } + + auto operator++() -> TokenStream & { + if( m_tokenBuffer.size() >= 2 ) { + m_tokenBuffer.erase( m_tokenBuffer.begin() ); + } else { + if( it != itEnd ) + ++it; + loadBuffer(); + } + return *this; + } + }; + + class ResultBase { + public: + enum Type { + Ok, LogicError, RuntimeError + }; + + protected: + ResultBase( Type type ) : m_type( type ) {} + virtual ~ResultBase() = default; + + virtual void enforceOk() const = 0; + + Type m_type; + }; + + template + class ResultValueBase : public ResultBase { + public: + auto value() const -> T const & { + enforceOk(); + return m_value; + } + + protected: + ResultValueBase( Type type ) : ResultBase( type ) {} + + ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) { + if( m_type == ResultBase::Ok ) + new( &m_value ) T( other.m_value ); + } + + ResultValueBase( Type, T const &value ) : ResultBase( Ok ) { + new( &m_value ) T( value ); + } + + auto operator=( ResultValueBase const &other ) -> ResultValueBase & { + if( m_type == ResultBase::Ok ) + m_value.~T(); + ResultBase::operator=(other); + if( m_type == ResultBase::Ok ) + new( &m_value ) T( other.m_value ); + return *this; + } + + ~ResultValueBase() override { + if( m_type == Ok ) + m_value.~T(); + } + + union { + T m_value; + }; + }; + + template<> + class ResultValueBase : public ResultBase { + protected: + using ResultBase::ResultBase; + }; + + template + class BasicResult : public ResultValueBase { + public: + template + explicit BasicResult( BasicResult const &other ) + : ResultValueBase( other.type() ), + m_errorMessage( other.errorMessage() ) + { + assert( type() != ResultBase::Ok ); + } + + template + static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; } + static auto ok() -> BasicResult { return { ResultBase::Ok }; } + static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; } + static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; } + + explicit operator bool() const { return m_type == ResultBase::Ok; } + auto type() const -> ResultBase::Type { return m_type; } + auto errorMessage() const -> std::string { return m_errorMessage; } + + protected: + void enforceOk() const override { + + // Errors shouldn't reach this point, but if they do + // the actual error message will be in m_errorMessage + assert( m_type != ResultBase::LogicError ); + assert( m_type != ResultBase::RuntimeError ); + if( m_type != ResultBase::Ok ) + std::abort(); + } + + std::string m_errorMessage; // Only populated if resultType is an error + + BasicResult( ResultBase::Type type, std::string const &message ) + : ResultValueBase(type), + m_errorMessage(message) + { + assert( m_type != ResultBase::Ok ); + } + + using ResultValueBase::ResultValueBase; + using ResultBase::m_type; + }; + + enum class ParseResultType { + Matched, NoMatch, ShortCircuitAll, ShortCircuitSame + }; + + class ParseState { + public: + + ParseState( ParseResultType type, TokenStream const &remainingTokens ) + : m_type(type), + m_remainingTokens( remainingTokens ) + {} + + auto type() const -> ParseResultType { return m_type; } + auto remainingTokens() const -> TokenStream { return m_remainingTokens; } + + private: + ParseResultType m_type; + TokenStream m_remainingTokens; + }; + + using Result = BasicResult; + using ParserResult = BasicResult; + using InternalParseResult = BasicResult; + + struct HelpColumns { + std::string left; + std::string right; + }; + + template + inline auto convertInto( std::string const &source, T& target ) -> ParserResult { + std::stringstream ss; + ss << source; + ss >> target; + if( ss.fail() ) + return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" ); + else + return ParserResult::ok( ParseResultType::Matched ); + } + inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult { + target = source; + return ParserResult::ok( ParseResultType::Matched ); + } + inline auto convertInto( std::string const &source, bool &target ) -> ParserResult { + std::string srcLC = source; + std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast( std::tolower(c) ); } ); + if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on") + target = true; + else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off") + target = false; + else + return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" ); + return ParserResult::ok( ParseResultType::Matched ); + } +#ifdef CLARA_CONFIG_OPTIONAL_TYPE + template + inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE& target ) -> ParserResult { + T temp; + auto result = convertInto( source, temp ); + if( result ) + target = std::move(temp); + return result; + } +#endif // CLARA_CONFIG_OPTIONAL_TYPE + + struct NonCopyable { + NonCopyable() = default; + NonCopyable( NonCopyable const & ) = delete; + NonCopyable( NonCopyable && ) = delete; + NonCopyable &operator=( NonCopyable const & ) = delete; + NonCopyable &operator=( NonCopyable && ) = delete; + }; + + struct BoundRef : NonCopyable { + virtual ~BoundRef() = default; + virtual auto isContainer() const -> bool { return false; } + virtual auto isFlag() const -> bool { return false; } + }; + struct BoundValueRefBase : BoundRef { + virtual auto setValue( std::string const &arg ) -> ParserResult = 0; + }; + struct BoundFlagRefBase : BoundRef { + virtual auto setFlag( bool flag ) -> ParserResult = 0; + virtual auto isFlag() const -> bool { return true; } + }; + + template + struct BoundValueRef : BoundValueRefBase { + T &m_ref; + + explicit BoundValueRef( T &ref ) : m_ref( ref ) {} + + auto setValue( std::string const &arg ) -> ParserResult override { + return convertInto( arg, m_ref ); + } + }; + + template + struct BoundValueRef> : BoundValueRefBase { + std::vector &m_ref; + + explicit BoundValueRef( std::vector &ref ) : m_ref( ref ) {} + + auto isContainer() const -> bool override { return true; } + + auto setValue( std::string const &arg ) -> ParserResult override { + T temp; + auto result = convertInto( arg, temp ); + if( result ) + m_ref.push_back( temp ); + return result; + } + }; + + struct BoundFlagRef : BoundFlagRefBase { + bool &m_ref; + + explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {} + + auto setFlag( bool flag ) -> ParserResult override { + m_ref = flag; + return ParserResult::ok( ParseResultType::Matched ); + } + }; + + template + struct LambdaInvoker { + static_assert( std::is_same::value, "Lambda must return void or clara::ParserResult" ); + + template + static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult { + return lambda( arg ); + } + }; + + template<> + struct LambdaInvoker { + template + static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult { + lambda( arg ); + return ParserResult::ok( ParseResultType::Matched ); + } + }; + + template + inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult { + ArgType temp{}; + auto result = convertInto( arg, temp ); + return !result + ? result + : LambdaInvoker::ReturnType>::invoke( lambda, temp ); + } + + template + struct BoundLambda : BoundValueRefBase { + L m_lambda; + + static_assert( UnaryLambdaTraits::isValid, "Supplied lambda must take exactly one argument" ); + explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {} + + auto setValue( std::string const &arg ) -> ParserResult override { + return invokeLambda::ArgType>( m_lambda, arg ); + } + }; + + template + struct BoundFlagLambda : BoundFlagRefBase { + L m_lambda; + + static_assert( UnaryLambdaTraits::isValid, "Supplied lambda must take exactly one argument" ); + static_assert( std::is_same::ArgType, bool>::value, "flags must be boolean" ); + + explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {} + + auto setFlag( bool flag ) -> ParserResult override { + return LambdaInvoker::ReturnType>::invoke( m_lambda, flag ); + } + }; + + enum class Optionality { Optional, Required }; + + struct Parser; + + class ParserBase { + public: + virtual ~ParserBase() = default; + virtual auto validate() const -> Result { return Result::ok(); } + virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0; + virtual auto cardinality() const -> size_t { return 1; } + + auto parse( Args const &args ) const -> InternalParseResult { + return parse( args.exeName(), TokenStream( args ) ); + } + }; + + template + class ComposableParserImpl : public ParserBase { + public: + template + auto operator|( T const &other ) const -> Parser; + + template + auto operator+( T const &other ) const -> Parser; + }; + + // Common code and state for Args and Opts + template + class ParserRefImpl : public ComposableParserImpl { + protected: + Optionality m_optionality = Optionality::Optional; + std::shared_ptr m_ref; + std::string m_hint; + std::string m_description; + + explicit ParserRefImpl( std::shared_ptr const &ref ) : m_ref( ref ) {} + + public: + template + ParserRefImpl( T &ref, std::string const &hint ) + : m_ref( std::make_shared>( ref ) ), + m_hint( hint ) + {} + + template + ParserRefImpl( LambdaT const &ref, std::string const &hint ) + : m_ref( std::make_shared>( ref ) ), + m_hint(hint) + {} + + auto operator()( std::string const &description ) -> DerivedT & { + m_description = description; + return static_cast( *this ); + } + + auto optional() -> DerivedT & { + m_optionality = Optionality::Optional; + return static_cast( *this ); + }; + + auto required() -> DerivedT & { + m_optionality = Optionality::Required; + return static_cast( *this ); + }; + + auto isOptional() const -> bool { + return m_optionality == Optionality::Optional; + } + + auto cardinality() const -> size_t override { + if( m_ref->isContainer() ) + return 0; + else + return 1; + } + + auto hint() const -> std::string { return m_hint; } + }; + + class ExeName : public ComposableParserImpl { + std::shared_ptr m_name; + std::shared_ptr m_ref; + + template + static auto makeRef(LambdaT const &lambda) -> std::shared_ptr { + return std::make_shared>( lambda) ; + } + + public: + ExeName() : m_name( std::make_shared( "" ) ) {} + + explicit ExeName( std::string &ref ) : ExeName() { + m_ref = std::make_shared>( ref ); + } + + template + explicit ExeName( LambdaT const& lambda ) : ExeName() { + m_ref = std::make_shared>( lambda ); + } + + // The exe name is not parsed out of the normal tokens, but is handled specially + auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override { + return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) ); + } + + auto name() const -> std::string { return *m_name; } + auto set( std::string const& newName ) -> ParserResult { + + auto lastSlash = newName.find_last_of( "\\/" ); + auto filename = ( lastSlash == std::string::npos ) + ? newName + : newName.substr( lastSlash+1 ); + + *m_name = filename; + if( m_ref ) + return m_ref->setValue( filename ); + else + return ParserResult::ok( ParseResultType::Matched ); + } + }; + + class Arg : public ParserRefImpl { + public: + using ParserRefImpl::ParserRefImpl; + + auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override { + auto validationResult = validate(); + if( !validationResult ) + return InternalParseResult( validationResult ); + + auto remainingTokens = tokens; + auto const &token = *remainingTokens; + if( token.type != TokenType::Argument ) + return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) ); + + assert( !m_ref->isFlag() ); + auto valueRef = static_cast( m_ref.get() ); + + auto result = valueRef->setValue( remainingTokens->token ); + if( !result ) + return InternalParseResult( result ); + else + return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) ); + } + }; + + inline auto normaliseOpt( std::string const &optName ) -> std::string { +#ifdef CATCH_PLATFORM_WINDOWS + if( optName[0] == '/' ) + return "-" + optName.substr( 1 ); + else +#endif + return optName; + } + + class Opt : public ParserRefImpl { + protected: + std::vector m_optNames; + + public: + template + explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared>( ref ) ) {} + + explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared( ref ) ) {} + + template + Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {} + + template + Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {} + + auto operator[]( std::string const &optName ) -> Opt & { + m_optNames.push_back( optName ); + return *this; + } + + auto getHelpColumns() const -> std::vector { + std::ostringstream oss; + bool first = true; + for( auto const &opt : m_optNames ) { + if (first) + first = false; + else + oss << ", "; + oss << opt; + } + if( !m_hint.empty() ) + oss << " <" << m_hint << ">"; + return { { oss.str(), m_description } }; + } + + auto isMatch( std::string const &optToken ) const -> bool { + auto normalisedToken = normaliseOpt( optToken ); + for( auto const &name : m_optNames ) { + if( normaliseOpt( name ) == normalisedToken ) + return true; + } + return false; + } + + using ParserBase::parse; + + auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override { + auto validationResult = validate(); + if( !validationResult ) + return InternalParseResult( validationResult ); + + auto remainingTokens = tokens; + if( remainingTokens && remainingTokens->type == TokenType::Option ) { + auto const &token = *remainingTokens; + if( isMatch(token.token ) ) { + if( m_ref->isFlag() ) { + auto flagRef = static_cast( m_ref.get() ); + auto result = flagRef->setFlag( true ); + if( !result ) + return InternalParseResult( result ); + if( result.value() == ParseResultType::ShortCircuitAll ) + return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) ); + } else { + auto valueRef = static_cast( m_ref.get() ); + ++remainingTokens; + if( !remainingTokens ) + return InternalParseResult::runtimeError( "Expected argument following " + token.token ); + auto const &argToken = *remainingTokens; + if( argToken.type != TokenType::Argument ) + return InternalParseResult::runtimeError( "Expected argument following " + token.token ); + auto result = valueRef->setValue( argToken.token ); + if( !result ) + return InternalParseResult( result ); + if( result.value() == ParseResultType::ShortCircuitAll ) + return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) ); + } + return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) ); + } + } + return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) ); + } + + auto validate() const -> Result override { + if( m_optNames.empty() ) + return Result::logicError( "No options supplied to Opt" ); + for( auto const &name : m_optNames ) { + if( name.empty() ) + return Result::logicError( "Option name cannot be empty" ); +#ifdef CATCH_PLATFORM_WINDOWS + if( name[0] != '-' && name[0] != '/' ) + return Result::logicError( "Option name must begin with '-' or '/'" ); +#else + if( name[0] != '-' ) + return Result::logicError( "Option name must begin with '-'" ); +#endif + } + return ParserRefImpl::validate(); + } + }; + + struct Help : Opt { + Help( bool &showHelpFlag ) + : Opt([&]( bool flag ) { + showHelpFlag = flag; + return ParserResult::ok( ParseResultType::ShortCircuitAll ); + }) + { + static_cast( *this ) + ("display usage information") + ["-?"]["-h"]["--help"] + .optional(); + } + }; + + struct Parser : ParserBase { + + mutable ExeName m_exeName; + std::vector m_options; + std::vector m_args; + + auto operator|=( ExeName const &exeName ) -> Parser & { + m_exeName = exeName; + return *this; + } + + auto operator|=( Arg const &arg ) -> Parser & { + m_args.push_back(arg); + return *this; + } + + auto operator|=( Opt const &opt ) -> Parser & { + m_options.push_back(opt); + return *this; + } + + auto operator|=( Parser const &other ) -> Parser & { + m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end()); + m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end()); + return *this; + } + + template + auto operator|( T const &other ) const -> Parser { + return Parser( *this ) |= other; + } + + // Forward deprecated interface with '+' instead of '|' + template + auto operator+=( T const &other ) -> Parser & { return operator|=( other ); } + template + auto operator+( T const &other ) const -> Parser { return operator|( other ); } + + auto getHelpColumns() const -> std::vector { + std::vector cols; + for (auto const &o : m_options) { + auto childCols = o.getHelpColumns(); + cols.insert( cols.end(), childCols.begin(), childCols.end() ); + } + return cols; + } + + void writeToStream( std::ostream &os ) const { + if (!m_exeName.name().empty()) { + os << "usage:\n" << " " << m_exeName.name() << " "; + bool required = true, first = true; + for( auto const &arg : m_args ) { + if (first) + first = false; + else + os << " "; + if( arg.isOptional() && required ) { + os << "["; + required = false; + } + os << "<" << arg.hint() << ">"; + if( arg.cardinality() == 0 ) + os << " ... "; + } + if( !required ) + os << "]"; + if( !m_options.empty() ) + os << " options"; + os << "\n\nwhere options are:" << std::endl; + } + + auto rows = getHelpColumns(); + size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH; + size_t optWidth = 0; + for( auto const &cols : rows ) + optWidth = (std::max)(optWidth, cols.left.size() + 2); + + optWidth = (std::min)(optWidth, consoleWidth/2); + + for( auto const &cols : rows ) { + auto row = + TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) + + TextFlow::Spacer(4) + + TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth ); + os << row << std::endl; + } + } + + friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& { + parser.writeToStream( os ); + return os; + } + + auto validate() const -> Result override { + for( auto const &opt : m_options ) { + auto result = opt.validate(); + if( !result ) + return result; + } + for( auto const &arg : m_args ) { + auto result = arg.validate(); + if( !result ) + return result; + } + return Result::ok(); + } + + using ParserBase::parse; + + auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override { + + struct ParserInfo { + ParserBase const* parser = nullptr; + size_t count = 0; + }; + const size_t totalParsers = m_options.size() + m_args.size(); + assert( totalParsers < 512 ); + // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do + ParserInfo parseInfos[512]; + + { + size_t i = 0; + for (auto const &opt : m_options) parseInfos[i++].parser = &opt; + for (auto const &arg : m_args) parseInfos[i++].parser = &arg; + } + + m_exeName.set( exeName ); + + auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) ); + while( result.value().remainingTokens() ) { + bool tokenParsed = false; + + for( size_t i = 0; i < totalParsers; ++i ) { + auto& parseInfo = parseInfos[i]; + if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) { + result = parseInfo.parser->parse(exeName, result.value().remainingTokens()); + if (!result) + return result; + if (result.value().type() != ParseResultType::NoMatch) { + tokenParsed = true; + ++parseInfo.count; + break; + } + } + } + + if( result.value().type() == ParseResultType::ShortCircuitAll ) + return result; + if( !tokenParsed ) + return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token ); + } + // !TBD Check missing required options + return result; + } + }; + + template + template + auto ComposableParserImpl::operator|( T const &other ) const -> Parser { + return Parser() | static_cast( *this ) | other; + } +} // namespace detail + +// A Combined parser +using detail::Parser; + +// A parser for options +using detail::Opt; + +// A parser for arguments +using detail::Arg; + +// Wrapper for argc, argv from main() +using detail::Args; + +// Specifies the name of the executable +using detail::ExeName; + +// Convenience wrapper for option parser that specifies the help option +using detail::Help; + +// enum of result types from a parse +using detail::ParseResultType; + +// Result type for parser operation +using detail::ParserResult; + +}} // namespace Catch::clara + +// end clara.hpp +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +// Restore Clara's value for console width, if present +#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH +#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH +#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH +#endif + +// end catch_clara.h +namespace Catch { + + clara::Parser makeCommandLineParser( ConfigData& config ); + +} // end namespace Catch + +// end catch_commandline.h +#include +#include + +namespace Catch { + + clara::Parser makeCommandLineParser( ConfigData& config ) { + + using namespace clara; + + auto const setWarning = [&]( std::string const& warning ) { + auto warningSet = [&]() { + if( warning == "NoAssertions" ) + return WarnAbout::NoAssertions; + + if ( warning == "NoTests" ) + return WarnAbout::NoTests; + + return WarnAbout::Nothing; + }(); + + if (warningSet == WarnAbout::Nothing) + return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" ); + config.warnings = static_cast( config.warnings | warningSet ); + return ParserResult::ok( ParseResultType::Matched ); + }; + auto const loadTestNamesFromFile = [&]( std::string const& filename ) { + std::ifstream f( filename.c_str() ); + if( !f.is_open() ) + return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" ); + + std::string line; + while( std::getline( f, line ) ) { + line = trim(line); + if( !line.empty() && !startsWith( line, '#' ) ) { + if( !startsWith( line, '"' ) ) + line = '"' + line + '"'; + config.testsOrTags.push_back( line + ',' ); + } + } + return ParserResult::ok( ParseResultType::Matched ); + }; + auto const setTestOrder = [&]( std::string const& order ) { + if( startsWith( "declared", order ) ) + config.runOrder = RunTests::InDeclarationOrder; + else if( startsWith( "lexical", order ) ) + config.runOrder = RunTests::InLexicographicalOrder; + else if( startsWith( "random", order ) ) + config.runOrder = RunTests::InRandomOrder; + else + return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" ); + return ParserResult::ok( ParseResultType::Matched ); + }; + auto const setRngSeed = [&]( std::string const& seed ) { + if( seed != "time" ) + return clara::detail::convertInto( seed, config.rngSeed ); + config.rngSeed = static_cast( std::time(nullptr) ); + return ParserResult::ok( ParseResultType::Matched ); + }; + auto const setColourUsage = [&]( std::string const& useColour ) { + auto mode = toLower( useColour ); + + if( mode == "yes" ) + config.useColour = UseColour::Yes; + else if( mode == "no" ) + config.useColour = UseColour::No; + else if( mode == "auto" ) + config.useColour = UseColour::Auto; + else + return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" ); + return ParserResult::ok( ParseResultType::Matched ); + }; + auto const setWaitForKeypress = [&]( std::string const& keypress ) { + auto keypressLc = toLower( keypress ); + if( keypressLc == "start" ) + config.waitForKeypress = WaitForKeypress::BeforeStart; + else if( keypressLc == "exit" ) + config.waitForKeypress = WaitForKeypress::BeforeExit; + else if( keypressLc == "both" ) + config.waitForKeypress = WaitForKeypress::BeforeStartAndExit; + else + return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" ); + return ParserResult::ok( ParseResultType::Matched ); + }; + auto const setVerbosity = [&]( std::string const& verbosity ) { + auto lcVerbosity = toLower( verbosity ); + if( lcVerbosity == "quiet" ) + config.verbosity = Verbosity::Quiet; + else if( lcVerbosity == "normal" ) + config.verbosity = Verbosity::Normal; + else if( lcVerbosity == "high" ) + config.verbosity = Verbosity::High; + else + return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" ); + return ParserResult::ok( ParseResultType::Matched ); + }; + auto const setReporter = [&]( std::string const& reporter ) { + IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); + + auto lcReporter = toLower( reporter ); + auto result = factories.find( lcReporter ); + + if( factories.end() != result ) + config.reporterName = lcReporter; + else + return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" ); + return ParserResult::ok( ParseResultType::Matched ); + }; + + auto cli + = ExeName( config.processName ) + | Help( config.showHelp ) + | Opt( config.listTests ) + ["-l"]["--list-tests"] + ( "list all/matching test cases" ) + | Opt( config.listTags ) + ["-t"]["--list-tags"] + ( "list all/matching tags" ) + | Opt( config.showSuccessfulTests ) + ["-s"]["--success"] + ( "include successful tests in output" ) + | Opt( config.shouldDebugBreak ) + ["-b"]["--break"] + ( "break into debugger on failure" ) + | Opt( config.noThrow ) + ["-e"]["--nothrow"] + ( "skip exception tests" ) + | Opt( config.showInvisibles ) + ["-i"]["--invisibles"] + ( "show invisibles (tabs, newlines)" ) + | Opt( config.outputFilename, "filename" ) + ["-o"]["--out"] + ( "output filename" ) + | Opt( setReporter, "name" ) + ["-r"]["--reporter"] + ( "reporter to use (defaults to console)" ) + | Opt( config.name, "name" ) + ["-n"]["--name"] + ( "suite name" ) + | Opt( [&]( bool ){ config.abortAfter = 1; } ) + ["-a"]["--abort"] + ( "abort at first failure" ) + | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" ) + ["-x"]["--abortx"] + ( "abort after x failures" ) + | Opt( setWarning, "warning name" ) + ["-w"]["--warn"] + ( "enable warnings" ) + | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" ) + ["-d"]["--durations"] + ( "show test durations" ) + | Opt( loadTestNamesFromFile, "filename" ) + ["-f"]["--input-file"] + ( "load test names to run from a file" ) + | Opt( config.filenamesAsTags ) + ["-#"]["--filenames-as-tags"] + ( "adds a tag for the filename" ) + | Opt( config.sectionsToRun, "section name" ) + ["-c"]["--section"] + ( "specify section to run" ) + | Opt( setVerbosity, "quiet|normal|high" ) + ["-v"]["--verbosity"] + ( "set output verbosity" ) + | Opt( config.listTestNamesOnly ) + ["--list-test-names-only"] + ( "list all/matching test cases names only" ) + | Opt( config.listReporters ) + ["--list-reporters"] + ( "list all reporters" ) + | Opt( setTestOrder, "decl|lex|rand" ) + ["--order"] + ( "test case order (defaults to decl)" ) + | Opt( setRngSeed, "'time'|number" ) + ["--rng-seed"] + ( "set a specific seed for random numbers" ) + | Opt( setColourUsage, "yes|no" ) + ["--use-colour"] + ( "should output be colourised" ) + | Opt( config.libIdentify ) + ["--libidentify"] + ( "report name and version according to libidentify standard" ) + | Opt( setWaitForKeypress, "start|exit|both" ) + ["--wait-for-keypress"] + ( "waits for a keypress before exiting" ) + | Opt( config.benchmarkResolutionMultiple, "multiplier" ) + ["--benchmark-resolution-multiple"] + ( "multiple of clock resolution to run benchmarks" ) + + | Arg( config.testsOrTags, "test name|pattern|tags" ) + ( "which test or tests to use" ); + + return cli; + } + +} // end namespace Catch +// end catch_commandline.cpp +// start catch_common.cpp + +#include +#include + +namespace Catch { + + bool SourceLineInfo::empty() const noexcept { + return file[0] == '\0'; + } + bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept { + return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0); + } + bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept { + // We can assume that the same file will usually have the same pointer. + // Thus, if the pointers are the same, there is no point in calling the strcmp + return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0)); + } + + std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) { +#ifndef __GNUG__ + os << info.file << '(' << info.line << ')'; +#else + os << info.file << ':' << info.line; +#endif + return os; + } + + std::string StreamEndStop::operator+() const { + return std::string(); + } + + NonCopyable::NonCopyable() = default; + NonCopyable::~NonCopyable() = default; + +} +// end catch_common.cpp +// start catch_config.cpp + +namespace Catch { + + Config::Config( ConfigData const& data ) + : m_data( data ), + m_stream( openStream() ) + { + TestSpecParser parser(ITagAliasRegistry::get()); + if (data.testsOrTags.empty()) { + parser.parse("~[.]"); // All not hidden tests + } + else { + m_hasTestFilters = true; + for( auto const& testOrTags : data.testsOrTags ) + parser.parse( testOrTags ); + } + m_testSpec = parser.testSpec(); + } + + std::string const& Config::getFilename() const { + return m_data.outputFilename ; + } + + bool Config::listTests() const { return m_data.listTests; } + bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; } + bool Config::listTags() const { return m_data.listTags; } + bool Config::listReporters() const { return m_data.listReporters; } + + std::string Config::getProcessName() const { return m_data.processName; } + std::string const& Config::getReporterName() const { return m_data.reporterName; } + + std::vector const& Config::getTestsOrTags() const { return m_data.testsOrTags; } + std::vector const& Config::getSectionsToRun() const { return m_data.sectionsToRun; } + + TestSpec const& Config::testSpec() const { return m_testSpec; } + bool Config::hasTestFilters() const { return m_hasTestFilters; } + + bool Config::showHelp() const { return m_data.showHelp; } + + // IConfig interface + bool Config::allowThrows() const { return !m_data.noThrow; } + std::ostream& Config::stream() const { return m_stream->stream(); } + std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; } + bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; } + bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); } + bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); } + ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; } + RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; } + unsigned int Config::rngSeed() const { return m_data.rngSeed; } + int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; } + UseColour::YesOrNo Config::useColour() const { return m_data.useColour; } + bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; } + int Config::abortAfter() const { return m_data.abortAfter; } + bool Config::showInvisibles() const { return m_data.showInvisibles; } + Verbosity Config::verbosity() const { return m_data.verbosity; } + + IStream const* Config::openStream() { + return Catch::makeStream(m_data.outputFilename); + } + +} // end namespace Catch +// end catch_config.cpp +// start catch_console_colour.cpp + +#if defined(__clang__) +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wexit-time-destructors" +#endif + +// start catch_errno_guard.h + +namespace Catch { + + class ErrnoGuard { + public: + ErrnoGuard(); + ~ErrnoGuard(); + private: + int m_oldErrno; + }; + +} + +// end catch_errno_guard.h +#include + +namespace Catch { + namespace { + + struct IColourImpl { + virtual ~IColourImpl() = default; + virtual void use( Colour::Code _colourCode ) = 0; + }; + + struct NoColourImpl : IColourImpl { + void use( Colour::Code ) {} + + static IColourImpl* instance() { + static NoColourImpl s_instance; + return &s_instance; + } + }; + + } // anon namespace +} // namespace Catch + +#if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI ) +# ifdef CATCH_PLATFORM_WINDOWS +# define CATCH_CONFIG_COLOUR_WINDOWS +# else +# define CATCH_CONFIG_COLOUR_ANSI +# endif +#endif + +#if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) ///////////////////////////////////////// + +namespace Catch { +namespace { + + class Win32ColourImpl : public IColourImpl { + public: + Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) ) + { + CONSOLE_SCREEN_BUFFER_INFO csbiInfo; + GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo ); + originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY ); + originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY ); + } + + virtual void use( Colour::Code _colourCode ) override { + switch( _colourCode ) { + case Colour::None: return setTextAttribute( originalForegroundAttributes ); + case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); + case Colour::Red: return setTextAttribute( FOREGROUND_RED ); + case Colour::Green: return setTextAttribute( FOREGROUND_GREEN ); + case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE ); + case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN ); + case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN ); + case Colour::Grey: return setTextAttribute( 0 ); + + case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY ); + case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED ); + case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN ); + case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); + case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN ); + + case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" ); + + default: + CATCH_ERROR( "Unknown colour requested" ); + } + } + + private: + void setTextAttribute( WORD _textAttribute ) { + SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes ); + } + HANDLE stdoutHandle; + WORD originalForegroundAttributes; + WORD originalBackgroundAttributes; + }; + + IColourImpl* platformColourInstance() { + static Win32ColourImpl s_instance; + + IConfigPtr config = getCurrentContext().getConfig(); + UseColour::YesOrNo colourMode = config + ? config->useColour() + : UseColour::Auto; + if( colourMode == UseColour::Auto ) + colourMode = UseColour::Yes; + return colourMode == UseColour::Yes + ? &s_instance + : NoColourImpl::instance(); + } + +} // end anon namespace +} // end namespace Catch + +#elif defined( CATCH_CONFIG_COLOUR_ANSI ) ////////////////////////////////////// + +#include + +namespace Catch { +namespace { + + // use POSIX/ ANSI console terminal codes + // Thanks to Adam Strzelecki for original contribution + // (http://github.com/nanoant) + // https://github.com/philsquared/Catch/pull/131 + class PosixColourImpl : public IColourImpl { + public: + virtual void use( Colour::Code _colourCode ) override { + switch( _colourCode ) { + case Colour::None: + case Colour::White: return setColour( "[0m" ); + case Colour::Red: return setColour( "[0;31m" ); + case Colour::Green: return setColour( "[0;32m" ); + case Colour::Blue: return setColour( "[0;34m" ); + case Colour::Cyan: return setColour( "[0;36m" ); + case Colour::Yellow: return setColour( "[0;33m" ); + case Colour::Grey: return setColour( "[1;30m" ); + + case Colour::LightGrey: return setColour( "[0;37m" ); + case Colour::BrightRed: return setColour( "[1;31m" ); + case Colour::BrightGreen: return setColour( "[1;32m" ); + case Colour::BrightWhite: return setColour( "[1;37m" ); + case Colour::BrightYellow: return setColour( "[1;33m" ); + + case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" ); + default: CATCH_INTERNAL_ERROR( "Unknown colour requested" ); + } + } + static IColourImpl* instance() { + static PosixColourImpl s_instance; + return &s_instance; + } + + private: + void setColour( const char* _escapeCode ) { + getCurrentContext().getConfig()->stream() + << '\033' << _escapeCode; + } + }; + + bool useColourOnPlatform() { + return +#ifdef CATCH_PLATFORM_MAC + !isDebuggerActive() && +#endif +#if !(defined(__DJGPP__) && defined(__STRICT_ANSI__)) + isatty(STDOUT_FILENO) +#else + false +#endif + ; + } + IColourImpl* platformColourInstance() { + ErrnoGuard guard; + IConfigPtr config = getCurrentContext().getConfig(); + UseColour::YesOrNo colourMode = config + ? config->useColour() + : UseColour::Auto; + if( colourMode == UseColour::Auto ) + colourMode = useColourOnPlatform() + ? UseColour::Yes + : UseColour::No; + return colourMode == UseColour::Yes + ? PosixColourImpl::instance() + : NoColourImpl::instance(); + } + +} // end anon namespace +} // end namespace Catch + +#else // not Windows or ANSI /////////////////////////////////////////////// + +namespace Catch { + + static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); } + +} // end namespace Catch + +#endif // Windows/ ANSI/ None + +namespace Catch { + + Colour::Colour( Code _colourCode ) { use( _colourCode ); } + Colour::Colour( Colour&& rhs ) noexcept { + m_moved = rhs.m_moved; + rhs.m_moved = true; + } + Colour& Colour::operator=( Colour&& rhs ) noexcept { + m_moved = rhs.m_moved; + rhs.m_moved = true; + return *this; + } + + Colour::~Colour(){ if( !m_moved ) use( None ); } + + void Colour::use( Code _colourCode ) { + static IColourImpl* impl = platformColourInstance(); + impl->use( _colourCode ); + } + + std::ostream& operator << ( std::ostream& os, Colour const& ) { + return os; + } + +} // end namespace Catch + +#if defined(__clang__) +# pragma clang diagnostic pop +#endif + +// end catch_console_colour.cpp +// start catch_context.cpp + +namespace Catch { + + class Context : public IMutableContext, NonCopyable { + + public: // IContext + virtual IResultCapture* getResultCapture() override { + return m_resultCapture; + } + virtual IRunner* getRunner() override { + return m_runner; + } + + virtual IConfigPtr const& getConfig() const override { + return m_config; + } + + virtual ~Context() override; + + public: // IMutableContext + virtual void setResultCapture( IResultCapture* resultCapture ) override { + m_resultCapture = resultCapture; + } + virtual void setRunner( IRunner* runner ) override { + m_runner = runner; + } + virtual void setConfig( IConfigPtr const& config ) override { + m_config = config; + } + + friend IMutableContext& getCurrentMutableContext(); + + private: + IConfigPtr m_config; + IRunner* m_runner = nullptr; + IResultCapture* m_resultCapture = nullptr; + }; + + IMutableContext *IMutableContext::currentContext = nullptr; + + void IMutableContext::createContext() + { + currentContext = new Context(); + } + + void cleanUpContext() { + delete IMutableContext::currentContext; + IMutableContext::currentContext = nullptr; + } + IContext::~IContext() = default; + IMutableContext::~IMutableContext() = default; + Context::~Context() = default; +} +// end catch_context.cpp +// start catch_debug_console.cpp + +// start catch_debug_console.h + +#include + +namespace Catch { + void writeToDebugConsole( std::string const& text ); +} + +// end catch_debug_console.h +#ifdef CATCH_PLATFORM_WINDOWS + + namespace Catch { + void writeToDebugConsole( std::string const& text ) { + ::OutputDebugStringA( text.c_str() ); + } + } + +#else + + namespace Catch { + void writeToDebugConsole( std::string const& text ) { + // !TBD: Need a version for Mac/ XCode and other IDEs + Catch::cout() << text; + } + } + +#endif // Platform +// end catch_debug_console.cpp +// start catch_debugger.cpp + +#ifdef CATCH_PLATFORM_MAC + +# include +# include +# include +# include +# include +# include +# include + +namespace Catch { + + // The following function is taken directly from the following technical note: + // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html + + // Returns true if the current process is being debugged (either + // running under the debugger or has a debugger attached post facto). + bool isDebuggerActive(){ + + int mib[4]; + struct kinfo_proc info; + std::size_t size; + + // Initialize the flags so that, if sysctl fails for some bizarre + // reason, we get a predictable result. + + info.kp_proc.p_flag = 0; + + // Initialize mib, which tells sysctl the info we want, in this case + // we're looking for information about a specific process ID. + + mib[0] = CTL_KERN; + mib[1] = KERN_PROC; + mib[2] = KERN_PROC_PID; + mib[3] = getpid(); + + // Call sysctl. + + size = sizeof(info); + if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) { + Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl; + return false; + } + + // We're being debugged if the P_TRACED flag is set. + + return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); + } + } // namespace Catch + +#elif defined(CATCH_PLATFORM_LINUX) + #include + #include + + namespace Catch{ + // The standard POSIX way of detecting a debugger is to attempt to + // ptrace() the process, but this needs to be done from a child and not + // this process itself to still allow attaching to this process later + // if wanted, so is rather heavy. Under Linux we have the PID of the + // "debugger" (which doesn't need to be gdb, of course, it could also + // be strace, for example) in /proc/$PID/status, so just get it from + // there instead. + bool isDebuggerActive(){ + // Libstdc++ has a bug, where std::ifstream sets errno to 0 + // This way our users can properly assert over errno values + ErrnoGuard guard; + std::ifstream in("/proc/self/status"); + for( std::string line; std::getline(in, line); ) { + static const int PREFIX_LEN = 11; + if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) { + // We're traced if the PID is not 0 and no other PID starts + // with 0 digit, so it's enough to check for just a single + // character. + return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0'; + } + } + + return false; + } + } // namespace Catch +#elif defined(_MSC_VER) + extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); + namespace Catch { + bool isDebuggerActive() { + return IsDebuggerPresent() != 0; + } + } +#elif defined(__MINGW32__) + extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent(); + namespace Catch { + bool isDebuggerActive() { + return IsDebuggerPresent() != 0; + } + } +#else + namespace Catch { + bool isDebuggerActive() { return false; } + } +#endif // Platform +// end catch_debugger.cpp +// start catch_decomposer.cpp + +namespace Catch { + + ITransientExpression::~ITransientExpression() = default; + + void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) { + if( lhs.size() + rhs.size() < 40 && + lhs.find('\n') == std::string::npos && + rhs.find('\n') == std::string::npos ) + os << lhs << " " << op << " " << rhs; + else + os << lhs << "\n" << op << "\n" << rhs; + } +} +// end catch_decomposer.cpp +// start catch_enforce.cpp + +namespace Catch { +#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER) + [[noreturn]] + void throw_exception(std::exception const& e) { + Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n" + << "The message was: " << e.what() << '\n'; + std::terminate(); + } +#endif +} // namespace Catch; +// end catch_enforce.cpp +// start catch_errno_guard.cpp + +#include + +namespace Catch { + ErrnoGuard::ErrnoGuard():m_oldErrno(errno){} + ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; } +} +// end catch_errno_guard.cpp +// start catch_exception_translator_registry.cpp + +// start catch_exception_translator_registry.h + +#include +#include +#include + +namespace Catch { + + class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry { + public: + ~ExceptionTranslatorRegistry(); + virtual void registerTranslator( const IExceptionTranslator* translator ); + virtual std::string translateActiveException() const override; + std::string tryTranslators() const; + + private: + std::vector> m_translators; + }; +} + +// end catch_exception_translator_registry.h +#ifdef __OBJC__ +#import "Foundation/Foundation.h" +#endif + +namespace Catch { + + ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() { + } + + void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) { + m_translators.push_back( std::unique_ptr( translator ) ); + } + +#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) + std::string ExceptionTranslatorRegistry::translateActiveException() const { + try { +#ifdef __OBJC__ + // In Objective-C try objective-c exceptions first + @try { + return tryTranslators(); + } + @catch (NSException *exception) { + return Catch::Detail::stringify( [exception description] ); + } +#else + // Compiling a mixed mode project with MSVC means that CLR + // exceptions will be caught in (...) as well. However, these + // do not fill-in std::current_exception and thus lead to crash + // when attempting rethrow. + // /EHa switch also causes structured exceptions to be caught + // here, but they fill-in current_exception properly, so + // at worst the output should be a little weird, instead of + // causing a crash. + if (std::current_exception() == nullptr) { + return "Non C++ exception. Possibly a CLR exception."; + } + return tryTranslators(); +#endif + } + catch( TestFailureException& ) { + std::rethrow_exception(std::current_exception()); + } + catch( std::exception& ex ) { + return ex.what(); + } + catch( std::string& msg ) { + return msg; + } + catch( const char* msg ) { + return msg; + } + catch(...) { + return "Unknown exception"; + } + } + + std::string ExceptionTranslatorRegistry::tryTranslators() const { + if (m_translators.empty()) { + std::rethrow_exception(std::current_exception()); + } else { + return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end()); + } + } + +#else // ^^ Exceptions are enabled // Exceptions are disabled vv + std::string ExceptionTranslatorRegistry::translateActiveException() const { + CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!"); + } + + std::string ExceptionTranslatorRegistry::tryTranslators() const { + CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!"); + } +#endif + +} +// end catch_exception_translator_registry.cpp +// start catch_fatal_condition.cpp + +#if defined(__GNUC__) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif + +#if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS ) + +namespace { + // Report the error condition + void reportFatal( char const * const message ) { + Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message ); + } +} + +#endif // signals/SEH handling + +#if defined( CATCH_CONFIG_WINDOWS_SEH ) + +namespace Catch { + struct SignalDefs { DWORD id; const char* name; }; + + // There is no 1-1 mapping between signals and windows exceptions. + // Windows can easily distinguish between SO and SigSegV, + // but SigInt, SigTerm, etc are handled differently. + static SignalDefs signalDefs[] = { + { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" }, + { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" }, + { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" }, + { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" }, + }; + + LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) { + for (auto const& def : signalDefs) { + if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) { + reportFatal(def.name); + } + } + // If its not an exception we care about, pass it along. + // This stops us from eating debugger breaks etc. + return EXCEPTION_CONTINUE_SEARCH; + } + + FatalConditionHandler::FatalConditionHandler() { + isSet = true; + // 32k seems enough for Catch to handle stack overflow, + // but the value was found experimentally, so there is no strong guarantee + guaranteeSize = 32 * 1024; + exceptionHandlerHandle = nullptr; + // Register as first handler in current chain + exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException); + // Pass in guarantee size to be filled + SetThreadStackGuarantee(&guaranteeSize); + } + + void FatalConditionHandler::reset() { + if (isSet) { + RemoveVectoredExceptionHandler(exceptionHandlerHandle); + SetThreadStackGuarantee(&guaranteeSize); + exceptionHandlerHandle = nullptr; + isSet = false; + } + } + + FatalConditionHandler::~FatalConditionHandler() { + reset(); + } + +bool FatalConditionHandler::isSet = false; +ULONG FatalConditionHandler::guaranteeSize = 0; +PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr; + +} // namespace Catch + +#elif defined( CATCH_CONFIG_POSIX_SIGNALS ) + +namespace Catch { + + struct SignalDefs { + int id; + const char* name; + }; + + // 32kb for the alternate stack seems to be sufficient. However, this value + // is experimentally determined, so that's not guaranteed. + constexpr static std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ; + + static SignalDefs signalDefs[] = { + { SIGINT, "SIGINT - Terminal interrupt signal" }, + { SIGILL, "SIGILL - Illegal instruction signal" }, + { SIGFPE, "SIGFPE - Floating point error signal" }, + { SIGSEGV, "SIGSEGV - Segmentation violation signal" }, + { SIGTERM, "SIGTERM - Termination request signal" }, + { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" } + }; + + void FatalConditionHandler::handleSignal( int sig ) { + char const * name = ""; + for (auto const& def : signalDefs) { + if (sig == def.id) { + name = def.name; + break; + } + } + reset(); + reportFatal(name); + raise( sig ); + } + + FatalConditionHandler::FatalConditionHandler() { + isSet = true; + stack_t sigStack; + sigStack.ss_sp = altStackMem; + sigStack.ss_size = sigStackSize; + sigStack.ss_flags = 0; + sigaltstack(&sigStack, &oldSigStack); + struct sigaction sa = { }; + + sa.sa_handler = handleSignal; + sa.sa_flags = SA_ONSTACK; + for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) { + sigaction(signalDefs[i].id, &sa, &oldSigActions[i]); + } + } + + FatalConditionHandler::~FatalConditionHandler() { + reset(); + } + + void FatalConditionHandler::reset() { + if( isSet ) { + // Set signals back to previous values -- hopefully nobody overwrote them in the meantime + for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) { + sigaction(signalDefs[i].id, &oldSigActions[i], nullptr); + } + // Return the old stack + sigaltstack(&oldSigStack, nullptr); + isSet = false; + } + } + + bool FatalConditionHandler::isSet = false; + struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {}; + stack_t FatalConditionHandler::oldSigStack = {}; + char FatalConditionHandler::altStackMem[sigStackSize] = {}; + +} // namespace Catch + +#else + +namespace Catch { + void FatalConditionHandler::reset() {} +} + +#endif // signals/SEH handling + +#if defined(__GNUC__) +# pragma GCC diagnostic pop +#endif +// end catch_fatal_condition.cpp +// start catch_generators.cpp + +// start catch_random_number_generator.h + +#include +#include + +namespace Catch { + + struct IConfig; + + std::mt19937& rng(); + void seedRng( IConfig const& config ); + unsigned int rngSeed(); + +} + +// end catch_random_number_generator.h +#include +#include + +namespace Catch { + +IGeneratorTracker::~IGeneratorTracker() {} + +const char* GeneratorException::what() const noexcept { + return m_msg; +} + +namespace Generators { + + GeneratorUntypedBase::~GeneratorUntypedBase() {} + + auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& { + return getResultCapture().acquireGeneratorTracker( lineInfo ); + } + +} // namespace Generators +} // namespace Catch +// end catch_generators.cpp +// start catch_interfaces_capture.cpp + +namespace Catch { + IResultCapture::~IResultCapture() = default; +} +// end catch_interfaces_capture.cpp +// start catch_interfaces_config.cpp + +namespace Catch { + IConfig::~IConfig() = default; +} +// end catch_interfaces_config.cpp +// start catch_interfaces_exception.cpp + +namespace Catch { + IExceptionTranslator::~IExceptionTranslator() = default; + IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default; +} +// end catch_interfaces_exception.cpp +// start catch_interfaces_registry_hub.cpp + +namespace Catch { + IRegistryHub::~IRegistryHub() = default; + IMutableRegistryHub::~IMutableRegistryHub() = default; +} +// end catch_interfaces_registry_hub.cpp +// start catch_interfaces_reporter.cpp + +// start catch_reporter_listening.h + +namespace Catch { + + class ListeningReporter : public IStreamingReporter { + using Reporters = std::vector; + Reporters m_listeners; + IStreamingReporterPtr m_reporter = nullptr; + ReporterPreferences m_preferences; + + public: + ListeningReporter(); + + void addListener( IStreamingReporterPtr&& listener ); + void addReporter( IStreamingReporterPtr&& reporter ); + + public: // IStreamingReporter + + ReporterPreferences getPreferences() const override; + + void noMatchingTestCases( std::string const& spec ) override; + + static std::set getSupportedVerbosities(); + + void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override; + void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override; + + void testRunStarting( TestRunInfo const& testRunInfo ) override; + void testGroupStarting( GroupInfo const& groupInfo ) override; + void testCaseStarting( TestCaseInfo const& testInfo ) override; + void sectionStarting( SectionInfo const& sectionInfo ) override; + void assertionStarting( AssertionInfo const& assertionInfo ) override; + + // The return value indicates if the messages buffer should be cleared: + bool assertionEnded( AssertionStats const& assertionStats ) override; + void sectionEnded( SectionStats const& sectionStats ) override; + void testCaseEnded( TestCaseStats const& testCaseStats ) override; + void testGroupEnded( TestGroupStats const& testGroupStats ) override; + void testRunEnded( TestRunStats const& testRunStats ) override; + + void skipTest( TestCaseInfo const& testInfo ) override; + bool isMulti() const override; + + }; + +} // end namespace Catch + +// end catch_reporter_listening.h +namespace Catch { + + ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig ) + : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {} + + ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream ) + : m_stream( &_stream ), m_fullConfig( _fullConfig ) {} + + std::ostream& ReporterConfig::stream() const { return *m_stream; } + IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; } + + TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {} + + GroupInfo::GroupInfo( std::string const& _name, + std::size_t _groupIndex, + std::size_t _groupsCount ) + : name( _name ), + groupIndex( _groupIndex ), + groupsCounts( _groupsCount ) + {} + + AssertionStats::AssertionStats( AssertionResult const& _assertionResult, + std::vector const& _infoMessages, + Totals const& _totals ) + : assertionResult( _assertionResult ), + infoMessages( _infoMessages ), + totals( _totals ) + { + assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression; + + if( assertionResult.hasMessage() ) { + // Copy message into messages list. + // !TBD This should have been done earlier, somewhere + MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() ); + builder << assertionResult.getMessage(); + builder.m_info.message = builder.m_stream.str(); + + infoMessages.push_back( builder.m_info ); + } + } + + AssertionStats::~AssertionStats() = default; + + SectionStats::SectionStats( SectionInfo const& _sectionInfo, + Counts const& _assertions, + double _durationInSeconds, + bool _missingAssertions ) + : sectionInfo( _sectionInfo ), + assertions( _assertions ), + durationInSeconds( _durationInSeconds ), + missingAssertions( _missingAssertions ) + {} + + SectionStats::~SectionStats() = default; + + TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo, + Totals const& _totals, + std::string const& _stdOut, + std::string const& _stdErr, + bool _aborting ) + : testInfo( _testInfo ), + totals( _totals ), + stdOut( _stdOut ), + stdErr( _stdErr ), + aborting( _aborting ) + {} + + TestCaseStats::~TestCaseStats() = default; + + TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo, + Totals const& _totals, + bool _aborting ) + : groupInfo( _groupInfo ), + totals( _totals ), + aborting( _aborting ) + {} + + TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo ) + : groupInfo( _groupInfo ), + aborting( false ) + {} + + TestGroupStats::~TestGroupStats() = default; + + TestRunStats::TestRunStats( TestRunInfo const& _runInfo, + Totals const& _totals, + bool _aborting ) + : runInfo( _runInfo ), + totals( _totals ), + aborting( _aborting ) + {} + + TestRunStats::~TestRunStats() = default; + + void IStreamingReporter::fatalErrorEncountered( StringRef ) {} + bool IStreamingReporter::isMulti() const { return false; } + + IReporterFactory::~IReporterFactory() = default; + IReporterRegistry::~IReporterRegistry() = default; + +} // end namespace Catch +// end catch_interfaces_reporter.cpp +// start catch_interfaces_runner.cpp + +namespace Catch { + IRunner::~IRunner() = default; +} +// end catch_interfaces_runner.cpp +// start catch_interfaces_testcase.cpp + +namespace Catch { + ITestInvoker::~ITestInvoker() = default; + ITestCaseRegistry::~ITestCaseRegistry() = default; +} +// end catch_interfaces_testcase.cpp +// start catch_leak_detector.cpp + +#ifdef CATCH_CONFIG_WINDOWS_CRTDBG +#include + +namespace Catch { + + LeakDetector::LeakDetector() { + int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); + flag |= _CRTDBG_LEAK_CHECK_DF; + flag |= _CRTDBG_ALLOC_MEM_DF; + _CrtSetDbgFlag(flag); + _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG); + _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); + // Change this to leaking allocation's number to break there + _CrtSetBreakAlloc(-1); + } +} + +#else + + Catch::LeakDetector::LeakDetector() {} + +#endif + +Catch::LeakDetector::~LeakDetector() { + Catch::cleanUp(); +} +// end catch_leak_detector.cpp +// start catch_list.cpp + +// start catch_list.h + +#include + +namespace Catch { + + std::size_t listTests( Config const& config ); + + std::size_t listTestsNamesOnly( Config const& config ); + + struct TagInfo { + void add( std::string const& spelling ); + std::string all() const; + + std::set spellings; + std::size_t count = 0; + }; + + std::size_t listTags( Config const& config ); + + std::size_t listReporters(); + + Option list( std::shared_ptr const& config ); + +} // end namespace Catch + +// end catch_list.h +// start catch_text.h + +namespace Catch { + using namespace clara::TextFlow; +} + +// end catch_text.h +#include +#include +#include + +namespace Catch { + + std::size_t listTests( Config const& config ) { + TestSpec testSpec = config.testSpec(); + if( config.hasTestFilters() ) + Catch::cout() << "Matching test cases:\n"; + else { + Catch::cout() << "All available test cases:\n"; + } + + auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); + for( auto const& testCaseInfo : matchedTestCases ) { + Colour::Code colour = testCaseInfo.isHidden() + ? Colour::SecondaryText + : Colour::None; + Colour colourGuard( colour ); + + Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n"; + if( config.verbosity() >= Verbosity::High ) { + Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl; + std::string description = testCaseInfo.description; + if( description.empty() ) + description = "(NO DESCRIPTION)"; + Catch::cout() << Column( description ).indent(4) << std::endl; + } + if( !testCaseInfo.tags.empty() ) + Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n"; + } + + if( !config.hasTestFilters() ) + Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl; + else + Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl; + return matchedTestCases.size(); + } + + std::size_t listTestsNamesOnly( Config const& config ) { + TestSpec testSpec = config.testSpec(); + std::size_t matchedTests = 0; + std::vector matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); + for( auto const& testCaseInfo : matchedTestCases ) { + matchedTests++; + if( startsWith( testCaseInfo.name, '#' ) ) + Catch::cout() << '"' << testCaseInfo.name << '"'; + else + Catch::cout() << testCaseInfo.name; + if ( config.verbosity() >= Verbosity::High ) + Catch::cout() << "\t@" << testCaseInfo.lineInfo; + Catch::cout() << std::endl; + } + return matchedTests; + } + + void TagInfo::add( std::string const& spelling ) { + ++count; + spellings.insert( spelling ); + } + + std::string TagInfo::all() const { + std::string out; + for( auto const& spelling : spellings ) + out += "[" + spelling + "]"; + return out; + } + + std::size_t listTags( Config const& config ) { + TestSpec testSpec = config.testSpec(); + if( config.hasTestFilters() ) + Catch::cout() << "Tags for matching test cases:\n"; + else { + Catch::cout() << "All available tags:\n"; + } + + std::map tagCounts; + + std::vector matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); + for( auto const& testCase : matchedTestCases ) { + for( auto const& tagName : testCase.getTestCaseInfo().tags ) { + std::string lcaseTagName = toLower( tagName ); + auto countIt = tagCounts.find( lcaseTagName ); + if( countIt == tagCounts.end() ) + countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first; + countIt->second.add( tagName ); + } + } + + for( auto const& tagCount : tagCounts ) { + ReusableStringStream rss; + rss << " " << std::setw(2) << tagCount.second.count << " "; + auto str = rss.str(); + auto wrapper = Column( tagCount.second.all() ) + .initialIndent( 0 ) + .indent( str.size() ) + .width( CATCH_CONFIG_CONSOLE_WIDTH-10 ); + Catch::cout() << str << wrapper << '\n'; + } + Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl; + return tagCounts.size(); + } + + std::size_t listReporters() { + Catch::cout() << "Available reporters:\n"; + IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); + std::size_t maxNameLen = 0; + for( auto const& factoryKvp : factories ) + maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() ); + + for( auto const& factoryKvp : factories ) { + Catch::cout() + << Column( factoryKvp.first + ":" ) + .indent(2) + .width( 5+maxNameLen ) + + Column( factoryKvp.second->getDescription() ) + .initialIndent(0) + .indent(2) + .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) + << "\n"; + } + Catch::cout() << std::endl; + return factories.size(); + } + + Option list( std::shared_ptr const& config ) { + Option listedCount; + getCurrentMutableContext().setConfig( config ); + if( config->listTests() ) + listedCount = listedCount.valueOr(0) + listTests( *config ); + if( config->listTestNamesOnly() ) + listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config ); + if( config->listTags() ) + listedCount = listedCount.valueOr(0) + listTags( *config ); + if( config->listReporters() ) + listedCount = listedCount.valueOr(0) + listReporters(); + return listedCount; + } + +} // end namespace Catch +// end catch_list.cpp +// start catch_matchers.cpp + +namespace Catch { +namespace Matchers { + namespace Impl { + + std::string MatcherUntypedBase::toString() const { + if( m_cachedToString.empty() ) + m_cachedToString = describe(); + return m_cachedToString; + } + + MatcherUntypedBase::~MatcherUntypedBase() = default; + + } // namespace Impl +} // namespace Matchers + +using namespace Matchers; +using Matchers::Impl::MatcherBase; + +} // namespace Catch +// end catch_matchers.cpp +// start catch_matchers_floating.cpp + +// start catch_polyfills.hpp + +namespace Catch { + bool isnan(float f); + bool isnan(double d); +} + +// end catch_polyfills.hpp +// start catch_to_string.hpp + +#include + +namespace Catch { + template + std::string to_string(T const& t) { +#if defined(CATCH_CONFIG_CPP11_TO_STRING) + return std::to_string(t); +#else + ReusableStringStream rss; + rss << t; + return rss.str(); +#endif + } +} // end namespace Catch + +// end catch_to_string.hpp +#include +#include +#include + +namespace Catch { +namespace Matchers { +namespace Floating { +enum class FloatingPointKind : uint8_t { + Float, + Double +}; +} +} +} + +namespace { + +template +struct Converter; + +template <> +struct Converter { + static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated"); + Converter(float f) { + std::memcpy(&i, &f, sizeof(f)); + } + int32_t i; +}; + +template <> +struct Converter { + static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated"); + Converter(double d) { + std::memcpy(&i, &d, sizeof(d)); + } + int64_t i; +}; + +template +auto convert(T t) -> Converter { + return Converter(t); +} + +template +bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) { + // Comparison with NaN should always be false. + // This way we can rule it out before getting into the ugly details + if (Catch::isnan(lhs) || Catch::isnan(rhs)) { + return false; + } + + auto lc = convert(lhs); + auto rc = convert(rhs); + + if ((lc.i < 0) != (rc.i < 0)) { + // Potentially we can have +0 and -0 + return lhs == rhs; + } + + auto ulpDiff = std::abs(lc.i - rc.i); + return ulpDiff <= maxUlpDiff; +} + +} + +namespace Catch { +namespace Matchers { +namespace Floating { + WithinAbsMatcher::WithinAbsMatcher(double target, double margin) + :m_target{ target }, m_margin{ margin } { + CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.' + << " Margin has to be non-negative."); + } + + // Performs equivalent check of std::fabs(lhs - rhs) <= margin + // But without the subtraction to allow for INFINITY in comparison + bool WithinAbsMatcher::match(double const& matchee) const { + return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee); + } + + std::string WithinAbsMatcher::describe() const { + return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target); + } + + WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType) + :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } { + CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.' + << " ULPs have to be non-negative."); + } + +#if defined(__clang__) +#pragma clang diagnostic push +// Clang <3.5 reports on the default branch in the switch below +#pragma clang diagnostic ignored "-Wunreachable-code" +#endif + + bool WithinUlpsMatcher::match(double const& matchee) const { + switch (m_type) { + case FloatingPointKind::Float: + return almostEqualUlps(static_cast(matchee), static_cast(m_target), m_ulps); + case FloatingPointKind::Double: + return almostEqualUlps(matchee, m_target, m_ulps); + default: + CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" ); + } + } + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + + std::string WithinUlpsMatcher::describe() const { + return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : ""); + } + +}// namespace Floating + +Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) { + return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double); +} + +Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) { + return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float); +} + +Floating::WithinAbsMatcher WithinAbs(double target, double margin) { + return Floating::WithinAbsMatcher(target, margin); +} + +} // namespace Matchers +} // namespace Catch + +// end catch_matchers_floating.cpp +// start catch_matchers_generic.cpp + +std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) { + if (desc.empty()) { + return "matches undescribed predicate"; + } else { + return "matches predicate: \"" + desc + '"'; + } +} +// end catch_matchers_generic.cpp +// start catch_matchers_string.cpp + +#include + +namespace Catch { +namespace Matchers { + + namespace StdString { + + CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ) + : m_caseSensitivity( caseSensitivity ), + m_str( adjustString( str ) ) + {} + std::string CasedString::adjustString( std::string const& str ) const { + return m_caseSensitivity == CaseSensitive::No + ? toLower( str ) + : str; + } + std::string CasedString::caseSensitivitySuffix() const { + return m_caseSensitivity == CaseSensitive::No + ? " (case insensitive)" + : std::string(); + } + + StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator ) + : m_comparator( comparator ), + m_operation( operation ) { + } + + std::string StringMatcherBase::describe() const { + std::string description; + description.reserve(5 + m_operation.size() + m_comparator.m_str.size() + + m_comparator.caseSensitivitySuffix().size()); + description += m_operation; + description += ": \""; + description += m_comparator.m_str; + description += "\""; + description += m_comparator.caseSensitivitySuffix(); + return description; + } + + EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {} + + bool EqualsMatcher::match( std::string const& source ) const { + return m_comparator.adjustString( source ) == m_comparator.m_str; + } + + ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {} + + bool ContainsMatcher::match( std::string const& source ) const { + return contains( m_comparator.adjustString( source ), m_comparator.m_str ); + } + + StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {} + + bool StartsWithMatcher::match( std::string const& source ) const { + return startsWith( m_comparator.adjustString( source ), m_comparator.m_str ); + } + + EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {} + + bool EndsWithMatcher::match( std::string const& source ) const { + return endsWith( m_comparator.adjustString( source ), m_comparator.m_str ); + } + + RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {} + + bool RegexMatcher::match(std::string const& matchee) const { + auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway + if (m_caseSensitivity == CaseSensitive::Choice::No) { + flags |= std::regex::icase; + } + auto reg = std::regex(m_regex, flags); + return std::regex_match(matchee, reg); + } + + std::string RegexMatcher::describe() const { + return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively"); + } + + } // namespace StdString + + StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) { + return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) ); + } + StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) { + return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) ); + } + StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) { + return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) ); + } + StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) { + return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) ); + } + + StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) { + return StdString::RegexMatcher(regex, caseSensitivity); + } + +} // namespace Matchers +} // namespace Catch +// end catch_matchers_string.cpp +// start catch_message.cpp + +// start catch_uncaught_exceptions.h + +namespace Catch { + bool uncaught_exceptions(); +} // end namespace Catch + +// end catch_uncaught_exceptions.h +#include +#include + +namespace Catch { + + MessageInfo::MessageInfo( StringRef const& _macroName, + SourceLineInfo const& _lineInfo, + ResultWas::OfType _type ) + : macroName( _macroName ), + lineInfo( _lineInfo ), + type( _type ), + sequence( ++globalCount ) + {} + + bool MessageInfo::operator==( MessageInfo const& other ) const { + return sequence == other.sequence; + } + + bool MessageInfo::operator<( MessageInfo const& other ) const { + return sequence < other.sequence; + } + + // This may need protecting if threading support is added + unsigned int MessageInfo::globalCount = 0; + + //////////////////////////////////////////////////////////////////////////// + + Catch::MessageBuilder::MessageBuilder( StringRef const& macroName, + SourceLineInfo const& lineInfo, + ResultWas::OfType type ) + :m_info(macroName, lineInfo, type) {} + + //////////////////////////////////////////////////////////////////////////// + + ScopedMessage::ScopedMessage( MessageBuilder const& builder ) + : m_info( builder.m_info ), m_moved() + { + m_info.message = builder.m_stream.str(); + getResultCapture().pushScopedMessage( m_info ); + } + + ScopedMessage::ScopedMessage( ScopedMessage&& old ) + : m_info( old.m_info ), m_moved() + { + old.m_moved = true; + } + + ScopedMessage::~ScopedMessage() { + if ( !uncaught_exceptions() && !m_moved ){ + getResultCapture().popScopedMessage(m_info); + } + } + + Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) { + auto trimmed = [&] (size_t start, size_t end) { + while (names[start] == ',' || isspace(names[start])) { + ++start; + } + while (names[end] == ',' || isspace(names[end])) { + --end; + } + return names.substr(start, end - start + 1); + }; + + size_t start = 0; + std::stack openings; + for (size_t pos = 0; pos < names.size(); ++pos) { + char c = names[pos]; + switch (c) { + case '[': + case '{': + case '(': + // It is basically impossible to disambiguate between + // comparison and start of template args in this context +// case '<': + openings.push(c); + break; + case ']': + case '}': + case ')': +// case '>': + openings.pop(); + break; + case ',': + if (start != pos && openings.size() == 0) { + m_messages.emplace_back(macroName, lineInfo, resultType); + m_messages.back().message = trimmed(start, pos); + m_messages.back().message += " := "; + start = pos; + } + } + } + assert(openings.size() == 0 && "Mismatched openings"); + m_messages.emplace_back(macroName, lineInfo, resultType); + m_messages.back().message = trimmed(start, names.size() - 1); + m_messages.back().message += " := "; + } + Capturer::~Capturer() { + if ( !uncaught_exceptions() ){ + assert( m_captured == m_messages.size() ); + for( size_t i = 0; i < m_captured; ++i ) + m_resultCapture.popScopedMessage( m_messages[i] ); + } + } + + void Capturer::captureValue( size_t index, std::string const& value ) { + assert( index < m_messages.size() ); + m_messages[index].message += value; + m_resultCapture.pushScopedMessage( m_messages[index] ); + m_captured++; + } + +} // end namespace Catch +// end catch_message.cpp +// start catch_output_redirect.cpp + +// start catch_output_redirect.h +#ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H +#define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H + +#include +#include +#include + +namespace Catch { + + class RedirectedStream { + std::ostream& m_originalStream; + std::ostream& m_redirectionStream; + std::streambuf* m_prevBuf; + + public: + RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream ); + ~RedirectedStream(); + }; + + class RedirectedStdOut { + ReusableStringStream m_rss; + RedirectedStream m_cout; + public: + RedirectedStdOut(); + auto str() const -> std::string; + }; + + // StdErr has two constituent streams in C++, std::cerr and std::clog + // This means that we need to redirect 2 streams into 1 to keep proper + // order of writes + class RedirectedStdErr { + ReusableStringStream m_rss; + RedirectedStream m_cerr; + RedirectedStream m_clog; + public: + RedirectedStdErr(); + auto str() const -> std::string; + }; + + class RedirectedStreams { + public: + RedirectedStreams(RedirectedStreams const&) = delete; + RedirectedStreams& operator=(RedirectedStreams const&) = delete; + RedirectedStreams(RedirectedStreams&&) = delete; + RedirectedStreams& operator=(RedirectedStreams&&) = delete; + + RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr); + ~RedirectedStreams(); + private: + std::string& m_redirectedCout; + std::string& m_redirectedCerr; + RedirectedStdOut m_redirectedStdOut; + RedirectedStdErr m_redirectedStdErr; + }; + +#if defined(CATCH_CONFIG_NEW_CAPTURE) + + // Windows's implementation of std::tmpfile is terrible (it tries + // to create a file inside system folder, thus requiring elevated + // privileges for the binary), so we have to use tmpnam(_s) and + // create the file ourselves there. + class TempFile { + public: + TempFile(TempFile const&) = delete; + TempFile& operator=(TempFile const&) = delete; + TempFile(TempFile&&) = delete; + TempFile& operator=(TempFile&&) = delete; + + TempFile(); + ~TempFile(); + + std::FILE* getFile(); + std::string getContents(); + + private: + std::FILE* m_file = nullptr; + #if defined(_MSC_VER) + char m_buffer[L_tmpnam] = { 0 }; + #endif + }; + + class OutputRedirect { + public: + OutputRedirect(OutputRedirect const&) = delete; + OutputRedirect& operator=(OutputRedirect const&) = delete; + OutputRedirect(OutputRedirect&&) = delete; + OutputRedirect& operator=(OutputRedirect&&) = delete; + + OutputRedirect(std::string& stdout_dest, std::string& stderr_dest); + ~OutputRedirect(); + + private: + int m_originalStdout = -1; + int m_originalStderr = -1; + TempFile m_stdoutFile; + TempFile m_stderrFile; + std::string& m_stdoutDest; + std::string& m_stderrDest; + }; + +#endif + +} // end namespace Catch + +#endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H +// end catch_output_redirect.h +#include +#include +#include +#include +#include + +#if defined(CATCH_CONFIG_NEW_CAPTURE) + #if defined(_MSC_VER) + #include //_dup and _dup2 + #define dup _dup + #define dup2 _dup2 + #define fileno _fileno + #else + #include // dup and dup2 + #endif +#endif + +namespace Catch { + + RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream ) + : m_originalStream( originalStream ), + m_redirectionStream( redirectionStream ), + m_prevBuf( m_originalStream.rdbuf() ) + { + m_originalStream.rdbuf( m_redirectionStream.rdbuf() ); + } + + RedirectedStream::~RedirectedStream() { + m_originalStream.rdbuf( m_prevBuf ); + } + + RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {} + auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); } + + RedirectedStdErr::RedirectedStdErr() + : m_cerr( Catch::cerr(), m_rss.get() ), + m_clog( Catch::clog(), m_rss.get() ) + {} + auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); } + + RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr) + : m_redirectedCout(redirectedCout), + m_redirectedCerr(redirectedCerr) + {} + + RedirectedStreams::~RedirectedStreams() { + m_redirectedCout += m_redirectedStdOut.str(); + m_redirectedCerr += m_redirectedStdErr.str(); + } + +#if defined(CATCH_CONFIG_NEW_CAPTURE) + +#if defined(_MSC_VER) + TempFile::TempFile() { + if (tmpnam_s(m_buffer)) { + CATCH_RUNTIME_ERROR("Could not get a temp filename"); + } + if (fopen_s(&m_file, m_buffer, "w")) { + char buffer[100]; + if (strerror_s(buffer, errno)) { + CATCH_RUNTIME_ERROR("Could not translate errno to a string"); + } + CATCH_RUNTIME_ERROR("Coul dnot open the temp file: '" << m_buffer << "' because: " << buffer); + } + } +#else + TempFile::TempFile() { + m_file = std::tmpfile(); + if (!m_file) { + CATCH_RUNTIME_ERROR("Could not create a temp file."); + } + } + +#endif + + TempFile::~TempFile() { + // TBD: What to do about errors here? + std::fclose(m_file); + // We manually create the file on Windows only, on Linux + // it will be autodeleted +#if defined(_MSC_VER) + std::remove(m_buffer); +#endif + } + + FILE* TempFile::getFile() { + return m_file; + } + + std::string TempFile::getContents() { + std::stringstream sstr; + char buffer[100] = {}; + std::rewind(m_file); + while (std::fgets(buffer, sizeof(buffer), m_file)) { + sstr << buffer; + } + return sstr.str(); + } + + OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) : + m_originalStdout(dup(1)), + m_originalStderr(dup(2)), + m_stdoutDest(stdout_dest), + m_stderrDest(stderr_dest) { + dup2(fileno(m_stdoutFile.getFile()), 1); + dup2(fileno(m_stderrFile.getFile()), 2); + } + + OutputRedirect::~OutputRedirect() { + Catch::cout() << std::flush; + fflush(stdout); + // Since we support overriding these streams, we flush cerr + // even though std::cerr is unbuffered + Catch::cerr() << std::flush; + Catch::clog() << std::flush; + fflush(stderr); + + dup2(m_originalStdout, 1); + dup2(m_originalStderr, 2); + + m_stdoutDest += m_stdoutFile.getContents(); + m_stderrDest += m_stderrFile.getContents(); + } + +#endif // CATCH_CONFIG_NEW_CAPTURE + +} // namespace Catch + +#if defined(CATCH_CONFIG_NEW_CAPTURE) + #if defined(_MSC_VER) + #undef dup + #undef dup2 + #undef fileno + #endif +#endif +// end catch_output_redirect.cpp +// start catch_polyfills.cpp + +#include + +namespace Catch { + +#if !defined(CATCH_CONFIG_POLYFILL_ISNAN) + bool isnan(float f) { + return std::isnan(f); + } + bool isnan(double d) { + return std::isnan(d); + } +#else + // For now we only use this for embarcadero + bool isnan(float f) { + return std::_isnan(f); + } + bool isnan(double d) { + return std::_isnan(d); + } +#endif + +} // end namespace Catch +// end catch_polyfills.cpp +// start catch_random_number_generator.cpp + +namespace Catch { + + std::mt19937& rng() { + static std::mt19937 s_rng; + return s_rng; + } + + void seedRng( IConfig const& config ) { + if( config.rngSeed() != 0 ) { + std::srand( config.rngSeed() ); + rng().seed( config.rngSeed() ); + } + } + + unsigned int rngSeed() { + return getCurrentContext().getConfig()->rngSeed(); + } +} +// end catch_random_number_generator.cpp +// start catch_registry_hub.cpp + +// start catch_test_case_registry_impl.h + +#include +#include +#include +#include + +namespace Catch { + + class TestCase; + struct IConfig; + + std::vector sortTests( IConfig const& config, std::vector const& unsortedTestCases ); + bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); + + void enforceNoDuplicateTestCases( std::vector const& functions ); + + std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ); + std::vector const& getAllTestCasesSorted( IConfig const& config ); + + class TestRegistry : public ITestCaseRegistry { + public: + virtual ~TestRegistry() = default; + + virtual void registerTest( TestCase const& testCase ); + + std::vector const& getAllTests() const override; + std::vector const& getAllTestsSorted( IConfig const& config ) const override; + + private: + std::vector m_functions; + mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder; + mutable std::vector m_sortedFunctions; + std::size_t m_unnamedCount = 0; + std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised + }; + + /////////////////////////////////////////////////////////////////////////// + + class TestInvokerAsFunction : public ITestInvoker { + void(*m_testAsFunction)(); + public: + TestInvokerAsFunction( void(*testAsFunction)() ) noexcept; + + void invoke() const override; + }; + + std::string extractClassName( StringRef const& classOrQualifiedMethodName ); + + /////////////////////////////////////////////////////////////////////////// + +} // end namespace Catch + +// end catch_test_case_registry_impl.h +// start catch_reporter_registry.h + +#include + +namespace Catch { + + class ReporterRegistry : public IReporterRegistry { + + public: + + ~ReporterRegistry() override; + + IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override; + + void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ); + void registerListener( IReporterFactoryPtr const& factory ); + + FactoryMap const& getFactories() const override; + Listeners const& getListeners() const override; + + private: + FactoryMap m_factories; + Listeners m_listeners; + }; +} + +// end catch_reporter_registry.h +// start catch_tag_alias_registry.h + +// start catch_tag_alias.h + +#include + +namespace Catch { + + struct TagAlias { + TagAlias(std::string const& _tag, SourceLineInfo _lineInfo); + + std::string tag; + SourceLineInfo lineInfo; + }; + +} // end namespace Catch + +// end catch_tag_alias.h +#include + +namespace Catch { + + class TagAliasRegistry : public ITagAliasRegistry { + public: + ~TagAliasRegistry() override; + TagAlias const* find( std::string const& alias ) const override; + std::string expandAliases( std::string const& unexpandedTestSpec ) const override; + void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ); + + private: + std::map m_registry; + }; + +} // end namespace Catch + +// end catch_tag_alias_registry.h +// start catch_startup_exception_registry.h + +#include +#include + +namespace Catch { + + class StartupExceptionRegistry { + public: + void add(std::exception_ptr const& exception) noexcept; + std::vector const& getExceptions() const noexcept; + private: + std::vector m_exceptions; + }; + +} // end namespace Catch + +// end catch_startup_exception_registry.h +// start catch_singletons.hpp + +namespace Catch { + + struct ISingleton { + virtual ~ISingleton(); + }; + + void addSingleton( ISingleton* singleton ); + void cleanupSingletons(); + + template + class Singleton : SingletonImplT, public ISingleton { + + static auto getInternal() -> Singleton* { + static Singleton* s_instance = nullptr; + if( !s_instance ) { + s_instance = new Singleton; + addSingleton( s_instance ); + } + return s_instance; + } + + public: + static auto get() -> InterfaceT const& { + return *getInternal(); + } + static auto getMutable() -> MutableInterfaceT& { + return *getInternal(); + } + }; + +} // namespace Catch + +// end catch_singletons.hpp +namespace Catch { + + namespace { + + class RegistryHub : public IRegistryHub, public IMutableRegistryHub, + private NonCopyable { + + public: // IRegistryHub + RegistryHub() = default; + IReporterRegistry const& getReporterRegistry() const override { + return m_reporterRegistry; + } + ITestCaseRegistry const& getTestCaseRegistry() const override { + return m_testCaseRegistry; + } + IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override { + return m_exceptionTranslatorRegistry; + } + ITagAliasRegistry const& getTagAliasRegistry() const override { + return m_tagAliasRegistry; + } + StartupExceptionRegistry const& getStartupExceptionRegistry() const override { + return m_exceptionRegistry; + } + + public: // IMutableRegistryHub + void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override { + m_reporterRegistry.registerReporter( name, factory ); + } + void registerListener( IReporterFactoryPtr const& factory ) override { + m_reporterRegistry.registerListener( factory ); + } + void registerTest( TestCase const& testInfo ) override { + m_testCaseRegistry.registerTest( testInfo ); + } + void registerTranslator( const IExceptionTranslator* translator ) override { + m_exceptionTranslatorRegistry.registerTranslator( translator ); + } + void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override { + m_tagAliasRegistry.add( alias, tag, lineInfo ); + } + void registerStartupException() noexcept override { + m_exceptionRegistry.add(std::current_exception()); + } + + private: + TestRegistry m_testCaseRegistry; + ReporterRegistry m_reporterRegistry; + ExceptionTranslatorRegistry m_exceptionTranslatorRegistry; + TagAliasRegistry m_tagAliasRegistry; + StartupExceptionRegistry m_exceptionRegistry; + }; + } + + using RegistryHubSingleton = Singleton; + + IRegistryHub const& getRegistryHub() { + return RegistryHubSingleton::get(); + } + IMutableRegistryHub& getMutableRegistryHub() { + return RegistryHubSingleton::getMutable(); + } + void cleanUp() { + cleanupSingletons(); + cleanUpContext(); + } + std::string translateActiveException() { + return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException(); + } + +} // end namespace Catch +// end catch_registry_hub.cpp +// start catch_reporter_registry.cpp + +namespace Catch { + + ReporterRegistry::~ReporterRegistry() = default; + + IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const { + auto it = m_factories.find( name ); + if( it == m_factories.end() ) + return nullptr; + return it->second->create( ReporterConfig( config ) ); + } + + void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) { + m_factories.emplace(name, factory); + } + void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) { + m_listeners.push_back( factory ); + } + + IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const { + return m_factories; + } + IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const { + return m_listeners; + } + +} +// end catch_reporter_registry.cpp +// start catch_result_type.cpp + +namespace Catch { + + bool isOk( ResultWas::OfType resultType ) { + return ( resultType & ResultWas::FailureBit ) == 0; + } + bool isJustInfo( int flags ) { + return flags == ResultWas::Info; + } + + ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) { + return static_cast( static_cast( lhs ) | static_cast( rhs ) ); + } + + bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; } + bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; } + +} // end namespace Catch +// end catch_result_type.cpp +// start catch_run_context.cpp + +#include +#include +#include + +namespace Catch { + + namespace Generators { + struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker { + GeneratorBasePtr m_generator; + + GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ) + : TrackerBase( nameAndLocation, ctx, parent ) + {} + ~GeneratorTracker(); + + static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) { + std::shared_ptr tracker; + + ITracker& currentTracker = ctx.currentTracker(); + if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) { + assert( childTracker ); + assert( childTracker->isGeneratorTracker() ); + tracker = std::static_pointer_cast( childTracker ); + } + else { + tracker = std::make_shared( nameAndLocation, ctx, ¤tTracker ); + currentTracker.addChild( tracker ); + } + + if( !ctx.completedCycle() && !tracker->isComplete() ) { + tracker->open(); + } + + return *tracker; + } + + // TrackerBase interface + bool isGeneratorTracker() const override { return true; } + auto hasGenerator() const -> bool override { + return !!m_generator; + } + void close() override { + TrackerBase::close(); + // Generator interface only finds out if it has another item on atual move + if (m_runState == CompletedSuccessfully && m_generator->next()) { + m_children.clear(); + m_runState = Executing; + } + } + + // IGeneratorTracker interface + auto getGenerator() const -> GeneratorBasePtr const& override { + return m_generator; + } + void setGenerator( GeneratorBasePtr&& generator ) override { + m_generator = std::move( generator ); + } + }; + GeneratorTracker::~GeneratorTracker() {} + } + + RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter) + : m_runInfo(_config->name()), + m_context(getCurrentMutableContext()), + m_config(_config), + m_reporter(std::move(reporter)), + m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal }, + m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions ) + { + m_context.setRunner(this); + m_context.setConfig(m_config); + m_context.setResultCapture(this); + m_reporter->testRunStarting(m_runInfo); + } + + RunContext::~RunContext() { + m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting())); + } + + void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) { + m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount)); + } + + void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) { + m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting())); + } + + Totals RunContext::runTest(TestCase const& testCase) { + Totals prevTotals = m_totals; + + std::string redirectedCout; + std::string redirectedCerr; + + auto const& testInfo = testCase.getTestCaseInfo(); + + m_reporter->testCaseStarting(testInfo); + + m_activeTestCase = &testCase; + + ITracker& rootTracker = m_trackerContext.startRun(); + assert(rootTracker.isSectionTracker()); + static_cast(rootTracker).addInitialFilters(m_config->getSectionsToRun()); + do { + m_trackerContext.startCycle(); + m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo)); + runCurrentTest(redirectedCout, redirectedCerr); + } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting()); + + Totals deltaTotals = m_totals.delta(prevTotals); + if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) { + deltaTotals.assertions.failed++; + deltaTotals.testCases.passed--; + deltaTotals.testCases.failed++; + } + m_totals.testCases += deltaTotals.testCases; + m_reporter->testCaseEnded(TestCaseStats(testInfo, + deltaTotals, + redirectedCout, + redirectedCerr, + aborting())); + + m_activeTestCase = nullptr; + m_testCaseTracker = nullptr; + + return deltaTotals; + } + + IConfigPtr RunContext::config() const { + return m_config; + } + + IStreamingReporter& RunContext::reporter() const { + return *m_reporter; + } + + void RunContext::assertionEnded(AssertionResult const & result) { + if (result.getResultType() == ResultWas::Ok) { + m_totals.assertions.passed++; + m_lastAssertionPassed = true; + } else if (!result.isOk()) { + m_lastAssertionPassed = false; + if( m_activeTestCase->getTestCaseInfo().okToFail() ) + m_totals.assertions.failedButOk++; + else + m_totals.assertions.failed++; + } + else { + m_lastAssertionPassed = true; + } + + // We have no use for the return value (whether messages should be cleared), because messages were made scoped + // and should be let to clear themselves out. + static_cast(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals))); + + if (result.getResultType() != ResultWas::Warning) + m_messageScopes.clear(); + + // Reset working state + resetAssertionInfo(); + m_lastResult = result; + } + void RunContext::resetAssertionInfo() { + m_lastAssertionInfo.macroName = StringRef(); + m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr; + } + + bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) { + ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo)); + if (!sectionTracker.isOpen()) + return false; + m_activeSections.push_back(§ionTracker); + + m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo; + + m_reporter->sectionStarting(sectionInfo); + + assertions = m_totals.assertions; + + return true; + } + auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& { + using namespace Generators; + GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) ); + assert( tracker.isOpen() ); + m_lastAssertionInfo.lineInfo = lineInfo; + return tracker; + } + + bool RunContext::testForMissingAssertions(Counts& assertions) { + if (assertions.total() != 0) + return false; + if (!m_config->warnAboutMissingAssertions()) + return false; + if (m_trackerContext.currentTracker().hasChildren()) + return false; + m_totals.assertions.failed++; + assertions.failed++; + return true; + } + + void RunContext::sectionEnded(SectionEndInfo const & endInfo) { + Counts assertions = m_totals.assertions - endInfo.prevAssertions; + bool missingAssertions = testForMissingAssertions(assertions); + + if (!m_activeSections.empty()) { + m_activeSections.back()->close(); + m_activeSections.pop_back(); + } + + m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions)); + m_messages.clear(); + m_messageScopes.clear(); + } + + void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) { + if (m_unfinishedSections.empty()) + m_activeSections.back()->fail(); + else + m_activeSections.back()->close(); + m_activeSections.pop_back(); + + m_unfinishedSections.push_back(endInfo); + } + void RunContext::benchmarkStarting( BenchmarkInfo const& info ) { + m_reporter->benchmarkStarting( info ); + } + void RunContext::benchmarkEnded( BenchmarkStats const& stats ) { + m_reporter->benchmarkEnded( stats ); + } + + void RunContext::pushScopedMessage(MessageInfo const & message) { + m_messages.push_back(message); + } + + void RunContext::popScopedMessage(MessageInfo const & message) { + m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end()); + } + + void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) { + m_messageScopes.emplace_back( builder ); + } + + std::string RunContext::getCurrentTestName() const { + return m_activeTestCase + ? m_activeTestCase->getTestCaseInfo().name + : std::string(); + } + + const AssertionResult * RunContext::getLastResult() const { + return &(*m_lastResult); + } + + void RunContext::exceptionEarlyReported() { + m_shouldReportUnexpected = false; + } + + void RunContext::handleFatalErrorCondition( StringRef message ) { + // First notify reporter that bad things happened + m_reporter->fatalErrorEncountered(message); + + // Don't rebuild the result -- the stringification itself can cause more fatal errors + // Instead, fake a result data. + AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } ); + tempResult.message = message; + AssertionResult result(m_lastAssertionInfo, tempResult); + + assertionEnded(result); + + handleUnfinishedSections(); + + // Recreate section for test case (as we will lose the one that was in scope) + auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); + SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name); + + Counts assertions; + assertions.failed = 1; + SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false); + m_reporter->sectionEnded(testCaseSectionStats); + + auto const& testInfo = m_activeTestCase->getTestCaseInfo(); + + Totals deltaTotals; + deltaTotals.testCases.failed = 1; + deltaTotals.assertions.failed = 1; + m_reporter->testCaseEnded(TestCaseStats(testInfo, + deltaTotals, + std::string(), + std::string(), + false)); + m_totals.testCases.failed++; + testGroupEnded(std::string(), m_totals, 1, 1); + m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false)); + } + + bool RunContext::lastAssertionPassed() { + return m_lastAssertionPassed; + } + + void RunContext::assertionPassed() { + m_lastAssertionPassed = true; + ++m_totals.assertions.passed; + resetAssertionInfo(); + m_messageScopes.clear(); + } + + bool RunContext::aborting() const { + return m_totals.assertions.failed >= static_cast(m_config->abortAfter()); + } + + void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) { + auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); + SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name); + m_reporter->sectionStarting(testCaseSection); + Counts prevAssertions = m_totals.assertions; + double duration = 0; + m_shouldReportUnexpected = true; + m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal }; + + seedRng(*m_config); + + Timer timer; + CATCH_TRY { + if (m_reporter->getPreferences().shouldRedirectStdOut) { +#if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT) + RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr); + + timer.start(); + invokeActiveTestCase(); +#else + OutputRedirect r(redirectedCout, redirectedCerr); + timer.start(); + invokeActiveTestCase(); +#endif + } else { + timer.start(); + invokeActiveTestCase(); + } + duration = timer.getElapsedSeconds(); + } CATCH_CATCH_ANON (TestFailureException&) { + // This just means the test was aborted due to failure + } CATCH_CATCH_ALL { + // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions + // are reported without translation at the point of origin. + if( m_shouldReportUnexpected ) { + AssertionReaction dummyReaction; + handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction ); + } + } + Counts assertions = m_totals.assertions - prevAssertions; + bool missingAssertions = testForMissingAssertions(assertions); + + m_testCaseTracker->close(); + handleUnfinishedSections(); + m_messages.clear(); + m_messageScopes.clear(); + + SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions); + m_reporter->sectionEnded(testCaseSectionStats); + } + + void RunContext::invokeActiveTestCase() { + FatalConditionHandler fatalConditionHandler; // Handle signals + m_activeTestCase->invoke(); + fatalConditionHandler.reset(); + } + + void RunContext::handleUnfinishedSections() { + // If sections ended prematurely due to an exception we stored their + // infos here so we can tear them down outside the unwind process. + for (auto it = m_unfinishedSections.rbegin(), + itEnd = m_unfinishedSections.rend(); + it != itEnd; + ++it) + sectionEnded(*it); + m_unfinishedSections.clear(); + } + + void RunContext::handleExpr( + AssertionInfo const& info, + ITransientExpression const& expr, + AssertionReaction& reaction + ) { + m_reporter->assertionStarting( info ); + + bool negated = isFalseTest( info.resultDisposition ); + bool result = expr.getResult() != negated; + + if( result ) { + if (!m_includeSuccessfulResults) { + assertionPassed(); + } + else { + reportExpr(info, ResultWas::Ok, &expr, negated); + } + } + else { + reportExpr(info, ResultWas::ExpressionFailed, &expr, negated ); + populateReaction( reaction ); + } + } + void RunContext::reportExpr( + AssertionInfo const &info, + ResultWas::OfType resultType, + ITransientExpression const *expr, + bool negated ) { + + m_lastAssertionInfo = info; + AssertionResultData data( resultType, LazyExpression( negated ) ); + + AssertionResult assertionResult{ info, data }; + assertionResult.m_resultData.lazyExpression.m_transientExpression = expr; + + assertionEnded( assertionResult ); + } + + void RunContext::handleMessage( + AssertionInfo const& info, + ResultWas::OfType resultType, + StringRef const& message, + AssertionReaction& reaction + ) { + m_reporter->assertionStarting( info ); + + m_lastAssertionInfo = info; + + AssertionResultData data( resultType, LazyExpression( false ) ); + data.message = message; + AssertionResult assertionResult{ m_lastAssertionInfo, data }; + assertionEnded( assertionResult ); + if( !assertionResult.isOk() ) + populateReaction( reaction ); + } + void RunContext::handleUnexpectedExceptionNotThrown( + AssertionInfo const& info, + AssertionReaction& reaction + ) { + handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction); + } + + void RunContext::handleUnexpectedInflightException( + AssertionInfo const& info, + std::string const& message, + AssertionReaction& reaction + ) { + m_lastAssertionInfo = info; + + AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) ); + data.message = message; + AssertionResult assertionResult{ info, data }; + assertionEnded( assertionResult ); + populateReaction( reaction ); + } + + void RunContext::populateReaction( AssertionReaction& reaction ) { + reaction.shouldDebugBreak = m_config->shouldDebugBreak(); + reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal); + } + + void RunContext::handleIncomplete( + AssertionInfo const& info + ) { + m_lastAssertionInfo = info; + + AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) ); + data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE"; + AssertionResult assertionResult{ info, data }; + assertionEnded( assertionResult ); + } + void RunContext::handleNonExpr( + AssertionInfo const &info, + ResultWas::OfType resultType, + AssertionReaction &reaction + ) { + m_lastAssertionInfo = info; + + AssertionResultData data( resultType, LazyExpression( false ) ); + AssertionResult assertionResult{ info, data }; + assertionEnded( assertionResult ); + + if( !assertionResult.isOk() ) + populateReaction( reaction ); + } + + IResultCapture& getResultCapture() { + if (auto* capture = getCurrentContext().getResultCapture()) + return *capture; + else + CATCH_INTERNAL_ERROR("No result capture instance"); + } +} +// end catch_run_context.cpp +// start catch_section.cpp + +namespace Catch { + + Section::Section( SectionInfo const& info ) + : m_info( info ), + m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) ) + { + m_timer.start(); + } + + Section::~Section() { + if( m_sectionIncluded ) { + SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() }; + if( uncaught_exceptions() ) + getResultCapture().sectionEndedEarly( endInfo ); + else + getResultCapture().sectionEnded( endInfo ); + } + } + + // This indicates whether the section should be executed or not + Section::operator bool() const { + return m_sectionIncluded; + } + +} // end namespace Catch +// end catch_section.cpp +// start catch_section_info.cpp + +namespace Catch { + + SectionInfo::SectionInfo + ( SourceLineInfo const& _lineInfo, + std::string const& _name ) + : name( _name ), + lineInfo( _lineInfo ) + {} + +} // end namespace Catch +// end catch_section_info.cpp +// start catch_session.cpp + +// start catch_session.h + +#include + +namespace Catch { + + class Session : NonCopyable { + public: + + Session(); + ~Session() override; + + void showHelp() const; + void libIdentify(); + + int applyCommandLine( int argc, char const * const * argv ); + #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE) + int applyCommandLine( int argc, wchar_t const * const * argv ); + #endif + + void useConfigData( ConfigData const& configData ); + + template + int run(int argc, CharT const * const argv[]) { + if (m_startupExceptions) + return 1; + int returnCode = applyCommandLine(argc, argv); + if (returnCode == 0) + returnCode = run(); + return returnCode; + } + + int run(); + + clara::Parser const& cli() const; + void cli( clara::Parser const& newParser ); + ConfigData& configData(); + Config& config(); + private: + int runInternal(); + + clara::Parser m_cli; + ConfigData m_configData; + std::shared_ptr m_config; + bool m_startupExceptions = false; + }; + +} // end namespace Catch + +// end catch_session.h +// start catch_version.h + +#include + +namespace Catch { + + // Versioning information + struct Version { + Version( Version const& ) = delete; + Version& operator=( Version const& ) = delete; + Version( unsigned int _majorVersion, + unsigned int _minorVersion, + unsigned int _patchNumber, + char const * const _branchName, + unsigned int _buildNumber ); + + unsigned int const majorVersion; + unsigned int const minorVersion; + unsigned int const patchNumber; + + // buildNumber is only used if branchName is not null + char const * const branchName; + unsigned int const buildNumber; + + friend std::ostream& operator << ( std::ostream& os, Version const& version ); + }; + + Version const& libraryVersion(); +} + +// end catch_version.h +#include +#include + +namespace Catch { + + namespace { + const int MaxExitCode = 255; + + IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) { + auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config); + CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'"); + + return reporter; + } + + IStreamingReporterPtr makeReporter(std::shared_ptr const& config) { + if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) { + return createReporter(config->getReporterName(), config); + } + + // On older platforms, returning std::unique_ptr + // when the return type is std::unique_ptr + // doesn't compile without a std::move call. However, this causes + // a warning on newer platforms. Thus, we have to work around + // it a bit and downcast the pointer manually. + auto ret = std::unique_ptr(new ListeningReporter); + auto& multi = static_cast(*ret); + auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners(); + for (auto const& listener : listeners) { + multi.addListener(listener->create(Catch::ReporterConfig(config))); + } + multi.addReporter(createReporter(config->getReporterName(), config)); + return ret; + } + + Catch::Totals runTests(std::shared_ptr const& config) { + auto reporter = makeReporter(config); + + RunContext context(config, std::move(reporter)); + + Totals totals; + + context.testGroupStarting(config->name(), 1, 1); + + TestSpec testSpec = config->testSpec(); + + auto const& allTestCases = getAllTestCasesSorted(*config); + for (auto const& testCase : allTestCases) { + if (!context.aborting() && matchTest(testCase, testSpec, *config)) + totals += context.runTest(testCase); + else + context.reporter().skipTest(testCase); + } + + if (config->warnAboutNoTests() && totals.testCases.total() == 0) { + ReusableStringStream testConfig; + + bool first = true; + for (const auto& input : config->getTestsOrTags()) { + if (!first) { testConfig << ' '; } + first = false; + testConfig << input; + } + + context.reporter().noMatchingTestCases(testConfig.str()); + totals.error = -1; + } + + context.testGroupEnded(config->name(), totals, 1, 1); + return totals; + } + + void applyFilenamesAsTags(Catch::IConfig const& config) { + auto& tests = const_cast&>(getAllTestCasesSorted(config)); + for (auto& testCase : tests) { + auto tags = testCase.tags; + + std::string filename = testCase.lineInfo.file; + auto lastSlash = filename.find_last_of("\\/"); + if (lastSlash != std::string::npos) { + filename.erase(0, lastSlash); + filename[0] = '#'; + } + + auto lastDot = filename.find_last_of('.'); + if (lastDot != std::string::npos) { + filename.erase(lastDot); + } + + tags.push_back(std::move(filename)); + setTags(testCase, tags); + } + } + + } // anon namespace + + Session::Session() { + static bool alreadyInstantiated = false; + if( alreadyInstantiated ) { + CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); } + CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); } + } + + // There cannot be exceptions at startup in no-exception mode. +#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) + const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions(); + if ( !exceptions.empty() ) { + m_startupExceptions = true; + Colour colourGuard( Colour::Red ); + Catch::cerr() << "Errors occurred during startup!" << '\n'; + // iterate over all exceptions and notify user + for ( const auto& ex_ptr : exceptions ) { + try { + std::rethrow_exception(ex_ptr); + } catch ( std::exception const& ex ) { + Catch::cerr() << Column( ex.what() ).indent(2) << '\n'; + } + } + } +#endif + + alreadyInstantiated = true; + m_cli = makeCommandLineParser( m_configData ); + } + Session::~Session() { + Catch::cleanUp(); + } + + void Session::showHelp() const { + Catch::cout() + << "\nCatch v" << libraryVersion() << "\n" + << m_cli << std::endl + << "For more detailed usage please see the project docs\n" << std::endl; + } + void Session::libIdentify() { + Catch::cout() + << std::left << std::setw(16) << "description: " << "A Catch test executable\n" + << std::left << std::setw(16) << "category: " << "testframework\n" + << std::left << std::setw(16) << "framework: " << "Catch Test\n" + << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl; + } + + int Session::applyCommandLine( int argc, char const * const * argv ) { + if( m_startupExceptions ) + return 1; + + auto result = m_cli.parse( clara::Args( argc, argv ) ); + if( !result ) { + config(); + getCurrentMutableContext().setConfig(m_config); + Catch::cerr() + << Colour( Colour::Red ) + << "\nError(s) in input:\n" + << Column( result.errorMessage() ).indent( 2 ) + << "\n\n"; + Catch::cerr() << "Run with -? for usage\n" << std::endl; + return MaxExitCode; + } + + if( m_configData.showHelp ) + showHelp(); + if( m_configData.libIdentify ) + libIdentify(); + m_config.reset(); + return 0; + } + +#if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE) + int Session::applyCommandLine( int argc, wchar_t const * const * argv ) { + + char **utf8Argv = new char *[ argc ]; + + for ( int i = 0; i < argc; ++i ) { + int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL ); + + utf8Argv[ i ] = new char[ bufSize ]; + + WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL ); + } + + int returnCode = applyCommandLine( argc, utf8Argv ); + + for ( int i = 0; i < argc; ++i ) + delete [] utf8Argv[ i ]; + + delete [] utf8Argv; + + return returnCode; + } +#endif + + void Session::useConfigData( ConfigData const& configData ) { + m_configData = configData; + m_config.reset(); + } + + int Session::run() { + if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) { + Catch::cout() << "...waiting for enter/ return before starting" << std::endl; + static_cast(std::getchar()); + } + int exitCode = runInternal(); + if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) { + Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl; + static_cast(std::getchar()); + } + return exitCode; + } + + clara::Parser const& Session::cli() const { + return m_cli; + } + void Session::cli( clara::Parser const& newParser ) { + m_cli = newParser; + } + ConfigData& Session::configData() { + return m_configData; + } + Config& Session::config() { + if( !m_config ) + m_config = std::make_shared( m_configData ); + return *m_config; + } + + int Session::runInternal() { + if( m_startupExceptions ) + return 1; + + if (m_configData.showHelp || m_configData.libIdentify) { + return 0; + } + + CATCH_TRY { + config(); // Force config to be constructed + + seedRng( *m_config ); + + if( m_configData.filenamesAsTags ) + applyFilenamesAsTags( *m_config ); + + // Handle list request + if( Option listed = list( m_config ) ) + return static_cast( *listed ); + + auto totals = runTests( m_config ); + // Note that on unices only the lower 8 bits are usually used, clamping + // the return value to 255 prevents false negative when some multiple + // of 256 tests has failed + return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast(totals.assertions.failed))); + } +#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) + catch( std::exception& ex ) { + Catch::cerr() << ex.what() << std::endl; + return MaxExitCode; + } +#endif + } + +} // end namespace Catch +// end catch_session.cpp +// start catch_singletons.cpp + +#include + +namespace Catch { + + namespace { + static auto getSingletons() -> std::vector*& { + static std::vector* g_singletons = nullptr; + if( !g_singletons ) + g_singletons = new std::vector(); + return g_singletons; + } + } + + ISingleton::~ISingleton() {} + + void addSingleton(ISingleton* singleton ) { + getSingletons()->push_back( singleton ); + } + void cleanupSingletons() { + auto& singletons = getSingletons(); + for( auto singleton : *singletons ) + delete singleton; + delete singletons; + singletons = nullptr; + } + +} // namespace Catch +// end catch_singletons.cpp +// start catch_startup_exception_registry.cpp + +namespace Catch { +void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept { + CATCH_TRY { + m_exceptions.push_back(exception); + } CATCH_CATCH_ALL { + // If we run out of memory during start-up there's really not a lot more we can do about it + std::terminate(); + } + } + + std::vector const& StartupExceptionRegistry::getExceptions() const noexcept { + return m_exceptions; + } + +} // end namespace Catch +// end catch_startup_exception_registry.cpp +// start catch_stream.cpp + +#include +#include +#include +#include +#include +#include + +namespace Catch { + + Catch::IStream::~IStream() = default; + + namespace detail { namespace { + template + class StreamBufImpl : public std::streambuf { + char data[bufferSize]; + WriterF m_writer; + + public: + StreamBufImpl() { + setp( data, data + sizeof(data) ); + } + + ~StreamBufImpl() noexcept { + StreamBufImpl::sync(); + } + + private: + int overflow( int c ) override { + sync(); + + if( c != EOF ) { + if( pbase() == epptr() ) + m_writer( std::string( 1, static_cast( c ) ) ); + else + sputc( static_cast( c ) ); + } + return 0; + } + + int sync() override { + if( pbase() != pptr() ) { + m_writer( std::string( pbase(), static_cast( pptr() - pbase() ) ) ); + setp( pbase(), epptr() ); + } + return 0; + } + }; + + /////////////////////////////////////////////////////////////////////////// + + struct OutputDebugWriter { + + void operator()( std::string const&str ) { + writeToDebugConsole( str ); + } + }; + + /////////////////////////////////////////////////////////////////////////// + + class FileStream : public IStream { + mutable std::ofstream m_ofs; + public: + FileStream( StringRef filename ) { + m_ofs.open( filename.c_str() ); + CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" ); + } + ~FileStream() override = default; + public: // IStream + std::ostream& stream() const override { + return m_ofs; + } + }; + + /////////////////////////////////////////////////////////////////////////// + + class CoutStream : public IStream { + mutable std::ostream m_os; + public: + // Store the streambuf from cout up-front because + // cout may get redirected when running tests + CoutStream() : m_os( Catch::cout().rdbuf() ) {} + ~CoutStream() override = default; + + public: // IStream + std::ostream& stream() const override { return m_os; } + }; + + /////////////////////////////////////////////////////////////////////////// + + class DebugOutStream : public IStream { + std::unique_ptr> m_streamBuf; + mutable std::ostream m_os; + public: + DebugOutStream() + : m_streamBuf( new StreamBufImpl() ), + m_os( m_streamBuf.get() ) + {} + + ~DebugOutStream() override = default; + + public: // IStream + std::ostream& stream() const override { return m_os; } + }; + + }} // namespace anon::detail + + /////////////////////////////////////////////////////////////////////////// + + auto makeStream( StringRef const &filename ) -> IStream const* { + if( filename.empty() ) + return new detail::CoutStream(); + else if( filename[0] == '%' ) { + if( filename == "%debug" ) + return new detail::DebugOutStream(); + else + CATCH_ERROR( "Unrecognised stream: '" << filename << "'" ); + } + else + return new detail::FileStream( filename ); + } + + // This class encapsulates the idea of a pool of ostringstreams that can be reused. + struct StringStreams { + std::vector> m_streams; + std::vector m_unused; + std::ostringstream m_referenceStream; // Used for copy state/ flags from + + auto add() -> std::size_t { + if( m_unused.empty() ) { + m_streams.push_back( std::unique_ptr( new std::ostringstream ) ); + return m_streams.size()-1; + } + else { + auto index = m_unused.back(); + m_unused.pop_back(); + return index; + } + } + + void release( std::size_t index ) { + m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state + m_unused.push_back(index); + } + }; + + ReusableStringStream::ReusableStringStream() + : m_index( Singleton::getMutable().add() ), + m_oss( Singleton::getMutable().m_streams[m_index].get() ) + {} + + ReusableStringStream::~ReusableStringStream() { + static_cast( m_oss )->str(""); + m_oss->clear(); + Singleton::getMutable().release( m_index ); + } + + auto ReusableStringStream::str() const -> std::string { + return static_cast( m_oss )->str(); + } + + /////////////////////////////////////////////////////////////////////////// + +#ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions + std::ostream& cout() { return std::cout; } + std::ostream& cerr() { return std::cerr; } + std::ostream& clog() { return std::clog; } +#endif +} +// end catch_stream.cpp +// start catch_string_manip.cpp + +#include +#include +#include +#include + +namespace Catch { + + namespace { + char toLowerCh(char c) { + return static_cast( std::tolower( c ) ); + } + } + + bool startsWith( std::string const& s, std::string const& prefix ) { + return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin()); + } + bool startsWith( std::string const& s, char prefix ) { + return !s.empty() && s[0] == prefix; + } + bool endsWith( std::string const& s, std::string const& suffix ) { + return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin()); + } + bool endsWith( std::string const& s, char suffix ) { + return !s.empty() && s[s.size()-1] == suffix; + } + bool contains( std::string const& s, std::string const& infix ) { + return s.find( infix ) != std::string::npos; + } + void toLowerInPlace( std::string& s ) { + std::transform( s.begin(), s.end(), s.begin(), toLowerCh ); + } + std::string toLower( std::string const& s ) { + std::string lc = s; + toLowerInPlace( lc ); + return lc; + } + std::string trim( std::string const& str ) { + static char const* whitespaceChars = "\n\r\t "; + std::string::size_type start = str.find_first_not_of( whitespaceChars ); + std::string::size_type end = str.find_last_not_of( whitespaceChars ); + + return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string(); + } + + bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) { + bool replaced = false; + std::size_t i = str.find( replaceThis ); + while( i != std::string::npos ) { + replaced = true; + str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() ); + if( i < str.size()-withThis.size() ) + i = str.find( replaceThis, i+withThis.size() ); + else + i = std::string::npos; + } + return replaced; + } + + pluralise::pluralise( std::size_t count, std::string const& label ) + : m_count( count ), + m_label( label ) + {} + + std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) { + os << pluraliser.m_count << ' ' << pluraliser.m_label; + if( pluraliser.m_count != 1 ) + os << 's'; + return os; + } + +} +// end catch_string_manip.cpp +// start catch_stringref.cpp + +#if defined(__clang__) +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wexit-time-destructors" +#endif + +#include +#include +#include + +namespace { + const uint32_t byte_2_lead = 0xC0; + const uint32_t byte_3_lead = 0xE0; + const uint32_t byte_4_lead = 0xF0; +} + +namespace Catch { + StringRef::StringRef( char const* rawChars ) noexcept + : StringRef( rawChars, static_cast(std::strlen(rawChars) ) ) + {} + + StringRef::operator std::string() const { + return std::string( m_start, m_size ); + } + + void StringRef::swap( StringRef& other ) noexcept { + std::swap( m_start, other.m_start ); + std::swap( m_size, other.m_size ); + std::swap( m_data, other.m_data ); + } + + auto StringRef::c_str() const -> char const* { + if( isSubstring() ) + const_cast( this )->takeOwnership(); + return m_start; + } + auto StringRef::currentData() const noexcept -> char const* { + return m_start; + } + + auto StringRef::isOwned() const noexcept -> bool { + return m_data != nullptr; + } + auto StringRef::isSubstring() const noexcept -> bool { + return m_start[m_size] != '\0'; + } + + void StringRef::takeOwnership() { + if( !isOwned() ) { + m_data = new char[m_size+1]; + memcpy( m_data, m_start, m_size ); + m_data[m_size] = '\0'; + m_start = m_data; + } + } + auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef { + if( start < m_size ) + return StringRef( m_start+start, size ); + else + return StringRef(); + } + auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool { + return + size() == other.size() && + (std::strncmp( m_start, other.m_start, size() ) == 0); + } + auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool { + return !operator==( other ); + } + + auto StringRef::operator[](size_type index) const noexcept -> char { + return m_start[index]; + } + + auto StringRef::numberOfCharacters() const noexcept -> size_type { + size_type noChars = m_size; + // Make adjustments for uft encodings + for( size_type i=0; i < m_size; ++i ) { + char c = m_start[i]; + if( ( c & byte_2_lead ) == byte_2_lead ) { + noChars--; + if (( c & byte_3_lead ) == byte_3_lead ) + noChars--; + if( ( c & byte_4_lead ) == byte_4_lead ) + noChars--; + } + } + return noChars; + } + + auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string { + std::string str; + str.reserve( lhs.size() + rhs.size() ); + str += lhs; + str += rhs; + return str; + } + auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string { + return std::string( lhs ) + std::string( rhs ); + } + auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string { + return std::string( lhs ) + std::string( rhs ); + } + + auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& { + return os.write(str.currentData(), str.size()); + } + + auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& { + lhs.append(rhs.currentData(), rhs.size()); + return lhs; + } + +} // namespace Catch + +#if defined(__clang__) +# pragma clang diagnostic pop +#endif +// end catch_stringref.cpp +// start catch_tag_alias.cpp + +namespace Catch { + TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {} +} +// end catch_tag_alias.cpp +// start catch_tag_alias_autoregistrar.cpp + +namespace Catch { + + RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) { + CATCH_TRY { + getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo); + } CATCH_CATCH_ALL { + // Do not throw when constructing global objects, instead register the exception to be processed later + getMutableRegistryHub().registerStartupException(); + } + } + +} +// end catch_tag_alias_autoregistrar.cpp +// start catch_tag_alias_registry.cpp + +#include + +namespace Catch { + + TagAliasRegistry::~TagAliasRegistry() {} + + TagAlias const* TagAliasRegistry::find( std::string const& alias ) const { + auto it = m_registry.find( alias ); + if( it != m_registry.end() ) + return &(it->second); + else + return nullptr; + } + + std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const { + std::string expandedTestSpec = unexpandedTestSpec; + for( auto const& registryKvp : m_registry ) { + std::size_t pos = expandedTestSpec.find( registryKvp.first ); + if( pos != std::string::npos ) { + expandedTestSpec = expandedTestSpec.substr( 0, pos ) + + registryKvp.second.tag + + expandedTestSpec.substr( pos + registryKvp.first.size() ); + } + } + return expandedTestSpec; + } + + void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) { + CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'), + "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo ); + + CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second, + "error: tag alias, '" << alias << "' already registered.\n" + << "\tFirst seen at: " << find(alias)->lineInfo << "\n" + << "\tRedefined at: " << lineInfo ); + } + + ITagAliasRegistry::~ITagAliasRegistry() {} + + ITagAliasRegistry const& ITagAliasRegistry::get() { + return getRegistryHub().getTagAliasRegistry(); + } + +} // end namespace Catch +// end catch_tag_alias_registry.cpp +// start catch_test_case_info.cpp + +#include +#include +#include +#include + +namespace Catch { + + namespace { + TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) { + if( startsWith( tag, '.' ) || + tag == "!hide" ) + return TestCaseInfo::IsHidden; + else if( tag == "!throws" ) + return TestCaseInfo::Throws; + else if( tag == "!shouldfail" ) + return TestCaseInfo::ShouldFail; + else if( tag == "!mayfail" ) + return TestCaseInfo::MayFail; + else if( tag == "!nonportable" ) + return TestCaseInfo::NonPortable; + else if( tag == "!benchmark" ) + return static_cast( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden ); + else + return TestCaseInfo::None; + } + bool isReservedTag( std::string const& tag ) { + return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast(tag[0]) ); + } + void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) { + CATCH_ENFORCE( !isReservedTag(tag), + "Tag name: [" << tag << "] is not allowed.\n" + << "Tag names starting with non alpha-numeric characters are reserved\n" + << _lineInfo ); + } + } + + TestCase makeTestCase( ITestInvoker* _testCase, + std::string const& _className, + NameAndTags const& nameAndTags, + SourceLineInfo const& _lineInfo ) + { + bool isHidden = false; + + // Parse out tags + std::vector tags; + std::string desc, tag; + bool inTag = false; + std::string _descOrTags = nameAndTags.tags; + for (char c : _descOrTags) { + if( !inTag ) { + if( c == '[' ) + inTag = true; + else + desc += c; + } + else { + if( c == ']' ) { + TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag ); + if( ( prop & TestCaseInfo::IsHidden ) != 0 ) + isHidden = true; + else if( prop == TestCaseInfo::None ) + enforceNotReservedTag( tag, _lineInfo ); + + tags.push_back( tag ); + tag.clear(); + inTag = false; + } + else + tag += c; + } + } + if( isHidden ) { + tags.push_back( "." ); + } + + TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo ); + return TestCase( _testCase, std::move(info) ); + } + + void setTags( TestCaseInfo& testCaseInfo, std::vector tags ) { + std::sort(begin(tags), end(tags)); + tags.erase(std::unique(begin(tags), end(tags)), end(tags)); + testCaseInfo.lcaseTags.clear(); + + for( auto const& tag : tags ) { + std::string lcaseTag = toLower( tag ); + testCaseInfo.properties = static_cast( testCaseInfo.properties | parseSpecialTag( lcaseTag ) ); + testCaseInfo.lcaseTags.push_back( lcaseTag ); + } + testCaseInfo.tags = std::move(tags); + } + + TestCaseInfo::TestCaseInfo( std::string const& _name, + std::string const& _className, + std::string const& _description, + std::vector const& _tags, + SourceLineInfo const& _lineInfo ) + : name( _name ), + className( _className ), + description( _description ), + lineInfo( _lineInfo ), + properties( None ) + { + setTags( *this, _tags ); + } + + bool TestCaseInfo::isHidden() const { + return ( properties & IsHidden ) != 0; + } + bool TestCaseInfo::throws() const { + return ( properties & Throws ) != 0; + } + bool TestCaseInfo::okToFail() const { + return ( properties & (ShouldFail | MayFail ) ) != 0; + } + bool TestCaseInfo::expectedToFail() const { + return ( properties & (ShouldFail ) ) != 0; + } + + std::string TestCaseInfo::tagsAsString() const { + std::string ret; + // '[' and ']' per tag + std::size_t full_size = 2 * tags.size(); + for (const auto& tag : tags) { + full_size += tag.size(); + } + ret.reserve(full_size); + for (const auto& tag : tags) { + ret.push_back('['); + ret.append(tag); + ret.push_back(']'); + } + + return ret; + } + + TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {} + + TestCase TestCase::withName( std::string const& _newName ) const { + TestCase other( *this ); + other.name = _newName; + return other; + } + + void TestCase::invoke() const { + test->invoke(); + } + + bool TestCase::operator == ( TestCase const& other ) const { + return test.get() == other.test.get() && + name == other.name && + className == other.className; + } + + bool TestCase::operator < ( TestCase const& other ) const { + return name < other.name; + } + + TestCaseInfo const& TestCase::getTestCaseInfo() const + { + return *this; + } + +} // end namespace Catch +// end catch_test_case_info.cpp +// start catch_test_case_registry_impl.cpp + +#include + +namespace Catch { + + std::vector sortTests( IConfig const& config, std::vector const& unsortedTestCases ) { + + std::vector sorted = unsortedTestCases; + + switch( config.runOrder() ) { + case RunTests::InLexicographicalOrder: + std::sort( sorted.begin(), sorted.end() ); + break; + case RunTests::InRandomOrder: + seedRng( config ); + std::shuffle( sorted.begin(), sorted.end(), rng() ); + break; + case RunTests::InDeclarationOrder: + // already in declaration order + break; + } + return sorted; + } + bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) { + return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() ); + } + + void enforceNoDuplicateTestCases( std::vector const& functions ) { + std::set seenFunctions; + for( auto const& function : functions ) { + auto prev = seenFunctions.insert( function ); + CATCH_ENFORCE( prev.second, + "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n" + << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n" + << "\tRedefined at " << function.getTestCaseInfo().lineInfo ); + } + } + + std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ) { + std::vector filtered; + filtered.reserve( testCases.size() ); + for( auto const& testCase : testCases ) + if( matchTest( testCase, testSpec, config ) ) + filtered.push_back( testCase ); + return filtered; + } + std::vector const& getAllTestCasesSorted( IConfig const& config ) { + return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config ); + } + + void TestRegistry::registerTest( TestCase const& testCase ) { + std::string name = testCase.getTestCaseInfo().name; + if( name.empty() ) { + ReusableStringStream rss; + rss << "Anonymous test case " << ++m_unnamedCount; + return registerTest( testCase.withName( rss.str() ) ); + } + m_functions.push_back( testCase ); + } + + std::vector const& TestRegistry::getAllTests() const { + return m_functions; + } + std::vector const& TestRegistry::getAllTestsSorted( IConfig const& config ) const { + if( m_sortedFunctions.empty() ) + enforceNoDuplicateTestCases( m_functions ); + + if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) { + m_sortedFunctions = sortTests( config, m_functions ); + m_currentSortOrder = config.runOrder(); + } + return m_sortedFunctions; + } + + /////////////////////////////////////////////////////////////////////////// + TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {} + + void TestInvokerAsFunction::invoke() const { + m_testAsFunction(); + } + + std::string extractClassName( StringRef const& classOrQualifiedMethodName ) { + std::string className = classOrQualifiedMethodName; + if( startsWith( className, '&' ) ) + { + std::size_t lastColons = className.rfind( "::" ); + std::size_t penultimateColons = className.rfind( "::", lastColons-1 ); + if( penultimateColons == std::string::npos ) + penultimateColons = 1; + className = className.substr( penultimateColons, lastColons-penultimateColons ); + } + return className; + } + +} // end namespace Catch +// end catch_test_case_registry_impl.cpp +// start catch_test_case_tracker.cpp + +#include +#include +#include +#include +#include + +#if defined(__clang__) +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wexit-time-destructors" +#endif + +namespace Catch { +namespace TestCaseTracking { + + NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location ) + : name( _name ), + location( _location ) + {} + + ITracker::~ITracker() = default; + + TrackerContext& TrackerContext::instance() { + static TrackerContext s_instance; + return s_instance; + } + + ITracker& TrackerContext::startRun() { + m_rootTracker = std::make_shared( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr ); + m_currentTracker = nullptr; + m_runState = Executing; + return *m_rootTracker; + } + + void TrackerContext::endRun() { + m_rootTracker.reset(); + m_currentTracker = nullptr; + m_runState = NotStarted; + } + + void TrackerContext::startCycle() { + m_currentTracker = m_rootTracker.get(); + m_runState = Executing; + } + void TrackerContext::completeCycle() { + m_runState = CompletedCycle; + } + + bool TrackerContext::completedCycle() const { + return m_runState == CompletedCycle; + } + ITracker& TrackerContext::currentTracker() { + return *m_currentTracker; + } + void TrackerContext::setCurrentTracker( ITracker* tracker ) { + m_currentTracker = tracker; + } + + TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ) + : m_nameAndLocation( nameAndLocation ), + m_ctx( ctx ), + m_parent( parent ) + {} + + NameAndLocation const& TrackerBase::nameAndLocation() const { + return m_nameAndLocation; + } + bool TrackerBase::isComplete() const { + return m_runState == CompletedSuccessfully || m_runState == Failed; + } + bool TrackerBase::isSuccessfullyCompleted() const { + return m_runState == CompletedSuccessfully; + } + bool TrackerBase::isOpen() const { + return m_runState != NotStarted && !isComplete(); + } + bool TrackerBase::hasChildren() const { + return !m_children.empty(); + } + + void TrackerBase::addChild( ITrackerPtr const& child ) { + m_children.push_back( child ); + } + + ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) { + auto it = std::find_if( m_children.begin(), m_children.end(), + [&nameAndLocation]( ITrackerPtr const& tracker ){ + return + tracker->nameAndLocation().location == nameAndLocation.location && + tracker->nameAndLocation().name == nameAndLocation.name; + } ); + return( it != m_children.end() ) + ? *it + : nullptr; + } + ITracker& TrackerBase::parent() { + assert( m_parent ); // Should always be non-null except for root + return *m_parent; + } + + void TrackerBase::openChild() { + if( m_runState != ExecutingChildren ) { + m_runState = ExecutingChildren; + if( m_parent ) + m_parent->openChild(); + } + } + + bool TrackerBase::isSectionTracker() const { return false; } + bool TrackerBase::isGeneratorTracker() const { return false; } + + void TrackerBase::open() { + m_runState = Executing; + moveToThis(); + if( m_parent ) + m_parent->openChild(); + } + + void TrackerBase::close() { + + // Close any still open children (e.g. generators) + while( &m_ctx.currentTracker() != this ) + m_ctx.currentTracker().close(); + + switch( m_runState ) { + case NeedsAnotherRun: + break; + + case Executing: + m_runState = CompletedSuccessfully; + break; + case ExecutingChildren: + if( m_children.empty() || m_children.back()->isComplete() ) + m_runState = CompletedSuccessfully; + break; + + case NotStarted: + case CompletedSuccessfully: + case Failed: + CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState ); + + default: + CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState ); + } + moveToParent(); + m_ctx.completeCycle(); + } + void TrackerBase::fail() { + m_runState = Failed; + if( m_parent ) + m_parent->markAsNeedingAnotherRun(); + moveToParent(); + m_ctx.completeCycle(); + } + void TrackerBase::markAsNeedingAnotherRun() { + m_runState = NeedsAnotherRun; + } + + void TrackerBase::moveToParent() { + assert( m_parent ); + m_ctx.setCurrentTracker( m_parent ); + } + void TrackerBase::moveToThis() { + m_ctx.setCurrentTracker( this ); + } + + SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ) + : TrackerBase( nameAndLocation, ctx, parent ) + { + if( parent ) { + while( !parent->isSectionTracker() ) + parent = &parent->parent(); + + SectionTracker& parentSection = static_cast( *parent ); + addNextFilters( parentSection.m_filters ); + } + } + + bool SectionTracker::isComplete() const { + bool complete = true; + + if ((m_filters.empty() || m_filters[0] == "") || + std::find(m_filters.begin(), m_filters.end(), + m_nameAndLocation.name) != m_filters.end()) + complete = TrackerBase::isComplete(); + return complete; + + } + + bool SectionTracker::isSectionTracker() const { return true; } + + SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) { + std::shared_ptr section; + + ITracker& currentTracker = ctx.currentTracker(); + if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) { + assert( childTracker ); + assert( childTracker->isSectionTracker() ); + section = std::static_pointer_cast( childTracker ); + } + else { + section = std::make_shared( nameAndLocation, ctx, ¤tTracker ); + currentTracker.addChild( section ); + } + if( !ctx.completedCycle() ) + section->tryOpen(); + return *section; + } + + void SectionTracker::tryOpen() { + if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) ) + open(); + } + + void SectionTracker::addInitialFilters( std::vector const& filters ) { + if( !filters.empty() ) { + m_filters.push_back(""); // Root - should never be consulted + m_filters.push_back(""); // Test Case - not a section filter + m_filters.insert( m_filters.end(), filters.begin(), filters.end() ); + } + } + void SectionTracker::addNextFilters( std::vector const& filters ) { + if( filters.size() > 1 ) + m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() ); + } + +} // namespace TestCaseTracking + +using TestCaseTracking::ITracker; +using TestCaseTracking::TrackerContext; +using TestCaseTracking::SectionTracker; + +} // namespace Catch + +#if defined(__clang__) +# pragma clang diagnostic pop +#endif +// end catch_test_case_tracker.cpp +// start catch_test_registry.cpp + +namespace Catch { + + auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* { + return new(std::nothrow) TestInvokerAsFunction( testAsFunction ); + } + + NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {} + + AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept { + CATCH_TRY { + getMutableRegistryHub() + .registerTest( + makeTestCase( + invoker, + extractClassName( classOrMethod ), + nameAndTags, + lineInfo)); + } CATCH_CATCH_ALL { + // Do not throw when constructing global objects, instead register the exception to be processed later + getMutableRegistryHub().registerStartupException(); + } + } + + AutoReg::~AutoReg() = default; +} +// end catch_test_registry.cpp +// start catch_test_spec.cpp + +#include +#include +#include +#include + +namespace Catch { + + TestSpec::Pattern::~Pattern() = default; + TestSpec::NamePattern::~NamePattern() = default; + TestSpec::TagPattern::~TagPattern() = default; + TestSpec::ExcludedPattern::~ExcludedPattern() = default; + + TestSpec::NamePattern::NamePattern( std::string const& name ) + : m_wildcardPattern( toLower( name ), CaseSensitive::No ) + {} + bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const { + return m_wildcardPattern.matches( toLower( testCase.name ) ); + } + + TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {} + bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const { + return std::find(begin(testCase.lcaseTags), + end(testCase.lcaseTags), + m_tag) != end(testCase.lcaseTags); + } + + TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {} + bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); } + + bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const { + // All patterns in a filter must match for the filter to be a match + for( auto const& pattern : m_patterns ) { + if( !pattern->matches( testCase ) ) + return false; + } + return true; + } + + bool TestSpec::hasFilters() const { + return !m_filters.empty(); + } + bool TestSpec::matches( TestCaseInfo const& testCase ) const { + // A TestSpec matches if any filter matches + for( auto const& filter : m_filters ) + if( filter.matches( testCase ) ) + return true; + return false; + } +} +// end catch_test_spec.cpp +// start catch_test_spec_parser.cpp + +namespace Catch { + + TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {} + + TestSpecParser& TestSpecParser::parse( std::string const& arg ) { + m_mode = None; + m_exclusion = false; + m_start = std::string::npos; + m_arg = m_tagAliases->expandAliases( arg ); + m_escapeChars.clear(); + for( m_pos = 0; m_pos < m_arg.size(); ++m_pos ) + visitChar( m_arg[m_pos] ); + if( m_mode == Name ) + addPattern(); + return *this; + } + TestSpec TestSpecParser::testSpec() { + addFilter(); + return m_testSpec; + } + + void TestSpecParser::visitChar( char c ) { + if( m_mode == None ) { + switch( c ) { + case ' ': return; + case '~': m_exclusion = true; return; + case '[': return startNewMode( Tag, ++m_pos ); + case '"': return startNewMode( QuotedName, ++m_pos ); + case '\\': return escape(); + default: startNewMode( Name, m_pos ); break; + } + } + if( m_mode == Name ) { + if( c == ',' ) { + addPattern(); + addFilter(); + } + else if( c == '[' ) { + if( subString() == "exclude:" ) + m_exclusion = true; + else + addPattern(); + startNewMode( Tag, ++m_pos ); + } + else if( c == '\\' ) + escape(); + } + else if( m_mode == EscapedName ) + m_mode = Name; + else if( m_mode == QuotedName && c == '"' ) + addPattern(); + else if( m_mode == Tag && c == ']' ) + addPattern(); + } + void TestSpecParser::startNewMode( Mode mode, std::size_t start ) { + m_mode = mode; + m_start = start; + } + void TestSpecParser::escape() { + if( m_mode == None ) + m_start = m_pos; + m_mode = EscapedName; + m_escapeChars.push_back( m_pos ); + } + std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); } + + void TestSpecParser::addFilter() { + if( !m_currentFilter.m_patterns.empty() ) { + m_testSpec.m_filters.push_back( m_currentFilter ); + m_currentFilter = TestSpec::Filter(); + } + } + + TestSpec parseTestSpec( std::string const& arg ) { + return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec(); + } + +} // namespace Catch +// end catch_test_spec_parser.cpp +// start catch_timer.cpp + +#include + +static const uint64_t nanosecondsInSecond = 1000000000; + +namespace Catch { + + auto getCurrentNanosecondsSinceEpoch() -> uint64_t { + return std::chrono::duration_cast( std::chrono::high_resolution_clock::now().time_since_epoch() ).count(); + } + + namespace { + auto estimateClockResolution() -> uint64_t { + uint64_t sum = 0; + static const uint64_t iterations = 1000000; + + auto startTime = getCurrentNanosecondsSinceEpoch(); + + for( std::size_t i = 0; i < iterations; ++i ) { + + uint64_t ticks; + uint64_t baseTicks = getCurrentNanosecondsSinceEpoch(); + do { + ticks = getCurrentNanosecondsSinceEpoch(); + } while( ticks == baseTicks ); + + auto delta = ticks - baseTicks; + sum += delta; + + // If we have been calibrating for over 3 seconds -- the clock + // is terrible and we should move on. + // TBD: How to signal that the measured resolution is probably wrong? + if (ticks > startTime + 3 * nanosecondsInSecond) { + return sum / ( i + 1u ); + } + } + + // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers + // - and potentially do more iterations if there's a high variance. + return sum/iterations; + } + } + auto getEstimatedClockResolution() -> uint64_t { + static auto s_resolution = estimateClockResolution(); + return s_resolution; + } + + void Timer::start() { + m_nanoseconds = getCurrentNanosecondsSinceEpoch(); + } + auto Timer::getElapsedNanoseconds() const -> uint64_t { + return getCurrentNanosecondsSinceEpoch() - m_nanoseconds; + } + auto Timer::getElapsedMicroseconds() const -> uint64_t { + return getElapsedNanoseconds()/1000; + } + auto Timer::getElapsedMilliseconds() const -> unsigned int { + return static_cast(getElapsedMicroseconds()/1000); + } + auto Timer::getElapsedSeconds() const -> double { + return getElapsedMicroseconds()/1000000.0; + } + +} // namespace Catch +// end catch_timer.cpp +// start catch_tostring.cpp + +#if defined(__clang__) +# pragma clang diagnostic push +# pragma clang diagnostic ignored "-Wexit-time-destructors" +# pragma clang diagnostic ignored "-Wglobal-constructors" +#endif + +// Enable specific decls locally +#if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER) +#define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER +#endif + +#include +#include + +namespace Catch { + +namespace Detail { + + const std::string unprintableString = "{?}"; + + namespace { + const int hexThreshold = 255; + + struct Endianness { + enum Arch { Big, Little }; + + static Arch which() { + union _{ + int asInt; + char asChar[sizeof (int)]; + } u; + + u.asInt = 1; + return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little; + } + }; + } + + std::string rawMemoryToString( const void *object, std::size_t size ) { + // Reverse order for little endian architectures + int i = 0, end = static_cast( size ), inc = 1; + if( Endianness::which() == Endianness::Little ) { + i = end-1; + end = inc = -1; + } + + unsigned char const *bytes = static_cast(object); + ReusableStringStream rss; + rss << "0x" << std::setfill('0') << std::hex; + for( ; i != end; i += inc ) + rss << std::setw(2) << static_cast(bytes[i]); + return rss.str(); + } +} + +template +std::string fpToString( T value, int precision ) { + if (Catch::isnan(value)) { + return "nan"; + } + + ReusableStringStream rss; + rss << std::setprecision( precision ) + << std::fixed + << value; + std::string d = rss.str(); + std::size_t i = d.find_last_not_of( '0' ); + if( i != std::string::npos && i != d.size()-1 ) { + if( d[i] == '.' ) + i++; + d = d.substr( 0, i+1 ); + } + return d; +} + +//// ======================================================= //// +// +// Out-of-line defs for full specialization of StringMaker +// +//// ======================================================= //// + +std::string StringMaker::convert(const std::string& str) { + if (!getCurrentContext().getConfig()->showInvisibles()) { + return '"' + str + '"'; + } + + std::string s("\""); + for (char c : str) { + switch (c) { + case '\n': + s.append("\\n"); + break; + case '\t': + s.append("\\t"); + break; + default: + s.push_back(c); + break; + } + } + s.append("\""); + return s; +} + +#ifdef CATCH_CONFIG_CPP17_STRING_VIEW +std::string StringMaker::convert(std::string_view str) { + return ::Catch::Detail::stringify(std::string{ str }); +} +#endif + +std::string StringMaker::convert(char const* str) { + if (str) { + return ::Catch::Detail::stringify(std::string{ str }); + } else { + return{ "{null string}" }; + } +} +std::string StringMaker::convert(char* str) { + if (str) { + return ::Catch::Detail::stringify(std::string{ str }); + } else { + return{ "{null string}" }; + } +} + +#ifdef CATCH_CONFIG_WCHAR +std::string StringMaker::convert(const std::wstring& wstr) { + std::string s; + s.reserve(wstr.size()); + for (auto c : wstr) { + s += (c <= 0xff) ? static_cast(c) : '?'; + } + return ::Catch::Detail::stringify(s); +} + +# ifdef CATCH_CONFIG_CPP17_STRING_VIEW +std::string StringMaker::convert(std::wstring_view str) { + return StringMaker::convert(std::wstring(str)); +} +# endif + +std::string StringMaker::convert(wchar_t const * str) { + if (str) { + return ::Catch::Detail::stringify(std::wstring{ str }); + } else { + return{ "{null string}" }; + } +} +std::string StringMaker::convert(wchar_t * str) { + if (str) { + return ::Catch::Detail::stringify(std::wstring{ str }); + } else { + return{ "{null string}" }; + } +} +#endif + +std::string StringMaker::convert(int value) { + return ::Catch::Detail::stringify(static_cast(value)); +} +std::string StringMaker::convert(long value) { + return ::Catch::Detail::stringify(static_cast(value)); +} +std::string StringMaker::convert(long long value) { + ReusableStringStream rss; + rss << value; + if (value > Detail::hexThreshold) { + rss << " (0x" << std::hex << value << ')'; + } + return rss.str(); +} + +std::string StringMaker::convert(unsigned int value) { + return ::Catch::Detail::stringify(static_cast(value)); +} +std::string StringMaker::convert(unsigned long value) { + return ::Catch::Detail::stringify(static_cast(value)); +} +std::string StringMaker::convert(unsigned long long value) { + ReusableStringStream rss; + rss << value; + if (value > Detail::hexThreshold) { + rss << " (0x" << std::hex << value << ')'; + } + return rss.str(); +} + +std::string StringMaker::convert(bool b) { + return b ? "true" : "false"; +} + +std::string StringMaker::convert(signed char value) { + if (value == '\r') { + return "'\\r'"; + } else if (value == '\f') { + return "'\\f'"; + } else if (value == '\n') { + return "'\\n'"; + } else if (value == '\t') { + return "'\\t'"; + } else if ('\0' <= value && value < ' ') { + return ::Catch::Detail::stringify(static_cast(value)); + } else { + char chstr[] = "' '"; + chstr[1] = value; + return chstr; + } +} +std::string StringMaker::convert(char c) { + return ::Catch::Detail::stringify(static_cast(c)); +} +std::string StringMaker::convert(unsigned char c) { + return ::Catch::Detail::stringify(static_cast(c)); +} + +std::string StringMaker::convert(std::nullptr_t) { + return "nullptr"; +} + +std::string StringMaker::convert(float value) { + return fpToString(value, 5) + 'f'; +} +std::string StringMaker::convert(double value) { + return fpToString(value, 10); +} + +std::string ratio_string::symbol() { return "a"; } +std::string ratio_string::symbol() { return "f"; } +std::string ratio_string::symbol() { return "p"; } +std::string ratio_string::symbol() { return "n"; } +std::string ratio_string::symbol() { return "u"; } +std::string ratio_string::symbol() { return "m"; } + +} // end namespace Catch + +#if defined(__clang__) +# pragma clang diagnostic pop +#endif + +// end catch_tostring.cpp +// start catch_totals.cpp + +namespace Catch { + + Counts Counts::operator - ( Counts const& other ) const { + Counts diff; + diff.passed = passed - other.passed; + diff.failed = failed - other.failed; + diff.failedButOk = failedButOk - other.failedButOk; + return diff; + } + + Counts& Counts::operator += ( Counts const& other ) { + passed += other.passed; + failed += other.failed; + failedButOk += other.failedButOk; + return *this; + } + + std::size_t Counts::total() const { + return passed + failed + failedButOk; + } + bool Counts::allPassed() const { + return failed == 0 && failedButOk == 0; + } + bool Counts::allOk() const { + return failed == 0; + } + + Totals Totals::operator - ( Totals const& other ) const { + Totals diff; + diff.assertions = assertions - other.assertions; + diff.testCases = testCases - other.testCases; + return diff; + } + + Totals& Totals::operator += ( Totals const& other ) { + assertions += other.assertions; + testCases += other.testCases; + return *this; + } + + Totals Totals::delta( Totals const& prevTotals ) const { + Totals diff = *this - prevTotals; + if( diff.assertions.failed > 0 ) + ++diff.testCases.failed; + else if( diff.assertions.failedButOk > 0 ) + ++diff.testCases.failedButOk; + else + ++diff.testCases.passed; + return diff; + } + +} +// end catch_totals.cpp +// start catch_uncaught_exceptions.cpp + +#include + +namespace Catch { + bool uncaught_exceptions() { +#if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) + return std::uncaught_exceptions() > 0; +#else + return std::uncaught_exception(); +#endif + } +} // end namespace Catch +// end catch_uncaught_exceptions.cpp +// start catch_version.cpp + +#include + +namespace Catch { + + Version::Version + ( unsigned int _majorVersion, + unsigned int _minorVersion, + unsigned int _patchNumber, + char const * const _branchName, + unsigned int _buildNumber ) + : majorVersion( _majorVersion ), + minorVersion( _minorVersion ), + patchNumber( _patchNumber ), + branchName( _branchName ), + buildNumber( _buildNumber ) + {} + + std::ostream& operator << ( std::ostream& os, Version const& version ) { + os << version.majorVersion << '.' + << version.minorVersion << '.' + << version.patchNumber; + // branchName is never null -> 0th char is \0 if it is empty + if (version.branchName[0]) { + os << '-' << version.branchName + << '.' << version.buildNumber; + } + return os; + } + + Version const& libraryVersion() { + static Version version( 2, 7, 0, "", 0 ); + return version; + } + +} +// end catch_version.cpp +// start catch_wildcard_pattern.cpp + +#include + +namespace Catch { + + WildcardPattern::WildcardPattern( std::string const& pattern, + CaseSensitive::Choice caseSensitivity ) + : m_caseSensitivity( caseSensitivity ), + m_pattern( adjustCase( pattern ) ) + { + if( startsWith( m_pattern, '*' ) ) { + m_pattern = m_pattern.substr( 1 ); + m_wildcard = WildcardAtStart; + } + if( endsWith( m_pattern, '*' ) ) { + m_pattern = m_pattern.substr( 0, m_pattern.size()-1 ); + m_wildcard = static_cast( m_wildcard | WildcardAtEnd ); + } + } + + bool WildcardPattern::matches( std::string const& str ) const { + switch( m_wildcard ) { + case NoWildcard: + return m_pattern == adjustCase( str ); + case WildcardAtStart: + return endsWith( adjustCase( str ), m_pattern ); + case WildcardAtEnd: + return startsWith( adjustCase( str ), m_pattern ); + case WildcardAtBothEnds: + return contains( adjustCase( str ), m_pattern ); + default: + CATCH_INTERNAL_ERROR( "Unknown enum" ); + } + } + + std::string WildcardPattern::adjustCase( std::string const& str ) const { + return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str; + } +} +// end catch_wildcard_pattern.cpp +// start catch_xmlwriter.cpp + +#include + +using uchar = unsigned char; + +namespace Catch { + +namespace { + + size_t trailingBytes(unsigned char c) { + if ((c & 0xE0) == 0xC0) { + return 2; + } + if ((c & 0xF0) == 0xE0) { + return 3; + } + if ((c & 0xF8) == 0xF0) { + return 4; + } + CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); + } + + uint32_t headerValue(unsigned char c) { + if ((c & 0xE0) == 0xC0) { + return c & 0x1F; + } + if ((c & 0xF0) == 0xE0) { + return c & 0x0F; + } + if ((c & 0xF8) == 0xF0) { + return c & 0x07; + } + CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); + } + + void hexEscapeChar(std::ostream& os, unsigned char c) { + std::ios_base::fmtflags f(os.flags()); + os << "\\x" + << std::uppercase << std::hex << std::setfill('0') << std::setw(2) + << static_cast(c); + os.flags(f); + } + +} // anonymous namespace + + XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat ) + : m_str( str ), + m_forWhat( forWhat ) + {} + + void XmlEncode::encodeTo( std::ostream& os ) const { + // Apostrophe escaping not necessary if we always use " to write attributes + // (see: http://www.w3.org/TR/xml/#syntax) + + for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { + uchar c = m_str[idx]; + switch (c) { + case '<': os << "<"; break; + case '&': os << "&"; break; + + case '>': + // See: http://www.w3.org/TR/xml/#syntax + if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') + os << ">"; + else + os << c; + break; + + case '\"': + if (m_forWhat == ForAttributes) + os << """; + else + os << c; + break; + + default: + // Check for control characters and invalid utf-8 + + // Escape control characters in standard ascii + // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 + if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { + hexEscapeChar(os, c); + break; + } + + // Plain ASCII: Write it to stream + if (c < 0x7F) { + os << c; + break; + } + + // UTF-8 territory + // Check if the encoding is valid and if it is not, hex escape bytes. + // Important: We do not check the exact decoded values for validity, only the encoding format + // First check that this bytes is a valid lead byte: + // This means that it is not encoded as 1111 1XXX + // Or as 10XX XXXX + if (c < 0xC0 || + c >= 0xF8) { + hexEscapeChar(os, c); + break; + } + + auto encBytes = trailingBytes(c); + // Are there enough bytes left to avoid accessing out-of-bounds memory? + if (idx + encBytes - 1 >= m_str.size()) { + hexEscapeChar(os, c); + break; + } + // The header is valid, check data + // The next encBytes bytes must together be a valid utf-8 + // This means: bitpattern 10XX XXXX and the extracted value is sane (ish) + bool valid = true; + uint32_t value = headerValue(c); + for (std::size_t n = 1; n < encBytes; ++n) { + uchar nc = m_str[idx + n]; + valid &= ((nc & 0xC0) == 0x80); + value = (value << 6) | (nc & 0x3F); + } + + if ( + // Wrong bit pattern of following bytes + (!valid) || + // Overlong encodings + (value < 0x80) || + (0x80 <= value && value < 0x800 && encBytes > 2) || + (0x800 < value && value < 0x10000 && encBytes > 3) || + // Encoded value out of range + (value >= 0x110000) + ) { + hexEscapeChar(os, c); + break; + } + + // If we got here, this is in fact a valid(ish) utf-8 sequence + for (std::size_t n = 0; n < encBytes; ++n) { + os << m_str[idx + n]; + } + idx += encBytes - 1; + break; + } + } + } + + std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { + xmlEncode.encodeTo( os ); + return os; + } + + XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer ) + : m_writer( writer ) + {} + + XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept + : m_writer( other.m_writer ){ + other.m_writer = nullptr; + } + XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept { + if ( m_writer ) { + m_writer->endElement(); + } + m_writer = other.m_writer; + other.m_writer = nullptr; + return *this; + } + + XmlWriter::ScopedElement::~ScopedElement() { + if( m_writer ) + m_writer->endElement(); + } + + XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) { + m_writer->writeText( text, indent ); + return *this; + } + + XmlWriter::XmlWriter( std::ostream& os ) : m_os( os ) + { + writeDeclaration(); + } + + XmlWriter::~XmlWriter() { + while( !m_tags.empty() ) + endElement(); + } + + XmlWriter& XmlWriter::startElement( std::string const& name ) { + ensureTagClosed(); + newlineIfNecessary(); + m_os << m_indent << '<' << name; + m_tags.push_back( name ); + m_indent += " "; + m_tagIsOpen = true; + return *this; + } + + XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) { + ScopedElement scoped( this ); + startElement( name ); + return scoped; + } + + XmlWriter& XmlWriter::endElement() { + newlineIfNecessary(); + m_indent = m_indent.substr( 0, m_indent.size()-2 ); + if( m_tagIsOpen ) { + m_os << "/>"; + m_tagIsOpen = false; + } + else { + m_os << m_indent << ""; + } + m_os << std::endl; + m_tags.pop_back(); + return *this; + } + + XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) { + if( !name.empty() && !attribute.empty() ) + m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; + return *this; + } + + XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) { + m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"'; + return *this; + } + + XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) { + if( !text.empty() ){ + bool tagWasOpen = m_tagIsOpen; + ensureTagClosed(); + if( tagWasOpen && indent ) + m_os << m_indent; + m_os << XmlEncode( text ); + m_needsNewline = true; + } + return *this; + } + + XmlWriter& XmlWriter::writeComment( std::string const& text ) { + ensureTagClosed(); + m_os << m_indent << ""; + m_needsNewline = true; + return *this; + } + + void XmlWriter::writeStylesheetRef( std::string const& url ) { + m_os << "\n"; + } + + XmlWriter& XmlWriter::writeBlankLine() { + ensureTagClosed(); + m_os << '\n'; + return *this; + } + + void XmlWriter::ensureTagClosed() { + if( m_tagIsOpen ) { + m_os << ">" << std::endl; + m_tagIsOpen = false; + } + } + + void XmlWriter::writeDeclaration() { + m_os << "\n"; + } + + void XmlWriter::newlineIfNecessary() { + if( m_needsNewline ) { + m_os << std::endl; + m_needsNewline = false; + } + } +} +// end catch_xmlwriter.cpp +// start catch_reporter_bases.cpp + +#include +#include +#include +#include +#include + +namespace Catch { + void prepareExpandedExpression(AssertionResult& result) { + result.getExpandedExpression(); + } + + // Because formatting using c++ streams is stateful, drop down to C is required + // Alternatively we could use stringstream, but its performance is... not good. + std::string getFormattedDuration( double duration ) { + // Max exponent + 1 is required to represent the whole part + // + 1 for decimal point + // + 3 for the 3 decimal places + // + 1 for null terminator + const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1; + char buffer[maxDoubleSize]; + + // Save previous errno, to prevent sprintf from overwriting it + ErrnoGuard guard; +#ifdef _MSC_VER + sprintf_s(buffer, "%.3f", duration); +#else + std::sprintf(buffer, "%.3f", duration); +#endif + return std::string(buffer); + } + + TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config) + :StreamingReporterBase(_config) {} + + std::set TestEventListenerBase::getSupportedVerbosities() { + return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High }; + } + + void TestEventListenerBase::assertionStarting(AssertionInfo const &) {} + + bool TestEventListenerBase::assertionEnded(AssertionStats const &) { + return false; + } + +} // end namespace Catch +// end catch_reporter_bases.cpp +// start catch_reporter_compact.cpp + +namespace { + +#ifdef CATCH_PLATFORM_MAC + const char* failedString() { return "FAILED"; } + const char* passedString() { return "PASSED"; } +#else + const char* failedString() { return "failed"; } + const char* passedString() { return "passed"; } +#endif + + // Colour::LightGrey + Catch::Colour::Code dimColour() { return Catch::Colour::FileName; } + + std::string bothOrAll( std::size_t count ) { + return count == 1 ? std::string() : + count == 2 ? "both " : "all " ; + } + +} // anon namespace + +namespace Catch { +namespace { +// Colour, message variants: +// - white: No tests ran. +// - red: Failed [both/all] N test cases, failed [both/all] M assertions. +// - white: Passed [both/all] N test cases (no assertions). +// - red: Failed N tests cases, failed M assertions. +// - green: Passed [both/all] N tests cases with M assertions. +void printTotals(std::ostream& out, const Totals& totals) { + if (totals.testCases.total() == 0) { + out << "No tests ran."; + } else if (totals.testCases.failed == totals.testCases.total()) { + Colour colour(Colour::ResultError); + const std::string qualify_assertions_failed = + totals.assertions.failed == totals.assertions.total() ? + bothOrAll(totals.assertions.failed) : std::string(); + out << + "Failed " << bothOrAll(totals.testCases.failed) + << pluralise(totals.testCases.failed, "test case") << ", " + "failed " << qualify_assertions_failed << + pluralise(totals.assertions.failed, "assertion") << '.'; + } else if (totals.assertions.total() == 0) { + out << + "Passed " << bothOrAll(totals.testCases.total()) + << pluralise(totals.testCases.total(), "test case") + << " (no assertions)."; + } else if (totals.assertions.failed) { + Colour colour(Colour::ResultError); + out << + "Failed " << pluralise(totals.testCases.failed, "test case") << ", " + "failed " << pluralise(totals.assertions.failed, "assertion") << '.'; + } else { + Colour colour(Colour::ResultSuccess); + out << + "Passed " << bothOrAll(totals.testCases.passed) + << pluralise(totals.testCases.passed, "test case") << + " with " << pluralise(totals.assertions.passed, "assertion") << '.'; + } +} + +// Implementation of CompactReporter formatting +class AssertionPrinter { +public: + AssertionPrinter& operator= (AssertionPrinter const&) = delete; + AssertionPrinter(AssertionPrinter const&) = delete; + AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages) + : stream(_stream) + , result(_stats.assertionResult) + , messages(_stats.infoMessages) + , itMessage(_stats.infoMessages.begin()) + , printInfoMessages(_printInfoMessages) {} + + void print() { + printSourceInfo(); + + itMessage = messages.begin(); + + switch (result.getResultType()) { + case ResultWas::Ok: + printResultType(Colour::ResultSuccess, passedString()); + printOriginalExpression(); + printReconstructedExpression(); + if (!result.hasExpression()) + printRemainingMessages(Colour::None); + else + printRemainingMessages(); + break; + case ResultWas::ExpressionFailed: + if (result.isOk()) + printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok")); + else + printResultType(Colour::Error, failedString()); + printOriginalExpression(); + printReconstructedExpression(); + printRemainingMessages(); + break; + case ResultWas::ThrewException: + printResultType(Colour::Error, failedString()); + printIssue("unexpected exception with message:"); + printMessage(); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::FatalErrorCondition: + printResultType(Colour::Error, failedString()); + printIssue("fatal error condition with message:"); + printMessage(); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::DidntThrowException: + printResultType(Colour::Error, failedString()); + printIssue("expected exception, got none"); + printExpressionWas(); + printRemainingMessages(); + break; + case ResultWas::Info: + printResultType(Colour::None, "info"); + printMessage(); + printRemainingMessages(); + break; + case ResultWas::Warning: + printResultType(Colour::None, "warning"); + printMessage(); + printRemainingMessages(); + break; + case ResultWas::ExplicitFailure: + printResultType(Colour::Error, failedString()); + printIssue("explicitly"); + printRemainingMessages(Colour::None); + break; + // These cases are here to prevent compiler warnings + case ResultWas::Unknown: + case ResultWas::FailureBit: + case ResultWas::Exception: + printResultType(Colour::Error, "** internal error **"); + break; + } + } + +private: + void printSourceInfo() const { + Colour colourGuard(Colour::FileName); + stream << result.getSourceInfo() << ':'; + } + + void printResultType(Colour::Code colour, std::string const& passOrFail) const { + if (!passOrFail.empty()) { + { + Colour colourGuard(colour); + stream << ' ' << passOrFail; + } + stream << ':'; + } + } + + void printIssue(std::string const& issue) const { + stream << ' ' << issue; + } + + void printExpressionWas() { + if (result.hasExpression()) { + stream << ';'; + { + Colour colour(dimColour()); + stream << " expression was:"; + } + printOriginalExpression(); + } + } + + void printOriginalExpression() const { + if (result.hasExpression()) { + stream << ' ' << result.getExpression(); + } + } + + void printReconstructedExpression() const { + if (result.hasExpandedExpression()) { + { + Colour colour(dimColour()); + stream << " for: "; + } + stream << result.getExpandedExpression(); + } + } + + void printMessage() { + if (itMessage != messages.end()) { + stream << " '" << itMessage->message << '\''; + ++itMessage; + } + } + + void printRemainingMessages(Colour::Code colour = dimColour()) { + if (itMessage == messages.end()) + return; + + // using messages.end() directly yields (or auto) compilation error: + std::vector::const_iterator itEnd = messages.end(); + const std::size_t N = static_cast(std::distance(itMessage, itEnd)); + + { + Colour colourGuard(colour); + stream << " with " << pluralise(N, "message") << ':'; + } + + for (; itMessage != itEnd; ) { + // If this assertion is a warning ignore any INFO messages + if (printInfoMessages || itMessage->type != ResultWas::Info) { + stream << " '" << itMessage->message << '\''; + if (++itMessage != itEnd) { + Colour colourGuard(dimColour()); + stream << " and"; + } + } + } + } + +private: + std::ostream& stream; + AssertionResult const& result; + std::vector messages; + std::vector::const_iterator itMessage; + bool printInfoMessages; +}; + +} // anon namespace + + std::string CompactReporter::getDescription() { + return "Reports test results on a single line, suitable for IDEs"; + } + + ReporterPreferences CompactReporter::getPreferences() const { + return m_reporterPrefs; + } + + void CompactReporter::noMatchingTestCases( std::string const& spec ) { + stream << "No test cases matched '" << spec << '\'' << std::endl; + } + + void CompactReporter::assertionStarting( AssertionInfo const& ) {} + + bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) { + AssertionResult const& result = _assertionStats.assertionResult; + + bool printInfoMessages = true; + + // Drop out if result was successful and we're not printing those + if( !m_config->includeSuccessfulResults() && result.isOk() ) { + if( result.getResultType() != ResultWas::Warning ) + return false; + printInfoMessages = false; + } + + AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); + printer.print(); + + stream << std::endl; + return true; + } + + void CompactReporter::sectionEnded(SectionStats const& _sectionStats) { + if (m_config->showDurations() == ShowDurations::Always) { + stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl; + } + } + + void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) { + printTotals( stream, _testRunStats.totals ); + stream << '\n' << std::endl; + StreamingReporterBase::testRunEnded( _testRunStats ); + } + + CompactReporter::~CompactReporter() {} + + CATCH_REGISTER_REPORTER( "compact", CompactReporter ) + +} // end namespace Catch +// end catch_reporter_compact.cpp +// start catch_reporter_console.cpp + +#include +#include + +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch + // Note that 4062 (not all labels are handled + // and default is missing) is enabled +#endif + +namespace Catch { + +namespace { + +// Formatter impl for ConsoleReporter +class ConsoleAssertionPrinter { +public: + ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete; + ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete; + ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages) + : stream(_stream), + stats(_stats), + result(_stats.assertionResult), + colour(Colour::None), + message(result.getMessage()), + messages(_stats.infoMessages), + printInfoMessages(_printInfoMessages) { + switch (result.getResultType()) { + case ResultWas::Ok: + colour = Colour::Success; + passOrFail = "PASSED"; + //if( result.hasMessage() ) + if (_stats.infoMessages.size() == 1) + messageLabel = "with message"; + if (_stats.infoMessages.size() > 1) + messageLabel = "with messages"; + break; + case ResultWas::ExpressionFailed: + if (result.isOk()) { + colour = Colour::Success; + passOrFail = "FAILED - but was ok"; + } else { + colour = Colour::Error; + passOrFail = "FAILED"; + } + if (_stats.infoMessages.size() == 1) + messageLabel = "with message"; + if (_stats.infoMessages.size() > 1) + messageLabel = "with messages"; + break; + case ResultWas::ThrewException: + colour = Colour::Error; + passOrFail = "FAILED"; + messageLabel = "due to unexpected exception with "; + if (_stats.infoMessages.size() == 1) + messageLabel += "message"; + if (_stats.infoMessages.size() > 1) + messageLabel += "messages"; + break; + case ResultWas::FatalErrorCondition: + colour = Colour::Error; + passOrFail = "FAILED"; + messageLabel = "due to a fatal error condition"; + break; + case ResultWas::DidntThrowException: + colour = Colour::Error; + passOrFail = "FAILED"; + messageLabel = "because no exception was thrown where one was expected"; + break; + case ResultWas::Info: + messageLabel = "info"; + break; + case ResultWas::Warning: + messageLabel = "warning"; + break; + case ResultWas::ExplicitFailure: + passOrFail = "FAILED"; + colour = Colour::Error; + if (_stats.infoMessages.size() == 1) + messageLabel = "explicitly with message"; + if (_stats.infoMessages.size() > 1) + messageLabel = "explicitly with messages"; + break; + // These cases are here to prevent compiler warnings + case ResultWas::Unknown: + case ResultWas::FailureBit: + case ResultWas::Exception: + passOrFail = "** internal error **"; + colour = Colour::Error; + break; + } + } + + void print() const { + printSourceInfo(); + if (stats.totals.assertions.total() > 0) { + printResultType(); + printOriginalExpression(); + printReconstructedExpression(); + } else { + stream << '\n'; + } + printMessage(); + } + +private: + void printResultType() const { + if (!passOrFail.empty()) { + Colour colourGuard(colour); + stream << passOrFail << ":\n"; + } + } + void printOriginalExpression() const { + if (result.hasExpression()) { + Colour colourGuard(Colour::OriginalExpression); + stream << " "; + stream << result.getExpressionInMacro(); + stream << '\n'; + } + } + void printReconstructedExpression() const { + if (result.hasExpandedExpression()) { + stream << "with expansion:\n"; + Colour colourGuard(Colour::ReconstructedExpression); + stream << Column(result.getExpandedExpression()).indent(2) << '\n'; + } + } + void printMessage() const { + if (!messageLabel.empty()) + stream << messageLabel << ':' << '\n'; + for (auto const& msg : messages) { + // If this assertion is a warning ignore any INFO messages + if (printInfoMessages || msg.type != ResultWas::Info) + stream << Column(msg.message).indent(2) << '\n'; + } + } + void printSourceInfo() const { + Colour colourGuard(Colour::FileName); + stream << result.getSourceInfo() << ": "; + } + + std::ostream& stream; + AssertionStats const& stats; + AssertionResult const& result; + Colour::Code colour; + std::string passOrFail; + std::string messageLabel; + std::string message; + std::vector messages; + bool printInfoMessages; +}; + +std::size_t makeRatio(std::size_t number, std::size_t total) { + std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0; + return (ratio == 0 && number > 0) ? 1 : ratio; +} + +std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) { + if (i > j && i > k) + return i; + else if (j > k) + return j; + else + return k; +} + +struct ColumnInfo { + enum Justification { Left, Right }; + std::string name; + int width; + Justification justification; +}; +struct ColumnBreak {}; +struct RowBreak {}; + +class Duration { + enum class Unit { + Auto, + Nanoseconds, + Microseconds, + Milliseconds, + Seconds, + Minutes + }; + static const uint64_t s_nanosecondsInAMicrosecond = 1000; + static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond; + static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond; + static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond; + + uint64_t m_inNanoseconds; + Unit m_units; + +public: + explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto) + : m_inNanoseconds(inNanoseconds), + m_units(units) { + if (m_units == Unit::Auto) { + if (m_inNanoseconds < s_nanosecondsInAMicrosecond) + m_units = Unit::Nanoseconds; + else if (m_inNanoseconds < s_nanosecondsInAMillisecond) + m_units = Unit::Microseconds; + else if (m_inNanoseconds < s_nanosecondsInASecond) + m_units = Unit::Milliseconds; + else if (m_inNanoseconds < s_nanosecondsInAMinute) + m_units = Unit::Seconds; + else + m_units = Unit::Minutes; + } + + } + + auto value() const -> double { + switch (m_units) { + case Unit::Microseconds: + return m_inNanoseconds / static_cast(s_nanosecondsInAMicrosecond); + case Unit::Milliseconds: + return m_inNanoseconds / static_cast(s_nanosecondsInAMillisecond); + case Unit::Seconds: + return m_inNanoseconds / static_cast(s_nanosecondsInASecond); + case Unit::Minutes: + return m_inNanoseconds / static_cast(s_nanosecondsInAMinute); + default: + return static_cast(m_inNanoseconds); + } + } + auto unitsAsString() const -> std::string { + switch (m_units) { + case Unit::Nanoseconds: + return "ns"; + case Unit::Microseconds: + return "us"; + case Unit::Milliseconds: + return "ms"; + case Unit::Seconds: + return "s"; + case Unit::Minutes: + return "m"; + default: + return "** internal error **"; + } + + } + friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& { + return os << duration.value() << " " << duration.unitsAsString(); + } +}; +} // end anon namespace + +class TablePrinter { + std::ostream& m_os; + std::vector m_columnInfos; + std::ostringstream m_oss; + int m_currentColumn = -1; + bool m_isOpen = false; + +public: + TablePrinter( std::ostream& os, std::vector columnInfos ) + : m_os( os ), + m_columnInfos( std::move( columnInfos ) ) {} + + auto columnInfos() const -> std::vector const& { + return m_columnInfos; + } + + void open() { + if (!m_isOpen) { + m_isOpen = true; + *this << RowBreak(); + for (auto const& info : m_columnInfos) + *this << info.name << ColumnBreak(); + *this << RowBreak(); + m_os << Catch::getLineOfChars<'-'>() << "\n"; + } + } + void close() { + if (m_isOpen) { + *this << RowBreak(); + m_os << std::endl; + m_isOpen = false; + } + } + + template + friend TablePrinter& operator << (TablePrinter& tp, T const& value) { + tp.m_oss << value; + return tp; + } + + friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) { + auto colStr = tp.m_oss.str(); + // This takes account of utf8 encodings + auto strSize = Catch::StringRef(colStr).numberOfCharacters(); + tp.m_oss.str(""); + tp.open(); + if (tp.m_currentColumn == static_cast(tp.m_columnInfos.size() - 1)) { + tp.m_currentColumn = -1; + tp.m_os << "\n"; + } + tp.m_currentColumn++; + + auto colInfo = tp.m_columnInfos[tp.m_currentColumn]; + auto padding = (strSize + 2 < static_cast(colInfo.width)) + ? std::string(colInfo.width - (strSize + 2), ' ') + : std::string(); + if (colInfo.justification == ColumnInfo::Left) + tp.m_os << colStr << padding << " "; + else + tp.m_os << padding << colStr << " "; + return tp; + } + + friend TablePrinter& operator << (TablePrinter& tp, RowBreak) { + if (tp.m_currentColumn > 0) { + tp.m_os << "\n"; + tp.m_currentColumn = -1; + } + return tp; + } +}; + +ConsoleReporter::ConsoleReporter(ReporterConfig const& config) + : StreamingReporterBase(config), + m_tablePrinter(new TablePrinter(config.stream(), + { + { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left }, + { "iters", 8, ColumnInfo::Right }, + { "elapsed ns", 14, ColumnInfo::Right }, + { "average", 14, ColumnInfo::Right } + })) {} +ConsoleReporter::~ConsoleReporter() = default; + +std::string ConsoleReporter::getDescription() { + return "Reports test results as plain lines of text"; +} + +void ConsoleReporter::noMatchingTestCases(std::string const& spec) { + stream << "No test cases matched '" << spec << '\'' << std::endl; +} + +void ConsoleReporter::assertionStarting(AssertionInfo const&) {} + +bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) { + AssertionResult const& result = _assertionStats.assertionResult; + + bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); + + // Drop out if result was successful but we're not printing them. + if (!includeResults && result.getResultType() != ResultWas::Warning) + return false; + + lazyPrint(); + + ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults); + printer.print(); + stream << std::endl; + return true; +} + +void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) { + m_headerPrinted = false; + StreamingReporterBase::sectionStarting(_sectionInfo); +} +void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) { + m_tablePrinter->close(); + if (_sectionStats.missingAssertions) { + lazyPrint(); + Colour colour(Colour::ResultError); + if (m_sectionStack.size() > 1) + stream << "\nNo assertions in section"; + else + stream << "\nNo assertions in test case"; + stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl; + } + if (m_config->showDurations() == ShowDurations::Always) { + stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl; + } + if (m_headerPrinted) { + m_headerPrinted = false; + } + StreamingReporterBase::sectionEnded(_sectionStats); +} + +void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) { + lazyPrintWithoutClosingBenchmarkTable(); + + auto nameCol = Column( info.name ).width( static_cast( m_tablePrinter->columnInfos()[0].width - 2 ) ); + + bool firstLine = true; + for (auto line : nameCol) { + if (!firstLine) + (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak(); + else + firstLine = false; + + (*m_tablePrinter) << line << ColumnBreak(); + } +} +void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) { + Duration average(stats.elapsedTimeInNanoseconds / stats.iterations); + (*m_tablePrinter) + << stats.iterations << ColumnBreak() + << stats.elapsedTimeInNanoseconds << ColumnBreak() + << average << ColumnBreak(); +} + +void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) { + m_tablePrinter->close(); + StreamingReporterBase::testCaseEnded(_testCaseStats); + m_headerPrinted = false; +} +void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) { + if (currentGroupInfo.used) { + printSummaryDivider(); + stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n"; + printTotals(_testGroupStats.totals); + stream << '\n' << std::endl; + } + StreamingReporterBase::testGroupEnded(_testGroupStats); +} +void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) { + printTotalsDivider(_testRunStats.totals); + printTotals(_testRunStats.totals); + stream << std::endl; + StreamingReporterBase::testRunEnded(_testRunStats); +} + +void ConsoleReporter::lazyPrint() { + + m_tablePrinter->close(); + lazyPrintWithoutClosingBenchmarkTable(); +} + +void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() { + + if (!currentTestRunInfo.used) + lazyPrintRunInfo(); + if (!currentGroupInfo.used) + lazyPrintGroupInfo(); + + if (!m_headerPrinted) { + printTestCaseAndSectionHeader(); + m_headerPrinted = true; + } +} +void ConsoleReporter::lazyPrintRunInfo() { + stream << '\n' << getLineOfChars<'~'>() << '\n'; + Colour colour(Colour::SecondaryText); + stream << currentTestRunInfo->name + << " is a Catch v" << libraryVersion() << " host application.\n" + << "Run with -? for options\n\n"; + + if (m_config->rngSeed() != 0) + stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n"; + + currentTestRunInfo.used = true; +} +void ConsoleReporter::lazyPrintGroupInfo() { + if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) { + printClosedHeader("Group: " + currentGroupInfo->name); + currentGroupInfo.used = true; + } +} +void ConsoleReporter::printTestCaseAndSectionHeader() { + assert(!m_sectionStack.empty()); + printOpenHeader(currentTestCaseInfo->name); + + if (m_sectionStack.size() > 1) { + Colour colourGuard(Colour::Headers); + + auto + it = m_sectionStack.begin() + 1, // Skip first section (test case) + itEnd = m_sectionStack.end(); + for (; it != itEnd; ++it) + printHeaderString(it->name, 2); + } + + SourceLineInfo lineInfo = m_sectionStack.back().lineInfo; + + if (!lineInfo.empty()) { + stream << getLineOfChars<'-'>() << '\n'; + Colour colourGuard(Colour::FileName); + stream << lineInfo << '\n'; + } + stream << getLineOfChars<'.'>() << '\n' << std::endl; +} + +void ConsoleReporter::printClosedHeader(std::string const& _name) { + printOpenHeader(_name); + stream << getLineOfChars<'.'>() << '\n'; +} +void ConsoleReporter::printOpenHeader(std::string const& _name) { + stream << getLineOfChars<'-'>() << '\n'; + { + Colour colourGuard(Colour::Headers); + printHeaderString(_name); + } +} + +// if string has a : in first line will set indent to follow it on +// subsequent lines +void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) { + std::size_t i = _string.find(": "); + if (i != std::string::npos) + i += 2; + else + i = 0; + stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n'; +} + +struct SummaryColumn { + + SummaryColumn( std::string _label, Colour::Code _colour ) + : label( std::move( _label ) ), + colour( _colour ) {} + SummaryColumn addRow( std::size_t count ) { + ReusableStringStream rss; + rss << count; + std::string row = rss.str(); + for (auto& oldRow : rows) { + while (oldRow.size() < row.size()) + oldRow = ' ' + oldRow; + while (oldRow.size() > row.size()) + row = ' ' + row; + } + rows.push_back(row); + return *this; + } + + std::string label; + Colour::Code colour; + std::vector rows; + +}; + +void ConsoleReporter::printTotals( Totals const& totals ) { + if (totals.testCases.total() == 0) { + stream << Colour(Colour::Warning) << "No tests ran\n"; + } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) { + stream << Colour(Colour::ResultSuccess) << "All tests passed"; + stream << " (" + << pluralise(totals.assertions.passed, "assertion") << " in " + << pluralise(totals.testCases.passed, "test case") << ')' + << '\n'; + } else { + + std::vector columns; + columns.push_back(SummaryColumn("", Colour::None) + .addRow(totals.testCases.total()) + .addRow(totals.assertions.total())); + columns.push_back(SummaryColumn("passed", Colour::Success) + .addRow(totals.testCases.passed) + .addRow(totals.assertions.passed)); + columns.push_back(SummaryColumn("failed", Colour::ResultError) + .addRow(totals.testCases.failed) + .addRow(totals.assertions.failed)); + columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure) + .addRow(totals.testCases.failedButOk) + .addRow(totals.assertions.failedButOk)); + + printSummaryRow("test cases", columns, 0); + printSummaryRow("assertions", columns, 1); + } +} +void ConsoleReporter::printSummaryRow(std::string const& label, std::vector const& cols, std::size_t row) { + for (auto col : cols) { + std::string value = col.rows[row]; + if (col.label.empty()) { + stream << label << ": "; + if (value != "0") + stream << value; + else + stream << Colour(Colour::Warning) << "- none -"; + } else if (value != "0") { + stream << Colour(Colour::LightGrey) << " | "; + stream << Colour(col.colour) + << value << ' ' << col.label; + } + } + stream << '\n'; +} + +void ConsoleReporter::printTotalsDivider(Totals const& totals) { + if (totals.testCases.total() > 0) { + std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total()); + std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total()); + std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total()); + while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1) + findMax(failedRatio, failedButOkRatio, passedRatio)++; + while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1) + findMax(failedRatio, failedButOkRatio, passedRatio)--; + + stream << Colour(Colour::Error) << std::string(failedRatio, '='); + stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '='); + if (totals.testCases.allPassed()) + stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '='); + else + stream << Colour(Colour::Success) << std::string(passedRatio, '='); + } else { + stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '='); + } + stream << '\n'; +} +void ConsoleReporter::printSummaryDivider() { + stream << getLineOfChars<'-'>() << '\n'; +} + +CATCH_REGISTER_REPORTER("console", ConsoleReporter) + +} // end namespace Catch + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif +// end catch_reporter_console.cpp +// start catch_reporter_junit.cpp + +#include +#include +#include +#include + +namespace Catch { + + namespace { + std::string getCurrentTimestamp() { + // Beware, this is not reentrant because of backward compatibility issues + // Also, UTC only, again because of backward compatibility (%z is C++11) + time_t rawtime; + std::time(&rawtime); + auto const timeStampSize = sizeof("2017-01-16T17:06:45Z"); + +#ifdef _MSC_VER + std::tm timeInfo = {}; + gmtime_s(&timeInfo, &rawtime); +#else + std::tm* timeInfo; + timeInfo = std::gmtime(&rawtime); +#endif + + char timeStamp[timeStampSize]; + const char * const fmt = "%Y-%m-%dT%H:%M:%SZ"; + +#ifdef _MSC_VER + std::strftime(timeStamp, timeStampSize, fmt, &timeInfo); +#else + std::strftime(timeStamp, timeStampSize, fmt, timeInfo); +#endif + return std::string(timeStamp); + } + + std::string fileNameTag(const std::vector &tags) { + auto it = std::find_if(begin(tags), + end(tags), + [] (std::string const& tag) {return tag.front() == '#'; }); + if (it != tags.end()) + return it->substr(1); + return std::string(); + } + } // anonymous namespace + + JunitReporter::JunitReporter( ReporterConfig const& _config ) + : CumulativeReporterBase( _config ), + xml( _config.stream() ) + { + m_reporterPrefs.shouldRedirectStdOut = true; + m_reporterPrefs.shouldReportAllAssertions = true; + } + + JunitReporter::~JunitReporter() {} + + std::string JunitReporter::getDescription() { + return "Reports test results in an XML format that looks like Ant's junitreport target"; + } + + void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {} + + void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) { + CumulativeReporterBase::testRunStarting( runInfo ); + xml.startElement( "testsuites" ); + if( m_config->rngSeed() != 0 ) { + xml.startElement( "properties" ); + xml.scopedElement( "property" ) + .writeAttribute( "name", "random-seed" ) + .writeAttribute( "value", m_config->rngSeed() ); + xml.endElement(); + } + } + + void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) { + suiteTimer.start(); + stdOutForSuite.clear(); + stdErrForSuite.clear(); + unexpectedExceptions = 0; + CumulativeReporterBase::testGroupStarting( groupInfo ); + } + + void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) { + m_okToFail = testCaseInfo.okToFail(); + } + + bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) { + if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail ) + unexpectedExceptions++; + return CumulativeReporterBase::assertionEnded( assertionStats ); + } + + void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { + stdOutForSuite += testCaseStats.stdOut; + stdErrForSuite += testCaseStats.stdErr; + CumulativeReporterBase::testCaseEnded( testCaseStats ); + } + + void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) { + double suiteTime = suiteTimer.getElapsedSeconds(); + CumulativeReporterBase::testGroupEnded( testGroupStats ); + writeGroup( *m_testGroups.back(), suiteTime ); + } + + void JunitReporter::testRunEndedCumulative() { + xml.endElement(); + } + + void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) { + XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" ); + TestGroupStats const& stats = groupNode.value; + xml.writeAttribute( "name", stats.groupInfo.name ); + xml.writeAttribute( "errors", unexpectedExceptions ); + xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions ); + xml.writeAttribute( "tests", stats.totals.assertions.total() ); + xml.writeAttribute( "hostname", "tbd" ); // !TBD + if( m_config->showDurations() == ShowDurations::Never ) + xml.writeAttribute( "time", "" ); + else + xml.writeAttribute( "time", suiteTime ); + xml.writeAttribute( "timestamp", getCurrentTimestamp() ); + + // Write test cases + for( auto const& child : groupNode.children ) + writeTestCase( *child ); + + xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false ); + xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false ); + } + + void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) { + TestCaseStats const& stats = testCaseNode.value; + + // All test cases have exactly one section - which represents the + // test case itself. That section may have 0-n nested sections + assert( testCaseNode.children.size() == 1 ); + SectionNode const& rootSection = *testCaseNode.children.front(); + + std::string className = stats.testInfo.className; + + if( className.empty() ) { + className = fileNameTag(stats.testInfo.tags); + if ( className.empty() ) + className = "global"; + } + + if ( !m_config->name().empty() ) + className = m_config->name() + "." + className; + + writeSection( className, "", rootSection ); + } + + void JunitReporter::writeSection( std::string const& className, + std::string const& rootName, + SectionNode const& sectionNode ) { + std::string name = trim( sectionNode.stats.sectionInfo.name ); + if( !rootName.empty() ) + name = rootName + '/' + name; + + if( !sectionNode.assertions.empty() || + !sectionNode.stdOut.empty() || + !sectionNode.stdErr.empty() ) { + XmlWriter::ScopedElement e = xml.scopedElement( "testcase" ); + if( className.empty() ) { + xml.writeAttribute( "classname", name ); + xml.writeAttribute( "name", "root" ); + } + else { + xml.writeAttribute( "classname", className ); + xml.writeAttribute( "name", name ); + } + xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) ); + + writeAssertions( sectionNode ); + + if( !sectionNode.stdOut.empty() ) + xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false ); + if( !sectionNode.stdErr.empty() ) + xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false ); + } + for( auto const& childNode : sectionNode.childSections ) + if( className.empty() ) + writeSection( name, "", *childNode ); + else + writeSection( className, name, *childNode ); + } + + void JunitReporter::writeAssertions( SectionNode const& sectionNode ) { + for( auto const& assertion : sectionNode.assertions ) + writeAssertion( assertion ); + } + + void JunitReporter::writeAssertion( AssertionStats const& stats ) { + AssertionResult const& result = stats.assertionResult; + if( !result.isOk() ) { + std::string elementName; + switch( result.getResultType() ) { + case ResultWas::ThrewException: + case ResultWas::FatalErrorCondition: + elementName = "error"; + break; + case ResultWas::ExplicitFailure: + elementName = "failure"; + break; + case ResultWas::ExpressionFailed: + elementName = "failure"; + break; + case ResultWas::DidntThrowException: + elementName = "failure"; + break; + + // We should never see these here: + case ResultWas::Info: + case ResultWas::Warning: + case ResultWas::Ok: + case ResultWas::Unknown: + case ResultWas::FailureBit: + case ResultWas::Exception: + elementName = "internalError"; + break; + } + + XmlWriter::ScopedElement e = xml.scopedElement( elementName ); + + xml.writeAttribute( "message", result.getExpandedExpression() ); + xml.writeAttribute( "type", result.getTestMacroName() ); + + ReusableStringStream rss; + if( !result.getMessage().empty() ) + rss << result.getMessage() << '\n'; + for( auto const& msg : stats.infoMessages ) + if( msg.type == ResultWas::Info ) + rss << msg.message << '\n'; + + rss << "at " << result.getSourceInfo(); + xml.writeText( rss.str(), false ); + } + } + + CATCH_REGISTER_REPORTER( "junit", JunitReporter ) + +} // end namespace Catch +// end catch_reporter_junit.cpp +// start catch_reporter_listening.cpp + +#include + +namespace Catch { + + ListeningReporter::ListeningReporter() { + // We will assume that listeners will always want all assertions + m_preferences.shouldReportAllAssertions = true; + } + + void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) { + m_listeners.push_back( std::move( listener ) ); + } + + void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) { + assert(!m_reporter && "Listening reporter can wrap only 1 real reporter"); + m_reporter = std::move( reporter ); + m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut; + } + + ReporterPreferences ListeningReporter::getPreferences() const { + return m_preferences; + } + + std::set ListeningReporter::getSupportedVerbosities() { + return std::set{ }; + } + + void ListeningReporter::noMatchingTestCases( std::string const& spec ) { + for ( auto const& listener : m_listeners ) { + listener->noMatchingTestCases( spec ); + } + m_reporter->noMatchingTestCases( spec ); + } + + void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) { + for ( auto const& listener : m_listeners ) { + listener->benchmarkStarting( benchmarkInfo ); + } + m_reporter->benchmarkStarting( benchmarkInfo ); + } + void ListeningReporter::benchmarkEnded( BenchmarkStats const& benchmarkStats ) { + for ( auto const& listener : m_listeners ) { + listener->benchmarkEnded( benchmarkStats ); + } + m_reporter->benchmarkEnded( benchmarkStats ); + } + + void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) { + for ( auto const& listener : m_listeners ) { + listener->testRunStarting( testRunInfo ); + } + m_reporter->testRunStarting( testRunInfo ); + } + + void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) { + for ( auto const& listener : m_listeners ) { + listener->testGroupStarting( groupInfo ); + } + m_reporter->testGroupStarting( groupInfo ); + } + + void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) { + for ( auto const& listener : m_listeners ) { + listener->testCaseStarting( testInfo ); + } + m_reporter->testCaseStarting( testInfo ); + } + + void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) { + for ( auto const& listener : m_listeners ) { + listener->sectionStarting( sectionInfo ); + } + m_reporter->sectionStarting( sectionInfo ); + } + + void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) { + for ( auto const& listener : m_listeners ) { + listener->assertionStarting( assertionInfo ); + } + m_reporter->assertionStarting( assertionInfo ); + } + + // The return value indicates if the messages buffer should be cleared: + bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) { + for( auto const& listener : m_listeners ) { + static_cast( listener->assertionEnded( assertionStats ) ); + } + return m_reporter->assertionEnded( assertionStats ); + } + + void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) { + for ( auto const& listener : m_listeners ) { + listener->sectionEnded( sectionStats ); + } + m_reporter->sectionEnded( sectionStats ); + } + + void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { + for ( auto const& listener : m_listeners ) { + listener->testCaseEnded( testCaseStats ); + } + m_reporter->testCaseEnded( testCaseStats ); + } + + void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) { + for ( auto const& listener : m_listeners ) { + listener->testGroupEnded( testGroupStats ); + } + m_reporter->testGroupEnded( testGroupStats ); + } + + void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) { + for ( auto const& listener : m_listeners ) { + listener->testRunEnded( testRunStats ); + } + m_reporter->testRunEnded( testRunStats ); + } + + void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) { + for ( auto const& listener : m_listeners ) { + listener->skipTest( testInfo ); + } + m_reporter->skipTest( testInfo ); + } + + bool ListeningReporter::isMulti() const { + return true; + } + +} // end namespace Catch +// end catch_reporter_listening.cpp +// start catch_reporter_xml.cpp + +#if defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch + // Note that 4062 (not all labels are handled + // and default is missing) is enabled +#endif + +namespace Catch { + XmlReporter::XmlReporter( ReporterConfig const& _config ) + : StreamingReporterBase( _config ), + m_xml(_config.stream()) + { + m_reporterPrefs.shouldRedirectStdOut = true; + m_reporterPrefs.shouldReportAllAssertions = true; + } + + XmlReporter::~XmlReporter() = default; + + std::string XmlReporter::getDescription() { + return "Reports test results as an XML document"; + } + + std::string XmlReporter::getStylesheetRef() const { + return std::string(); + } + + void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) { + m_xml + .writeAttribute( "filename", sourceInfo.file ) + .writeAttribute( "line", sourceInfo.line ); + } + + void XmlReporter::noMatchingTestCases( std::string const& s ) { + StreamingReporterBase::noMatchingTestCases( s ); + } + + void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) { + StreamingReporterBase::testRunStarting( testInfo ); + std::string stylesheetRef = getStylesheetRef(); + if( !stylesheetRef.empty() ) + m_xml.writeStylesheetRef( stylesheetRef ); + m_xml.startElement( "Catch" ); + if( !m_config->name().empty() ) + m_xml.writeAttribute( "name", m_config->name() ); + if( m_config->rngSeed() != 0 ) + m_xml.scopedElement( "Randomness" ) + .writeAttribute( "seed", m_config->rngSeed() ); + } + + void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) { + StreamingReporterBase::testGroupStarting( groupInfo ); + m_xml.startElement( "Group" ) + .writeAttribute( "name", groupInfo.name ); + } + + void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) { + StreamingReporterBase::testCaseStarting(testInfo); + m_xml.startElement( "TestCase" ) + .writeAttribute( "name", trim( testInfo.name ) ) + .writeAttribute( "description", testInfo.description ) + .writeAttribute( "tags", testInfo.tagsAsString() ); + + writeSourceInfo( testInfo.lineInfo ); + + if ( m_config->showDurations() == ShowDurations::Always ) + m_testCaseTimer.start(); + m_xml.ensureTagClosed(); + } + + void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) { + StreamingReporterBase::sectionStarting( sectionInfo ); + if( m_sectionDepth++ > 0 ) { + m_xml.startElement( "Section" ) + .writeAttribute( "name", trim( sectionInfo.name ) ); + writeSourceInfo( sectionInfo.lineInfo ); + m_xml.ensureTagClosed(); + } + } + + void XmlReporter::assertionStarting( AssertionInfo const& ) { } + + bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) { + + AssertionResult const& result = assertionStats.assertionResult; + + bool includeResults = m_config->includeSuccessfulResults() || !result.isOk(); + + if( includeResults || result.getResultType() == ResultWas::Warning ) { + // Print any info messages in tags. + for( auto const& msg : assertionStats.infoMessages ) { + if( msg.type == ResultWas::Info && includeResults ) { + m_xml.scopedElement( "Info" ) + .writeText( msg.message ); + } else if ( msg.type == ResultWas::Warning ) { + m_xml.scopedElement( "Warning" ) + .writeText( msg.message ); + } + } + } + + // Drop out if result was successful but we're not printing them. + if( !includeResults && result.getResultType() != ResultWas::Warning ) + return true; + + // Print the expression if there is one. + if( result.hasExpression() ) { + m_xml.startElement( "Expression" ) + .writeAttribute( "success", result.succeeded() ) + .writeAttribute( "type", result.getTestMacroName() ); + + writeSourceInfo( result.getSourceInfo() ); + + m_xml.scopedElement( "Original" ) + .writeText( result.getExpression() ); + m_xml.scopedElement( "Expanded" ) + .writeText( result.getExpandedExpression() ); + } + + // And... Print a result applicable to each result type. + switch( result.getResultType() ) { + case ResultWas::ThrewException: + m_xml.startElement( "Exception" ); + writeSourceInfo( result.getSourceInfo() ); + m_xml.writeText( result.getMessage() ); + m_xml.endElement(); + break; + case ResultWas::FatalErrorCondition: + m_xml.startElement( "FatalErrorCondition" ); + writeSourceInfo( result.getSourceInfo() ); + m_xml.writeText( result.getMessage() ); + m_xml.endElement(); + break; + case ResultWas::Info: + m_xml.scopedElement( "Info" ) + .writeText( result.getMessage() ); + break; + case ResultWas::Warning: + // Warning will already have been written + break; + case ResultWas::ExplicitFailure: + m_xml.startElement( "Failure" ); + writeSourceInfo( result.getSourceInfo() ); + m_xml.writeText( result.getMessage() ); + m_xml.endElement(); + break; + default: + break; + } + + if( result.hasExpression() ) + m_xml.endElement(); + + return true; + } + + void XmlReporter::sectionEnded( SectionStats const& sectionStats ) { + StreamingReporterBase::sectionEnded( sectionStats ); + if( --m_sectionDepth > 0 ) { + XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" ); + e.writeAttribute( "successes", sectionStats.assertions.passed ); + e.writeAttribute( "failures", sectionStats.assertions.failed ); + e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk ); + + if ( m_config->showDurations() == ShowDurations::Always ) + e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds ); + + m_xml.endElement(); + } + } + + void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) { + StreamingReporterBase::testCaseEnded( testCaseStats ); + XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" ); + e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() ); + + if ( m_config->showDurations() == ShowDurations::Always ) + e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() ); + + if( !testCaseStats.stdOut.empty() ) + m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false ); + if( !testCaseStats.stdErr.empty() ) + m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false ); + + m_xml.endElement(); + } + + void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) { + StreamingReporterBase::testGroupEnded( testGroupStats ); + // TODO: Check testGroupStats.aborting and act accordingly. + m_xml.scopedElement( "OverallResults" ) + .writeAttribute( "successes", testGroupStats.totals.assertions.passed ) + .writeAttribute( "failures", testGroupStats.totals.assertions.failed ) + .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk ); + m_xml.endElement(); + } + + void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) { + StreamingReporterBase::testRunEnded( testRunStats ); + m_xml.scopedElement( "OverallResults" ) + .writeAttribute( "successes", testRunStats.totals.assertions.passed ) + .writeAttribute( "failures", testRunStats.totals.assertions.failed ) + .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk ); + m_xml.endElement(); + } + + CATCH_REGISTER_REPORTER( "xml", XmlReporter ) + +} // end namespace Catch + +#if defined(_MSC_VER) +#pragma warning(pop) +#endif +// end catch_reporter_xml.cpp + +namespace Catch { + LeakDetector leakDetector; +} + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +// end catch_impl.hpp +#endif + +#ifdef CATCH_CONFIG_MAIN +// start catch_default_main.hpp + +#ifndef __OBJC__ + +#if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN) +// Standard C/C++ Win32 Unicode wmain entry point +extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) { +#else +// Standard C/C++ main entry point +int main (int argc, char * argv[]) { +#endif + + return Catch::Session().run( argc, argv ); +} + +#else // __OBJC__ + +// Objective-C entry point +int main (int argc, char * const argv[]) { +#if !CATCH_ARC_ENABLED + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; +#endif + + Catch::registerTestMethods(); + int result = Catch::Session().run( argc, (char**)argv ); + +#if !CATCH_ARC_ENABLED + [pool drain]; +#endif + + return result; +} + +#endif // __OBJC__ + +// end catch_default_main.hpp +#endif + +#if !defined(CATCH_CONFIG_IMPL_ONLY) + +#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED +# undef CLARA_CONFIG_MAIN +#endif + +#if !defined(CATCH_CONFIG_DISABLE) +////// +// If this config identifier is defined then all CATCH macros are prefixed with CATCH_ +#ifdef CATCH_CONFIG_PREFIX_ALL + +#define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) +#define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) + +#define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) +#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) +#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) +#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) +#endif// CATCH_CONFIG_DISABLE_MATCHERS +#define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) + +#define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) +#define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) + +#define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) +#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) +#endif // CATCH_CONFIG_DISABLE_MATCHERS +#define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) + +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) +#define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) + +#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) +#endif // CATCH_CONFIG_DISABLE_MATCHERS + +#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg ) +#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) +#define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ ) + +#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) +#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) +#define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) +#define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) +#define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) +#define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) +#define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) + +#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) +#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#else +#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) +#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) +#endif + +#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) +#define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ ) +#define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ ) +#else +#define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ ) +#define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ ) +#endif + +// "BDD-style" convenience wrappers +#define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ ) +#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) +#define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) +#define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) +#define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) +#define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) +#define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) +#define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) + +// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required +#else + +#define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ ) +#define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) + +#define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ ) +#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr ) +#define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr ) +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) +#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr ) +#endif // CATCH_CONFIG_DISABLE_MATCHERS +#define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ ) + +#define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ ) +#define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ ) + +#define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr ) +#define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) +#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr ) +#endif // CATCH_CONFIG_DISABLE_MATCHERS +#define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) + +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) +#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg ) + +#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg ) +#endif // CATCH_CONFIG_DISABLE_MATCHERS + +#define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg ) +#define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg ) +#define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg ) +#define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ ) + +#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) +#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) +#define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) +#define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) +#define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ ) +#define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ ) +#define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ ) +#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE() + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) +#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) +#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#else +#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) ) +#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) +#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) ) +#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) ) +#endif + +#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE) +#define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ ) +#define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" ) +#else +#define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ ) +#define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ ) +#endif + +#endif + +#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) + +// "BDD-style" convenience wrappers +#define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ ) +#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ ) + +#define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc ) +#define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc ) +#define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc ) +#define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc ) +#define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc ) +#define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc ) + +using Catch::Detail::Approx; + +#else // CATCH_CONFIG_DISABLE + +////// +// If this config identifier is defined then all CATCH macros are prefixed with CATCH_ +#ifdef CATCH_CONFIG_PREFIX_ALL + +#define CATCH_REQUIRE( ... ) (void)(0) +#define CATCH_REQUIRE_FALSE( ... ) (void)(0) + +#define CATCH_REQUIRE_THROWS( ... ) (void)(0) +#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) +#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) +#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) +#endif// CATCH_CONFIG_DISABLE_MATCHERS +#define CATCH_REQUIRE_NOTHROW( ... ) (void)(0) + +#define CATCH_CHECK( ... ) (void)(0) +#define CATCH_CHECK_FALSE( ... ) (void)(0) +#define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__) +#define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) +#define CATCH_CHECK_NOFAIL( ... ) (void)(0) + +#define CATCH_CHECK_THROWS( ... ) (void)(0) +#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0) +#define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0) +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) +#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) +#endif // CATCH_CONFIG_DISABLE_MATCHERS +#define CATCH_CHECK_NOTHROW( ... ) (void)(0) + +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) +#define CATCH_CHECK_THAT( arg, matcher ) (void)(0) + +#define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0) +#endif // CATCH_CONFIG_DISABLE_MATCHERS + +#define CATCH_INFO( msg ) (void)(0) +#define CATCH_WARN( msg ) (void)(0) +#define CATCH_CAPTURE( msg ) (void)(0) + +#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) +#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) +#define CATCH_METHOD_AS_TEST_CASE( method, ... ) +#define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0) +#define CATCH_SECTION( ... ) +#define CATCH_DYNAMIC_SECTION( ... ) +#define CATCH_FAIL( ... ) (void)(0) +#define CATCH_FAIL_CHECK( ... ) (void)(0) +#define CATCH_SUCCEED( ... ) (void)(0) + +#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) ) +#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), className ) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#else +#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) ) ) +#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), className ) ) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) +#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#endif + +// "BDD-style" convenience wrappers +#define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) +#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) +#define CATCH_GIVEN( desc ) +#define CATCH_AND_GIVEN( desc ) +#define CATCH_WHEN( desc ) +#define CATCH_AND_WHEN( desc ) +#define CATCH_THEN( desc ) +#define CATCH_AND_THEN( desc ) + +#define CATCH_STATIC_REQUIRE( ... ) (void)(0) +#define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0) + +// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required +#else + +#define REQUIRE( ... ) (void)(0) +#define REQUIRE_FALSE( ... ) (void)(0) + +#define REQUIRE_THROWS( ... ) (void)(0) +#define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0) +#define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0) +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) +#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) +#endif // CATCH_CONFIG_DISABLE_MATCHERS +#define REQUIRE_NOTHROW( ... ) (void)(0) + +#define CHECK( ... ) (void)(0) +#define CHECK_FALSE( ... ) (void)(0) +#define CHECKED_IF( ... ) if (__VA_ARGS__) +#define CHECKED_ELSE( ... ) if (!(__VA_ARGS__)) +#define CHECK_NOFAIL( ... ) (void)(0) + +#define CHECK_THROWS( ... ) (void)(0) +#define CHECK_THROWS_AS( expr, exceptionType ) (void)(0) +#define CHECK_THROWS_WITH( expr, matcher ) (void)(0) +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) +#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0) +#endif // CATCH_CONFIG_DISABLE_MATCHERS +#define CHECK_NOTHROW( ... ) (void)(0) + +#if !defined(CATCH_CONFIG_DISABLE_MATCHERS) +#define CHECK_THAT( arg, matcher ) (void)(0) + +#define REQUIRE_THAT( arg, matcher ) (void)(0) +#endif // CATCH_CONFIG_DISABLE_MATCHERS + +#define INFO( msg ) (void)(0) +#define WARN( msg ) (void)(0) +#define CAPTURE( msg ) (void)(0) + +#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) +#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) +#define METHOD_AS_TEST_CASE( method, ... ) +#define REGISTER_TEST_CASE( Function, ... ) (void)(0) +#define SECTION( ... ) +#define DYNAMIC_SECTION( ... ) +#define FAIL( ... ) (void)(0) +#define FAIL_CHECK( ... ) (void)(0) +#define SUCCEED( ... ) (void)(0) +#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )) + +#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR +#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) ) +#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), className ) +#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) +#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#else +#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ) ) ) +#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_M_P_L_A_T_E____T_E_S_T____ ), className ) ) +#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ ) +#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) +#endif + +#define STATIC_REQUIRE( ... ) (void)(0) +#define STATIC_REQUIRE_FALSE( ... ) (void)(0) + +#endif + +#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) + +// "BDD-style" convenience wrappers +#define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) ) +#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className ) + +#define GIVEN( desc ) +#define AND_GIVEN( desc ) +#define WHEN( desc ) +#define AND_WHEN( desc ) +#define THEN( desc ) +#define AND_THEN( desc ) + +using Catch::Detail::Approx; + +#endif + +#endif // ! CATCH_CONFIG_IMPL_ONLY + +// start catch_reenable_warnings.h + + +#ifdef __clang__ +# ifdef __ICC // icpc defines the __clang__ macro +# pragma warning(pop) +# else +# pragma clang diagnostic pop +# endif +#elif defined __GNUC__ +# pragma GCC diagnostic pop +#endif + +// end catch_reenable_warnings.h +// end catch.hpp +#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED + diff --git a/cleansharedmemory.sh b/cleansharedmemory.sh deleted file mode 100644 index ab6ad287b..000000000 --- a/cleansharedmemory.sh +++ /dev/null @@ -1 +0,0 @@ -rm /dev/shm/slsDetectorPackage*; diff --git a/cmake/Catch.cmake b/cmake/Catch.cmake new file mode 100755 index 000000000..486e32331 --- /dev/null +++ b/cmake/Catch.cmake @@ -0,0 +1,175 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +#[=======================================================================[.rst: +Catch +----- + +This module defines a function to help use the Catch test framework. + +The :command:`catch_discover_tests` discovers tests by asking the compiled test +executable to enumerate its tests. This does not require CMake to be re-run +when tests change. However, it may not work in a cross-compiling environment, +and setting test properties is less convenient. + +This command is intended to replace use of :command:`add_test` to register +tests, and will create a separate CTest test for each Catch test case. Note +that this is in some cases less efficient, as common set-up and tear-down logic +cannot be shared by multiple test cases executing in the same instance. +However, it provides more fine-grained pass/fail information to CTest, which is +usually considered as more beneficial. By default, the CTest test name is the +same as the Catch name; see also ``TEST_PREFIX`` and ``TEST_SUFFIX``. + +.. command:: catch_discover_tests + + Automatically add tests with CTest by querying the compiled test executable + for available tests:: + + catch_discover_tests(target + [TEST_SPEC arg1...] + [EXTRA_ARGS arg1...] + [WORKING_DIRECTORY dir] + [TEST_PREFIX prefix] + [TEST_SUFFIX suffix] + [PROPERTIES name1 value1...] + [TEST_LIST var] + ) + + ``catch_discover_tests`` sets up a post-build command on the test executable + that generates the list of tests by parsing the output from running the test + with the ``--list-test-names-only`` argument. This ensures that the full + list of tests is obtained. Since test discovery occurs at build time, it is + not necessary to re-run CMake when the list of tests changes. + However, it requires that :prop_tgt:`CROSSCOMPILING_EMULATOR` is properly set + in order to function in a cross-compiling environment. + + Additionally, setting properties on tests is somewhat less convenient, since + the tests are not available at CMake time. Additional test properties may be + assigned to the set of tests as a whole using the ``PROPERTIES`` option. If + more fine-grained test control is needed, custom content may be provided + through an external CTest script using the :prop_dir:`TEST_INCLUDE_FILES` + directory property. The set of discovered tests is made accessible to such a + script via the ``_TESTS`` variable. + + The options are: + + ``target`` + Specifies the Catch executable, which must be a known CMake executable + target. CMake will substitute the location of the built executable when + running the test. + + ``TEST_SPEC arg1...`` + Specifies test cases, wildcarded test cases, tags and tag expressions to + pass to the Catch executable with the ``--list-test-names-only`` argument. + + ``EXTRA_ARGS arg1...`` + Any extra arguments to pass on the command line to each test case. + + ``WORKING_DIRECTORY dir`` + Specifies the directory in which to run the discovered test cases. If this + option is not provided, the current binary directory is used. + + ``TEST_PREFIX prefix`` + Specifies a ``prefix`` to be prepended to the name of each discovered test + case. This can be useful when the same test executable is being used in + multiple calls to ``catch_discover_tests()`` but with different + ``TEST_SPEC`` or ``EXTRA_ARGS``. + + ``TEST_SUFFIX suffix`` + Similar to ``TEST_PREFIX`` except the ``suffix`` is appended to the name of + every discovered test case. Both ``TEST_PREFIX`` and ``TEST_SUFFIX`` may + be specified. + + ``PROPERTIES name1 value1...`` + Specifies additional properties to be set on all tests discovered by this + invocation of ``catch_discover_tests``. + + ``TEST_LIST var`` + Make the list of tests available in the variable ``var``, rather than the + default ``_TESTS``. This can be useful when the same test + executable is being used in multiple calls to ``catch_discover_tests()``. + Note that this variable is only available in CTest. + +#]=======================================================================] + +#------------------------------------------------------------------------------ +function(catch_discover_tests TARGET) + cmake_parse_arguments( + "" + "" + "TEST_PREFIX;TEST_SUFFIX;WORKING_DIRECTORY;TEST_LIST" + "TEST_SPEC;EXTRA_ARGS;PROPERTIES" + ${ARGN} + ) + + if(NOT _WORKING_DIRECTORY) + set(_WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}") + endif() + if(NOT _TEST_LIST) + set(_TEST_LIST ${TARGET}_TESTS) + endif() + + ## Generate a unique name based on the extra arguments + string(SHA1 args_hash "${_TEST_SPEC} ${_EXTRA_ARGS}") + string(SUBSTRING ${args_hash} 0 7 args_hash) + + # Define rule to generate test list for aforementioned test executable + set(ctest_include_file "${CMAKE_CURRENT_BINARY_DIR}/${TARGET}_include-${args_hash}.cmake") + set(ctest_tests_file "${CMAKE_CURRENT_BINARY_DIR}/${TARGET}_tests-${args_hash}.cmake") + get_property(crosscompiling_emulator + TARGET ${TARGET} + PROPERTY CROSSCOMPILING_EMULATOR + ) + add_custom_command( + TARGET ${TARGET} POST_BUILD + BYPRODUCTS "${ctest_tests_file}" + COMMAND "${CMAKE_COMMAND}" + -D "TEST_TARGET=${TARGET}" + -D "TEST_EXECUTABLE=$" + -D "TEST_EXECUTOR=${crosscompiling_emulator}" + -D "TEST_WORKING_DIR=${_WORKING_DIRECTORY}" + -D "TEST_SPEC=${_TEST_SPEC}" + -D "TEST_EXTRA_ARGS=${_EXTRA_ARGS}" + -D "TEST_PROPERTIES=${_PROPERTIES}" + -D "TEST_PREFIX=${_TEST_PREFIX}" + -D "TEST_SUFFIX=${_TEST_SUFFIX}" + -D "TEST_LIST=${_TEST_LIST}" + -D "CTEST_FILE=${ctest_tests_file}" + -P "${_CATCH_DISCOVER_TESTS_SCRIPT}" + VERBATIM + ) + + file(WRITE "${ctest_include_file}" + "if(EXISTS \"${ctest_tests_file}\")\n" + " include(\"${ctest_tests_file}\")\n" + "else()\n" + " add_test(${TARGET}_NOT_BUILT-${args_hash} ${TARGET}_NOT_BUILT-${args_hash})\n" + "endif()\n" + ) + + if(NOT ${CMAKE_VERSION} VERSION_LESS "3.10.0") + # Add discovered tests to directory TEST_INCLUDE_FILES + set_property(DIRECTORY + APPEND PROPERTY TEST_INCLUDE_FILES "${ctest_include_file}" + ) + else() + # Add discovered tests as directory TEST_INCLUDE_FILE if possible + get_property(test_include_file_set DIRECTORY PROPERTY TEST_INCLUDE_FILE SET) + if (NOT ${test_include_file_set}) + set_property(DIRECTORY + PROPERTY TEST_INCLUDE_FILE "${ctest_include_file}" + ) + else() + message(FATAL_ERROR + "Cannot set more than one TEST_INCLUDE_FILE" + ) + endif() + endif() + +endfunction() + +############################################################################### + +set(_CATCH_DISCOVER_TESTS_SCRIPT + ${CMAKE_CURRENT_LIST_DIR}/CatchAddTests.cmake +) diff --git a/cmake/CatchAddTests.cmake b/cmake/CatchAddTests.cmake new file mode 100755 index 000000000..2220ce3ac --- /dev/null +++ b/cmake/CatchAddTests.cmake @@ -0,0 +1,78 @@ +# Distributed under the OSI-approved BSD 3-Clause License. See accompanying +# file Copyright.txt or https://cmake.org/licensing for details. + +set(prefix "${TEST_PREFIX}") +set(suffix "${TEST_SUFFIX}") +set(spec ${TEST_SPEC}) +set(extra_args ${TEST_EXTRA_ARGS}) +set(properties ${TEST_PROPERTIES}) +set(script) +set(suite) +set(tests) + +function(add_command NAME) + set(_args "") + foreach(_arg ${ARGN}) + if(_arg MATCHES "[^-./:a-zA-Z0-9_]") + set(_args "${_args} [==[${_arg}]==]") # form a bracket_argument + else() + set(_args "${_args} ${_arg}") + endif() + endforeach() + set(script "${script}${NAME}(${_args})\n" PARENT_SCOPE) +endfunction() + +# Run test executable to get list of available tests +if(NOT EXISTS "${TEST_EXECUTABLE}") + message(FATAL_ERROR + "Specified test executable '${TEST_EXECUTABLE}' does not exist" + ) +endif() +execute_process( + COMMAND ${TEST_EXECUTOR} "${TEST_EXECUTABLE}" ${spec} --list-test-names-only + OUTPUT_VARIABLE output + RESULT_VARIABLE result +) +# Catch --list-test-names-only reports the number of tests, so 0 is... surprising +if(${result} EQUAL 0) + message(WARNING + "Test executable '${TEST_EXECUTABLE}' contains no tests!\n" + ) +elseif(${result} LESS 0) + message(FATAL_ERROR + "Error running test executable '${TEST_EXECUTABLE}':\n" + " Result: ${result}\n" + " Output: ${output}\n" + ) +endif() + +string(REPLACE "\n" ";" output "${output}") + +# Parse output +foreach(line ${output}) + set(test ${line}) + # use escape commas to handle properly test cases with commans inside the name + string(REPLACE "," "\\," test_name ${test}) + # ...and add to script + add_command(add_test + "${prefix}${test}${suffix}" + ${TEST_EXECUTOR} + "${TEST_EXECUTABLE}" + "${test_name}" + ${extra_args} + ) + add_command(set_tests_properties + "${prefix}${test}${suffix}" + PROPERTIES + WORKING_DIRECTORY "${TEST_WORKING_DIR}" + ${properties} + ) + list(APPEND tests "${prefix}${test}${suffix}") +endforeach() + +# Create a list of all discovered tests, which users may use to e.g. set +# properties on the tests +add_command(set ${TEST_LIST} ${tests}) + +# Write CTest script +file(WRITE "${CTEST_FILE}" "${script}") diff --git a/cmake/FindCBF.cmake b/cmake/FindCBF.cmake old mode 100644 new mode 100755 diff --git a/cmake/FindQwt.cmake b/cmake/FindQwt.cmake old mode 100644 new mode 100755 diff --git a/cmake/FindROOT.cmake b/cmake/FindROOT.cmake old mode 100644 new mode 100755 diff --git a/cmake/FindZeroMQ.cmake b/cmake/FindZeroMQ.cmake new file mode 100755 index 000000000..5bc561386 --- /dev/null +++ b/cmake/FindZeroMQ.cmake @@ -0,0 +1,112 @@ + +# This file is originally from https://github.com/zeromq/azmq and distributed +# under Boost Software Lincese 1.0 +# Boost Software License - Version 1.0 - August 17th, 2003 + +# Permission is hereby granted, free of charge, to any person or organization +# obtaining a copy of the software and accompanying documentation covered by +# this license (the "Software") to use, reproduce, display, distribute, +# execute, and transmit the Software, and to prepare derivative works of the +# Software, and to permit third-parties to whom the Software is furnished to +# do so, all subject to the following: + +# The copyright notices in the Software and this entire statement, including +# the above license grant, this restriction and the following disclaimer, +# must be included in all copies of the Software, in whole or in part, and +# all derivative works of the Software, unless such copies or derivative +# works are solely in the form of machine-executable object code generated by +# a source language processor. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +# SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +# FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +# DEALINGS IN THE SOFTWARE. +# -------------------------------------------------------------------------------- + +# Find ZeroMQ Headers/Libs + +# Variables +# ZMQ_ROOT - set this to a location where ZeroMQ may be found +# +# ZeroMQ_FOUND - True of ZeroMQ found +# ZeroMQ_INCLUDE_DIRS - Location of ZeroMQ includes +# ZeroMQ_LIBRARIES - ZeroMQ libraries + +include(FindPackageHandleStandardArgs) + +if (NOT ZMQ_ROOT) + set(ZMQ_ROOT "$ENV{ZMQ_ROOT}") +endif() + +if (NOT ZMQ_ROOT) + find_path(_ZeroMQ_ROOT NAMES include/zmq.h) +else() + set(_ZeroMQ_ROOT "${ZMQ_ROOT}") +endif() + +find_path(ZeroMQ_INCLUDE_DIRS NAMES zmq.h HINTS ${_ZeroMQ_ROOT}/include) + +if (ZeroMQ_INCLUDE_DIRS) + set(_ZeroMQ_H ${ZeroMQ_INCLUDE_DIRS}/zmq.h) + + function(_zmqver_EXTRACT _ZeroMQ_VER_COMPONENT _ZeroMQ_VER_OUTPUT) + set(CMAKE_MATCH_1 "0") + set(_ZeroMQ_expr "^[ \\t]*#define[ \\t]+${_ZeroMQ_VER_COMPONENT}[ \\t]+([0-9]+)$") + file(STRINGS "${_ZeroMQ_H}" _ZeroMQ_ver REGEX "${_ZeroMQ_expr}") + string(REGEX MATCH "${_ZeroMQ_expr}" ZeroMQ_ver "${_ZeroMQ_ver}") + set(${_ZeroMQ_VER_OUTPUT} "${CMAKE_MATCH_1}" PARENT_SCOPE) + endfunction() + + _zmqver_EXTRACT("ZMQ_VERSION_MAJOR" ZeroMQ_VERSION_MAJOR) + _zmqver_EXTRACT("ZMQ_VERSION_MINOR" ZeroMQ_VERSION_MINOR) + _zmqver_EXTRACT("ZMQ_VERSION_PATCH" ZeroMQ_VERSION_PATCH) + + message(STATUS "ZeroMQ version: ${ZeroMQ_VERSION_MAJOR}.${ZeroMQ_VERSION_MINOR}.${ZeroMQ_VERSION_PATCH}") + + # We should provide version to find_package_handle_standard_args in the same format as it was requested, + # otherwise it can't check whether version matches exactly. + if (ZeroMQ_FIND_VERSION_COUNT GREATER 2) + set(ZeroMQ_VERSION "${ZeroMQ_VERSION_MAJOR}.${ZeroMQ_VERSION_MINOR}.${ZeroMQ_VERSION_PATCH}") + else() + # User has requested ZeroMQ version without patch part => user is not interested in specific patch => + # any patch should be an exact match. + set(ZeroMQ_VERSION "${ZeroMQ_VERSION_MAJOR}.${ZeroMQ_VERSION_MINOR}") + endif() + + if (NOT ${CMAKE_CXX_PLATFORM_ID} STREQUAL "Windows") + find_library(ZeroMQ_LIBRARIES NAMES zmq HINTS ${_ZeroMQ_ROOT}/lib) + else() + find_library( + ZeroMQ_LIBRARY_RELEASE + NAMES + libzmq + "libzmq-${CMAKE_VS_PLATFORM_TOOLSET}-mt-${ZeroMQ_VERSION_MAJOR}_${ZeroMQ_VERSION_MINOR}_${ZeroMQ_VERSION_PATCH}" + HINTS + ${_ZeroMQ_ROOT}/lib + ) + + find_library( + ZeroMQ_LIBRARY_DEBUG + NAMES + libzmq_d + "libzmq-${CMAKE_VS_PLATFORM_TOOLSET}-mt-gd-${ZeroMQ_VERSION_MAJOR}_${ZeroMQ_VERSION_MINOR}_${ZeroMQ_VERSION_PATCH}" + HINTS + ${_ZeroMQ_ROOT}/lib) + + # On Windows we have to use corresponding version (i.e. Release or Debug) of ZeroMQ because of `errno` CRT global variable + # See more at http://www.drdobbs.com/avoiding-the-visual-c-runtime-library/184416623 + set(ZeroMQ_LIBRARIES optimized "${ZeroMQ_LIBRARY_RELEASE}" debug "${ZeroMQ_LIBRARY_DEBUG}") + endif() +endif() + +find_package_handle_standard_args(ZeroMQ FOUND_VAR ZeroMQ_FOUND + REQUIRED_VARS ZeroMQ_INCLUDE_DIRS ZeroMQ_LIBRARIES + VERSION_VAR ZeroMQ_VERSION) + +if (ZeroMQ_FOUND) + mark_as_advanced(ZeroMQ_INCLUDE_DIRS ZeroMQ_LIBRARIES ZeroMQ_VERSION + ZeroMQ_VERSION_MAJOR ZeroMQ_VERSION_MINOR ZeroMQ_VERSION_PATCH) +endif() \ No newline at end of file diff --git a/cmake/ParseAndAddCatchTests.cmake b/cmake/ParseAndAddCatchTests.cmake new file mode 100755 index 000000000..ff4fc6677 --- /dev/null +++ b/cmake/ParseAndAddCatchTests.cmake @@ -0,0 +1,203 @@ +#==================================================================================================# +# supported macros # +# - TEST_CASE, # +# - SCENARIO, # +# - TEST_CASE_METHOD, # +# - CATCH_TEST_CASE, # +# - CATCH_SCENARIO, # +# - CATCH_TEST_CASE_METHOD. # +# # +# Usage # +# 1. make sure this module is in the path or add this otherwise: # +# set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake.modules/") # +# 2. make sure that you've enabled testing option for the project by the call: # +# enable_testing() # +# 3. add the lines to the script for testing target (sample CMakeLists.txt): # +# project(testing_target) # +# set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake.modules/") # +# enable_testing() # +# # +# find_path(CATCH_INCLUDE_DIR "catch.hpp") # +# include_directories(${INCLUDE_DIRECTORIES} ${CATCH_INCLUDE_DIR}) # +# # +# file(GLOB SOURCE_FILES "*.cpp") # +# add_executable(${PROJECT_NAME} ${SOURCE_FILES}) # +# # +# include(ParseAndAddCatchTests) # +# ParseAndAddCatchTests(${PROJECT_NAME}) # +# # +# The following variables affect the behavior of the script: # +# # +# PARSE_CATCH_TESTS_VERBOSE (Default OFF) # +# -- enables debug messages # +# PARSE_CATCH_TESTS_NO_HIDDEN_TESTS (Default OFF) # +# -- excludes tests marked with [!hide], [.] or [.foo] tags # +# PARSE_CATCH_TESTS_ADD_FIXTURE_IN_TEST_NAME (Default ON) # +# -- adds fixture class name to the test name # +# PARSE_CATCH_TESTS_ADD_TARGET_IN_TEST_NAME (Default ON) # +# -- adds cmake target name to the test name # +# PARSE_CATCH_TESTS_ADD_TO_CONFIGURE_DEPENDS (Default OFF) # +# -- causes CMake to rerun when file with tests changes so that new tests will be discovered # +# # +# One can also set (locally) the optional variable OptionalCatchTestLauncher to precise the way # +# a test should be run. For instance to use test MPI, one can write # +# set(OptionalCatchTestLauncher ${MPIEXEC} ${MPIEXEC_NUMPROC_FLAG} ${NUMPROC}) # +# just before calling this ParseAndAddCatchTests function # +# # +#==================================================================================================# + +cmake_minimum_required(VERSION 2.8.8) + +option(PARSE_CATCH_TESTS_VERBOSE "Print Catch to CTest parser debug messages" OFF) +option(PARSE_CATCH_TESTS_NO_HIDDEN_TESTS "Exclude tests with [!hide], [.] or [.foo] tags" OFF) +option(PARSE_CATCH_TESTS_ADD_FIXTURE_IN_TEST_NAME "Add fixture class name to the test name" ON) +option(PARSE_CATCH_TESTS_ADD_TARGET_IN_TEST_NAME "Add target name to the test name" ON) +option(PARSE_CATCH_TESTS_ADD_TO_CONFIGURE_DEPENDS "Add test file to CMAKE_CONFIGURE_DEPENDS property" OFF) + +function(PrintDebugMessage) + if(PARSE_CATCH_TESTS_VERBOSE) + message(STATUS "ParseAndAddCatchTests: ${ARGV}") + endif() +endfunction() + +# This removes the contents between +# - block comments (i.e. /* ... */) +# - full line comments (i.e. // ... ) +# contents have been read into '${CppCode}'. +# !keep partial line comments +function(RemoveComments CppCode) + string(ASCII 2 CMakeBeginBlockComment) + string(ASCII 3 CMakeEndBlockComment) + string(REGEX REPLACE "/\\*" "${CMakeBeginBlockComment}" ${CppCode} "${${CppCode}}") + string(REGEX REPLACE "\\*/" "${CMakeEndBlockComment}" ${CppCode} "${${CppCode}}") + string(REGEX REPLACE "${CMakeBeginBlockComment}[^${CMakeEndBlockComment}]*${CMakeEndBlockComment}" "" ${CppCode} "${${CppCode}}") + string(REGEX REPLACE "\n[ \t]*//+[^\n]+" "\n" ${CppCode} "${${CppCode}}") + + set(${CppCode} "${${CppCode}}" PARENT_SCOPE) +endfunction() + +# Worker function +function(ParseFile SourceFile TestTarget) + # According to CMake docs EXISTS behavior is well-defined only for full paths. + get_filename_component(SourceFile ${SourceFile} ABSOLUTE) + if(NOT EXISTS ${SourceFile}) + message(WARNING "Cannot find source file: ${SourceFile}") + return() + endif() + PrintDebugMessage("parsing ${SourceFile}") + file(STRINGS ${SourceFile} Contents NEWLINE_CONSUME) + + # Remove block and fullline comments + RemoveComments(Contents) + + # Find definition of test names + string(REGEX MATCHALL "[ \t]*(CATCH_)?(TEST_CASE_METHOD|SCENARIO|TEST_CASE)[ \t]*\\([^\)]+\\)+[ \t\n]*{+[ \t]*(//[^\n]*[Tt][Ii][Mm][Ee][Oo][Uu][Tt][ \t]*[0-9]+)*" Tests "${Contents}") + + if(PARSE_CATCH_TESTS_ADD_TO_CONFIGURE_DEPENDS AND Tests) + PrintDebugMessage("Adding ${SourceFile} to CMAKE_CONFIGURE_DEPENDS property") + set_property( + DIRECTORY + APPEND + PROPERTY CMAKE_CONFIGURE_DEPENDS ${SourceFile} + ) + endif() + + foreach(TestName ${Tests}) + # Strip newlines + string(REGEX REPLACE "\\\\\n|\n" "" TestName "${TestName}") + + # Get test type and fixture if applicable + string(REGEX MATCH "(CATCH_)?(TEST_CASE_METHOD|SCENARIO|TEST_CASE)[ \t]*\\([^,^\"]*" TestTypeAndFixture "${TestName}") + string(REGEX MATCH "(CATCH_)?(TEST_CASE_METHOD|SCENARIO|TEST_CASE)" TestType "${TestTypeAndFixture}") + string(REGEX REPLACE "${TestType}\\([ \t]*" "" TestFixture "${TestTypeAndFixture}") + + # Get string parts of test definition + string(REGEX MATCHALL "\"+([^\\^\"]|\\\\\")+\"+" TestStrings "${TestName}") + + # Strip wrapping quotation marks + string(REGEX REPLACE "^\"(.*)\"$" "\\1" TestStrings "${TestStrings}") + string(REPLACE "\";\"" ";" TestStrings "${TestStrings}") + + # Validate that a test name and tags have been provided + list(LENGTH TestStrings TestStringsLength) + if(TestStringsLength GREATER 2 OR TestStringsLength LESS 1) + message(FATAL_ERROR "You must provide a valid test name and tags for all tests in ${SourceFile}") + endif() + + # Assign name and tags + list(GET TestStrings 0 Name) + if("${TestType}" STREQUAL "SCENARIO") + set(Name "Scenario: ${Name}") + endif() + if(PARSE_CATCH_TESTS_ADD_FIXTURE_IN_TEST_NAME AND TestFixture) + set(CTestName "${TestFixture}:${Name}") + else() + set(CTestName "${Name}") + endif() + if(PARSE_CATCH_TESTS_ADD_TARGET_IN_TEST_NAME) + set(CTestName "${TestTarget}:${CTestName}") + endif() + # add target to labels to enable running all tests added from this target + set(Labels ${TestTarget}) + if(TestStringsLength EQUAL 2) + list(GET TestStrings 1 Tags) + string(TOLOWER "${Tags}" Tags) + # remove target from labels if the test is hidden + if("${Tags}" MATCHES ".*\\[!?(hide|\\.)\\].*") + list(REMOVE_ITEM Labels ${TestTarget}) + endif() + string(REPLACE "]" ";" Tags "${Tags}") + string(REPLACE "[" "" Tags "${Tags}") + else() + # unset tags variable from previous loop + unset(Tags) + endif() + + list(APPEND Labels ${Tags}) + + list(FIND Labels "!hide" IndexOfHideLabel) + set(HiddenTagFound OFF) + foreach(label ${Labels}) + string(REGEX MATCH "^!hide|^\\." result ${label}) + if(result) + set(HiddenTagFound ON) + break() + endif(result) + endforeach(label) + if(PARSE_CATCH_TESTS_NO_HIDDEN_TESTS AND ${HiddenTagFound} AND ${CMAKE_VERSION} VERSION_LESS "3.9") + PrintDebugMessage("Skipping test \"${CTestName}\" as it has [!hide], [.] or [.foo] label") + else() + PrintDebugMessage("Adding test \"${CTestName}\"") + if(Labels) + PrintDebugMessage("Setting labels to ${Labels}") + endif() + + # Escape commas in the test spec + string(REPLACE "," "\\," Name ${Name}) + + # Add the test and set its properties + add_test(NAME "\"${CTestName}\"" COMMAND ${OptionalCatchTestLauncher} ${TestTarget} ${Name} ${AdditionalCatchParameters}) + # Old CMake versions do not document VERSION_GREATER_EQUAL, so we use VERSION_GREATER with 3.8 instead + if(PARSE_CATCH_TESTS_NO_HIDDEN_TESTS AND ${HiddenTagFound} AND ${CMAKE_VERSION} VERSION_GREATER "3.8") + PrintDebugMessage("Setting DISABLED test property") + set_tests_properties("\"${CTestName}\"" PROPERTIES DISABLED ON) + else() + set_tests_properties("\"${CTestName}\"" PROPERTIES FAIL_REGULAR_EXPRESSION "No tests ran" + LABELS "${Labels}") + endif() + endif() + + + endforeach() +endfunction() + +# entry point +function(ParseAndAddCatchTests TestTarget) + PrintDebugMessage("Started parsing ${TestTarget}") + get_target_property(SourceFiles ${TestTarget} SOURCES) + PrintDebugMessage("Found the following sources: ${SourceFiles}") + foreach(SourceFile ${SourceFiles}) + ParseFile(${SourceFile} ${TestTarget}) + endforeach() + PrintDebugMessage("Finished parsing ${TestTarget}") +endfunction() diff --git a/cmake/package_config.cmake b/cmake/package_config.cmake new file mode 100755 index 000000000..9411a0a03 --- /dev/null +++ b/cmake/package_config.cmake @@ -0,0 +1,31 @@ +# This cmake code creates the configuration that is found and used by +# find_package() of another cmake project + +# get lower and upper case project name for the configuration files + +# configure and install the configuration files +include(CMakePackageConfigHelpers) + +configure_package_config_file( + "${CMAKE_SOURCE_DIR}/cmake/project-config.cmake.in" + "${PROJECT_BINARY_DIR}/${PROJECT_NAME_LOWER}-config.cmake" + INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME_LOWER} + PATH_VARS CMAKE_INSTALL_DIR) + +write_basic_package_version_file( + "${PROJECT_BINARY_DIR}/${PROJECT_NAME_LOWER}-config-version.cmake" + VERSION ${PROJECT_VERSION} + COMPATIBILITY SameMajorVersion) + +install(FILES + "${PROJECT_BINARY_DIR}/${PROJECT_NAME_LOWER}-config.cmake" + "${PROJECT_BINARY_DIR}/${PROJECT_NAME_LOWER}-config-version.cmake" + COMPONENT devel + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME_LOWER}) + +if (PROJECT_LIBRARIES OR PROJECT_STATIC_LIBRARIES) + install( + EXPORT "${TARGETS_EXPORT_NAME}" + FILE ${PROJECT_NAME_LOWER}-targets.cmake + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME_LOWER}) +endif () diff --git a/cmake/project-config.cmake.in b/cmake/project-config.cmake.in new file mode 100755 index 000000000..3d8646c6e --- /dev/null +++ b/cmake/project-config.cmake.in @@ -0,0 +1,24 @@ +# Config file for @PROJECT_NAME_LOWER@ +# +# It defines the following variables: +# +# @PROJECT_NAME_UPPER@_INCLUDE_DIRS - include directory +# @PROJECT_NAME_UPPER@_LIBRARIES - all dynamic libraries +# @PROJECT_NAME_UPPER@_STATIC_LIBRARIES - all static libraries + +@PACKAGE_INIT@ + +include(CMakeFindDependencyMacro) + +set(SLS_USE_HDF5 "@SLS_USE_HDF5@") + +# Add optional dependencies here +find_dependency(Threads) +if (SLS_USE_HDF5) + find_dependency(HDF5) +endif () + +set_and_check(@PROJECT_NAME_UPPER@_CMAKE_INCLUDE_DIRS "@PACKAGE_CMAKE_INSTALL_DIR@") + +include("${CMAKE_CURRENT_LIST_DIR}/@TARGETS_EXPORT_NAME@.cmake") +check_required_components("@PROJECT_NAME@") diff --git a/cmake/project_version.cc.in b/cmake/project_version.cc.in new file mode 100755 index 000000000..0260decc5 --- /dev/null +++ b/cmake/project_version.cc.in @@ -0,0 +1,14 @@ +#include "project_version.h" +/// project version as major.minor.patch string +const char* @PROJECT_NAME@_runtime_project_version(){ return "@PROJECT_VERSION@"; } +/// package version as string, possibly with git commit: v1.2.3+4+g56789abc +const char* @PROJECT_NAME@_runtime_package_version(){ return "@PACKAGE_VERSION@"; } +/// project version as integer: major * 10000 + minor * 100 + patch +int @PROJECT_NAME@_runtime_version_int() { return @PROJECT_VERSION_INT@; } +/// project version as integer: major +int @PROJECT_NAME@_runtime_version_major(){ return @PACKAGE_VERSION_MAJOR@; } +/// project version as integer: minor +int @PROJECT_NAME@_runtime_version_minor(){ return @PACKAGE_VERSION_MINOR@; } +/// project version as integer: patch +int @PROJECT_NAME@_runtime_version_patch(){ return @PACKAGE_VERSION_PATCH@; } + diff --git a/cmake/project_version.cmake b/cmake/project_version.cmake new file mode 100755 index 000000000..e7a2bd8ec --- /dev/null +++ b/cmake/project_version.cmake @@ -0,0 +1,154 @@ +# +# Sets PROJECT_VERSION and PACKAGE_VERSION +# + +# Don't set PROJECT_VERSION to empty string when no VERSION is given to project() command. +#if(POLICY CMP0048) +# cmake_policy(SET CMP0048 OLD) +#endif() + +# Split a version number into separate components +# version the version number to split +# major variable name to store the major version in +# minor variable name to store the minor version in +# patch variable name to store the patch version in +# extra variable name to store a version suffix in +function(version_split version major minor patch extra) + string(REGEX MATCH "([0-9]+)\\.([0-9]+)\\.([0-9]+)(.*)?" version_valid ${version}) + if(version_valid) + string(REGEX REPLACE "([0-9]+)\\.([0-9]+)\\.([0-9]+)(.*)?" "\\1;\\2;\\3;\\4" VERSION_MATCHES ${version}) + list(GET VERSION_MATCHES 0 version_major) + set(${major} ${version_major} PARENT_SCOPE) + list(GET VERSION_MATCHES 1 version_minor) + set(${minor} ${version_minor} PARENT_SCOPE) + list(GET VERSION_MATCHES 2 version_patch) + set(${patch} ${version_patch} PARENT_SCOPE) + list(GET VERSION_MATCHES 3 version_extra) + set(${extra} ${version_extra} PARENT_SCOPE) + else(version_valid) + message(AUTHOR_WARNING "Bad version ${version}; falling back to 0 (have you made an initial release?)") + set(${major} "0" PARENT_SCOPE) + set(${minor} "0" PARENT_SCOPE) + set(${patch} "0" PARENT_SCOPE) + set(${extra} "" PARENT_SCOPE) + endif(version_valid) +endfunction(version_split) + +############################## +# get PROJECT_VERSION from git +############################## +find_program(GIT_CMD git) +mark_as_advanced(GIT_CMD) +if (GIT_CMD) + execute_process(COMMAND ${GIT_CMD} rev-parse --show-toplevel + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + OUTPUT_VARIABLE GIT_TOPLEVEL + ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) +endif() +if (GIT_CMD AND NOT "${GIT_TOPLEVEL}" STREQUAL "") + execute_process(COMMAND ${GIT_CMD} rev-parse --short HEAD + WORKING_DIRECTORY ${GIT_TOPLEVEL} + OUTPUT_VARIABLE GIT_SHA1 + OUTPUT_STRIP_TRAILING_WHITESPACE) + #message(STATUS "GIT_SHA1: " ${GIT_SHA1}) + execute_process(COMMAND ${GIT_CMD} describe --match "*[0-9].[0-9]*" HEAD + WORKING_DIRECTORY ${GIT_TOPLEVEL} + OUTPUT_VARIABLE GIT_DESCRIBE + ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) + #message(STATUS "GIT_DESCRIBE: " ${GIT_DESCRIBE}) + + # if (GIT_DESCRIBE) + # string(REGEX REPLACE "v?([0-9.]+).*" "\\1" GIT_VERSION ${GIT_DESCRIBE}) + # message(STATUS "GIT_VERSION: " ${GIT_VERSION}) + + # # as package version we use the full version from git describe: 1.7.1+7+ge324c81 + # if (GIT_DESCRIBE MATCHES ".*-g.*") + # # convert a git describe string to usable debian version, e.g. v1.7.1-7-ge324c81 to 1.7.1+7+ge324c81 + # string(REGEX REPLACE "v?([0-9]*.[0-9.]*).*-([0-9]*)-([a-g0-9]*)" "\\1+\\2+\\3" GIT_FULL_VERSION ${GIT_DESCRIBE}) + # else() + # # current HEAD is git tag (i.e. releaase), directly use the version + # set(GIT_FULL_VERSION ${GIT_VERSION}) + # endif() + # else () + # # no (suitable) tag found + # set(GIT_VERSION "0.0.0") + # # get number of commits in repo + # execute_process(COMMAND ${GIT_CMD} rev-list --count HEAD + # WORKING_DIRECTORY ${GIT_TOPLEVEL} + # OUTPUT_VARIABLE GIT_COMMIT_COUNT + # OUTPUT_STRIP_TRAILING_WHITESPACE) + # set(GIT_FULL_VERSION 0.0.0+${GIT_COMMIT_COUNT}+g${GIT_SHA1}) + # endif () +endif () + +# get version from package.xml if it exists +if (EXISTS "${PROJECT_SOURCE_DIR}/package.xml") + file(STRINGS "${PROJECT_SOURCE_DIR}/package.xml" PACKAGE_XML_VERSION_LINE REGEX [0-9.]*) + string(REGEX REPLACE .*\([0-9.]*\).* \\1 PACKAGE_XML_VERSION "${PACKAGE_XML_VERSION_LINE}") + MESSAGE(STATUS "PACKAGE_XML_VERSION: " ${PACKAGE_XML_VERSION}) +endif () + +# set version (if not already manually specified) +# check versions from different sources and set actually used version +if (NOT PROJECT_VERSION) + # set PROJECT_VERSION to MAJOR.MINOR.PATCH + # PACKAGE_VERSION can have extra info + if (GIT_VERSION) + set(PROJECT_VERSION ${GIT_VERSION}) + set(PACKAGE_VERSION ${GIT_FULL_VERSION}) + elseif (PACKAGE_XML_VERSION) + set(PROJECT_VERSION ${PACKAGE_XML_VERSION}) + set(PACKAGE_VERSION ${PROJECT_VERSION}) + else () + message(WARNING "PROJECT_VERSION not set. Defaulting to 0.0.0") + set(PROJECT_VERSION "0.0.0") + endif () +endif () +# if (NOT PACKAGE_VERSION) + # message(WARNING "PACKAGE_VERSION not set! Falling back to (${PROJECT_VERSION})") + set(PACKAGE_VERSION ${PROJECT_VERSION}) +# endif () + +# warn if versions don't match +if (GIT_VERSION AND NOT GIT_VERSION MATCHES ${PROJECT_VERSION}) + message(WARNING "Version from git (${GIT_VERSION}) doesn't match PROJECT_VERSION (${PROJECT_VERSION})") +endif() +if (PACKAGE_XML_VERSION AND NOT PACKAGE_XML_VERSION MATCHES ${PROJECT_VERSION}) + message(WARNING "Version from package.xml (${PACKAGE_XML_VERSION}) doesn't match PROJECT_VERSION (${PROJECT_VERSION})") +endif() + +message(STATUS "PROJECT_VERSION: " ${PROJECT_VERSION}) +message(STATUS "PACKAGE_VERSION: " ${PACKAGE_VERSION}) + + +version_split(${PROJECT_VERSION} PACKAGE_VERSION_MAJOR PACKAGE_VERSION_MINOR PACKAGE_VERSION_PATCH extra) +#message(STATUS "PACKAGE_VERSION_MAJOR: " ${PACKAGE_VERSION_MAJOR}) +#message(STATUS "PACKAGE_VERSION_MINOR: " ${PACKAGE_VERSION_MINOR}) +#message(STATUS "PACKAGE_VERSION_PATCH: " ${PACKAGE_VERSION_PATCH}) + +# generate an integer version number: major * 10000 + minor * 100 + patch +math(EXPR PROJECT_VERSION_INT "${PACKAGE_VERSION_MAJOR} * 10000 + ${PACKAGE_VERSION_MINOR} * 100 + ${PACKAGE_VERSION_PATCH}") + +# make PROJECT_VERSION available as define in the project source +#add_definitions(-DPROJECT_VERSION="${PROJECT_VERSION}") +#add_definitions(-DPROJECT_VERSION_INT=${PROJECT_VERSION_INT}) +#add_definitions(-DPACKAGE_VERSION="${PACKAGE_VERSION}") +#add_definitions(-DPACKAGE_VERSION_MAJOR=${PACKAGE_VERSION_MAJOR}) +#add_definitions(-DPACKAGE_VERSION_MINOR=${PACKAGE_VERSION_MINOR}) +#add_definitions(-DPACKAGE_VERSION_PATCH=${PACKAGE_VERSION_PATCH}) + +# set ABI version to major.minor, which will be used for the SOVERSION +set(abiversion "${PACKAGE_VERSION_MAJOR}.${PACKAGE_VERSION_MINOR}") + +# generate a version.h file in the binary output dir, don't forget to install it... +string(TOUPPER "${PROJECT_NAME}" PROJECT_NAME_UPPER) + +# These files provide compile-time and runtime version information about your project. +# To offer the version info to the users of your library, you need to +# adapt the following lines in your respective CMakeLists.txt: +# add_library( SHARED ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}/project_version.cc) +# install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}/project_version.h COMPONENT dev DESTINATION include/) +# To use it within your library or tests you need to add the include directory: +# > target_include_directories(yourtarget PUBLIC ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}) +configure_file(${CMAKE_CURRENT_LIST_DIR}/project_version.h.in ${PROJECT_NAME}/project_version.h @ONLY) +configure_file(${CMAKE_CURRENT_LIST_DIR}/project_version.cc.in ${PROJECT_NAME}/project_version.cc @ONLY) diff --git a/cmake/project_version.h.in b/cmake/project_version.h.in new file mode 100755 index 000000000..394b1137d --- /dev/null +++ b/cmake/project_version.h.in @@ -0,0 +1,34 @@ +#ifndef @PROJECT_NAME_UPPER@_VERSION_H_ +#define @PROJECT_NAME_UPPER@_VERSION_H_ + +/// project version as major.minor.patch string +#define @PROJECT_NAME_UPPER@_VERSION "@PROJECT_VERSION@" +/// project version as integer: major * 10000 + minor * 100 + patch +#define @PROJECT_NAME_UPPER@_VERSION_INT @PROJECT_VERSION_INT@ +#define @PROJECT_NAME_UPPER@_VERSION_MAJOR @PACKAGE_VERSION_MAJOR@ +#define @PROJECT_NAME_UPPER@_VERSION_MINOR @PACKAGE_VERSION_MINOR@ +#define @PROJECT_NAME_UPPER@_VERSION_PATCH @PACKAGE_VERSION_PATCH@ +/// package version as string, possibly with git commit: v1.2.3+4+g56789abc +#define @PROJECT_NAME_UPPER@_PACKAGE_VERSION "@PACKAGE_VERSION@" + +///runtime versions, where the above values are linked into a lib and therefore reflect the version +///of the library itself (not the version of the header at compile time of the user code) +const char* @PROJECT_NAME@_runtime_project_version(); +const char* @PROJECT_NAME@_runtime_package_version(); +int @PROJECT_NAME@_runtime_version_int(); +int @PROJECT_NAME@_runtime_version_major(); +int @PROJECT_NAME@_runtime_version_minor(); +int @PROJECT_NAME@_runtime_version_patch(); + +///Check consistency of runtime vs compile-time version number. I.e. the header used +///for compilation was from the same version as the linked library. +inline bool @PROJECT_NAME@_check_version_consistency(bool major_minor_only) +{ + return @PROJECT_NAME@_runtime_version_major() == @PROJECT_NAME_UPPER@_VERSION_MAJOR && + @PROJECT_NAME@_runtime_version_minor() == @PROJECT_NAME_UPPER@_VERSION_MINOR && + (major_minor_only || + @PROJECT_NAME@_runtime_version_patch() == @PROJECT_NAME_UPPER@_VERSION_PATCH); +} + + +#endif diff --git a/cmk.sh b/cmk.sh index d73649f99..c2d23a45d 100755 --- a/cmk.sh +++ b/cmk.sh @@ -116,7 +116,8 @@ done if [ $TEXTCLIENT -eq 0 ] && [ $RECEIVER -eq 0 ] && [ $GUI -eq 0 ]; then - CMAKE_POST+=" -DSLS_USE_TEXTCLIENT=ON -DSLS_USE_RECEIVER=ON -DSLS_USE_GUI=ON " + #CMAKE_POST+=" -DSLS_USE_TEXTCLIENT=ON -DSLS_USE_RECEIVER=ON -DSLS_USE_GUI=ON " + CMAKE_POST+=" -DSLS_USE_TEXTCLIENT=ON -DSLS_USE_RECEIVER=ON -DSLS_USE_GUI=OFF " echo "Compile Option: TextClient, Receiver and GUI" else if [ $TEXTCLIENT -eq 1 ]; then @@ -177,7 +178,7 @@ echo "in "$PWD #cmake if [ $REBUILD -eq 1 ]; then rm -f CMakeCache.txt - BUILDCOMMAND="$CMAKE_PRE cmake $CMAKE_POST .." + BUILDCOMMAND="$CMAKE_PRE cmake3 $CMAKE_POST .." echo $BUILDCOMMAND eval $BUILDCOMMAND fi diff --git a/commitVersions.sh b/commitVersions.sh deleted file mode 100644 index a3cbc5f44..000000000 --- a/commitVersions.sh +++ /dev/null @@ -1,15 +0,0 @@ -sh updateSvnVersion.sh - -cd slsDetectorGui -git commit -a -m "updating versions" -git push origin developer:developer - -cd ../slsDetectorSoftware -git commit -a -m "updating versions" -git push origin developer:developer - -cd ../slsReceiverSoftware -git commit -a -m "updating versions" -git push origin developer:developer - -cd .. diff --git a/recipe/build.sh b/conda-recepie/build.sh old mode 100644 new mode 100755 similarity index 64% rename from recipe/build.sh rename to conda-recepie/build.sh index fba3f4626..5791635b4 --- a/recipe/build.sh +++ b/conda-recepie/build.sh @@ -6,10 +6,14 @@ cmake .. \ -DCMAKE_INSTALL_PREFIX=install \ -DSLS_USE_TEXTCLIENT=ON \ -DSLS_USE_RECEIVER=ON \ - -DSLS_USE_GUI=ON \ + -DSLS_USE_GUI=OFF \ + -DSLS_USE_TESTS=ON \ + -DSLS_USE_PYTHON=OFF \ -DCMAKE_BUILD_TYPE=Release \ -DSLS_USE_HDF5=OFF\ cmake --build . -- -j10 -cmake --build . --target install \ No newline at end of file +cmake --build . --target install + +CTEST_OUTPUT_ON_FAILURE=1 ctest -j 2 \ No newline at end of file diff --git a/conda-recepie/build_pylib.sh b/conda-recepie/build_pylib.sh new file mode 100755 index 000000000..0a423dbef --- /dev/null +++ b/conda-recepie/build_pylib.sh @@ -0,0 +1,14 @@ + +# mkdir $PREFIX/lib +# mkdir $PREFIX/include + + +# #Shared and static libraries +# cp build/bin/_sls_detector* $PREFIX/lib/. + + +# #Binaries +# cp -r build/bin/sls_detector $PREFIX/lib/. + +cd python +${PYTHON} setup.py install \ No newline at end of file diff --git a/recipe/copy_gui.sh b/conda-recepie/copy_gui.sh old mode 100644 new mode 100755 similarity index 100% rename from recipe/copy_gui.sh rename to conda-recepie/copy_gui.sh diff --git a/recipe/copy_lib.sh b/conda-recepie/copy_lib.sh old mode 100644 new mode 100755 similarity index 87% rename from recipe/copy_lib.sh rename to conda-recepie/copy_lib.sh index 4c427ee92..9a33e00d2 --- a/recipe/copy_lib.sh +++ b/conda-recepie/copy_lib.sh @@ -6,9 +6,8 @@ mkdir $PREFIX/include/slsDetectorPackage #Shared and static libraries cp build/bin/libSlsDetector.so $PREFIX/lib/. -cp build/bin/libSlsDetector.a $PREFIX/lib/. cp build/bin/libSlsReceiver.so $PREFIX/lib/. -cp build/bin/libSlsReceiver.a $PREFIX/lib/. +cp build/bin/libSlsSupport.so $PREFIX/lib/. #Binaries cp build/bin/sls_detector_acquire $PREFIX/bin/. diff --git a/conda-recepie/meta.yaml b/conda-recepie/meta.yaml new file mode 100755 index 000000000..b60529d28 --- /dev/null +++ b/conda-recepie/meta.yaml @@ -0,0 +1,120 @@ + +package: + name: sls_detector_software + version: "refactor" + +source: + - path: .. + +build: + number: 0 + rpaths: + - lib/ + +requirements: + build: + - {{ compiler('c') }} + - {{compiler('cxx')}} + - cmake + - qwt 6.* + - qt=4.8.7=7 + - zeromq=4.2.5=hfc679d8_5 + - pyzmq + - xorg-libx11 + - xorg-libice + - xorg-libxext + - xorg-libsm + - xorg-libxau + - xorg-libxrender + - xorg-libxfixes + - {{ cdt('mesa-libgl-devel') }} # [linux] + - {{ cdt('mesa-libegl-devel') }} # [linux] + - {{ cdt('mesa-dri-drivers') }} # [linux] + - {{ cdt('libselinux') }} # [linux] + - {{ cdt('libxdamage') }} # [linux] + - {{ cdt('libxxf86vm') }} # [linux] + + host: + - libstdcxx-ng + - libgcc-ng + - xorg-libx11 + - xorg-libice + - xorg-libxext + - xorg-libsm + - xorg-libxau + - xorg-libxrender + - xorg-libxfixes + + run: + - libstdcxx-ng + - libgcc-ng + + +outputs: + - name: sls_detector_lib + script: copy_lib.sh + + - name: sls_detector + script: build_pylib.sh + + requirements: + build: + - {{ compiler('c') }} + - {{compiler('cxx')}} + - python {{ python }} + - setuptools + - sls_detector_lib + - pyzmq + - pybind11 2.2 + host: + - python + - pybind11 2.2 + - pyzmq + - sls_detector_lib + - libstdcxx-ng + - libgcc-ng + run: + - python + - numpy + - sls_detector_lib=refactor + - pyzmq + - libstdcxx-ng + - libgcc-ng + test: + imports: + - sls_detector + + # requirements: + # build: + # - {{ compiler('c') }} + # - {{compiler('cxx')}} + + # - name: sls_detector_gui + # version: "refactor" + # script: copy_gui.sh + # requirements: + # build: + # - {{ compiler('c') }} + # - {{compiler('cxx')}} + # - cmake + # - qwt 6.* + # - qt=4.8.7=7 + # - zeromq=4.2.5=hfc679d8_5 + # - pyzmq + # - xorg-libx11 + # - xorg-libice + # - xorg-libxext + # - xorg-libsm + # - xorg-libxau + # - xorg-libxrender + # - xorg-libxfixes + # - {{ cdt('mesa-libgl-devel') }} # [linux] + # - {{ cdt('mesa-libegl-devel') }} # [linux] + # - {{ cdt('mesa-dri-drivers') }} # [linux] + # - {{ cdt('libselinux') }} # [linux] + # - {{ cdt('libxdamage') }} # [linux] + # - {{ cdt('libxxf86vm') }} # [linux] + # run: + # - sls_detector_lib=refactor + # - qwt 6.* + # - qt=4.8.7=7 diff --git a/conda-recepie/run_test.sh b/conda-recepie/run_test.sh new file mode 100755 index 000000000..e707b86f7 --- /dev/null +++ b/conda-recepie/run_test.sh @@ -0,0 +1 @@ +ctest -j2 \ No newline at end of file diff --git a/evalVersionVariables.sh b/evalVersionVariables.sh old mode 100644 new mode 100755 diff --git a/examples/bad.chans b/examples/bad.chans old mode 100644 new mode 100755 diff --git a/examples/bchip2modules_pc8829.config b/examples/bchip2modules_pc8829.config deleted file mode 100644 index 38def95ed..000000000 --- a/examples/bchip2modules_pc8829.config +++ /dev/null @@ -1,61 +0,0 @@ -detsizechan 2560 1 - -hostname bchip074+bchip075+ - -#replace my_installation_path -settingsdir /my_installation_path/slsDetectorPackage/settingsdir/gotthard -caldir /my_installation_path/slsDetectorPackage/settingsdir/gotthard - -0:extsig:0 trigger_in_rising_edge -0:rx_tcpport 1954 -0:rx_udpport 50001 -0:vhighvoltage 0 - -1:extsig:0 trigger_in_rising_edge -1:rx_tcpport 1955 -1:rx_udpport 50002 -#1:detectorip 10.1.1.52 -1:vhighvoltage 0 - -############################################################################## -######### -######### Uncomment this part to use the gotthard25umZmq process -######### -############################################################################## - -# #replace my_receiver_hostname with the hostname of IP of the machine where the receiver runs -#0:rx_zmqip my_receiver_hostname -#0:rx_zmqport 30003 -# #replace my_client_hostname with the hostname of IP of the machine where the client/GUI or softIOC runs -#0:zmqip my_client_hostname -#0:zmqport 40003 - -# #replace my_receiver_hostname with the hostname of IP of the machine where the receiver runs -#1:rx_zmqip my_receiver_hostname -#1:rx_zmqport 30004 -# #replace my_client_hostname with the hostname of IP of the machine where the client/GUI or softIOC runs -#1:zmqip my_client_hostname -#1:zmqport 40004 - -############################################################################## -######### -######### until here -######### -############################################################################## - - -r_readfreq 1 -rx_datastream 1 - -#replace my_receiver_hostname with the hostname of 1Gb IP of the machine where the receiver runs -rx_hostname my_receiver_hostname -rx_datastream 1 -outdir /tmp/ -angconv none -threaded 1 - -settings veryhighgain -exptime 0.000005 -period 0.0001 - -vhighvoltage 90 \ No newline at end of file diff --git a/examples/config_gen_script/beb_31_25.config_gen b/examples/config_gen_script/beb_31_25.config_gen old mode 100644 new mode 100755 diff --git a/examples/config_gen_script/eiger_2m_1gb.config_gen b/examples/config_gen_script/eiger_2m_1gb.config_gen old mode 100644 new mode 100755 diff --git a/examples/eiger_10Gb.config b/examples/eiger_10Gb.config old mode 100644 new mode 100755 diff --git a/examples/eiger_1Gb.config b/examples/eiger_1Gb.config old mode 100644 new mode 100755 diff --git a/examples/gotthard.config b/examples/gotthard.config old mode 100644 new mode 100755 diff --git a/examples/gotthard_setup.det b/examples/gotthard_setup.det old mode 100644 new mode 100755 diff --git a/examples/bchip2modules.config b/examples/gotthard_two.config old mode 100644 new mode 100755 similarity index 86% rename from examples/bchip2modules.config rename to examples/gotthard_two.config index 38def95ed..655d4f457 --- a/examples/bchip2modules.config +++ b/examples/gotthard_two.config @@ -2,9 +2,6 @@ detsizechan 2560 1 hostname bchip074+bchip075+ -#replace my_installation_path -settingsdir /my_installation_path/slsDetectorPackage/settingsdir/gotthard -caldir /my_installation_path/slsDetectorPackage/settingsdir/gotthard 0:extsig:0 trigger_in_rising_edge 0:rx_tcpport 1954 @@ -14,7 +11,6 @@ caldir /my_installation_path/slsDetectorPackage/settingsdir/gotthard 1:extsig:0 trigger_in_rising_edge 1:rx_tcpport 1955 1:rx_udpport 50002 -#1:detectorip 10.1.1.52 1:vhighvoltage 0 ############################################################################## @@ -51,11 +47,11 @@ rx_datastream 1 rx_hostname my_receiver_hostname rx_datastream 1 outdir /tmp/ -angconv none -threaded 1 + settings veryhighgain exptime 0.000005 period 0.0001 -vhighvoltage 90 \ No newline at end of file +vhighvoltage 90 + diff --git a/examples/howto_gotthatd_twomodules.txt b/examples/howto_gotthard_twomodules.txt old mode 100644 new mode 100755 similarity index 84% rename from examples/howto_gotthatd_twomodules.txt rename to examples/howto_gotthard_twomodules.txt index f966dc735..f9a3e8681 --- a/examples/howto_gotthatd_twomodules.txt +++ b/examples/howto_gotthard_twomodules.txt @@ -1,6 +1,6 @@ Turn on the two receivers: -slsReceiver --rx_tcpport 1954 & -slsReceiver --rx_tcpport 1955 & +slsReceiver -t1954 & +slsReceiver -t1955 & Switch on the photon conversion on the receiver machine (replace my_receiver_hostname): gotthard25umZmq my_receiver_hostname 30003 my_receiver_hostname 40003 & @@ -11,4 +11,3 @@ sls_detector_put config bchip2modules.config Start your measurements using the command line, the slsDetectorGui or the EPICS driver - diff --git a/examples/jungfrau.config b/examples/jungfrau.config old mode 100644 new mode 100755 diff --git a/examples/jungfrau_two.config b/examples/jungfrau_two.config old mode 100644 new mode 100755 diff --git a/examples/moench03_T1_lab.config b/examples/moench01_T1_lab.config old mode 100644 new mode 100755 similarity index 99% rename from examples/moench03_T1_lab.config rename to examples/moench01_T1_lab.config index f2d309bf3..6140887b9 --- a/examples/moench03_T1_lab.config +++ b/examples/moench01_T1_lab.config @@ -487,3 +487,5 @@ period 0.1 outdir /scratch/ enablefwrite 0 + + diff --git a/examples/mythen.config b/examples/mythen.config old mode 100644 new mode 100755 diff --git a/examples/receiver.config b/examples/receiver.config old mode 100644 new mode 100755 diff --git a/slsDetectorSoftware/slsDetector/remove_shm.sh b/examples/remove_shm.sh similarity index 100% rename from slsDetectorSoftware/slsDetector/remove_shm.sh rename to examples/remove_shm.sh diff --git a/examples/scripts/.parab b/examples/scripts/.parab old mode 100644 new mode 100755 diff --git a/examples/two_gotthard.config b/examples/two_gotthard.config old mode 100644 new mode 100755 diff --git a/examples/two_no_receiver.config b/examples/two_no_receiver.config old mode 100644 new mode 100755 diff --git a/integrationTests/CMakeLists.txt b/integrationTests/CMakeLists.txt new file mode 100755 index 000000000..df8f9aa07 --- /dev/null +++ b/integrationTests/CMakeLists.txt @@ -0,0 +1,48 @@ +# MESSAGE( STATUS "CMAKE_CURRENT_SOURCE_DIR: " ${CMAKE_CURRENT_SOURCE_DIR} ) +# MESSAGE( STATUS "PROJECT_SOURCE_DIR: " ${PROJECT_SOURCE_DIR} ) + + + +# include_directories( +# ${PROJECT_SOURCE_DIR}/catch +# ) + +target_sources(tests PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/test-integrationMulti.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test-integrationDectector.cpp +) + +# if(SLS_USE_TESTS) +# set(TEST_SOURCES +# src/test-slsDetector.cpp +# src/test.cpp +# ) +# add_executable(detector_test ${TEST_SOURCES}) + +# target_link_libraries(detector_test +# slsDetectorShared +# slsProjectOptions +# slsProjectWarnings +# slsSupportLib +# pthread +# rt +# ) +# set_target_properties(detector_test PROPERTIES +# RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin +# ) + +# add_executable(a src/a.cpp) +# target_link_libraries(a +# slsProjectOptions +# slsProjectWarnings +# slsDetectorShared +# slsSupportLib +# pthread +# rt +# ) +# set_target_properties(a PROPERTIES +# RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin +# ) + +# endif() + diff --git a/integrationTests/a.cpp b/integrationTests/a.cpp new file mode 100644 index 000000000..40cc3044a --- /dev/null +++ b/integrationTests/a.cpp @@ -0,0 +1,87 @@ + +#include "catch.hpp" + +#include "ClientSocket.h" +#include "Timer.h" +#include "logger.h" +#include "network_utils.h" +#include "slsDetector.h" +#include "sls_detector_defs.h" +#include "sls_detector_exceptions.h" +#include "sls_detector_funcs.h" +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include "network_utils.h" + +using namespace sls; +using ROI = slsDetectorDefs::ROI; + +// Easy printing of an ROI +std::ostream &operator<<(std::ostream &out, const ROI &r) { + return out << "xmin: " << std::setw(5) << r.xmin + << " xmax: " << std::setw(5) << r.xmax + << " ymin: " << std::setw(5) << r.ymin + << " ymax: " << std::setw(5) << r.ymax; +} + +int main() { + + int ret[]{0,0,0}; + for (auto i: ret) + std::cout << i << "\n"; + // uint32_t imageSize = 101; + // uint32_t packetSize = 100; + // std::cout << "a: " << std::ceil((double)imageSize / (double)packetSize) <<'\n'; + // std::cout << "b: " << imageSize / packetSize <<'\n'; + // std::cout << "c: " << static_cast(imageSize / packetSize) << '\n'; + // std::cout << "c: " << (imageSize + packetSize-1) / packetSize << '\n'; + + // slsDetectorDefs::ROI roilimits[5]; + // roilimits[0].xmin = 5; + // roilimits[0].xmax = 12; + // roilimits[0].ymin = 5; + // roilimits[0].ymax = 15; + + // roilimits[1].xmin = 0; + // roilimits[1].xmax = 3; + // roilimits[1].ymin = 20; + // roilimits[1].ymax = 25; + + // roilimits[2].xmin = 500; + // roilimits[2].xmax = 600; + // roilimits[2].ymin = 100; + // roilimits[2].ymax = 200; + + // roilimits[3].xmin = 300; + // roilimits[3].xmax = 500; + // roilimits[3].ymin = 800; + // roilimits[3].ymax = 900; + + // roilimits[4].xmin = 1000; + // roilimits[4].xmax = 2000; + // roilimits[4].ymin = 300; + // roilimits[4].ymax = 500; + + // std::cout << "Before sorting:\n"; + // for (auto r : roilimits) { + // std::cout << r << '\n'; + // } + + // std::sort(std::begin(roilimits), std::end(roilimits), + // [](ROI a, ROI b) { return a.xmin < b.xmin; }); + + // std::cout << "After sorting: \n"; + // for (auto r : roilimits) { + // std::cout << r << '\n'; + // } +} diff --git a/integrationTests/config.h b/integrationTests/config.h new file mode 100644 index 000000000..37ebd8189 --- /dev/null +++ b/integrationTests/config.h @@ -0,0 +1,9 @@ +#pragma once +#include +struct SingleDetectorConfig { + slsDetectorDefs::detectorType type_enum = + slsDetectorDefs::detectorType::EIGER; + const std::string hostname = "beb083"; + const std::string type_string = "Eiger"; + const std::string my_ip = "129.129.205.242"; +}; diff --git a/integrationTests/test-integrationDectector.cpp b/integrationTests/test-integrationDectector.cpp new file mode 100755 index 000000000..27c1f29e2 --- /dev/null +++ b/integrationTests/test-integrationDectector.cpp @@ -0,0 +1,224 @@ + +#include "catch.hpp" + +#include "ClientSocket.h" +#include "logger.h" +#include "slsDetector.h" +#include "sls_detector_defs.h" + +#include "Timer.h" +#include "sls_detector_funcs.h" +#include +#include +#define VERBOSE + +//Header holding all configurations for different detectors +#include "config.h" + +TEST_CASE("single EIGER detector no receiver basic set and get", "[.integration]") { + //TODO! this test should take command line arguments for config + SingleDetectorConfig c; + + //Read type by connecting to the detector + auto type = slsDetector::getTypeFromDetector(c.hostname); + CHECK(type == c.type_enum); + + //Create slsDetector of said type and set hostname and detector online + slsDetector d(type); + CHECK(d.getDetectorTypeAsEnum() == type); + CHECK(d.getDetectorTypeAsString() == c.type_string); + + d.setHostname(c.hostname); + CHECK(d.getHostname() == c.hostname); + + d.setOnline(true); + CHECK(d.getOnlineFlag() == true); + + CHECK(d.getReceiverOnline() == false); + CHECK(d.checkDetectorVersionCompatibility() == slsDetectorDefs::OK); + + //Setting and reading exposure time + auto t = 1000000000; + d.setTimer(slsDetectorDefs::timerIndex::ACQUISITION_TIME, t); + CHECK(d.setTimer(slsDetectorDefs::timerIndex::ACQUISITION_TIME) == t); + + //size of an eiger half module with and without gap pixels + CHECK(d.getTotalNumberOfChannels() == 256 * 256 * 4); + CHECK(d.getTotalNumberOfChannels(slsDetectorDefs::dimension::X) == 1024); + CHECK(d.getTotalNumberOfChannels(slsDetectorDefs::dimension::Y) == 256); + // CHECK(d.getTotalNumberOfChannels(slsDetectorDefs::dimension::Z) == 1); + CHECK(d.getTotalNumberOfChannelsInclGapPixels(slsDetectorDefs::dimension::X) == 1024); + CHECK(d.getTotalNumberOfChannelsInclGapPixels(slsDetectorDefs::dimension::Y) == 256); + // CHECK(d.getTotalNumberOfChannelsInclGapPixels(slsDetectorDefs::dimension::Z) == 1); + + CHECK(d.getNChans() == 256 * 256); + CHECK(d.getNChans(slsDetectorDefs::dimension::X) == 256); + CHECK(d.getNChans(slsDetectorDefs::dimension::Y) == 256); + // CHECK(d.getNChans(slsDetectorDefs::dimension::Z) == 1); + + CHECK(d.getNChips() == 4); + CHECK(d.getNChips(slsDetectorDefs::dimension::X) == 4); + CHECK(d.getNChips(slsDetectorDefs::dimension::Y) == 1); + // CHECK(d.getNChips(slsDetectorDefs::dimension::Z) == 1); + + d.freeSharedMemory(); +} + +TEST_CASE("Set control port then create a new object with this control port", + "[.integration]") { + /* + TODO! + Standard port but should not be hardcoded + Is this the best way to initialize the detectors + Using braces to make the object go out of scope + */ + int old_cport = DEFAULT_PORTNO; + int old_sport = DEFAULT_PORTNO + 1; + int new_cport = 1993; + int new_sport = 2000; + SingleDetectorConfig c; + { + auto type = slsDetector::getTypeFromDetector(c.hostname); + CHECK(type == c.type_enum); + slsDetector d(type); + d.setHostname(c.hostname); + d.setOnline(true); + CHECK(d.getControlPort() == old_cport); + d.setControlPort(new_cport); + CHECK(d.getStopPort() == old_sport); + d.setStopPort(new_sport); + d.freeSharedMemory(); + } + { + auto type = slsDetector::getTypeFromDetector(c.hostname, new_cport); + CHECK(type == c.type_enum); + slsDetector d(type); + d.setHostname(c.hostname); + d.setControlPort(new_cport); + d.setStopPort(new_sport); + CHECK(d.getControlPort() == new_cport); + CHECK(d.getStopPort() == new_sport); + + d.setOnline(true); + + //Reset standard ports + d.setControlPort(old_cport); + d.setStopPort(old_sport); + d.freeSharedMemory(); + } + + auto type = slsDetector::getTypeFromDetector(c.hostname); + CHECK(type == c.type_enum); + slsDetector d(type); + d.setHostname(c.hostname); + d.setOnline(true); + CHECK(d.getStopPort() == DEFAULT_PORTNO + 1); + d.freeSharedMemory(); +} + +TEST_CASE("Locking mechanism and last ip", "[.integration]") { + SingleDetectorConfig c; + auto type = slsDetector::getTypeFromDetector(c.hostname); + slsDetector d(type); + d.setHostname(c.hostname); + d.setOnline(true); + + //Check that detector server is unlocked then lock + CHECK(d.lockServer() == 0); + d.lockServer(1); + CHECK(d.lockServer() == 1); + + //Can we still access the detector while it's locked + auto t = 1300000000; + d.setTimer(slsDetectorDefs::timerIndex::ACQUISITION_TIME, t); + CHECK(d.setTimer(slsDetectorDefs::timerIndex::ACQUISITION_TIME) == t); + + //unlock again and free + d.lockServer(0); + CHECK(d.lockServer() == 0); + + CHECK(d.getLastClientIP() == c.my_ip); + d.freeSharedMemory(); +} + +TEST_CASE("Excersise all possible set timer functions", "[.integration]") { + // FRAME_NUMBER, /**< number of real time frames: total number of acquisitions is number or frames*number of cycles */ + // ACQUISITION_TIME, /**< exposure time */ + // FRAME_PERIOD, /**< period between exposures */ + // DELAY_AFTER_TRIGGER, /**< delay between trigger and start of exposure or readout (in triggered mode) */ + // GATES_NUMBER, /**< number of gates per frame (in gated mode) */ + // CYCLES_NUMBER, /**< number of cycles: total number of acquisitions is number or frames*number of cycles */ + // ACTUAL_TIME, /**< Actual time of the detector's internal timer */ + // MEASUREMENT_TIME, /**< Time of the measurement from the detector (fifo) */ + + // PROGRESS, /**< fraction of measurement elapsed - only get! */ + // MEASUREMENTS_NUMBER, + // FRAMES_FROM_START, + // FRAMES_FROM_START_PG, + // SAMPLES, + // SUBFRAME_ACQUISITION_TIME, /**< subframe exposure time */ + // STORAGE_CELL_NUMBER, /** +// TEST_CASE("Initialize a detector") { +// multiSlsDetector det(0, true, true); +// std::cout << "Size: " << det.getNumberOfDetectors() << std::endl; +// std::cout << "Hostname: " << det.getHostname() << std::endl; +// REQUIRE(false); + +// } \ No newline at end of file diff --git a/integrationTests/test.cpp b/integrationTests/test.cpp new file mode 100755 index 000000000..8daed99c4 --- /dev/null +++ b/integrationTests/test.cpp @@ -0,0 +1,3 @@ +// tests-main.cpp +#define CATCH_CONFIG_MAIN +#include "catch.hpp" \ No newline at end of file diff --git a/manual/Makefile b/manual/Makefile old mode 100644 new mode 100755 diff --git a/manual/index.html b/manual/index.html old mode 100644 new mode 100755 diff --git a/manual/manual-acq/Makefile b/manual/manual-acq/Makefile deleted file mode 100644 index c7255f287..000000000 --- a/manual/manual-acq/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -INCLUDES = -I . -SRC_TEST = main.cpp -LIBDIR = ../../bin -ZLIBDIR = ../../slsReceiverSoftware/include - -LBITS := $(shell getconf LONG_BIT) -SERVER_TYPE = "64 bits compile server detected..." -LDFLAG_DET = -I. -L$(LIBDIR) -L$(ZLIBDIR) -lSlsReceiver -lSlsDetector -L/usr/lib64/ -pthread -lrt -L. -lzmq - -all: manual-acq - -manual-acq:$(SRC_TEST) - @echo "------------------------------------------------------------" - @echo "creating test software" - @echo $(SERVER_TYPE) - @echo "------------------------------------------------------------" - - mkdir -p bin - g++ -o bin/manual-acq $(SRC_TEST) $(INCLUDES) $(LDFLAG_DET) -lm -lstdc++ - cp bin/manual-acq ../../bin - -clean: - @echo "------------------------------------------------------------" - @echo "cleaning test software" - @echo "------------------------------------------------------------" - rm -rf bin/manual-acq diff --git a/manual/manual-acq/ansi.h b/manual/manual-acq/ansi.h deleted file mode 120000 index a122db0ad..000000000 --- a/manual/manual-acq/ansi.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/ansi.h \ No newline at end of file diff --git a/manual/manual-acq/gotthard25.config b/manual/manual-acq/gotthard25.config deleted file mode 100644 index 8ae5869ef..000000000 --- a/manual/manual-acq/gotthard25.config +++ /dev/null @@ -1,21 +0,0 @@ -hostname bchip065+bchip195+ - -0:rx_tcpport 1954 -0:rx_udpport 50005 -0:detectorip 10.1.2.185 -0:rx_udpip 10.1.2.102 - -1:rx_tcpport 1955 -1:rx_udpport 50006 -1:detectorip 10.1.2.186 -1:rx_udpip 10.1.2.102 - -rx_hostname pc1875 - -outdir /home/l_msdetect/dhanya/outdir - -vhighvoltage 0 - -enablefwrite 0 - -timing auto diff --git a/manual/manual-acq/libzmq.a b/manual/manual-acq/libzmq.a deleted file mode 120000 index 2ecd6f21c..000000000 --- a/manual/manual-acq/libzmq.a +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/libzmq.a \ No newline at end of file diff --git a/manual/manual-acq/main.cpp b/manual/manual-acq/main.cpp deleted file mode 100644 index 09fe3ce81..000000000 --- a/manual/manual-acq/main.cpp +++ /dev/null @@ -1,900 +0,0 @@ -//------------------------------------------------------------------------------------------------------ -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "sls_receiver_defs.h" -#include "slsReceiverUsers.h" - -#include "sls_detector_defs.h" -#include "slsDetectorUsers.h" - -//#define GOTTHARD_25_TEST -//#define JUNGFRAU_TEST -#define GOTTHARD_TEST - -//====================================================================================================== -// test configuration -//====================================================================================================== -int acquisition_nb = 1; // number of acquisition to make -int acquisition_nb_ok = 0; // number of correct acquisition -uint64_t last_acquisition_received_frames; // number of received frames during the last acquisition -std::vector acquisition_nb_list; - -bool use_trace = false; // activate the acquisition log - -//------------------------------------------------------------------------------------------------------ -// GOTTHARD 25um -//------------------------------------------------------------------------------------------------------ -#ifdef GOTTHARD_25_TEST - const int receivers_nb = 2; // number of receivers - const int receivers_rx_tcpport[receivers_nb] = {1954, 1955}; // tcp port for each receiver - - const int detector_id = 0; // detector identifier for slsDetectorUsers constructor - const std::string detector_config_file_name = "gotthard25.config"; // configuration file name (must be present in the same folder of this application) - - const long detector_receiver_fifo_depth = 2500; - double detector_exposure_time_sec = 0.005; - double detector_exposure_period_sec = 0.10; - const double detector_delay_after_trigger_sec = 0.0; - const std::string detector_trig_mode = "auto"; // "auto" or "trigger" - int64_t detector_nb_frames_per_cycle = 10; - const int64_t detector_nb_cycles = 1; - int detector_module_index[receivers_nb] = {0, 1}; -#else -//------------------------------------------------------------------------------------------------------ -// GOTTHARD -//------------------------------------------------------------------------------------------------------ -#ifdef GOTTHARD_TEST - const int receivers_nb = 1; // number of receivers - const int receivers_rx_tcpport[receivers_nb] = {1954}; // tcp port for each receiver - - const int detector_id = 0; // detector identifier for slsDetectorUsers constructor - const std::string detector_config_file_name = "gotthard25.config"; // configuration file name (must be present in the same folder of this application) - - const long detector_receiver_fifo_depth = 2500; - double detector_exposure_time_sec = 0.005; - double detector_exposure_period_sec = 0.1; - const double detector_delay_after_trigger_sec = 0.0; - const std::string detector_trig_mode = "auto"; // "auto" or "trigger" - int64_t detector_nb_frames_per_cycle = 10; - const int64_t detector_nb_cycles = 1; - int detector_module_index[receivers_nb] = {0}; -#else -//------------------------------------------------------------------------------------------------------ -// JUNGFRAU -//------------------------------------------------------------------------------------------------------ -#ifdef JUNGFRAU_TEST - const int receivers_nb = 1; // number of receivers - const int receivers_rx_tcpport[receivers_nb] = {1954}; // tcp port for each receiver - - const int detector_id = 0; // detector identifier for slsDetectorUsers constructor - const std::string detector_config_file_name = "jungfrau_nanoscopium_switch.config"; // configuration file name (must be present in the same folder of this application) - - const long detector_receiver_fifo_depth = 2500; - double detector_exposure_time_sec = 0.0005; - double detector_exposure_period_sec = 0.001; - const double detector_delay_after_trigger_sec = 0.0; - const std::string detector_trig_mode = "auto"; // "auto" or "trigger" - int64_t detector_nb_frames_per_cycle = 10000; - const int64_t detector_nb_cycles = 1; - const int detector_clock_divider = 1; - int detector_module_index[receivers_nb] = {0}; -#endif -#endif -#endif - -//------------------------------------------------------------------------------------------------------ -// test instances -//------------------------------------------------------------------------------------------------------ -std::vector receivers; -slsDetectorUsers * detector = NULL; - -//------------------------------------------------------------------------------------------------------ -// tools functions -//------------------------------------------------------------------------------------------------------ -/** Define Colors to print data call back in different colors for different recievers */ -#define PRINT_IN_COLOR(c,f, ...) printf ("\033[%dm" f RESET, 30 + c+1, ##__VA_ARGS__) - -#define PRINT_SEPARATOR() cprintf(MAGENTA, "============================================\n") - -/************************************************************************ - * \brief cleans the shared memory used by the camera - ************************************************************************/ -void clean_shared_memory() -{ - std::string cmd = "rm /dev/shm/slsDetectorPackage*;"; - std::system(cmd.c_str()); -} - -/******************************************************************* - * \brief converts a version id to a string - * \return version in string format (uppercase & hexa) - *******************************************************************/ -std::string convertVersionToString(int64_t in_version) -{ - std::stringstream tempStream; - tempStream << "0x" << std::uppercase << std::hex << in_version; - return tempStream.str(); -} - -//================================================================== -// Related to commands (put & get) -//================================================================== -/******************************************************************* - * \brief Converts a standard string to args arguments - * \param in_command command in command line format - * \param out_argv output c-strings c-array - * \param out_argc output number of arguments of out_argv - *******************************************************************/ -void convertStringToArgs(const std::string & in_command, - char * * & out_argv , - int & out_argc ) -{ - out_argv = NULL; - out_argc = 0 ; - - // filling a string vector with the command line elements - std::vector elements; - std::stringstream ss(in_command); - - while (ss) - { - std::string element; - ss >> element; - - if(element.size() > 0) - { - elements.push_back(element); - } - } - - // setting argc value - out_argc = elements.size(); - - // allocating argv array - out_argv = new char * [out_argc]; - - // filling argv array - for (int element_index = 0; element_index < out_argc; element_index++) - { - out_argv[element_index] = new char[elements[element_index].size() + 1]; // adding the allocation of end of c-string - strcpy(out_argv[element_index], elements[element_index].c_str()); // copying the string including the eos - } -} - -/******************************************************************* - * \brief Releases args arguments - * \param in_out_argv output c-strings c-array*(static_cast(p)) - * \param in_out_argc output number of arguments of out_argv - *******************************************************************/ -void releaseArgs(char * * & in_out_argv , - int & in_out_argc ) -{ - if(in_out_argv != NULL) - { - // releasing the c_strings array content - for (int element_index = 0; element_index < in_out_argc; element_index++) - { - delete [] in_out_argv[element_index]; - } - - // releasing the c_strings array - delete [] in_out_argv; - - in_out_argv = NULL; - in_out_argc = 0 ; - } -} - -/******************************************************************* - * \brief Executes a set command - * \param in_command command in command line format - * \param in_module_index module index - * \return the command result - *******************************************************************/ -std::string setCmd(const std::string & in_command, int in_module_index=-1) -{ - std::cout << "setCmd - execute set command:\"" << in_command << "\"" << std::endl; - - char * * argv ; - int argc ; - std::string result; - - convertStringToArgs(in_command, argv, argc); - - if(argc > 0) - { - result = detector->putCommand(argc, argv, in_module_index); - } - - releaseArgs(argv, argc); - - std::cout << "result=\"" << result << "\"" << std::endl; - return result; -} - -/******************************************************************* - * \brief Executes a get command - * \param in_command command in command line format - * \param in_module_index module index - * \return the command result - *******************************************************************/ -std::string getCmd(const std::string & in_command, int in_module_index=-1) -{ - std::cout << "getCmd - execute get command:\"" << in_command << "\"" << std::endl; - - char * * argv ; - int argc ; - std::string result; - - convertStringToArgs(in_command, argv, argc); - - if(argc > 0) - { - result = detector->getCommand(argc, argv, in_module_index); - } - - releaseArgs(argv, argc); - - std::cout << "result=\"" << result << "\"" << std::endl; - return result; -} - -//------------------------------------------------------------------------------------------------------ -// Receivers callbacks -//------------------------------------------------------------------------------------------------------ -/** - * Start Acquisition Call back - * slsReceiver writes data if file write enabled. - * Users get data to write using call back if registerCallBackRawDataReady is registered. - * @param filepath file path - * @param filename file name - * @param fileindex file index - * @param datasize data size in bytes - * @param p pointer to object - * \returns ignored - */ -int StartAcq(char* filepath, char* filename, uint64_t fileindex, uint32_t datasize, void*p){ - cprintf(BLUE, "#### StartAcq: filepath:%s filename:%s fileindex:%llu datasize:%u ####\n", - filepath, filename, fileindex, datasize); - - cprintf(BLUE, "--StartAcq: returning 0\n"); - last_acquisition_received_frames = 0LL; - return 0; -} - -/** - * Acquisition Finished Call back - * @param frames Number of frames caught - * @param p pointer to object - */ -void AcquisitionFinished(uint64_t frames, void*p){ - cprintf(BLUE, "#### AcquisitionFinished: frames:%llu ####\n",frames); - last_acquisition_received_frames = frames; -} - -/** - * Get Receiver Data Call back - * Prints in different colors(for each receiver process) the different headers for each image call back. - * @param metadata sls_receiver_header metadata - * @param datapointer pointer to data - * @param datasize data size in bytes. - * @param p pointer to object - */ -void GetData(char* metadata, char* datapointer, uint32_t datasize, void* p) -{ - if(use_trace) - { - slsReceiverDefs::sls_receiver_header* header = (slsReceiverDefs::sls_receiver_header*)metadata; - const slsReceiverDefs::sls_detector_header & detectorHeader = header->detHeader; - - PRINT_IN_COLOR (*(static_cast(p)), - "#### %d GetData: ####\n" - "frameNumber: %llu\t\texpLength: %u\t\tpacketNumber: %u\t\tbunchId: %llu" - "\t\ttimestamp: %llu\t\tmodId: %u\t\t" - "row: %u\t\tcolumn: %u\t\treserved: %u\t\tdebug: %u" - "\t\troundRNumber: %u\t\tdetType: %u\t\tversion: %u" - //"\t\tpacketsMask:%s" - "\t\tfirstbytedata: 0x%x\t\tdatsize: %u\n\n", - *(static_cast(p)), - (long long unsigned int)detectorHeader.frameNumber, - detectorHeader.expLength, - detectorHeader.packetNumber, - (long long unsigned int)detectorHeader.bunchId, - (long long unsigned int)detectorHeader.timestamp, - detectorHeader.modId, - detectorHeader.row, - detectorHeader.column, - detectorHeader.reserved, - detectorHeader.debug, - detectorHeader.roundRNumber, - detectorHeader.detType, - detectorHeader.version, - //header->packetsMask.to_string().c_str(), - ((uint8_t)(*((uint8_t*)(datapointer)))), - datasize); - } - - if((datapointer != NULL) && (datasize > 0)) - { - char * buffer = new char[datasize]; - memcpy(buffer, datapointer, datasize); - delete [] buffer; - } -} - -//------------------------------------------------------------------------------------------------------ -// CreateReceivers -//------------------------------------------------------------------------------------------------------ -void CreateReceivers(void) -{ - // preparing the args for receivers creation - char temp_port[10]; - const int argc = 3; - char * args[argc] = {(char*)"slsReceiver", (char*)"--rx_tcpport", temp_port}; - - // creating the receivers instances - for(int i = 0 ; i < receivers_nb ; i++) - { - int ret = slsReceiverDefs::OK; - - // changing the udp port in the args - sprintf(temp_port, "%d", receivers_rx_tcpport[i]); - - // creating the receiver using the args - slsReceiverUsers * receiver = new slsReceiverUsers(argc, args, ret); - - // managing a failed result - if(ret==slsReceiverDefs::FAIL) - { - delete receiver; - exit(EXIT_FAILURE); - } - - // adding the receiver to the receivers container - receivers.push_back(receiver); - - std::cout << "receiver (" << i << ") created - port (" << receivers_rx_tcpport[i] << ")" << std::endl; - - // registering callbacks - // Call back for start acquisition - cprintf(BLUE, "Registering StartAcq()\n"); - receiver->registerCallBackStartAcquisition(StartAcq, NULL); - - // Call back for acquisition finished - cprintf(BLUE, "Registering AcquisitionFinished()\n"); - receiver->registerCallBackAcquisitionFinished(AcquisitionFinished, NULL); - - // Call back for raw data - cprintf(BLUE, "Registering GetData() \n"); - receiver->registerCallBackRawDataReady(GetData, NULL);//&(detector_module_index[i])); - - // starting tcp server thread - if (receiver->start() == slsReceiverDefs::FAIL) - { - delete receiver; - cprintf(BLUE,"Could not start receiver (%d)\n", i); - exit(EXIT_FAILURE); - } - } -} - -//------------------------------------------------------------------------------------------------------ -// ReleaseReceivers -//------------------------------------------------------------------------------------------------------ -void ReleaseReceivers(void) -{ - // deleting the receivers instances - for(int i = 0 ; i < receivers.size() ; i++) - { - slsReceiverUsers * receiver = receivers[i]; - - // stoping tcp server thread - receiver->stop(); - - delete receiver; - } -} - -//------------------------------------------------------------------------------------------------------ -// CreateDetector -//------------------------------------------------------------------------------------------------------ -void CreateDetector(void) -{ - int result; - - // create the detector instance - detector = new slsDetectorUsers(result, detector_id); - - if(result == slsDetectorDefs::FAIL) - { - std::cout << "slsDetectorUsers constructor failed! Could not initialize the camera!" << std::endl; - exit(EXIT_FAILURE); - } - - // configuration file is used to properly configure advanced settings in the shared memory - result = detector->readConfigurationFile(detector_config_file_name); - - if(result == slsDetectorDefs::FAIL) - { - std::cout << "readConfigurationFile failed! Could not initialize the camera!" << std::endl; - exit(EXIT_FAILURE); - } - - // set detector in shared memory online (in case no config file was used) */ - detector->setOnline(slsDetectorDefs::ONLINE_FLAG); - - // set receiver in shared memory online (in case no config file was used) */ - detector->setReceiverOnline(slsDetectorDefs::ONLINE_FLAG); - - // disabling the file write by the camera - detector->enableWriteToFile(slsDetectorDefs::DISABLED); - - // logging some versions informations - std::cout << "Detector developer : " << detector->getDetectorDeveloper() << std::endl; - std::cout << "Detector type : " << detector->getDetectorType() << std::endl; - std::cout << "Detector Firmware Version : " << convertVersionToString(detector->getDetectorFirmwareVersion()) << std::endl; - std::cout << "Detector Software Version : " << convertVersionToString(detector->getDetectorSoftwareVersion()) << std::endl; - - // ensuring detector status is idle - int status = detector->getDetectorStatus(); - - if((status != slsDetectorDefs::IDLE) && (status != slsDetectorDefs::STOPPED)) - { - std::cout << "Detector not ready: " << slsDetectorUsers::runStatusType(status) << std::endl; - exit(EXIT_FAILURE); - } -} - -//------------------------------------------------------------------------------------------------------ -// ReleaseDetector -//------------------------------------------------------------------------------------------------------ -void ReleaseDetector(void) -{ - if(detector != NULL) - { - detector->setReceiverOnline(slsDetectorDefs::OFFLINE_FLAG); - detector->setOnline(slsDetectorDefs::OFFLINE_FLAG); - - delete detector; - detector = NULL; - } -} - -//------------------------------------------------------------------------------------------------------ -// RunAcquisition -//------------------------------------------------------------------------------------------------------ -int RunAcquisition(void) -{ - std::string trig_mode_label; - - double exposure_time ; - double exposure_period; - double delay_after_trigger; - - int64_t nb_frames_per_cycle; - int64_t nb_cycles; - int64_t nb_frames; -#ifdef JUNGFRAU_TEST - int clock_divider; -#endif - //---------------------------------------------------------------------------------------------------- - // setting the receiver fifo depth (number of frames in the receiver memory) - detector->setReceiverFifoDepth(detector_receiver_fifo_depth); - - //---------------------------------------------------------------------------------------------------- - detector->setExposureTime (detector_exposure_time_sec , true); // in seconds - detector->setExposurePeriod (detector_exposure_period_sec, true); // in seconds - detector->setDelayAfterTrigger(detector_delay_after_trigger_sec, true); // in seconds - - exposure_time = detector->setExposureTime (-1, true); // in seconds - exposure_period = detector->setExposurePeriod (-1, true); // in seconds - delay_after_trigger = detector->setDelayAfterTrigger(-1, true, 0); // in seconds - - //---------------------------------------------------------------------------------------------------- - // initing the number of frames per cycle and number of cycles - // to avoid problems during the trigger mode change. - detector->setNumberOfFrames(1); - detector->setNumberOfCycles(1); - - // conversion of trigger mode label to trigger mode index - int trigger_mode_index = slsDetectorUsers::getTimingMode(detector_trig_mode); - - // apply the trigger change - detector->setTimingMode(trigger_mode_index); - - // converting trigger mode index to trigger mode label - trig_mode_label = slsDetectorUsers::getTimingMode(trigger_mode_index); - - // setting the number of cycles - nb_cycles = detector->setNumberOfCycles(detector_nb_cycles); - - // setting the number of frames per cycle - nb_frames_per_cycle = detector->setNumberOfFrames(detector_nb_frames_per_cycle); - - // setting the gain mode - detector->setSettings(slsDetectorUsers::getDetectorSettings("dynamicgain")); -#ifndef JUNGFRAU_TEST - detector->setSettings(slsDetectorUsers::getDetectorSettings("mediumgain")); -#else - detector->setSettings(slsDetectorUsers::getDetectorSettings("dynamichg0")); -#endif - // computing the number of frames - nb_frames = nb_cycles * nb_frames_per_cycle; - - //---------------------------------------------------------------------------------------------------- -#ifdef JUNGFRAU_TEST - // clock divider - detector->setClockDivider(detector_clock_divider); - clock_divider = detector->setClockDivider(-1); -#endif - //---------------------------------------------------------------------------------------------------- - std::cout << "receiver fifo depth : " << detector_receiver_fifo_depth << std::endl; - std::cout << "Exposure time in seconds : " << exposure_time << std::endl; - std::cout << "Exposure period in seconds : " << exposure_period << std::endl; - std::cout << "Delay after trigger in seconds : " << delay_after_trigger << std::endl; - std::cout << "Trigger mode : " << trig_mode_label << std::endl; - std::cout << "Nb frames per cycle : " << nb_frames_per_cycle << std::endl; - std::cout << "Nb cycles : " << nb_cycles << std::endl; - std::cout << "Nb frames : " << nb_frames << std::endl; -#ifdef JUNGFRAU_TEST - std::cout << "Clock divider : " << clock_divider << std::endl; -#endif - std::cout << "Estimated frame rate : " << (1.0 / exposure_period) << std::endl; - - //---------------------------------------------------------------------------------------------------- - // reset the number of caught frames in the sdk - detector->resetFramesCaughtInReceiver(); - - //---------------------------------------------------------------------------------------------------- - const unsigned int sleep_time_sec = 1; // sleep the thread in seconds - - // starting receiver listening mode - if(detector->startReceiver() == slsDetectorDefs::FAIL) - { - std::cout << "Could not start the receiver listening mode!" << std::endl; - return slsDetectorDefs::FAIL; - } - - // starting real time acquisition in non blocking mode - // returns OK if all detectors are properly started, FAIL otherwise - if(detector->startAcquisition() == slsDetectorDefs::FAIL) - { - detector->stopReceiver(); - std::cout << "Could not start real time acquisition!" << std::endl; - return slsDetectorDefs::FAIL; - } - - for(;;) - { - // checking if the hardware acquisition is running - int status = detector->getDetectorStatus(); - if((status == slsDetectorDefs::IDLE ) || - (status == slsDetectorDefs::STOPPED) || - (status == slsDetectorDefs::ERROR )) - { - // we stop the treatment - break; - } - else - // hardware acquisition is running, we are waiting for new frames not using the cpu during this time - { - usleep(sleep_time_sec * 1000 * 1000); // sleep the thread in seconds - } - } - - // stopping receiver listening mode - if(detector->stopReceiver() == slsDetectorDefs::FAIL) - { - std::cout << "Could not stop real time acquisition!" << std::endl; - return slsDetectorDefs::FAIL; - } - - //---------------------------------------------------------------------------------------------------- - PRINT_SEPARATOR(); - std::cout << "receiver fifo depth : " << detector_receiver_fifo_depth << std::endl; - std::cout << "Exposure time in seconds : " << exposure_time << std::endl; - std::cout << "Exposure period in seconds : " << exposure_period << std::endl; - std::cout << "Delay after trigger in seconds : " << delay_after_trigger << std::endl; - std::cout << "Trigger mode : " << trig_mode_label << std::endl; - std::cout << "Nb frames per cycle : " << nb_frames_per_cycle << std::endl; - std::cout << "Nb cyles : " << nb_cycles << std::endl; - std::cout << "Nb frames : " << nb_frames << std::endl; -#ifdef JUNGFRAU_TEST - std::cout << "Clock divider : " << clock_divider << std::endl; -#endif - std::cout << "Estimated frame rate : " << (1.0 / exposure_period) << std::endl; - - if(last_acquisition_received_frames == nb_frames) - { - acquisition_nb_ok++; - return slsDetectorDefs::OK; - } - - PRINT_SEPARATOR(); - return slsDetectorDefs::FAIL; -} - -//------------------------------------------------------------------------------------------------------ -// test -//------------------------------------------------------------------------------------------------------ -void Test(void) -{ - try - { - PRINT_SEPARATOR(); - std::cout << "CreateReceivers" << std::endl; - PRINT_SEPARATOR(); - - CreateReceivers(); - - PRINT_SEPARATOR(); - std::cout << "CreateDetector" << std::endl; - PRINT_SEPARATOR(); - - CreateDetector(); - - PRINT_SEPARATOR(); - std::cout << "RunAcquisition" << std::endl; - PRINT_SEPARATOR(); - - for(int acquisition_index = 0 ; acquisition_index < acquisition_nb ; acquisition_index++) - { - cprintf(MAGENTA, "Acquisition number : %d\n", acquisition_index); - if (RunAcquisition() == slsDetectorDefs::FAIL) { - acquisition_nb_list.push_back(acquisition_index); - } - } - - PRINT_SEPARATOR(); - std::cout << "ReleaseDetector" << std::endl; - PRINT_SEPARATOR(); - - ReleaseDetector(); - - PRINT_SEPARATOR(); - std::cout << "ReleaseReceivers" << std::endl; - PRINT_SEPARATOR(); - - ReleaseReceivers(); - - PRINT_SEPARATOR(); - if (acquisition_nb - acquisition_nb_ok) - cprintf(BOLD RED, "Correct acquisition(s) %d/%d\n", acquisition_nb_ok, acquisition_nb); - else - cprintf(BOLD GREEN, "Correct acquisition(s) %d/%d\n", acquisition_nb_ok, acquisition_nb); - if (acquisition_nb - acquisition_nb_ok) { - cprintf(RED, "Acquisition(s) gone wrong :\n"); - for (int list_index = 0; list_index < acquisition_nb_list.size(); ++list_index) { - cprintf(RED, "%d\n", acquisition_nb_list[list_index]); - } - } - PRINT_SEPARATOR(); - } - catch (...) - { - std::cout << "unknown exception!" << std::endl; - exit(EXIT_FAILURE); - } -} - -std::string roi_result = -"detector 0:\n" -"0 255 -1 -1\n" -"detector 1:\n" -"1024 1279 -1 -1\n" -"\n" -"xmin xmax ymin ymax\n" -"0 255 -1 -1\n" -"2304 2559 -1 -1\n" -"roi 2\n"; - -#include - -// use example : -// std::vector rois; -// get_rois_from_string(roi_result, rois); -/******************************************************************* - * \brief Cuts the string in pieces - * \param[in] in_string source string - * \param[in] in_delimitor line delimitor - * \param[out] out_lines line container result - *******************************************************************/ -void split_string_line(const std::string & in_string, const char in_delimitor, std::vector & out_lines) -{ - std::stringstream ss(in_string); - std::string sub_string; - - while (getline(ss, sub_string, in_delimitor)) - { - out_lines.push_back(sub_string); - } -} - -/******************************************************************* - * \brief retrieve the ROIs from a string - * \param[in] in_rois_string string from "get roi" command - * \param[out] out_rois ROI container result (empty if no set ROI) - *******************************************************************/ -void get_rois_from_string(const std::string & in_rois_string, std::vector & out_rois) -{ - out_rois.clear(); - - try - { - // cuts the string in lines - std::vector lines; - split_string_line(in_rois_string, '\n', lines); - - if(lines.size() >= 1) - { - // checks if no ROI ? - if(lines[0] != "roi 0") - { - for(int roi_index = 0 ; roi_index < 2 ; roi_index++) - { - if(lines.size() >= ((roi_index + 1) * 2)) // two lines per ROI definition - { - std::stringstream detector_name; - detector_name << "detector " << roi_index << ":"; - - // checks the first line - if(lines[roi_index * 2] == detector_name.str()) - { - std::stringstream ss(lines[(roi_index * 2) + 1]); - - slsReceiverDefs::ROI roi; - ss >> roi.xmin; - ss >> roi.xmax; - ss >> roi.ymin; - ss >> roi.ymax; - - out_rois.push_back(roi); - } - } - } - } - } - } - catch(...) - { - out_rois.clear(); - } -} - -//------------------------------------------------------------------------------------------------------ -// read_simple_option -//------------------------------------------------------------------------------------------------------ -bool read_simple_option(int argc, char* argv[], const char * in_option_name) -{ - int option_index = 1; - - while(option_index < argc) - { - if (strcmp(argv[option_index], in_option_name) == 0) - { - std::cout << "Found option:" << in_option_name << std::endl; - return true; - } - - option_index++; - } - - return false; -} - -//------------------------------------------------------------------------------------------------------ -// read_option_value -//------------------------------------------------------------------------------------------------------ -template bool read_option_value(int argc, char* argv[], const char * in_option_name, T & out_option_value) -{ - int option_index = 1; - - while(option_index < argc) - { - if (strcmp(argv[option_index], in_option_name) == 0) - { - option_index++; - - if(option_index < argc) - { - std::stringstream ss(std::string(argv[option_index])); - ss >> out_option_value; - std::cout << "Found option: " << in_option_name << " " << out_option_value << std::endl; - return true; - } - } - - option_index++; - } - - return false; -} - -//------------------------------------------------------------------------------------------------------ -// main -//------------------------------------------------------------------------------------------------------ -int main (int argc, char* argv[]) -{ - if(read_simple_option(argc, argv, "-help") || read_simple_option(argc, argv, "--help")) - { - PRINT_SEPARATOR(); - std::cout << "Options:" << std::endl; - std::cout << "-clean -> clean shared memory" << std::endl; - std::cout << "-trace -> activate acquisition log" << std::endl; - std::cout << "-exp -> set exposure time value in seconds (for example: -exp 0.0005)" << std::endl; - std::cout << "-period -> set period time value in seconds (for example: -period 0.001)" << std::endl; - std::cout << "-frames -> set number of frames (for example: -frames 10000)" << std::endl; - std::cout << "-acq -> set number of acquisition (for example: -acq 10)" << std::endl; - std::cout << std::endl; - std::cout << "example: ./manual-acq -clean -trace -acq 1 -exp 0.0005 -period 0.001 -frames 1000" << std::endl; - PRINT_SEPARATOR(); - return 0; - } - - if(read_simple_option(argc, argv, "-clean")) - { - PRINT_SEPARATOR(); - std::cout << "Cleaning shared memory" << std::endl; - PRINT_SEPARATOR(); - - clean_shared_memory(); - } - - if(read_simple_option(argc, argv, "-trace")) - { - PRINT_SEPARATOR(); - std::cout << "Activating acquisition log..." << std::endl; - PRINT_SEPARATOR(); - - use_trace = true; - } - - int64_t frames_value; - - if(read_option_value(argc, argv, "-frames", frames_value)) - { - detector_nb_frames_per_cycle = frames_value; - } - - double exp_value; - - if(read_option_value(argc, argv, "-exp", exp_value)) - { - detector_exposure_time_sec = exp_value; - } - - double period_value; - - if(read_option_value(argc, argv, "-period", period_value)) - { - detector_exposure_period_sec = period_value; - } - - int acq_nb; - - if(read_option_value(argc, argv, "-acq", acq_nb)) - { - acquisition_nb = acq_nb; - } - - Test(); - - std::cout << "====================== ENDING ======================" << std::endl; - - return 0; -} - -//------------------------------------------------------------------------------------------------------ diff --git a/manual/manual-acq/slsDetectorUsers.h b/manual/manual-acq/slsDetectorUsers.h deleted file mode 120000 index 307c966ad..000000000 --- a/manual/manual-acq/slsDetectorUsers.h +++ /dev/null @@ -1 +0,0 @@ -../../slsDetectorSoftware/slsDetector/slsDetectorUsers.h \ No newline at end of file diff --git a/manual/manual-acq/slsReceiverUsers.h b/manual/manual-acq/slsReceiverUsers.h deleted file mode 120000 index c8727f200..000000000 --- a/manual/manual-acq/slsReceiverUsers.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/slsReceiverUsers.h \ No newline at end of file diff --git a/manual/manual-acq/sls_detector_defs.h b/manual/manual-acq/sls_detector_defs.h deleted file mode 120000 index a504c1374..000000000 --- a/manual/manual-acq/sls_detector_defs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsDetectorSoftware/commonFiles/sls_detector_defs.h \ No newline at end of file diff --git a/manual/manual-acq/sls_detector_funcs.h b/manual/manual-acq/sls_detector_funcs.h deleted file mode 120000 index 7e4d8a662..000000000 --- a/manual/manual-acq/sls_detector_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsDetectorSoftware/commonFiles/sls_detector_funcs.h \ No newline at end of file diff --git a/manual/manual-acq/sls_receiver_defs.h b/manual/manual-acq/sls_receiver_defs.h deleted file mode 120000 index 1de31caf5..000000000 --- a/manual/manual-acq/sls_receiver_defs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_defs.h \ No newline at end of file diff --git a/manual/manual-acq/sls_receiver_funcs.h b/manual/manual-acq/sls_receiver_funcs.h deleted file mode 120000 index c2ea4ded9..000000000 --- a/manual/manual-acq/sls_receiver_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_funcs.h \ No newline at end of file diff --git a/manual/manual-acq/zmq.h b/manual/manual-acq/zmq.h deleted file mode 120000 index f2002f1d8..000000000 --- a/manual/manual-acq/zmq.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/zmq.h \ No newline at end of file diff --git a/manual/manual-api/CMakeLists.txt b/manual/manual-api/CMakeLists.txt old mode 100644 new mode 100755 index 0f7841626..57cea1a04 --- a/manual/manual-api/CMakeLists.txt +++ b/manual/manual-api/CMakeLists.txt @@ -3,8 +3,8 @@ set(SOURCES ) include_directories( + ../../slsSupportLib/include ../../slsReceiverSoftware/include - ../../slsDetectorSoftware/slsDetectorAnalysis ../../build/bin ../../slsdetectorSoftware/slsDetector ) @@ -16,15 +16,12 @@ add_executable(slsMultiReceiver target_link_libraries(slsMultiReceiver slsReceiverShared pthread - zmq + ${ZeroMQ_LIBRARIES} rt - ${HDF5_LIBRARIES} ) if (HDF5_FOUND) - target_link_libraries(slsMultiReceiver - ${HDF5_LIBRARIES} - ) + target_link_libraries(slsMultiReceiver ${HDF5_LIBRARIES}) endif () diff --git a/manual/manual-api/Makefile b/manual/manual-api/Makefile old mode 100644 new mode 100755 index 44b6d7420..ee5550398 --- a/manual/manual-api/Makefile +++ b/manual/manual-api/Makefile @@ -1,9 +1,9 @@ PKGDIR = ../.. LIBDIR = $(PKGDIR)/bin -INCLUDES = -I . -I$(PKGDIR)/slsReceiverSoftware/include -I$(PKGDIR)/slsDetectorSoftware/slsDetectorAnalysis -I$(LIBDIR) -I$(PKGDIR)/slsDetectorSoftware/slsDetector +INCLUDES = -I . -I$(PKGDIR)/slsSupportLib/include -I$(LIBDIR) -I$(PKGDIR)/slsDetectorSoftware/slsDetector -I$(PKGDIR)/slsReceiversoftware/include SRC_DET = mainClient.cpp SRC_REC = mainReceiver.cpp -ZMQLIBDIR = $(PKGDIR)/slsReceiverSoftware/include +ZMQLIBDIR = $(PKGDIR)/slsSupportLib/include LDFLAG_DET = -I. -L$(LIBDIR) -Wl,-rpath=$(LIBDIR) -lSlsDetector -L/usr/lib64/ -pthread -lrt -L$(ZMQLIBDIR) -Wl,-rpath=$(ZMQLIBDIR) -lzmq LDFLAG_REC = -I. -L$(LIBDIR) -Wl,-rpath=$(LIBDIR) -lSlsReceiver -L/usr/lib64/ -pthread -lrt -L$(ZMQLIBDIR) -Wl,-rpath=$(ZMQLIBDIR) -lzmq DESTDIR ?= ../docs diff --git a/manual/manual-api/mainClient.cpp b/manual/manual-api/mainClient.cpp old mode 100644 new mode 100755 diff --git a/manual/manual-api/mainReceiver.cpp b/manual/manual-api/mainReceiver.cpp old mode 100644 new mode 100755 index 469eb8a4c..ca6e0f591 --- a/manual/manual-api/mainReceiver.cpp +++ b/manual/manual-api/mainReceiver.cpp @@ -16,7 +16,7 @@ It is linked in manual/manual-api from slsReceiverSoftware/include ] */ -#include "sls_receiver_defs.h" +#include "sls_detector_defs.h" #include "slsReceiverUsers.h" #include @@ -96,20 +96,20 @@ void AcquisitionFinished(uint64_t frames, void*p){ * @param p pointer to object */ void GetData(char* metadata, char* datapointer, uint32_t datasize, void* p){ - slsReceiverDefs::sls_receiver_header* header = (slsReceiverDefs::sls_receiver_header*)metadata; - slsReceiverDefs::sls_detector_header detectorHeader = header->detHeader; + slsDetectorDefs::sls_receiver_header* header = (slsDetectorDefs::sls_receiver_header*)metadata; + slsDetectorDefs::sls_detector_header detectorHeader = header->detHeader; PRINT_IN_COLOR (detectorHeader.modId?detectorHeader.modId:detectorHeader.row, "#### %d GetData: ####\n" - "frameNumber: %llu\t\texpLength: %u\t\tpacketNumber: %u\t\tbunchId: %llu" - "\t\ttimestamp: %llu\t\tmodId: %u\t\t" + "frameNumber: %lu\t\texpLength: %u\t\tpacketNumber: %u\t\tbunchId: %lu" + "\t\ttimestamp: %lu\t\tmodId: %u\t\t" "row: %u\t\tcolumn: %u\t\treserved: %u\t\tdebug: %u" "\t\troundRNumber: %u\t\tdetType: %u\t\tversion: %u" //"\t\tpacketsMask:%s" "\t\tfirstbytedata: 0x%x\t\tdatsize: %u\n\n", - detectorHeader.row, (long long unsigned int)detectorHeader.frameNumber, - detectorHeader.expLength, detectorHeader.packetNumber, (long long unsigned int)detectorHeader.bunchId, - (long long unsigned int)detectorHeader.timestamp, detectorHeader.modId, + detectorHeader.row, (long unsigned int)detectorHeader.frameNumber, + detectorHeader.expLength, detectorHeader.packetNumber, (long unsigned int)detectorHeader.bunchId, + (long unsigned int)detectorHeader.timestamp, detectorHeader.modId, detectorHeader.row, detectorHeader.column, detectorHeader.reserved, detectorHeader.debug, detectorHeader.roundRNumber, detectorHeader.detType, detectorHeader.version, @@ -130,8 +130,8 @@ void GetData(char* metadata, char* datapointer, uint32_t datasize, void* p){ * @param p pointer to object */ void GetData(char* metadata, char* datapointer, uint32_t &revDatasize, void* p){ - slsReceiverDefs::sls_receiver_header* header = (slsReceiverDefs::sls_receiver_header*)metadata; - slsReceiverDefs::sls_detector_header detectorHeader = header->detHeader; + slsDetectorDefs::sls_receiver_header* header = (slsDetectorDefs::sls_receiver_header*)metadata; + slsDetectorDefs::sls_detector_header detectorHeader = header->detHeader; PRINT_IN_COLOR (detectorHeader.modId?detectorHeader.modId:detectorHeader.row, "#### %d GetData: ####\n" @@ -187,7 +187,7 @@ int main(int argc, char *argv[]) { sa.sa_flags=0; // no flags sa.sa_handler=sigInterruptHandler; // handler function sigemptyset(&sa.sa_mask); // dont block additional signals during invocation of handler - if (sigaction(SIGINT, &sa, NULL) == -1) { + if (sigaction(SIGINT, &sa, nullptr) == -1) { cprintf(RED, "Could not set handler function for SIGINT\n"); } @@ -197,7 +197,7 @@ int main(int argc, char *argv[]) { asa.sa_flags=0; // no flags asa.sa_handler=SIG_IGN; // handler function sigemptyset(&asa.sa_mask); // dont block additional signals during invocation of handler - if (sigaction(SIGPIPE, &asa, NULL) == -1) { + if (sigaction(SIGPIPE, &asa, nullptr) == -1) { cprintf(RED, "Could not set handler function for SIGPIPE\n"); } @@ -221,10 +221,10 @@ int main(int argc, char *argv[]) { char temp[10]; sprintf(temp,"%d",startTCPPort + i); char* args[] = {(char*)"ignored", (char*)"--rx_tcpport", temp}; - int ret = slsReceiverDefs::OK; + int ret = slsDetectorDefs::OK; /** - create slsReceiverUsers object with appropriate arguments */ slsReceiverUsers *receiver = new slsReceiverUsers(3, args, ret); - if(ret==slsReceiverDefs::FAIL){ + if(ret==slsDetectorDefs::FAIL){ delete receiver; exit(EXIT_FAILURE); } @@ -236,22 +236,22 @@ int main(int argc, char *argv[]) { /** - Call back for start acquisition */ cprintf(BLUE, "Registering StartAcq()\n"); - receiver->registerCallBackStartAcquisition(StartAcq, NULL); + receiver->registerCallBackStartAcquisition(StartAcq, nullptr); /** - Call back for acquisition finished */ cprintf(BLUE, "Registering AcquisitionFinished()\n"); - receiver->registerCallBackAcquisitionFinished(AcquisitionFinished, NULL); + receiver->registerCallBackAcquisitionFinished(AcquisitionFinished, nullptr); /* - Call back for raw data */ cprintf(BLUE, "Registering GetData() \n"); - if (withCallback == 1) receiver->registerCallBackRawDataReady(GetData,NULL); - else if (withCallback == 2) receiver->registerCallBackRawDataModifyReady(GetData,NULL); + if (withCallback == 1) receiver->registerCallBackRawDataReady(GetData,nullptr); + else if (withCallback == 2) receiver->registerCallBackRawDataModifyReady(GetData,nullptr); } /** - start tcp server thread */ - if (receiver->start() == slsReceiverDefs::FAIL){ + if (receiver->start() == slsDetectorDefs::FAIL){ delete receiver; cprintf(BLUE,"Exiting Child Process [ Tid: %ld ]\n", (long)syscall(SYS_gettid)); exit(EXIT_FAILURE); @@ -272,7 +272,7 @@ int main(int argc, char *argv[]) { sa.sa_flags=0; // no flags sa.sa_handler=SIG_IGN; // handler function sigemptyset(&sa.sa_mask); // dont block additional signals during invocation of handler - if (sigaction(SIGINT, &sa, NULL) == -1) { + if (sigaction(SIGINT, &sa, nullptr) == -1) { cprintf(RED, "Could not set handler function for SIGINT\n"); } @@ -283,7 +283,7 @@ int main(int argc, char *argv[]) { /** - Parent process waits for all child processes to exit */ for(;;) { - pid_t childPid = waitpid (-1, NULL, 0); + pid_t childPid = waitpid (-1, nullptr, 0); // no child closed if (childPid == -1) { diff --git a/manual/manual-api/slsDetectorUsers.doxy b/manual/manual-api/slsDetectorUsers.doxy old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/Advanced.png b/manual/manual-calwiz/Advanced.png old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/Constant_step.png b/manual/manual-calwiz/Constant_step.png old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/GUI_Advanced.eps b/manual/manual-calwiz/GUI_Advanced.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/GUI_ThresholdScan.eps b/manual/manual-calwiz/GUI_ThresholdScan.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/Makefile b/manual/manual-calwiz/Makefile old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/addEnergy.eps b/manual/manual-calwiz/addEnergy.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/addEnergy.png b/manual/manual-calwiz/addEnergy.png old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/ancCal.tex b/manual/manual-calwiz/ancCal.tex old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/angleFit.eps b/manual/manual-calwiz/angleFit.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/angleFit.png b/manual/manual-calwiz/angleFit.png old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/angularCalibrationHowTo.tex b/manual/manual-calwiz/angularCalibrationHowTo.tex old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/calibrateModule.eps b/manual/manual-calwiz/calibrateModule.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/calibrateModule.png b/manual/manual-calwiz/calibrateModule.png old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/calibrationWizardsHowTo.tex b/manual/manual-calwiz/calibrationWizardsHowTo.tex old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/enCal.tex b/manual/manual-calwiz/enCal.tex old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/enable_angcal.eps b/manual/manual-calwiz/enable_angcal.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/eneble_angcal.png b/manual/manual-calwiz/eneble_angcal.png old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/energyCalibrationHowTo.tex b/manual/manual-calwiz/energyCalibrationHowTo.tex old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/fig4.eps b/manual/manual-calwiz/fig4.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/fig5.eps b/manual/manual-calwiz/fig5.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/fig7.eps b/manual/manual-calwiz/fig7.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/fig8.eps b/manual/manual-calwiz/fig8.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/installation.tex b/manual/manual-calwiz/installation.tex old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/peakFit.eps b/manual/manual-calwiz/peakFit.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/peakFit.png b/manual/manual-calwiz/peakFit.png old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/position_scan.eps b/manual/manual-calwiz/position_scan.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/position_scan.png b/manual/manual-calwiz/position_scan.png old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/setupAngcal.eps b/manual/manual-calwiz/setupAngcal.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/setupAngcal.png b/manual/manual-calwiz/setupAngcal.png old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/spectrum_expl.eps b/manual/manual-calwiz/spectrum_expl.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/thr_scan_expl.eps b/manual/manual-calwiz/thr_scan_expl.eps old mode 100644 new mode 100755 diff --git a/manual/manual-calwiz/thr_scan_fluo.eps b/manual/manual-calwiz/thr_scan_fluo.eps old mode 100644 new mode 100755 diff --git a/manual/manual-client/Boards.png b/manual/manual-client/Boards.png old mode 100644 new mode 100755 diff --git a/manual/manual-client/Client2.eps b/manual/manual-client/Client2.eps old mode 100644 new mode 100755 diff --git a/manual/manual-client/Client2.png b/manual/manual-client/Client2.png old mode 100644 new mode 100755 diff --git a/manual/manual-client/EIGERUDPHeader.png b/manual/manual-client/EIGERUDPHeader.png old mode 100644 new mode 100755 diff --git a/manual/manual-client/Eiger-Chips.png b/manual/manual-client/Eiger-Chips.png new file mode 100755 index 000000000..a83fc52c4 Binary files /dev/null and b/manual/manual-client/Eiger-Chips.png differ diff --git a/manual/manual-client/Eiger_short.pdf b/manual/manual-client/Eiger_short.pdf deleted file mode 100644 index e6d55e71e..000000000 Binary files a/manual/manual-client/Eiger_short.pdf and /dev/null differ diff --git a/manual/manual-client/Eiger_short.tex b/manual/manual-client/Eiger_short.tex old mode 100644 new mode 100755 index 3379fdfc7..3d3d4d3c3 --- a/manual/manual-client/Eiger_short.tex +++ b/manual/manual-client/Eiger_short.tex @@ -6,6 +6,7 @@ \usepackage{verbatim} \usepackage{xspace} \usepackage{hyperref} +\usepackage{xcolor} \newcommand{\E}{EIGER\xspace} \newcommand{\p}{sls\_detector\_put} \newcommand{\g}{sls\_detector\_get} @@ -24,7 +25,7 @@ Figure ~\ref{boards} show the readout board basic components on an Eiger half mo \begin{center} \includegraphics[width=1\textwidth]{Boards} \end{center} -\caption{Picture with most relevant components of the EIGER readout system. The readout system starts with the Front End Boards (FEB) which performs data descrambling (also converts the packets from 12 $\to$ 16 bits) and rate correction. The BackEndBoard (BEB) has 2x2GB DDR2 memories and can perform data buffering (storing images on board) and data summation (16 bit $\to$ 32 bits). The controls to the detector are passed through the 1Gb, while in most installations, the data are sent out through the 10GB ethernet connection.} +\caption{Picture with most relevant components of the EIGER readout system. The readout system starts with the Front End Boards (FEB) which performs data descrambling (also converts the packets from 12 $\to$ 16 bits) and rate correction. The BackEndBoard (BEB) has 2x2GB DDR2 memories and can perform data buffering (storing images on board) and data summation (16 bit $\to$ 32 bits). The controls to the detector are passed through the 1Gb, while in most installations, the data are sent out through the 10~GB ethernet connection.} \label{boards} \end{figure} @@ -156,6 +157,14 @@ outdir /sls/X12SA/data/x12saop/Data10/Eiger0.5M threaded 1 \end{verbatim} +The geometry on af an EIGER module, showing the quadrants corresponding to the udp ports and the 2 receivers is shown in figure~\ref{fig:eigerports}. +\begin{figure}[t] +\begin{center} +\includegraphics[width=0.9\textwidth]{Eiger-Chips} +\end{center} +\caption{Geometry of UDP ports and receivers in a singel module.} +\label{fig:eigerports} +\end{figure} In the case you are developing your own receiver, then you need to remove the 1Gb receiver hostname {\tt{rx\_hostname}} and substitute it with the mac address of the device: \begin{verbatim} @@ -163,7 +172,6 @@ configuremac 0 rx_udpmac xx:xx:... \end{verbatim} - One can configure all the detector settings in a parameter file {\tt{setup.det}}, which is loaded by doing: \begin{verbatim} sls_detector_put 0-parameters setup.det @@ -412,18 +420,9 @@ where the 'minimum time between frames' and the minimum period will be discussed \hline 4 & 0 & \tiny {parallel} & 3.4 & 22 & 44 & 44.01 & 30k/50k\\ \hline -4 & 1 & \tiny {parallel} & 6 & 10.5 & 92 & 92.02 & 30k/100k\\ -\hline -4 & 2 & \tiny {parallel} & 11.2 & 5.4 & 197& 197.01 & infinite\\ -\hline \hline 8 & 0 & \tiny {parallel} & 3.4 & 11.1 & 89 & 89.01 & 15k/24k\\ \hline -8 & 1 & \tiny {parallel} & 6.1 & 5.7 & 181 & 181.01 & 15k/52k\\ -\hline -8 & 2 & \tiny {parallel} & 11.2 & 2.9 & 342 & 342.01 & infinite\\ -\hline -\hline 16 & 0 & \tiny {parallel} & 3.4 & 6.1 & (126+38)* =164 & 164.02 & 8k/12k\\ \hline 16 & 0 & \tiny {nonparallel} & 127 & 5.6 & (126+52)*= 179 & 179.01& 8k/23k\\ @@ -432,14 +431,6 @@ where the 'minimum time between frames' and the minimum period will be discussed \hline 16 & 1 & \tiny {nonparallel} & 255 & 3.3 & 303 & 303.01 & infinite\\ \hline -16 & 2 & \tiny {parallel} & 11.2 & 1.9 & 526 & 526.2 & infinite \\ -\hline -16 & 2 & \tiny {nonparallel} & 505 & 1.8 & 555 & 555.01& infinite\\ -\hline -%32 & 2 & parallel & 11 & 2& & &\\ -%\hline -%32 & 2 & nonparallel & 504 & $<2$& & &\\ -%\hline \end{tabular} \caption{Readout settings. The {\tiny{min exptime}} possible is 5$-$10~$\mu$s. This is due to the time to pass the pixel enable signal in the whole chip. The time between frames ($\Delta$t) has been measured with the oscilloscope and the maximum frames rate (max FR) has been tested with an external gating from a pulse generator at known frequency. The minimum period is obtained as 1/$\textrm{max frame rate}$.} \label{tframes} @@ -450,7 +441,6 @@ where the 'minimum time between frames' and the minimum period will be discussed \textbf{From software version 4.0.0, there is a very useful function {\tt{sls\_detector\_get measuredperiod}} which return the measured period AFTER the acquisition. This is important to check that the settings to obtain the targeted frame rate was correct.} \textbf{If you run too fast, the detector could become noisier (see problem shooting), it is important to match the detector settings to your frame rate. This can be done having more parameters files and load the one suitable with your experiment.} We experienced that with low energy settings could not reach 6~kHz and no noise. - In 16 bit mode, it could make sense, in case of noise and low threshold to either reduce the frame rate: \begin{equation} \textrm{new period} = \textrm{exptime} + \textrm{minimum time between frames} + (\textrm{10$-$20 }\mu \textrm{s}) @@ -460,7 +450,54 @@ to let the signal settle or, if the frame rate is important, leave the {\tt{pe \textrm{new exptime} = \textrm{old exptime} - (\textrm{10$-$20 }\mu \textrm{s}) \end{equation} -In general, choose first the desired dead time: this will tell you if you want to run in parallel or non parallel mode, although most likely it is parallel mode. Then, choose the maximum frame rate you want to aim, not exceeding what you aim for not to increase the noise. In 4 and 8 bit modes it makes no sense to run nonparallel as the exposure time is too small compared to the readout time. +In general, choose the maximum frame rate you want to aim, not exceeding what you aim for not to increase the noise. In 4 and 8 bit modes it makes no sense to run nonparallel as the exposure time is too small compared to the readout time. + +Here below are the final tables for settting the detcetor correctly: + +\begin{itemize} +\item CONTINUOUS redout (imagesnot stored on board memories, frames can be achieved. {\tt{flags parallel}}, {\tt{clkdivider 0}} are always set. In 32-bit no extra {\tt{subdeadtime}} is assumed. The difference between {\tt{exptime}} and {\tt{period}} has to be $\approx$5 $\mu$s: +\begin{center} + \begin{tabular}{ |c| c| } + \hline + max frame rate & settings\\ + \hline + \textcolor{red}{170 Hz} & \textcolor{red}{32-bit} \\ + & Nframes=infinite\\ + \hline + \textcolor{red}{2.56 kHz} & \textcolor{red}{16-bit}\\ + & Nframes=infinite\\ + \hline + \textcolor{red}{5.1 kHz} & \textcolor{red}{8-bit}\\ + & Nframes=infinite\\ + \hline + \textcolor{red}{10.2 kHz} & \textcolor{red}{4-bit}\\ + & Nframes=infinite\\ + \hline + \end{tabular} +\end{center} +\item BUFFERED redout (images stored on board memories, such that the maximum frame rate can be achieved for a limited amount of frames. {\tt{flags parallel}}, {\tt{clkdivider 0}} are always set. In 32-bit no extra {\tt{subdeadtime}} is assumed. The difference between {\tt{exptime}} and {\tt{period}} has to be $\approx$5 $\mu$s: +\begin{center} + \begin{tabular}{ |c| c| } + \hline + max frame rate & settings\\ + \hline + \textcolor{red}{170 Hz} & \textcolor{red}{32-bit} \\ + & Nframes=infinite\\ + \hline + \textcolor{red}{6.1 kHz} & \textcolor{red}{16-bit}\\ + & Nframes=7600\\ + \hline + \textcolor{red}{11.1 kHz} & \textcolor{red}{8-bit}\\ + & Nframes=15000\\ + \hline + \textcolor{red}{22 kHz} & \textcolor{red}{4-bit}\\ + & Nframes=30000\\ + \hline + \end{tabular} +\end{center} +\end{itemize} + + \subsubsection{4 and 8 bit mode} In {\tt{parallel}} mode, the minimum time between frames is due to the time required to latch the values of the counter with capacitors. These values are determined in firmware and they can be estimated as: @@ -712,7 +749,7 @@ To activate back a module, do: \end{verbatim} \end{itemize} -\subsection{Setting up 10Gb correctly: experience so far}\label{10g} +\section{Setting up the PC settings for 10Gb}\label{10g} For configuring well the 10Gb card not to loose packets, \begin{itemize} @@ -734,13 +771,74 @@ Very important is to activate the flow control in 10Gb (in 1Gb it is on by defau \begin{verbatim} ./sls_detector_put flowcontrol_10g 1 \end{verbatim} -Set the transmission delays as explained in the manual. +You ned to check that flow control is setup on the reeceiving interfaces. Check with: +\begin{verbatim} +ethtool -a eth1 +\end{verbatim} +.RX should be ON. Set the transmission delays as explained in the manual if necessary. These transmission delays should help matching teh writing speed performance of your disk. You can check how fast you are writing using the {\tt{dstat}} command. + +Now setup the computer server propery: +Check the size of: +\begin{verbatim} +sysctl -a | grep backlog +sysctl -a | grep rmem +\end{verbatim} +Set it correctly with: +\begin{verbatim} +sysctl net.core.netdev_max_backlog=250000 +sysctl net.core.rmem_default=$((100*1024*1024)) +sysctl net.core.rmem_max=$((100*1024*1024)) +\end{verbatim} + +Other way to setup the same, increase the socket receiving buffer size and the maximum length of the input queue: +\begin{verbatim} +echo $((100*1024*1024)) > /proc/sys/net/core/rmem_max +echo 250000 > /proc/sys/net/core/netdev_max_backlog +\end{verbatim} +to make the settings permanent, edit /etc/sysctl.conf: + \begin{verbatim} +# 100MiB +net.core.rmem_max = 104857600 +net.core.netdev_max_backlog = 250000 +\end{verbatim} +and run \textbf{sysctl -p}. + +Last, you can disable power saving in the CPU frequency (chose the appropriate command for your system): +\begin{verbatim} +cpupower frequency-info +cpupower frequency-set -g performance +\end{verbatim} +or +\begin{verbatim} +cpufreq-info +for i in `seq 0 7`; do cpufreq-set -c $i -g performance; done +\end{verbatim} It can help to increase the fifo size of the receiver to {\tt{rx\_fifodepth}} to 1000 images \begin{verbatim} ./sls_detector_put rx_fifodepth 1000 \end{verbatim} -One needs to keep into account that in 16 bit mode for 1 image we expect each slsReceiver to allocate 0.5MB. So for 1000 images, we expect 500MB memory for each receiver. This can be monitored in Linux with "top" or "free -m". +One needs to keep into account that in 16 bit mode for 1 image we expect each slsReceiver to allocate 0.5MB. So for 1000 images, we expect 500MB memory for each receiver. This can be monitored in Linux with "top" or "free -m". To receive the max number of images possible on the detector, a minimum of 8~GB of memories are required. +For very high frame rate, very long measurements, we had to increase the {\tt{rx\_fifodepth}} to 10000 images but this only in 4, 8, 16 bit mode. In 32 bit mode it will assign 40~GB of memory, which is more than what normal PC would have. So make sure you do not require too much memory. + +Last, it is very important that not too many files are created. There is high possibility to loose packets in the time to close and open files for the writer. IN 3.1.x, the default number of images written per file, in Eiger is 2000. This is defined by the line: +\begin{verbatim} +#define EIGER_MAX_FRAMES_PER_FILE 2000 +\end{verbatim} +in {\tt{slsDetectorsPackage/slsReceiverSoftware/include/sls\_receiver\_defs.h}}. In 4.0.x, this is interactively defined using the command: {\tt{r\_framesperfile}}. By default it is 10000. + +If you do not have a large disk, you can write to memory if your pc is not fast enough: +\begin{verbatim} +mount -t tmpfs none /ramdisk_folder +\end{verbatim} +or +\begin{verbatim} +mount -t tmpfs none /mnt/ramdisk -o size=10G +\end{verbatim} +check how many GB memory you can allocate, to avoid swapping otherwise + + + \section{Offline processing and monitoring} @@ -820,9 +918,14 @@ Checkout the {\tt{developer}} branch if in a 3.1.X release or the {\tt{v4.0.0}} Three possible conversions are possible: into \textbf{cbf}, \textbf{hdf5} and \textbf{root} format. The detector writes 4 raw files per receiver. An offline image reconstruction executable has been written to collate the possible files together and produce output files. By default an interpolation between the values of the large pixels is performed. Gap pixels between modules are also inserted. +Note that the number of images per file is hardcoded and needs to match whatever you are using in {\tt{slsDetectorsPackage/slsReceiverSoftware/include/sls\_receiver\_defs.h}}: +\begin{verbatim} +#define EIGER_MAX_FRAMES_PER_FILE 2000 +\end{verbatim} +The default is 2000. \subsubsection{cbf} -The cbf executable executable uses the CBFlib-0.9.5 library (downloaded from the web as it download some architecture dependent packages at installation).Edit the Makefile to correclty point at it.\\ +The cbf executable executable uses the CBFlib-0.9.5 library (downloaded from the web as it downloads architecture dependent packages at installation).Edit the Makefile to correclty point at it.\\ \underline{At cSAXS, the CBFlib-0.9.5 has been compiled -such that the required packages are}\\\underline{ downloaded in /sls/X12SA/data/x12saop/EigerPackage/CBFlib-0.9.5.}\\ To use it for a single module: @@ -833,7 +936,7 @@ eg. {\tt{cbfMaker /scratch/run\_63\_d1\_f000000000000\_3.raw}}\\ To use it any geometry:\\ -{\tt{cbfMaker [filename] [pixels x, def=1024] [pixels y, def=512] [singlemodulelongside\_x, def=1] [fillgaps, def=Interpolate Big Pixels] [hdf5datasetname, def="Eiger"] [start det,def=0]}}\\ +{\tt{cbfMaker [filename] [outdir, def=same as filename] [pixels x, def=1024] [pixels y, def=512] [singlemodulelongside\_x, def=1] [fillgaps, def=Interpolate Big Pixels] [hdf5datasetname, def="Eiger"] [start det,def=0]}}\\ eg. {\tt cbfMaker /scratch/run\_63\_d0\_f000000000000\_3.raw 3072 512 1 2 ``Eiger'' 0}.\\ @@ -877,7 +980,7 @@ make cbfMaker; make cbfMakerOMNY; \end{verbatim} \subsubsection{hdf5} -In case of HDF5 output file, we rely on having the HDF5 1.10.1 library installed. Edit the Makefile to correclty point at it. Different compression methods are being tried so different external filters might be to be installed. This work is not finished yet. +In case of HDF5 output file, we rely on having the HDF5 1.10.1 library installed and {\tt{HDF5-External-Filter-Plugins}} installed. With HDF5 1.10.3, no need of the external plugings package is needed, but a small modification to the file is needed. Edit the Makefile to correclty point at it. Different compression methods are being tried so different external filters might be to be installed. This work is not finished yet. To choose HDF5, with ZLIB implementation, open {\tt{slsImageReconstruction/src/main\_csaxs.cpp}} and make sure that \begin{verbatim} @@ -889,7 +992,7 @@ are not commented out. All other options need to be commented out. Copile the co make hdf5Maker; make hdf5MakerOMNY; \end{verbatim} -If you are at cSAXS. all images collected will be written in a single file. If you are not at CSAXS, most likely you want to have all the images written in a single raw file into an HDF5 file. The multiple HDF5 files are then linked in a master file, with many subdatasets (can be read by albula) or by a virtual file with a single dataset. If you want a mster o virtual file, uncomment this option: +If you are at cSAXS. all images collected will be written in a single file. If you are not at CSAXS, most likely you want to have all the images written in a single raw file into an HDF5 file. The multiple HDF5 files are then linked in a master file, with many subdatasets (can be read by albula) or by a virtual file with a single dataset. If you want a master o virtual file, uncomment this option: \begin{verbatim} #define MASTERVIRTUAL \end{verbatim} @@ -911,7 +1014,7 @@ The data will be written as TH2D in root format. Edit the {\tt{Makefile}} to poi \begin{verbatim} make image \end{verbatim} -There is no program other executable that alredy keeps into account the geometry for it. +There is no program other executable that already keeps into account the geometry for it. To use it any geometry:\\ {\tt{image [filename] [pixels x, def=1024] [pixels y, def=512] [singlemodulelongside\_x, def=1] [fillgaps, def=Interpolate Big Pixels] [hdf5datasetname, def="Eiger"] [start det,def=0]}}\\ eg. @@ -979,9 +1082,9 @@ ssh root@$i sync; done \section{Loading firmware bitfiles} -\textbf{As a new procedure, the first thing to do is to kill the server on the boards, copy the new one there without starting it.} Note taht failure to do this step before may cause the linux on the baords to crash and not being able to ping it (this if the registers between the old and new firmware change). +\textbf{As a new procedure, the first thing to do is to kill the server on the boards, copy the new one there without starting it.} Note that failure to do this step before may cause the linux on the boards to crash and not being able to ping it (this if the registers between the old and new firmware change). -This is teh procedure from a terminal; +This is the procedure from a terminal; \begin{verbatim} for i in beb111 beb070; do ssh root@$i killall eigerDetectorServer; @@ -1059,19 +1162,19 @@ To load the special noise file look at {\tt{settingsdir/eiger/standard/eigernois \begin{verbatim} sls_detector_put trimbits ../settingsdir/eiger/standard/eigernoise \end{verbatim} -To exit from this pattern noise, just set the theshold to something known. +To exit from this pattern noise, just set the threshold to something known. \begin{verbatim} \item sls_detector_put threshold 50000 standard \end{verbatim} where 5000 would be a value in eV and {/tt{standard}} is important in this case. \section{(Fast) threshold scans during beam operation}\label{sec:fastthresholdscan} -Occasionally you might need to do threshold scans during your data taking (for example for Laue experiments or to get any spectral information). Settinng the threshold in thsi case would be not optimal as you would change thrimbits at every energy and this could give you a ``step'' behaviour. What you could do is to use the +Occasionally you might need to do threshold scans during your data taking (for example for Laue experiments or to get any spectral information). Setting the threshold in this case would be not optimal as you would change trimbits at every energy and this could give you a ``step'' behaviour. What you could do is to use the \begin{verbatim} \item sls_detector_put thresholdnotb 50000 \end{verbatim} which set the threshold to an energy but does not change trimbits. We suggest that before using this function you load the {\tt{threshold}} at an energy in the middle of your scan range and then change {\tt{thresholdnotb}}. -We have also been requested if we could speed up the threshold scan. At the moment no specific function has been integrated in firware, but one could use the software thrigger option to perform what you need: +We have also been requested if we could speed up the threshold scan. At the moment no specific function has been integrated in firmware, but one could use the software trigger option to perform what you need: \begin{verbatim} ./sls_detector_put exptime 0.01 ./sls_detector_put timing trigger @@ -1084,8 +1187,8 @@ We have also been requested if we could speed up the threshold scan. At the mome for i in $(seq 0 20); do #./sls_detector_put thresholdnotb 5000 ##this is still too slow as it loads the module - ./sls_detector_put 0:vrf 3199 #need to know the appropriat vrf at every energy - ./sls_detector_put 1:vrf 3199 #need to know the appropriat vrf at every energy + ./sls_detector_put 0:vrf 3199 #need to know the appropriate vrf at every energy + ./sls_detector_put 1:vrf 3199 #need to know the appropriate vrf at every energy ./sls_detector_put status trigger #sleep 0.005 done @@ -1244,7 +1347,7 @@ Scroll up in the terminal till you find:\\ *************** MASTER/SLAVE ***************\\ *************** NORMAL/SPECIAL ***************\\ -There is also an easier way, that is that only the master module will reaturn the real value of the HV. If you have more than 1 detector system, then you will have more than 1 physical master, as the HV needs to be applied to all the systems. +There is also an easier way, that is that only the master module will return the real value of the HV. If you have more than 1 detector system, then you will have more than 1 physical master, as the HV needs to be applied to all the systems. \begin{verbatim} for i in $(seq 0 36); do sls_detector_put $i:vhighvoltage; done @@ -1254,10 +1357,14 @@ for i in $(seq 0 36); do sls_detector_put $i:vhighvoltage; done \subsection{'Cannot connect to socket'} This error is typically due to the detector server not running. For why, see section~\ref{servernot}. +\subsection{Running at low frame rate, the communication to receiver stops} +If running in 32-bit mode (or even in 16-bit mode), if more memory than what your machine can handle is asked for, the receiver process could be terminated by the kernel of your machine. It would loook like you had executed a clean control-c on the receiver executable. This has been the case, when setting up by mistake +\tt{rx\_fifodepth} to 10000 images in 32 bit mode. In 32 bit mode it will assign 40~GB of memory, which is more than what normal PC would have. So make sure you do not require too much memory. The same is tru also for smaller values of {\tt{rx\_fifodepth}} if your machine has not much memory. + \subsection{Detector server is not running}\label{servernot} The detector server could not be running: either the detector was powered off, or it powered off itself due to too high temperature or, in the case of the 9M, if the waterflow sensor detected no flux and powered it off (the chiller stops occasionally as cSAXS). -If the powering and the temperature are OK, instead, it can be that the firmware version is incompatible to the server version and/or the client software version. So check the consistency of firmware/software/server versions. +If the powering and the temperature are OK, instead, it can be that the firmware version is incompatible to the server version and/or the client software version. In software packages 3.x.y, the eigerDetectorServer was killed automatically. So check the consistency of firmware/software/server versions if using this version of the software. From 4.x.y onwards, the server, if associated to a wrong firmware, does not kill itself. \subsection{'Acquire has already started' error message} If you see the client returning the following error message:\\ @@ -1268,10 +1375,10 @@ If you see the client returning the following error message:\\ \end{verbatim} \subsection{There is noise running the detector in 32-bit} -If you are running the detector in 32-bit (autosumming), there might be some noise, particularly at lower thereshold energies. This is due to the fact that the analog part of the chips require some latency time to settle which is larger than the readout time. It is possible to run the detector only in {\tt{parallel}} or {\tt{nonparallel}} mode, respectively with readout times between frames of 12~$\mu$s and 504~$\mu$s. If you switch {\tt{flags}} to non {\tt{nonparallel}} mode you will give enough time for the signals to settle. From release 4.0.0, there is a configurable delay that can be set through the {\tt{subdeadtime}} variable, such that you can remain with the {\tt{parallel}} flag, but can obtain a configurable dead time between frames. Ask the SLS detector group for an appropriate dead time for your detector, but typically a dead time of 20-50~$\mu$s should be enough. Note that this {\tt{subdeadtime}} need to include the 12~$\mu$s minimum readout time, so it has to be larger than 12~$\mu$s to do anything. +If you are running the detector in 32-bit (autosumming), there might be some noise, particularly at lower threshold energies. This is due to the fact that the analog part of the chips require some latency time to settle which is larger than the readout time. It is possible to run the detector only in {\tt{parallel}} or {\tt{nonparallel}} mode, respectively with readout times between frames of 12~$\mu$s and 504~$\mu$s. If you switch {\tt{flags}} to non {\tt{nonparallel}} mode you will give enough time for the signals to settle. From release 4.0.0, there is a configurable delay that can be set through the {\tt{subdeadtime}} variable, such that you can remain with the {\tt{parallel}} flag, but can obtain a configurable dead time between frames. Ask the SLS detector group for an appropriate dead time for your detector, but typically a dead time of 20-50~$\mu$s should be enough. Note that this {\tt{subdeadtime}} need to include the 12~$\mu$s minimum readout time, so it has to be larger than 12~$\mu$s to do anything. \subsection{There is noise running the detector at high frame rate(4,8,16 bit)} -If are running in {\tt{parallel}} mode, in particular at low thereshold energies, you might encounter some noise. The reason is that the analog part of the chips require some latency time to settle which is larger than the readout time. +If are running in {\tt{parallel}} mode, in particular at low threshold energies, you might encounter some noise. The reason is that the analog part of the chips require some latency time to settle which is larger than the readout time. \begin{enumerate} \item You can lower the frame rate and relax requirements on period: At low frame rate, you normally leave enough time between the end of the acquisition and the starting of the next, so you should not see this effect. In any case setting a {\tt{period}}={\tt{exptime}}+readout time from Table~\ref{tchipro} +extra 20$\mu$s cures the problem. The 20$\mu$s could also be 10~$\mu$s, they are very hardware dependent. diff --git a/manual/manual-client/GapPixels.png b/manual/manual-client/GapPixels.png old mode 100644 new mode 100755 diff --git a/manual/manual-client/LEDSim.png b/manual/manual-client/LEDSim.png old mode 100644 new mode 100755 diff --git a/manual/manual-client/Makefile b/manual/manual-client/Makefile old mode 100644 new mode 100755 diff --git a/manual/manual-client/TansmissionRates.png b/manual/manual-client/TansmissionRates.png old mode 100644 new mode 100755 diff --git a/manual/manual-client/commands.txt b/manual/manual-client/commands.txt old mode 100644 new mode 100755 diff --git a/manual/manual-client/libs.txt b/manual/manual-client/libs.txt old mode 100644 new mode 100755 diff --git a/manual/manual-client/slsDetectorClient.doxy b/manual/manual-client/slsDetectorClient.doxy old mode 100644 new mode 100755 diff --git a/manual/manual-client/slsDetectorClientHowTo.tex b/manual/manual-client/slsDetectorClientHowTo.tex old mode 100644 new mode 100755 diff --git a/manual/manual-client/tiggerIN.png b/manual/manual-client/tiggerIN.png old mode 100644 new mode 100755 diff --git a/manual/manual-gui/Makefile b/manual/manual-gui/Makefile old mode 100644 new mode 100755 diff --git a/manual/manual-gui/libs.txt b/manual/manual-gui/libs.txt old mode 100644 new mode 100755 diff --git a/manual/manual-gui/slsDetectorGuiHowTo.tex b/manual/manual-gui/slsDetectorGuiHowTo.tex old mode 100644 new mode 100755 diff --git a/manual/manual-main/AngConv.eps b/manual/manual-main/AngConv.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/AngConv_fml.tex b/manual/manual-main/AngConv_fml.tex old mode 100644 new mode 100755 diff --git a/manual/manual-main/F90-C++Interface.doc b/manual/manual-main/F90-C++Interface.doc old mode 100644 new mode 100755 diff --git a/manual/manual-main/Makefile b/manual/manual-main/Makefile old mode 100644 new mode 100755 diff --git a/manual/manual-main/Waver.tex b/manual/manual-main/Waver.tex old mode 100644 new mode 100755 diff --git a/manual/manual-main/angConv-FAQ.tex b/manual/manual-main/angConv-FAQ.tex old mode 100644 new mode 100755 diff --git a/manual/manual-main/chargeInt-FAQ.tex b/manual/manual-main/chargeInt-FAQ.tex old mode 100644 new mode 100755 diff --git a/manual/manual-main/data_receiver.eps b/manual/manual-main/data_receiver.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/data_receiver.fig b/manual/manual-main/data_receiver.fig old mode 100644 new mode 100755 diff --git a/manual/manual-main/generalDet-FAQ.tex b/manual/manual-main/generalDet-FAQ.tex old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/FFSetup.eps b/manual/manual-main/images/FFSetup.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/bad_ff_col.eps b/manual/manual-main/images/bad_ff_col.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/continuos_trigger_acquisition.eps b/manual/manual-main/images/continuos_trigger_acquisition.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/continuos_trigger_acquisition.fig b/manual/manual-main/images/continuos_trigger_acquisition.fig old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/ff_calibration.eps b/manual/manual-main/images/ff_calibration.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/ff_window.eps b/manual/manual-main/images/ff_window.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/gated_acquisition.eps b/manual/manual-main/images/gated_acquisition.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/gated_acquisition.fig b/manual/manual-main/images/gated_acquisition.fig old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/gated_acquisition.fig.bak b/manual/manual-main/images/gated_acquisition.fig.bak old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/noise_thresholdscantrimmed.eps b/manual/manual-main/images/noise_thresholdscantrimmed.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/noise_thresholdscanuntrimmed.eps b/manual/manual-main/images/noise_thresholdscanuntrimmed.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/normal_acquisition.eps b/manual/manual-main/images/normal_acquisition.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/normal_acquisition.fig b/manual/manual-main/images/normal_acquisition.fig old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/normal_acquisition.fig.bak b/manual/manual-main/images/normal_acquisition.fig.bak old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/ro_trigger_acquisition.eps b/manual/manual-main/images/ro_trigger_acquisition.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/ro_trigger_acquisition.fig b/manual/manual-main/images/ro_trigger_acquisition.fig old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/ro_trigger_acquisition.fig.bak b/manual/manual-main/images/ro_trigger_acquisition.fig.bak old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/sample_with_fluorescence.eps b/manual/manual-main/images/sample_with_fluorescence.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/settings.eps b/manual/manual-main/images/settings.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/single_trigger_acquisition.eps b/manual/manual-main/images/single_trigger_acquisition.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/single_trigger_acquisition.fig b/manual/manual-main/images/single_trigger_acquisition.fig old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/thr_scan_expl.eps b/manual/manual-main/images/thr_scan_expl.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/thr_scan_fluo.eps b/manual/manual-main/images/thr_scan_fluo.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/trigger_acquisition.eps b/manual/manual-main/images/trigger_acquisition.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/trigger_acquisition.fig b/manual/manual-main/images/trigger_acquisition.fig old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/trigger_acquisition.fig.bak b/manual/manual-main/images/trigger_acquisition.fig.bak old mode 100644 new mode 100755 diff --git a/manual/manual-main/images/win_acquisition.eps b/manual/manual-main/images/win_acquisition.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/libs.txt b/manual/manual-main/libs.txt old mode 100644 new mode 100755 diff --git a/manual/manual-main/manual.tex b/manual/manual-main/manual.tex old mode 100644 new mode 100755 diff --git a/manual/manual-main/multi_detector.eps b/manual/manual-main/multi_detector.eps old mode 100644 new mode 100755 diff --git a/manual/manual-main/multi_detector.fig b/manual/manual-main/multi_detector.fig old mode 100644 new mode 100755 diff --git a/manual/manual-main/singlePhotonCounting-FAQ.tex b/manual/manual-main/singlePhotonCounting-FAQ.tex old mode 100644 new mode 100755 diff --git a/manual/manual-main/slsDetector-softFAQ.tex b/manual/manual-main/slsDetector-softFAQ.tex old mode 100644 new mode 100755 diff --git a/manual/manual-main/slsDetectorClientHowTo.tex b/manual/manual-main/slsDetectorClientHowTo.tex old mode 100644 new mode 100755 diff --git a/manual/manual-main/slsDetectorGuiHowTo.tex b/manual/manual-main/slsDetectorGuiHowTo.tex old mode 100644 new mode 100755 diff --git a/manual/manual-main/slsDetectorInstall.tex b/manual/manual-main/slsDetectorInstall.tex old mode 100644 new mode 100755 diff --git a/manual/manual-main/slsDetectors-FAQ.tex b/manual/manual-main/slsDetectors-FAQ.tex old mode 100644 new mode 100755 diff --git a/python/CMakeLists.txt b/python/CMakeLists.txt new file mode 100755 index 000000000..16d4a95e3 --- /dev/null +++ b/python/CMakeLists.txt @@ -0,0 +1,47 @@ +add_subdirectory(pybind11) +pybind11_add_module(_sls_detector src/main.cpp) + + + +target_link_libraries(_sls_detector PUBLIC + slsProjectOptions + slsProjectWarnings + slsDetectorShared + slsReceiverShared + slsSupportLib + zmq ) + + + +set_target_properties(_sls_detector PROPERTIES + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin + ) + +#Copy Python code +set( PYTHON_FILES + __init__.py + adcs.py + dacs.py + decorators.py + detector_property.py + detector.py + eiger.py + errors.py + experimental.py + jungfrau_ctb.py + jungfrau.py + registers.py + utils.py + +) + +foreach(FILE ${PYTHON_FILES}) + configure_file( sls_detector/${FILE} + ${CMAKE_BINARY_DIR}/bin/sls_detector/${FILE} ) + +endforeach(FILE ${PYTHON_FILES}) + + +configure_file( scripts/basic.py + ${CMAKE_BINARY_DIR}/basic.py +) \ No newline at end of file diff --git a/python/LICENSE b/python/LICENSE new file mode 100755 index 000000000..94a9ed024 --- /dev/null +++ b/python/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/python/README.md b/python/README.md new file mode 100755 index 000000000..619ff6def --- /dev/null +++ b/python/README.md @@ -0,0 +1,63 @@ +# sls_detector: Python interface to slsDetectorPackage +Python interface to the Sls Detector Software. + +### Documentation ### +Sphinx built documentation is available here: +[https://slsdetectorgroup.github.io/sls_detector/](https://slsdetectorgroup.github.io/sls_detector/) + + +### Install using conda ### + +Binaries are available using conda. This installs both the detector software and the Python +interface. + +```bash +#Add conda channels +conda config --add channels conda-forge +conda config --add channels slsdetectorgroup + +#Install latest version +conda install sls_detector + +#Install specific version +conda install sls_detector=3.0.1 + +#Scientific Linux 6 version (GLIBC2.12) +conda install sls_detector=SL6_3.0.1 +``` + +### Building using conda-build ### + +Needs [sls_detector_software](https://github.com/slsdetectorgroup/sls_detector_software) installed. + +```bash +#Clone source code +git clone https://github.com/slsdetectorgroup/sls_detector.git + +#Checkout the branch needed +git checkout 3.0.1 + +#Build and install the local version +conda-build sls_detector +conda install --use-local sls_detector + + +``` +### Developer build ### + +IF you if you are developing and are making constant changes to the code it's a bit cumbersome +to build with conda and install. Then an easier way is to build the C/C++ parts in the package +directory and temporary add this to the path + +```bash +#in path/to/sls_detector +python setup.py build_ext --inplace +``` +Then in your Python script +```python + +import sys +sys.path.append('/path/to/sls_detector') +from sls_detector import Detector +``` + diff --git a/python/pybind11 b/python/pybind11 new file mode 160000 index 000000000..a23996fce --- /dev/null +++ b/python/pybind11 @@ -0,0 +1 @@ +Subproject commit a23996fce38ff6ccfbcdc09f1e63f2c4be5ea2ef diff --git a/python/scripts/basic.py b/python/scripts/basic.py new file mode 100755 index 000000000..8f199146c --- /dev/null +++ b/python/scripts/basic.py @@ -0,0 +1,20 @@ +import os +import sys +import numpy as np +sys.path.append(os.path.join(os.getcwd(), 'bin')) +from sls_detector import Eiger +from sls_detector import ExperimentalDetector + +from _sls_detector.io import read_ctb_file + +d = Eiger() +e = ExperimentalDetector() + +# ncols = 192 +# start = 600 +# end = 1800 +# nrows = end-start +# data = np.zeros((nrows, ncols)) + +# for i in range(nrows): +# data[i, :] = read_ctb_file(f'/home/l_frojdh/mythendata/MoKbZr_30kV60mA_1s_200V_thr{start+i}_1.raw', 8, 24) \ No newline at end of file diff --git a/python/setup.py b/python/setup.py new file mode 100755 index 000000000..0ccbf9f04 --- /dev/null +++ b/python/setup.py @@ -0,0 +1,125 @@ +""" +Setup file for sls_detector +Build upon the pybind11 example found here: https://github.com/pybind/python_example +""" +from setuptools import setup, Extension, find_packages +from setuptools.command.build_ext import build_ext +import sys +import setuptools +import os + +__version__ = 'refactor' + + +def get_conda_path(): + """ + Keep this a function if we need some fancier logic later + """ + print('Prefix: ', os.environ['CONDA_PREFIX']) + return os.environ['CONDA_PREFIX'] + + +class get_pybind_include(object): + """Helper class to determine the pybind11 include path + The purpose of this class is to postpone importing pybind11 + until it is actually installed, so that the ``get_include()`` + method can be invoked. """ + + def __init__(self, user=False): + self.user = user + + def __str__(self): + import pybind11 + return pybind11.get_include(self.user) + + +ext_modules = [ + Extension( + '_sls_detector', + ['src/main.cpp'], + include_dirs=[ + # Path to pybind11 headers + get_pybind_include(), + get_pybind_include(user=True), + os.path.join(get_conda_path(), 'include/slsDetectorPackage'), + + ], + libraries=['SlsDetector', 'SlsReceiver', 'zmq'], + library_dirs=[ + os.path.join(get_conda_path(), 'lib'), + os.path.join(get_conda_path(), 'bin'), + ], + + language='c++' + ), +] + + +# As of Python 3.6, CCompiler has a `has_flag` method. +# cf http://bugs.python.org/issue26689 +def has_flag(compiler, flagname): + """Return a boolean indicating whether a flag name is supported on + the specified compiler. + """ + import tempfile + with tempfile.NamedTemporaryFile('w', suffix='.cpp') as f: + f.write('int main (int argc, char **argv) { return 0; }') + try: + compiler.compile([f.name], extra_postargs=[flagname]) + except setuptools.distutils.errors.CompileError: + return False + return True + + +def cpp_flag(compiler): + """Return the -std=c++[11/14] compiler flag. + The c++14 is prefered over c++11 (when it is available). + """ + if has_flag(compiler, '-std=c++14'): + return '-std=c++14' + elif has_flag(compiler, '-std=c++11'): + return '-std=c++11' + else: + raise RuntimeError('Unsupported compiler -- at least C++11 support ' + 'is needed!') + + +class BuildExt(build_ext): + """A custom build extension for adding compiler-specific options.""" + c_opts = { + 'msvc': ['/EHsc'], + 'unix': [], + } + + if sys.platform == 'darwin': + c_opts['unix'] += ['-stdlib=libc++', '-mmacosx-version-min=10.7'] + + def build_extensions(self): + ct = self.compiler.compiler_type + opts = self.c_opts.get(ct, []) + if ct == 'unix': + opts.append('-DVERSION_INFO="%s"' % self.distribution.get_version()) + opts.append(cpp_flag(self.compiler)) + if has_flag(self.compiler, '-fvisibility=hidden'): + opts.append('-fvisibility=hidden') + elif ct == 'msvc': + opts.append('/DVERSION_INFO=\\"%s\\"' % self.distribution.get_version()) + for ext in self.extensions: + ext.extra_compile_args = opts + build_ext.build_extensions(self) + + +setup( + name='sls_detector', + version=__version__, + author='Erik Frojdh', + author_email='erik.frojdh@psi.ch', + url='https://github.com/slsdetectorgroup/sls_detector', + description='Detector API for SLS Detector Group detectors', + long_description='', + packages=find_packages(exclude=['contrib', 'docs', 'tests']), + ext_modules=ext_modules, + install_requires=['pybind11>=2.2'], + cmdclass={'build_ext': BuildExt}, + zip_safe=False, +) diff --git a/python/simple-integration-tests/eiger/config_test.py b/python/simple-integration-tests/eiger/config_test.py new file mode 100755 index 000000000..690adbd06 --- /dev/null +++ b/python/simple-integration-tests/eiger/config_test.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Tue Nov 14 16:49:07 2017 + +@author: l_frojdh +""" + +fw_version = 23 +detector_type = 'Eiger' +known_hostnames = ['beb083', 'beb098'] +image_size = (512,1024) #rows, cols +module_geometry = (1,2) #horizontal, vertical + +#Remember to change these in the settings file as well! +settings_path = '/home/l_frojdh/slsDetectorPackage/settingsdir/eiger' +file_path = '/home/l_frojdh/out' \ No newline at end of file diff --git a/python/simple-integration-tests/eiger/fixtures.py b/python/simple-integration-tests/eiger/fixtures.py new file mode 100755 index 000000000..a59fa6961 --- /dev/null +++ b/python/simple-integration-tests/eiger/fixtures.py @@ -0,0 +1,27 @@ +import pytest + +from sls_detector import Detector + +@pytest.fixture +def detector(): + from sls_detector import Detector + return Detector() + +@pytest.fixture +def eiger(): + from sls_detector import Eiger + d = Eiger() + d.n_frames = 1 + d.exposure_time = 1 + d.file_write = False + return d + + +@pytest.fixture +def jungfrau(): + from sls_detector import Jungfrau + return Jungfrau() + +detector_type = Detector().detector_type +eigertest = pytest.mark.skipif(detector_type != 'Eiger', reason = 'Only valid for Eiger') +jungfrautest = pytest.mark.skipif(detector_type != 'Jungfrau', reason = 'Only valid for Jungfrau') \ No newline at end of file diff --git a/python/simple-integration-tests/eiger/settingsdir/standard/5000eV/noise.sn083 b/python/simple-integration-tests/eiger/settingsdir/standard/5000eV/noise.sn083 new file mode 100755 index 000000000..71f43f7bd Binary files /dev/null and b/python/simple-integration-tests/eiger/settingsdir/standard/5000eV/noise.sn083 differ diff --git a/python/simple-integration-tests/eiger/settingsdir/standard/5000eV/noise.sn098 b/python/simple-integration-tests/eiger/settingsdir/standard/5000eV/noise.sn098 new file mode 100755 index 000000000..71f43f7bd Binary files /dev/null and b/python/simple-integration-tests/eiger/settingsdir/standard/5000eV/noise.sn098 differ diff --git a/python/simple-integration-tests/eiger/settingsdir/standard/5000eV/trimbits.sn000 b/python/simple-integration-tests/eiger/settingsdir/standard/5000eV/trimbits.sn000 new file mode 100755 index 000000000..086352948 Binary files /dev/null and b/python/simple-integration-tests/eiger/settingsdir/standard/5000eV/trimbits.sn000 differ diff --git a/python/simple-integration-tests/eiger/settingsdir/standard/6000eV/noise.sn083 b/python/simple-integration-tests/eiger/settingsdir/standard/6000eV/noise.sn083 new file mode 100755 index 000000000..a22532e3f Binary files /dev/null and b/python/simple-integration-tests/eiger/settingsdir/standard/6000eV/noise.sn083 differ diff --git a/python/simple-integration-tests/eiger/settingsdir/standard/6000eV/noise.sn098 b/python/simple-integration-tests/eiger/settingsdir/standard/6000eV/noise.sn098 new file mode 100755 index 000000000..a22532e3f Binary files /dev/null and b/python/simple-integration-tests/eiger/settingsdir/standard/6000eV/noise.sn098 differ diff --git a/python/simple-integration-tests/eiger/settingsdir/standard/6000eV/trimbits.sn000 b/python/simple-integration-tests/eiger/settingsdir/standard/6000eV/trimbits.sn000 new file mode 100755 index 000000000..086352948 Binary files /dev/null and b/python/simple-integration-tests/eiger/settingsdir/standard/6000eV/trimbits.sn000 differ diff --git a/python/simple-integration-tests/eiger/settingsdir/standard/7000eV/noise.sn083 b/python/simple-integration-tests/eiger/settingsdir/standard/7000eV/noise.sn083 new file mode 100755 index 000000000..4a57a7341 Binary files /dev/null and b/python/simple-integration-tests/eiger/settingsdir/standard/7000eV/noise.sn083 differ diff --git a/python/simple-integration-tests/eiger/settingsdir/standard/7000eV/noise.sn098 b/python/simple-integration-tests/eiger/settingsdir/standard/7000eV/noise.sn098 new file mode 100755 index 000000000..4a57a7341 Binary files /dev/null and b/python/simple-integration-tests/eiger/settingsdir/standard/7000eV/noise.sn098 differ diff --git a/python/simple-integration-tests/eiger/settingsdir/standard/7000eV/trimbits.sn000 b/python/simple-integration-tests/eiger/settingsdir/standard/7000eV/trimbits.sn000 new file mode 100755 index 000000000..086352948 Binary files /dev/null and b/python/simple-integration-tests/eiger/settingsdir/standard/7000eV/trimbits.sn000 differ diff --git a/python/simple-integration-tests/eiger/test.config b/python/simple-integration-tests/eiger/test.config new file mode 100755 index 000000000..75fc82b40 --- /dev/null +++ b/python/simple-integration-tests/eiger/test.config @@ -0,0 +1,33 @@ +detsizechan 1024 512 + +#hostname for top+bottom+ +hostname beb083+beb098+ + +#top +0:rx_tcpport 1954 +0:lock 0 +0:rx_udpport 50010 +0:rx_udpport2 50011 +0:rx_hostname mpc2048 +0:flippeddatax 0 + +#bottom +1:rx_tcpport 1955 +1:lock 0 +1:rx_udpport 50004 +1:rx_udpport2 50005 +1:rx_hostname mpc2048 +1:flippeddatax 1 + +settingsdir /home/l_frojdh/slsDetectorPackage/settingsdir/eiger +outdir /home/l_frojdh/out +vthreshold 1500 +vtr 4000 +dr 32 + +threaded 1 +tengiga 0 +vhighvoltage 150 +iodelay 660 + +#gappixels 1 diff --git a/python/simple-integration-tests/eiger/test.par b/python/simple-integration-tests/eiger/test.par new file mode 100755 index 000000000..7fef9adcb --- /dev/null +++ b/python/simple-integration-tests/eiger/test.par @@ -0,0 +1,2 @@ +vrf 3000 +vthreshold 1800 diff --git a/python/simple-integration-tests/eiger/test_dynamic_range.py b/python/simple-integration-tests/eiger/test_dynamic_range.py new file mode 100755 index 000000000..1a162fca6 --- /dev/null +++ b/python/simple-integration-tests/eiger/test_dynamic_range.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Testing setting dynamic range for Eiger. +If the detector is not Eiger the tests are skipped +""" +import pytest +import config_test +from fixtures import detector, eiger, jungfrau, eigertest, jungfrautest +from sls_detector.errors import DetectorValueError + + +@eigertest +def test_set_dynamic_range_and_make_acq(eiger): + eiger.exposure_time = 0.5 + eiger.n_frames = 2 + for dr in [4, 8, 16, 32]: + eiger.dynamic_range = dr + assert eiger.dynamic_range == dr + eiger.acq() + assert eiger.frames_caught == 2 + + +@eigertest +def test_set_dynamic_range_raises(eiger): + with pytest.raises(DetectorValueError): + eiger.dynamic_range = 1 + with pytest.raises(DetectorValueError): + eiger.dynamic_range = 75 + with pytest.raises(DetectorValueError): + eiger.dynamic_range = -3 + with pytest.raises(DetectorValueError): + eiger.dynamic_range = 12 + +@eigertest +def test_set_dynamic_range_reduces_speed(eiger): + eiger.readout_clock = 'Full Speed' + eiger.dynamic_range = 32 + assert eiger.dynamic_range == 32 + assert eiger.readout_clock == 'Quarter Speed' + + eiger.dynamic_range = 16 + assert eiger.dynamic_range == 16 + assert eiger.readout_clock == 'Half Speed' diff --git a/python/simple-integration-tests/eiger/test_eiger_specific.py b/python/simple-integration-tests/eiger/test_eiger_specific.py new file mode 100755 index 000000000..31f656ab6 --- /dev/null +++ b/python/simple-integration-tests/eiger/test_eiger_specific.py @@ -0,0 +1,119 @@ +import pytest +import config_test +import time +from sls_detector.errors import DetectorValueError + +from fixtures import eiger, eigertest + + + + + +@eigertest +def test_set_matrix_reset(eiger): + eiger.eiger_matrix_reset = False + assert eiger.eiger_matrix_reset == False + eiger.eiger_matrix_reset = True + assert eiger.eiger_matrix_reset == True + +@eigertest +def test_set_tx_delay_left_single(eiger): + eiger.tx_delay.left[0] = 130 + assert eiger.tx_delay.left[0] == 130 + eiger.tx_delay.left[1] = 150 + assert eiger.tx_delay.left[1] == 150 + eiger.tx_delay.left[0] = 0 + eiger.tx_delay.left[1] = 0 + assert eiger.tx_delay.left[0] == 0 + assert eiger.tx_delay.left[1] == 0 + +@eigertest +def test_set_tx_delay_right_single(eiger): + eiger.tx_delay.right[0] = 130 + assert eiger.tx_delay.right[0] == 130 + eiger.tx_delay.right[1] = 150 + assert eiger.tx_delay.right[1] == 150 + eiger.tx_delay.right[0] = 0 + eiger.tx_delay.right[1] = 0 + assert eiger.tx_delay.right[0] == 0 + assert eiger.tx_delay.right[1] == 0 + +@eigertest +def test_set_tx_delay_frame_single(eiger): + eiger.tx_delay.frame[0] = 500 + eiger.tx_delay.frame[1] = 600 + assert eiger.tx_delay.frame[0] == 500 + assert eiger.tx_delay.frame[1] == 600 + + eiger.tx_delay.frame[0] = 0 + eiger.tx_delay.frame[1] = 0 + assert eiger.tx_delay.frame[0] == 0 + assert eiger.tx_delay.frame[1] == 0 + +@eigertest +def test_tx_delay_from_list(eiger): + eiger.tx_delay.left = [123,456] + assert eiger.tx_delay.left[:] == [123,456] + eiger.tx_delay.right = [789,100] + assert eiger.tx_delay.right[:] == [789,100] + eiger.tx_delay.frame = [1000,90000] + assert eiger.tx_delay.frame[:] == [1000,90000] + + eiger.tx_delay.left = [0, 0] + eiger.tx_delay.right = [0, 0] + eiger.tx_delay.frame = [0, 0] + assert eiger.tx_delay.left[:] == [0, 0] + assert eiger.tx_delay.right[:] == [0, 0] + assert eiger.tx_delay.frame[:] == [0, 0] + +@eigertest +def test_acitve(eiger): + eiger.file_write = False + eiger.reset_frames_caught() + eiger.active[1] = False + eiger.acq() + assert eiger._api.getFramesCaughtByReceiver(1) == 0 + assert eiger._api.getFramesCaughtByReceiver(0) == 1 + eiger.active = True + time.sleep(0.5) + eiger.acq() + assert eiger.frames_caught == 1 + +@eigertest +def test_set_default_settings(eiger): + eiger.default_settings() + assert eiger.n_frames == 1 + assert eiger.exposure_time == 1 + assert eiger.period == 0 + assert eiger.n_cycles == 1 + assert eiger.dynamic_range == 16 + +@eigertest +def test_flowcontrol10g(eiger): + eiger.flowcontrol_10g = True + assert eiger.flowcontrol_10g == True + eiger.flowcontrol_10g = False + assert eiger.flowcontrol_10g == False + +@eigertest +def test_read_vcmp(eiger): + eiger.vthreshold = 1500 + assert eiger.vcmp[:] == [1500]*4*eiger.n_modules + +@eigertest +def test_set_vcmp(eiger): + eiger.vcmp = [1000,1100,1200,1300,1400,1500,1600,1700] + assert eiger.vcmp[:] == [1000,1100,1200,1300,1400,1500,1600,1700] + eiger.vthreshold = 1500 + +#Disabled only works with receiver on the same pc +# @eigertest +# def test_setup500k(): +# from sls_detector import Eiger, free_shared_memory +# free_shared_memory() +# d = Eiger() +# d.setup500k(config_test.known_hostnames) +# d.acq() +# assert d.rx_tcpport == [1954,1955] +# assert d.frames_caught == 1 +# #could assert more setting but if the frame is caught it worked... \ No newline at end of file diff --git a/python/simple-integration-tests/eiger/test_firmware.py b/python/simple-integration-tests/eiger/test_firmware.py new file mode 100755 index 000000000..e3892f696 --- /dev/null +++ b/python/simple-integration-tests/eiger/test_firmware.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Tests specific for the firmware. + +Check that register values are correct after starting an exposure + +0x4 exposure time +0x5 period +0x6 sub exposure time + +""" +import pytest +import config_test +from fixtures import detector, eiger, jungfrau, eigertest, jungfrautest +from sls_detector.errors import DetectorValueError +from sls_detector.utils import eiger_register_to_time + +# testdata_exptimes = [0.001, 0.002, 0.0236] + +@eigertest +def test_short_exposure_time(eiger): + t = 1.23 + eiger.exposure_time = t + eiger.file_write = False + eiger.start_detector() + eiger.stop_detector() + + #Register 0x4 holds exposure time + reg = eiger.register[0x4] + assert pytest.approx(t, 1e-9) == eiger_register_to_time(reg) + +@eigertest +def test_short_minimal_exposure_time(eiger): + t = 1e-8 + eiger.exposure_time = t + eiger.file_write = False + eiger.start_detector() + eiger.stop_detector() + + #Register 0x4 holds exposure time + reg = eiger.register[0x4] + assert pytest.approx(t, 1e-9) == eiger_register_to_time(reg) + + +@eigertest +def test_long_exposure_time(eiger): + t = 623 + eiger.exposure_time = t + eiger.file_write = False + eiger.start_detector() + eiger.stop_detector() + + # Register 0x4 holds exposure time + reg = eiger.register[0x4] + assert pytest.approx(t, 1e-9) == eiger_register_to_time(reg) + + +@eigertest +def test_short_period(eiger): + t = 0.1 + eiger.exposure_time = 0.001 + eiger.period = t + eiger.file_write = False + eiger.start_detector() + eiger.stop_detector() + + # Register 0x5 holds period + reg = eiger.register[0x5] + assert pytest.approx(t, 1e-9) == eiger_register_to_time(reg) + + +@eigertest +def test_long_period(eiger): + t = 8900 + eiger.exposure_time = 0.001 + eiger.period = t + eiger.file_write = False + eiger.start_detector() + eiger.stop_detector() + + # Register 0x5 holds period + reg = eiger.register[0x5] + assert pytest.approx(t, 1e-9) == eiger_register_to_time(reg) + +@eigertest +def test_zero_period_with_acq(eiger): + t = 0 + eiger.exposure_time = 0.001 + eiger.period = t + eiger.file_write = False + eiger.start_detector() + eiger.stop_detector() + + # Register 0x5 holds period + reg = eiger.register[0x5] + assert pytest.approx(t, 1e-9) == eiger_register_to_time(reg) + + +testdata_times = [0.001, 0.002, 0.0236] +@eigertest +@pytest.mark.parametrize("t", testdata_times) +def test_subexptime(eiger,t): + eiger.sub_exposure_time = t + eiger.file_write = False + eiger.start_detector() + eiger.stop_detector() + + # Register 0x6 holds sub exposure time + # time is stored straight as n clocks + reg = eiger.register[0x6] + assert pytest.approx(t, 1e-9) == reg/100e6 + + +@eigertest +@pytest.mark.parametrize("t", testdata_times) +def test_subdeadtime(eiger, t): + eiger.sub_deadtime = t + eiger.sub_exposure_time = 1 + eiger.sub_exposure_time = 0.001 + eiger.file_write = False + eiger.start_detector() + eiger.stop_detector() + + # Register 0x7 holds sub period + # time is stored straight as n clocks + # exptime+deadtime + reg = eiger.register[0x7] + assert pytest.approx(t, 1e-7) == (reg/100e6-0.001) diff --git a/python/simple-integration-tests/eiger/test_general.py b/python/simple-integration-tests/eiger/test_general.py new file mode 100755 index 000000000..314f33e3b --- /dev/null +++ b/python/simple-integration-tests/eiger/test_general.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +General tests for the Detector class. Should not depend on the connected detector. Aim is to have tests working +for both Jungfrau and Eiger. + +NOTE! Uses hostnames from config_test +""" + +import pytest +import config_test +from fixtures import detector +from sls_detector.errors import DetectorValueError, DetectorError + + + +def test_error_handling(detector): + with pytest.raises(DetectorError): + detector._provoke_error() + +def test_not_busy(detector): + """Test that the detector is not busy from the start""" + assert detector.busy == False + +def test_reset_frames_caught(detector): + detector.file_write = False + detector.acq() + assert detector.frames_caught == 1 + detector.reset_frames_caught() + assert detector.frames_caught == 0 + +def test_set_busy_true_then_false(detector): + """Test both cases of assignment""" + detector.busy = True + assert detector.busy == True + detector.busy = False + assert detector.busy == False + +def test_set_readout_speed(detector): + for s in ['Full Speed', 'Half Speed', 'Quarter Speed', 'Super Slow Speed']: + detector.readout_clock = s + assert detector.readout_clock == s + +def test_wrong_speed_raises_error(detector): + with pytest.raises(KeyError): + detector.readout_clock = 'Something strange' + +def test_readout_clock_remains(detector): + s = detector.readout_clock + try: + detector.readout_clock = 'This does not exists' + except KeyError: + pass + assert detector.readout_clock == s + +def test_len_method(detector): + """to test this we need to know the length, this we get from the configuration of hostnames""" + assert len(detector) == len(config_test.known_hostnames) + +def test_setting_n_cycles_to_zero_gives_error(detector): + with pytest.raises(DetectorValueError): + detector.n_cycles = 0 + +def test_setting_n_cycles_to_negative_gives_error(detector): + with pytest.raises(DetectorValueError): + detector.n_cycles = -50 + +def test_set_cycles_frome_one_to_ten(detector): + for i in range(1,11): + detector.n_cycles = i + assert detector.n_cycles == i + detector.n_cycles = 1 + assert detector.n_cycles == 1 + +def test_get_detector_type(detector): + assert detector.detector_type == config_test.detector_type + + + +def test_set_file_index(detector): + detector.file_index = 5 + assert detector.file_index == 5 + +def test_negative_file_index_raises(detector): + with pytest.raises(ValueError): + detector.file_index = -8 + +def test_setting_file_name(detector): + fname = 'hej' + detector.file_name = fname + assert detector.file_name == fname + +def test_set_file_write(detector): + detector.file_write = True + assert detector.file_write == True + + detector.file_write = False + assert detector.file_write == False + + + +def test_set_high_voltage(detector): + detector.high_voltage = 55 + assert detector.high_voltage == 55 + +def test_negative_voltage_raises(detector): + with pytest.raises(DetectorValueError): + detector.high_voltage = -5 + +def test_high_voltage_raises_on_to_high(detector): + with pytest.raises(DetectorValueError): + detector.high_voltage = 500 + + + +def test_get_image_size(detector): + """Compares with the size in the config file""" + assert detector.image_size.rows == config_test.image_size[0] + assert detector.image_size.cols == config_test.image_size[1] + +def test_get_module_geometry(detector): + """Compares with the size in the config file""" + assert detector.module_geometry.horizontal == config_test.module_geometry[0] + assert detector.module_geometry.vertical == config_test.module_geometry[1] + +def test_set_nframes(detector): + detector.n_frames = 5 + assert detector.n_frames == 5 + detector.n_frames = 1 + assert detector.n_frames == 1 + +def test_set_n_measurements(detector): + detector.n_measurements = 7 + assert detector.n_measurements == 7 + detector.n_measurements = 1 + assert detector.n_measurements == 1 + +def test_negative_nframes_raises(detector): + with pytest.raises(DetectorValueError): + detector.n_frames = -2 + +def test_nmodules(detector): + """Assume that the number of modules should be the same as the number of hostnames""" + assert detector.n_modules == len(config_test.known_hostnames) + +def test_is_detector_online(detector): + assert detector.online == True + +def test_set_online(detector): + detector.online = False + assert detector.online == False + detector.online = True + assert detector.online == True + + + +def test_receiver_is_online(detector): + assert detector.receiver_online == True + +def test_set_receiver_online(detector): + detector.receiver_online = False + assert detector.receiver_online == False + detector.receiver_online = True + assert detector.receiver_online == True + +def test_set_receiver_online_raises_on_non_bool(detector): + with pytest.raises(TypeError): + detector.receiver_online = 'probably not this' + + + + +def test_set_period(detector): + detector.period = 5.123 + assert detector.period == 5.123 + detector.period = 0 + assert detector.period == 0 + + + +def test_set_timing_mode(detector): + detector.timing_mode = 'trigger' + assert detector.timing_mode == 'trigger' + detector.timing_mode = 'auto' + assert detector.timing_mode == 'auto' + + diff --git a/python/simple-integration-tests/eiger/test_load_config.py b/python/simple-integration-tests/eiger/test_load_config.py new file mode 100755 index 000000000..f9aa09de7 --- /dev/null +++ b/python/simple-integration-tests/eiger/test_load_config.py @@ -0,0 +1,38 @@ + +import pytest +import config_test +import os +dir_path = os.path.dirname(os.path.realpath(__file__)) +from sls_detector.detector import element_if_equal +from sls_detector.errors import DetectorValueError + + +from fixtures import eiger, eigertest + + +@eigertest +def test_load_config_file_eiger(eiger): + """Load a settings file and assert all settings""" + eiger.load_config(os.path.join(dir_path, 'test.config')) + + + assert eiger.rx_tcpport == [1954, 1955] + assert eiger.lock == False + assert eiger.rx_udpport == [50010, 50011, 50004, 50005] + assert eiger.rx_hostname == 'mpc2048' + assert eiger.flipped_data_x[:] == [False, True] + assert eiger.settings_path == config_test.settings_path + assert eiger.file_path == config_test.file_path + assert eiger.vthreshold == 1500 + assert element_if_equal(eiger.dacs.vtr[:]) == 4000 + assert eiger.dynamic_range == 32 + assert eiger.tengiga == False + assert eiger.high_voltage == 150 + assert element_if_equal(eiger.dacs.iodelay[:]) == 660 + +@eigertest +def test_load_parameters_file_eiger(eiger): + """Load a parametes file and assert the settings in the file""" + eiger.load_parameters(os.path.join(dir_path, 'test.par')) + assert element_if_equal(eiger.dacs.vrf[:]) == 3000 + assert eiger.vthreshold == 1800 \ No newline at end of file diff --git a/python/simple-integration-tests/eiger/test_network.py b/python/simple-integration-tests/eiger/test_network.py new file mode 100755 index 000000000..7d2282b2d --- /dev/null +++ b/python/simple-integration-tests/eiger/test_network.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Tests for network related functions of the detector +""" +import pytest +import config_test +from fixtures import eiger, eigertest, detector + + +# def test_last_client(detector): +# import socket +# # We probably should check for multiple ip's +# myip = socket.gethostbyname_ex(socket.gethostname())[-1][0] +# assert detector.last_client_ip == myip + +def test_get_hostname(detector): + for detector_host, config_host in zip(detector.hostname, config_test.known_hostnames): + assert detector_host == config_host + +def test_hostname_has_same_length_as_n_modules(detector): + assert len(detector.hostname) == detector.n_modules + + +# # def test_get_receiver_hostname(detector): +# # """Assume that the receiver are on the local computer""" +# # import socket +# # host = socket.gethostname().split('.')[0] +# # assert detector.rx_hostname == host + +# def test_set_receiver_hostname(detector): +# import socket +# host = socket.gethostname().split('.')[0] +# phony_host = 'madeup' +# detector.rx_hostname = phony_host +# assert detector.rx_hostname == phony_host +# detector.rx_hostname = host +# assert detector.rx_hostname == host + +@eigertest +def test_set_rx_zmqport_single_value(eiger): + eiger.rx_zmqport = 35000 + assert eiger.rx_zmqport == [35000, 35001, 35002, 35003] + +@eigertest +def test_set_rx_zmqport_list(eiger): + eiger.rx_zmqport = [37000, 38000] + assert eiger.rx_zmqport == [37000, 37001, 38000, 38001] + +@eigertest +def test_set_rx_updport(eiger): + ports = [60010,60011,60012,60013] + eiger.rx_udpport = ports + assert eiger.rx_udpport == ports + eiger.acq() + assert eiger.frames_caught == 1 + +@eigertest +def test_rx_tcpport(eiger): + ports = eiger.rx_tcpport + eiger.rx_tcpport = [2000,2001] + assert eiger.rx_tcpport == [2000,2001] + eiger.rx_tcpport = ports + assert eiger.rx_tcpport == ports + eiger.acq() + assert eiger.frames_caught == 1 + +# @eigertest +# @pytest.mark.new +# def test_enable_disable_tengiga(eiger): +# """ +# This test does not check for dat on the 10Gbit link, only the set and get functions +# """ +# eiger.tengiga = True +# assert eiger.tengiga == True +# eiger.tengiga = False +# assert eiger.tengiga == False + + + +#TODO! Add test for Jungfrau \ No newline at end of file diff --git a/python/simple-integration-tests/eiger/test_paths_and_files.py b/python/simple-integration-tests/eiger/test_paths_and_files.py new file mode 100755 index 000000000..7728c17ac --- /dev/null +++ b/python/simple-integration-tests/eiger/test_paths_and_files.py @@ -0,0 +1,54 @@ +import pytest +import config_test +from fixtures import detector, eiger, jungfrau, eigertest, jungfrautest +from sls_detector.errors import DetectorValueError + + + + +@eigertest +@pytest.mark.local +def test_set_path(eiger, tmpdir): + import os + path = os.path.join(tmpdir.dirname, tmpdir.basename) + eiger.file_path = path + assert eiger.file_path == path + +@eigertest +@pytest.mark.local +def test_set_path_and_write_files(eiger, tmpdir): + import os + prefix = 'testprefix' + path = os.path.join(tmpdir.dirname, tmpdir.basename) + eiger.file_path = path + eiger.file_write = True + eiger.exposure_time = 0.1 + eiger.n_frames = 1 + eiger.timing_mode = 'auto' + eiger.file_name = prefix + eiger.file_index = 0 + eiger.acq() + + files = [f.basename for f in tmpdir.listdir()] + + assert len(files) == 5 + assert (prefix+'_d0_0.raw' in files) == True + assert (prefix+'_d1_0.raw' in files) == True + assert (prefix+'_d2_0.raw' in files) == True + assert (prefix+'_d3_0.raw' in files) == True + +def test_set_discard_policy(detector): + detector.frame_discard_policy = 'nodiscard' + assert detector.frame_discard_policy == 'nodiscard' + detector.frame_discard_policy = 'discardpartial' + assert detector.frame_discard_policy == 'discardpartial' + detector.frame_discard_policy = 'discardempty' + assert detector.frame_discard_policy == 'discardempty' + +def test_set_discard_policy_raises(detector): + with pytest.raises(ValueError): + detector.frame_discard_policy = 'adjfvadksvsj' + +def test_set_frames_perfile(detector): + detector.frames_per_file = 5000 + assert detector.frames_per_file == 5000 \ No newline at end of file diff --git a/python/simple-integration-tests/eiger/test_threshold.py b/python/simple-integration-tests/eiger/test_threshold.py new file mode 100755 index 000000000..0eb3b3ed5 --- /dev/null +++ b/python/simple-integration-tests/eiger/test_threshold.py @@ -0,0 +1,47 @@ +import pytest +import config_test +import time +from sls_detector.errors import DetectorValueError +import os +from fixtures import eiger, eigertest + + +testdata_th = [0,333,500,1750,2000] + +@eigertest +@pytest.mark.parametrize("th", testdata_th) +def test_set_vthreshold(eiger, th): + eiger.vthreshold = th + assert eiger.vthreshold == th + +@eigertest +def test_vthreshold_with_different_vcmp(eiger): + #When vcmp is different for the chip vthreshold should return -1 + eiger.vthreshold = 1500 + eiger.dacs.vcmp_ll = 1400 + assert eiger.vthreshold == -1 + +@eigertest +def test_set_settingsdir(eiger): + path = os.path.dirname( os.path.realpath(__file__) ) + path = os.path.join(path, 'settingsdir') + eiger.settings_path = path + assert eiger.settings_path == path + +@eigertest +def test_set_trimmed_energies(eiger): + en = [5000,6000,7000] + eiger.trimmed_energies = en + assert eiger.trimmed_energies == en + + +#TODO! add checks for vcmp as well and improve naming +#TODO! remove dependency on beb number +testdata_en = [(5000, 500),(5500,750),(6000,1000),(6200,1100),(7000,1500)] +@eigertest +@pytest.mark.parametrize('val', testdata_en) +def test_set_energy_threshold(eiger, val): + eiger.settings = 'standard' + eiger.threshold = val[0] + assert eiger.threshold == val[0] + assert eiger.dacs.vrf[0] == val[1] \ No newline at end of file diff --git a/python/simple-integration-tests/eiger/test_time.py b/python/simple-integration-tests/eiger/test_time.py new file mode 100755 index 000000000..017eed3e4 --- /dev/null +++ b/python/simple-integration-tests/eiger/test_time.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Tests regarding exposure time and period of the detector +Set and get test as well as test for duration and on detector +measurement of the time. +""" +import pytest +import config_test +from fixtures import detector, eiger, jungfrau, eigertest, jungfrautest +from sls_detector.errors import DetectorValueError, DetectorError +import time + + +testdata_times = [1e-8, 0.001, 0.5, 3.125, 5.0, 600, 784] +@pytest.mark.parametrize("t", testdata_times) +def test_set_and_get_exposure_time(eiger, t): + """ + Test that the exposure time we set in the detector + is the same as the one read back + """ + eiger.exposure_time = t + assert eiger.exposure_time == t + + +def test_negative_exposure_time_raises_error(eiger): + with pytest.raises(DetectorValueError): + eiger.exposure_time = -15 + + +testdata_times = [0.001, 0.0025, 0.005, 5] +@pytest.mark.parametrize("t", testdata_times) +def test_set_subexptime(eiger, t): + eiger.sub_exposure_time = t + assert eiger.sub_exposure_time == t + + +testdata_times = [-5,6,7,50] +@pytest.mark.parametrize("t", testdata_times) +def test_set_subextime_too_large_or_neg(eiger, t): + with pytest.raises((DetectorError, DetectorValueError)): + eiger.sub_exposure_time = t + + + +testdata_times = [0.2, 0.5, 1, 2, 5, 7] +@pytest.mark.slow +@pytest.mark.parametrize("t", testdata_times) +def test_measure_exposure_time_from_python(eiger, t): + """ + The main idea with this test is to make sure the overhead of a + single acq is less than tol[s]. This test also catches stupid bugs + that would for example not change the exposure time or make acquire + not blocking. + """ + tol = 0.5 + eiger.dynamic_range = 16 + eiger.file_write = False + eiger.n_frames = 1 + eiger.exposure_time = t + assert eiger.exposure_time == t + t0 = time.time() + eiger.acq() + duration = time.time()-t0 + assert duration < (t+tol) + + +testdata_times = [0.5, 1, 3, 5] + + +@pytest.mark.slow +@pytest.mark.parametrize("t", testdata_times) +def test_measure_period_from_python_and_detector(eiger, t): + tol = 0.5 + nframes = 5 + eiger.dynamic_range = 16 + eiger.file_write = False + eiger.n_frames = nframes + eiger.exposure_time = 0.001 + eiger.period = t + t0 = time.time() + eiger.acq() + duration = time.time()-t0 + assert duration < t*(nframes-1)+tol + for mp in eiger.measured_period: + assert pytest.approx(mp, 1e-5) == t + + +testdata_times = [0.001, 0.002, 0.003, 0.005, 0.01] +@pytest.mark.parametrize("t", testdata_times) +def test_measure_subperiod_nonparallel(eiger, t): + readout_time = 500e-6 + eiger.dynamic_range = 32 + eiger.file_write = False + eiger.flags = 'nonparallel' + eiger.n_frames = 1 + eiger.period = 0 + eiger.exposure_time = 0.5 + eiger.sub_exposure_time = t + eiger.sub_deadtime = 0 + eiger.acq() + for mp in eiger.measured_subperiod: + assert pytest.approx(mp, abs=1e-5) == t+readout_time + + +@pytest.mark.parametrize("t", testdata_times) +def test_measure_subperiod_parallel(eiger, t): + readout_time = 12e-6 + eiger.dynamic_range = 32 + eiger.file_write = False + eiger.flags = 'parallel' + eiger.n_frames = 1 + eiger.period = 0 + eiger.exposure_time = 0.5 + eiger.sub_exposure_time = t + eiger.sub_deadtime = 0 + eiger.acq() + for mp in eiger.measured_subperiod: + assert pytest.approx(mp, abs=1e-5) == t+readout_time + + +@pytest.mark.parametrize("t", testdata_times) +def test_measure_subperiod_parallel_when_changing_deadtime(eiger, t): + readout_time = 12e-6 + exposure_time = 0.001 + eiger.dynamic_range = 32 + eiger.file_write = False + eiger.flags = 'parallel' + eiger.n_frames = 1 + eiger.period = 0 + eiger.exposure_time = 0.5 + eiger.sub_exposure_time = exposure_time + eiger.sub_deadtime = t + eiger.acq() + for mp in eiger.measured_subperiod: + assert pytest.approx(mp, abs=1e-5) == t+exposure_time \ No newline at end of file diff --git a/python/simple-integration-tests/eiger/test_trimbits_and_dacs.py b/python/simple-integration-tests/eiger/test_trimbits_and_dacs.py new file mode 100755 index 000000000..3053ca75f --- /dev/null +++ b/python/simple-integration-tests/eiger/test_trimbits_and_dacs.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Tests for trimbit and dac related functions +""" +import pytest +import config_test +from fixtures import detector, eiger, jungfrau, eigertest, jungfrautest +from sls_detector.errors import DetectorValueError + + +@eigertest +def test_set_trimbits(eiger): + """Limited values due to time""" + for i in [17, 32, 60]: + print(i) + eiger.trimbits = i + assert eiger.trimbits == i + +@eigertest +def test_set_trimbits_raises_on_too_big(eiger): + with pytest.raises(DetectorValueError): + eiger.trimbits = 75 + +@eigertest +def test_set_trimbits_raises_on_negative(eiger): + with pytest.raises(DetectorValueError): + eiger.trimbits = -5 + + +# @jungfrautest +# def test_jungfrau(jungfrau): +# """Example of a test that is not run with Eiger connected""" +# pass diff --git a/python/simple-integration-tests/eiger/test_version_numbers.py b/python/simple-integration-tests/eiger/test_version_numbers.py new file mode 100755 index 000000000..246712254 --- /dev/null +++ b/python/simple-integration-tests/eiger/test_version_numbers.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Tests for hostname related functions of the detector +""" +import pytest +import config_test +from fixtures import detector, eiger, jungfrau, eigertest, jungfrautest +from sls_detector.errors import DetectorValueError + + + +def test_firmware_version(detector): + assert detector.firmware_version == config_test.fw_version + + diff --git a/python/simple-integration-tests/eiger/write_tb_files.py b/python/simple-integration-tests/eiger/write_tb_files.py new file mode 100755 index 000000000..b8ec9ba38 --- /dev/null +++ b/python/simple-integration-tests/eiger/write_tb_files.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Tue May 22 14:13:48 2018 + +@author: l_frojdh +""" +import os +from sls_detector_tools.io import write_trimbit_file +from sls_detector_tools import mask + +energy = [5000, 6000, 7000] +vrf = [500, 1000, 1500] + +for i,e in enumerate(energy): + dacs = np.array( [[ 0., 0.], #vsvp + [4000., 4000.], #vtr + [vrf[i], vrf[i]], #vrf + [1400., 1400.], #vrs + [4000., 4000.], #vsvn + [2556., 2556.], #vtgstv + [1400., 1400.], #vcmp_ll + [1500., 1500.], #vcmp_lr + [4000., 4000.], #vcall + [1500., 1500.], #vcmp_rl + [1100., 1100.], #rxb_rb + [1100., 1100.], #rxb_lb + [1500., 1500.], #vcmp_rr + [1500., 1500.], #vcp + [2000., 2000.], #vcn + [1550., 1550.], #vis + [ 660., 660.], #iodelay + [ 0., 0.], #tau + ]) + + tb = np.zeros((256,1024)) + + for beb in [83,98]: + write_trimbit_file(f'settingsdir/standard/{e}eV/noise.sn{beb:03d}', tb, dacs[:,0]) +#print(os.getcwd()) + +#print( os.path.realpath(__file__)) \ No newline at end of file diff --git a/python/simple-integration-tests/jungfrau_0_6/config_test.py b/python/simple-integration-tests/jungfrau_0_6/config_test.py new file mode 100755 index 000000000..045d04d8e --- /dev/null +++ b/python/simple-integration-tests/jungfrau_0_6/config_test.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Tue Nov 14 16:49:07 2017 + +@author: l_frojdh +""" + +fw_version = 0x180220 +detector_type = 'Jungfrau' +known_hostnames = ['bchip038'] +image_size = (512,1024) #rows, cols +module_geometry = (1,1) #horizontal, vertical + +#Remember to change these in the settings file as well! +settings_path = '/home/l_lopez/projects/slsDetectorPackage/settingsdir/jungfrau' +file_path = '/home/l_lopez/out' \ No newline at end of file diff --git a/python/simple-integration-tests/jungfrau_0_6/fixtures.py b/python/simple-integration-tests/jungfrau_0_6/fixtures.py new file mode 100755 index 000000000..d99c9e08f --- /dev/null +++ b/python/simple-integration-tests/jungfrau_0_6/fixtures.py @@ -0,0 +1,23 @@ +import pytest + +from sls_detector import Detector + +@pytest.fixture +def detector(): + from sls_detector import Detector + return Detector() + +@pytest.fixture +def eiger(): + from sls_detector import Eiger + return Eiger() + + +@pytest.fixture +def jungfrau(): + from sls_detector import Jungfrau + return Jungfrau() + +detector_type = Detector().detector_type +eigertest = pytest.mark.skipif(detector_type != 'Eiger', reason = 'Only valid for Eiger') +jungfrautest = pytest.mark.skipif(detector_type != 'Jungfrau', reason = 'Only valid for Jungfrau') \ No newline at end of file diff --git a/python/simple-integration-tests/jungfrau_0_6/test_main.py b/python/simple-integration-tests/jungfrau_0_6/test_main.py new file mode 100755 index 000000000..948e0b172 --- /dev/null +++ b/python/simple-integration-tests/jungfrau_0_6/test_main.py @@ -0,0 +1,17 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +General tests for the Jungfrau detector. + +NOTE! Uses hostnames from config_test +""" + +import pytest +import config_test +import tests + +import os +dir_path = os.path.dirname(os.path.realpath(__file__)) + +pytest.main(['-x', '-s', os.path.join(dir_path, 'tests/test_load_config.py')]) #Test 1 +pytest.main(['-x', '-s', os.path.join(dir_path, 'tests/test_overtemperature.py')]) #Test 2 diff --git a/python/simple-integration-tests/jungfrau_0_6/tests/test.config b/python/simple-integration-tests/jungfrau_0_6/tests/test.config new file mode 100755 index 000000000..8ac8d98d8 --- /dev/null +++ b/python/simple-integration-tests/jungfrau_0_6/tests/test.config @@ -0,0 +1,21 @@ +detsizechan 1024 512 + +settingsdir /home/l_lopez/projects/slsDetectorPackage/settingsdir/jungfrau +caldir /home/l_lopez/projects/slsDetectorPackage/settingsdir/jungfrau +lock 0 + +hostname bchip094+ + +rx_udpport 1754 +rx_udpip 10.1.1.107 +rx_udpmac 90:E2:BA:9A:4F:D4 +detectorip 10.1.1.9 +detectormac 00:aa:bb:cc:dd:ee +configuremac 0 + +powerchip 1 +timing auto + +outdir /home/l_lopez/out +threaded 1 +high diff --git a/python/simple-integration-tests/jungfrau_0_6/tests/test.par b/python/simple-integration-tests/jungfrau_0_6/tests/test.par new file mode 100755 index 000000000..b04533952 --- /dev/null +++ b/python/simple-integration-tests/jungfrau_0_6/tests/test.par @@ -0,0 +1 @@ +vhighvoltage 200 \ No newline at end of file diff --git a/python/simple-integration-tests/jungfrau_0_6/tests/test_load_config.py b/python/simple-integration-tests/jungfrau_0_6/tests/test_load_config.py new file mode 100755 index 000000000..de29b41b8 --- /dev/null +++ b/python/simple-integration-tests/jungfrau_0_6/tests/test_load_config.py @@ -0,0 +1,43 @@ + +import pytest +import config_test +import os +dir_path = os.path.dirname(os.path.realpath(__file__)) + +from fixtures import jungfrau, jungfrautest + + +def load_config_file_jungfrau_test(jungfrau): + """Load a settings file and assert all settings""" + + print('\tStarting load_config_file_jungfrau_test test case') + + jungfrau.free_shared_memory + jungfrau.load_config(os.path.join(dir_path, 'test.config')) + + assert jungfrau.lock == False + assert jungfrau.rx_udpport == ['1754'] + assert jungfrau.hostname == ['bchip094'] + assert jungfrau.firmware_version == config_test.fw_version + + print('\tFinished load_config_file_jungfrau_test test case') + +def load_parameters_file_jungfrau_test(jungfrau): + """Load a parametes file and assert the settings in the file""" + + print('\tStarting load_parameters_file_jungfrau_test test case') + + jungfrau.load_parameters(os.path.join(dir_path, 'test.par')) + assert jungfrau.high_voltage == 200 + + print('\tFinished load_parameters_file_jungfrau_test test case') + +@jungfrautest +def test_main(jungfrau): + print('\nTesting configuration file loading') + + load_config_file_jungfrau_test(jungfrau) + load_parameters_file_jungfrau_test(jungfrau) + + print('Tested configuration file loading') + diff --git a/python/simple-integration-tests/jungfrau_0_6/tests/test_overtemperature.py b/python/simple-integration-tests/jungfrau_0_6/tests/test_overtemperature.py new file mode 100755 index 000000000..0bcbbfc24 --- /dev/null +++ b/python/simple-integration-tests/jungfrau_0_6/tests/test_overtemperature.py @@ -0,0 +1,68 @@ + +import pytest +import config_test +import time +from fixtures import jungfrau, jungfrautest + +def powerchip_test(jungfrau, control): + """ + + Test the main overtemperature protection control + + """ + #Set test initial conditions + print('\tStarting powerchip_test test case') + + jungfrau.power_chip = False + jungfrau.temperature_control = control + assert jungfrau.power_chip == False + jungfrau.temperature_threshold = 35 + jungfrau.power_chip = True + + + if jungfrau.temperature_control is True: + if jungfrau.temperature_event is True: + assert jungfrau.power_chip == False + jungfrau.power_chip = True + assert jungfrau.power_chip == False + jungfrau.temperature_control = False + assert jungfrau.power_chip == True + jungfrau.temperature_control = True + jungfrau.temperature_threshold = 50 + assert jungfrau.power_chip == False + + print('\t\tWaiting to cool down the board. This may take a while...') + while jungfrau.temperature_threshold < jungfrau.temp.fpga[0]: + time.sleep(5) + print('\t\tJungfrau MCB temperature: {0:.2f} °C'.format(jungfrau.temp.fpga[0])) + + #Leave enough time to let the board cool down a bit more + time.sleep(30) + jungfrau.reset_temperature_event() + + assert jungfrau.temperature_event == False + assert jungfrau.power_chip == True + + else: + assert jungfrau.power_chip == True + else: + print('\t\tWaiting to warm up the board. This may take a while...') + while jungfrau.temperature_threshold > jungfrau.temp.fpga[0]: + time.sleep(5) + print('\t\tJungfrau MCB temperature: {0:.2f} °C'.format(jungfrau.temp.fpga[0])) + + assert jungfrau.temperature_event == False + assert jungfrau.power_chip == True + + print('\tFinished powerchip_test test case') + + +#@jungfrautest +def test_main(jungfrau): + + print('\nTesting overtemperature protection control') + + powerchip_test(jungfrau, False) + powerchip_test(jungfrau, True) + + print('Tested overtemperature protection control') diff --git a/python/sls_detector/__init__.py b/python/sls_detector/__init__.py new file mode 100755 index 000000000..ff98359a3 --- /dev/null +++ b/python/sls_detector/__init__.py @@ -0,0 +1,6 @@ +from .detector import Detector, DetectorError, free_shared_memory +from .eiger import Eiger +from .experimental import ExperimentalDetector +from .jungfrau import Jungfrau +from .jungfrau_ctb import JungfrauCTB +from _sls_detector import DetectorApi diff --git a/python/sls_detector/adcs.py b/python/sls_detector/adcs.py new file mode 100755 index 000000000..f8df51b37 --- /dev/null +++ b/python/sls_detector/adcs.py @@ -0,0 +1,40 @@ +from functools import partial +class Adc: + def __init__(self, name, detector): + self.name = name + self._detector = detector + self.get_nmod = self._detector._api.getNumberOfDetectors + # Bind functions to get and set the dac + self.get = partial(self._detector._api.getAdc, self.name) + + + def __getitem__(self, key): + """ + Get dacs either by slice, key or list + """ + if key == slice(None, None, None): + return [self.get(i) / 1000 for i in range(self.get_nmod())] + elif isinstance(key, Iterable): + return [self.get(k) / 1000 for k in key] + else: + return self.get(key) / 1000 + + def __repr__(self): + """String representation for a single adc in all modules""" + degree_sign = u'\N{DEGREE SIGN}' + r_str = ['{:14s}: '.format(self.name)] + r_str += ['{:6.2f}{:s}C, '.format(self.get(i)/1000, degree_sign) for i in range(self.get_nmod())] + return ''.join(r_str).strip(', ') + + + +class DetectorAdcs: + """ + Interface to the ADCs on the readout board + """ + def __iter__(self): + for attr, value in self.__dict__.items(): + yield value + + def __repr__(self): + return '\n'.join([str(t) for t in self]) \ No newline at end of file diff --git a/python/sls_detector/dacs.py b/python/sls_detector/dacs.py new file mode 100755 index 000000000..50ea8a1a7 --- /dev/null +++ b/python/sls_detector/dacs.py @@ -0,0 +1,125 @@ +from .detector_property import DetectorProperty +from functools import partial +import numpy as np + +class Dac(DetectorProperty): + """ + This class represents a dac on the detector. One instance handles all + dacs with the same name for a multi detector instance. + + .. note :: + + This class is used to build up DetectorDacs and is in general + not directly accessed to the user. + + + """ + def __init__(self, name, low, high, default, detector): + + super().__init__(partial(detector._api.getDac, name), + partial(detector._api.setDac, name), + detector._api.getNumberOfDetectors, + name) + + self.min_value = low + self.max_value = high + self.default = default + + + + def __repr__(self): + """String representation for a single dac in all modules""" + r_str = ['{:10s}: '.format(self.__name__)] + r_str += ['{:5d}, '.format(self.get(i)) for i in range(self.get_nmod())] + return ''.join(r_str).strip(', ') + + +class DetectorDacs: + _dacs = [('vsvp', 0, 4000, 0), + ('vtr', 0, 4000, 2500), + ('vrf', 0, 4000, 3300), + ('vrs', 0, 4000, 1400), + ('vsvn', 0, 4000, 4000), + ('vtgstv', 0, 4000, 2556), + ('vcmp_ll', 0, 4000, 1500), + ('vcmp_lr', 0, 4000, 1500), + ('vcall', 0, 4000, 4000), + ('vcmp_rl', 0, 4000, 1500), + ('rxb_rb', 0, 4000, 1100), + ('rxb_lb', 0, 4000, 1100), + ('vcmp_rr', 0, 4000, 1500), + ('vcp', 0, 4000, 200), + ('vcn', 0, 4000, 2000), + ('vis', 0, 4000, 1550), + ('iodelay', 0, 4000, 660)] + _dacnames = [_d[0] for _d in _dacs] + + def __init__(self, detector): + # We need to at least initially know which detector we are connected to + self._detector = detector + + # Index to support iteration + self._current = 0 + + # Populate the dacs + for _d in self._dacs: + setattr(self, '_'+_d[0], Dac(*_d, detector)) + + def __getattr__(self, name): + return self.__getattribute__('_' + name) + + + def __setattr__(self, name, value): + if name in self._dacnames: + return self.__getattribute__('_' + name).__setitem__(slice(None, None, None), value) + else: + super().__setattr__(name, value) + + def __next__(self): + if self._current >= len(self._dacs): + self._current = 0 + raise StopIteration + else: + self._current += 1 + return self.__getattr__(self._dacnames[self._current-1]) + + def __iter__(self): + return self + + def __repr__(self): + r_str = ['========== DACS ========='] + r_str += [repr(dac) for dac in self] + return '\n'.join(r_str) + + def get_asarray(self): + """ + Read the dacs into a numpy array with dimensions [ndacs, nmodules] + """ + dac_array = np.zeros((len(self._dacs), self._detector.n_modules)) + for i, _d in enumerate(self): + dac_array[i,:] = _d[:] + return dac_array + + def set_from_array(self, dac_array): + """ + Set the dacs from an numpy array with dac values. [ndacs, nmodules] + """ + dac_array = dac_array.astype(np.int) + for i, _d in enumerate(self): + _d[:] = dac_array[i] + + def set_default(self): + """ + Set all dacs to their default values + """ + for _d in self: + _d[:] = _d.default + + def update_nmod(self): + """ + Update the cached value of nmod, needs to be run after adding or + removing detectors + """ + for _d in self: + _d._n_modules = self._detector.n_modules + diff --git a/python/sls_detector/decorators.py b/python/sls_detector/decorators.py new file mode 100755 index 000000000..d1ec4482a --- /dev/null +++ b/python/sls_detector/decorators.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Function decorators for the sls_detector. +""" +from .errors import DetectorError +import functools + + +def error_handling(func): + """ + Check for errors registered by the slsDetectorSoftware + """ + @functools.wraps(func) + def wrapper(self, *args, **kwargs): + + # remove any previous errors + self._api.clearErrorMask() + + # call function + result = func(self, *args, **kwargs) + + # check for new errors + m = self.error_mask + if m != 0: + msg = self.error_message + self._api.clearErrorMask() + raise DetectorError(msg) + return result + + return wrapper + + +def property_error_handling(func): + """ + Check for errors registered by the slsDetectorSoftware + """ + + @functools.wraps(func) + def wrapper(self, *args, **kwargs): + # remove any previous errors + self._detector._api.clearErrorMask() + + # call function + result = func(self, *args, **kwargs) + + # check for new errors + m = self._detector.error_mask + if m != 0: + msg = self._detector.error_message + self._detector._api.clearErrorMask() + raise DetectorError(msg) + return result + + return wrapper \ No newline at end of file diff --git a/python/sls_detector/detector.py b/python/sls_detector/detector.py new file mode 100755 index 000000000..3a6a7a366 --- /dev/null +++ b/python/sls_detector/detector.py @@ -0,0 +1,1364 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Python - sls +============= + +""" +import os +from collections.abc import Iterable +from collections import namedtuple + +from _sls_detector import DetectorApi +from .decorators import error_handling +from .detector_property import DetectorProperty +from .errors import DetectorError, DetectorValueError +from .registers import Register +from .utils import element_if_equal + + +class Detector: + """ + Base class used as interface with the slsDetectorSoftware. To control a specific detector use the + derived classes such as Eiger and Jungfrau. Functions as an interface to the C++ API and provides a + more Pythonic interface + """ + + _speed_names = {0: 'Full Speed', 1: 'Half Speed', 2: 'Quarter Speed', 3: 'Super Slow Speed'} + _speed_int = {'Full Speed': 0, 'Half Speed': 1, 'Quarter Speed': 2, 'Super Slow Speed': 3} + _settings = [] + + def __init__(self, multi_id=0): + self._api = DetectorApi(multi_id) + self._register = Register(self) + + self._flippeddatax = DetectorProperty(self._api.getFlippedDataX, + self._api.setFlippedDataX, + self._api.getNumberOfDetectors, + 'flippeddatax') + self._flippeddatay = DetectorProperty(self._api.getFlippedDataY, + self._api.setFlippedDataY, + self._api.getNumberOfDetectors, + 'flippeddatay') + try: + self.online = True + self.receiver_online = True + except DetectorError: + print('WARNING: Cannot connect to detector') + + + def __len__(self): + return self._api.getNumberOfDetectors() + + def __repr__(self): + return '{}(id = {})'.format(self.__class__.__name__, + self._api.getMultiDetectorId()) + + + def acq(self): + """ + Blocking command to launch the programmed measurement. Number of frames specified by frames, cycles etc. + """ + self._api.acq() + + + @property + def busy(self): + """ + Checks the detector is acquiring. Can also be set but should only be used if the acquire fails and + leaves the detector with busy == True + + .. note :: + + Only works when the measurement is launched using acquire, not with status start! + + Returns + -------- + bool + :py:obj:`True` if the detector is acquiring otherwise :py:obj:`False` + + Examples + ---------- + + :: + + d.busy + >> True + + #If the detector is stuck reset by: + d.busy = False + + + """ + return self._api.getAcquiringFlag() + + @busy.setter + def busy(self, value): + self._api.setAcquiringFlag(value) + + def clear_errors(self): + """Clear the error mask for the detector. Used to reset after checking.""" + self._api.clearErrorMask() + + @property + def client_version(self): + """ + :py:obj:`str` The date of commit for the client API version + + Examples + ---------- + + :: + + d.client_version + >> '20180327' + + """ + v = hex(self._api.getClientVersion()) + return v[2:] + + @property + def detectornumber(self): + """ + Get all detector numbers as a list. For Eiger the detector numbers + correspond to the beb numbers. + + Examples + --------- + + :: + + #for beb083 and beb098 + detector.detector_number + >> [83, 98] + + """ + return self._api.getDetectorNumber() + + @property + def detector_type(self): + """ + Return either a string or list of strings with the detector type. + + * Eiger + * Jungfrau + * etc. + + Examples + ---------- + + :: + + detector.detector_type + >> 'Eiger' + + detector.detector_type + >> ['Eiger', 'Jungfrau'] + + """ + return element_if_equal(self._api.getDetectorType()) + + @property + def dynamic_range(self): + """ + :obj:`int`: Dynamic range of the detector. + + +----+-------------+------------------------------+ + | dr | max counts | comments | + +====+=============+==============================+ + | 4 | 15 | | + +----+-------------+------------------------------+ + | 8 | 255 | | + +----+-------------+------------------------------+ + |16 | 4095 | 12 bit internally | + +----+-------------+------------------------------+ + |32 | 4294967295 | Autosumming of 12 bit frames | + +----+-------------+------------------------------+ + + Raises + ------- + ValueError + If the dynamic range is not available in the detector + + + """ + return self._api.getDynamicRange() + + @dynamic_range.setter + def dynamic_range(self, dr): + if dr in self._detector_dynamic_range: + self._api.setDynamicRange(dr) + return + else: + raise DetectorValueError('Cannot set dynamic range to: {:d} availble options: '.format(dr), + self._detector_dynamic_range) + + + @property + def exposure_time(self): + """ + :obj:`double` Exposure time in [s] of a single frame. + """ + return self._api.getExposureTime() / 1e9 + + @exposure_time.setter + def exposure_time(self, t): + ns_time = int(t * 1e9) + if ns_time <= 0: + raise DetectorValueError('Exposure time must be larger than 0') + self._api.setExposureTime(ns_time) + + @property + def file_index(self): + """ + :obj:`int` Index for frames and file names + + Raises + ------- + ValueError + If the user tries to set an index less than zero + + Examples + --------- + + :: + + detector.file_index + >> 0 + + detector.file_index = 10 + detector.file_index + >> 10 + + """ + return self._api.getFileIndex() + + @file_index.setter + def file_index(self, i): + if i < 0: + raise ValueError('Index needs to be positive') + self._api.setFileIndex(i) + + @property + def file_name(self): + """ + :obj:`str`: Base file name for writing images + + Examples + --------- + + :: + + detector.file_name + >> 'run' + + detector.file_name = 'myrun' + + #For a single acquisition the detector now writes + # myrun_master_0.raw + # myrun_d0_0.raw + # myrun_d1_0.raw + # myrun_d2_0.raw + # myrun_d3_0.raw + + """ + return self._api.getFileName() + + @file_name.setter + def file_name(self, fname): + self._api.setFileName(fname) + + @property + def file_path(self): + """ + :obj:`str`: Path where images are written + + Raises + ------- + FileNotFoundError + If path does not exists + + Examples + --------- + + :: + + detector.file_path + >> '/path/to/files' + + detector.file_path = '/new/path/to/other/files' + + """ + fp = self._api.getFilePath() + if fp == '': + return [self._api.getFilePath(i) for i in range(len(self))] + else: + return fp + + @file_path.setter + def file_path(self, path): + if os.path.exists(path) is True: + self._api.setFilePath(path) + else: + raise FileNotFoundError('File path does not exists') + + @property + def file_write(self): + """ + :obj:`bool` If True write files to disk + """ + return self._api.getFileWrite() + + @file_write.setter + def file_write(self, fwrite): + self._api.setFileWrite(fwrite) + + + @property + def file_overwrite(self): + """ + :obj:`bool` If true overwrite files on disk + """ + return self._api.getFileOverWrite() + + @file_overwrite.setter + def file_overwrite(self, value): + self._api.setFileOverWrite(value) + + @property + def file_padding(self): + """ + Pad files in the receiver + :obj:`bool` If true pads partial frames + """ + return self._api.getReceiverPartialFramesPadding() + + @file_padding.setter + def file_padding(self, value): + self._api.getReceiverPartialFramesPadding(value) + + @property + def firmware_version(self): + """ + :py:obj:`int` Firmware version of the detector + """ + return self._api.getFirmwareVersion() + + @property + def flags(self): + """Read and set flags. Accepts both single flag as + string or list of flags. + + Raises + -------- + RuntimeError + If flag not recognized + + + Examples + ---------- + + :: + + #Eiger + detector.flags + >> ['storeinram', 'parallel'] + + detector.flags = 'nonparallel' + detector.flags + >> ['storeinram', 'nonparallel'] + + detector.flags = ['continous', 'parallel'] + + + """ + return self._api.getReadoutFlags() + + @flags.setter + def flags(self, flags): + if isinstance(flags, str): + self._api.setReadoutFlag(flags) + elif isinstance(flags, Iterable): + for f in flags: + self._api.setReadoutFlag(f) + + @property + def frames_caught(self): + """ + Number of frames caught by the receiver. Can be used to check for + package loss. + """ + return self._api.getFramesCaughtByReceiver() + + + @property + def frame_discard_policy(self): + """ + Decides what the receiver does when packet loss occurs. + nodiscard - keep all frames + discardempty - discard only empty frames + discardpartial - discard partial and empty frames + """ + return self._api.getReceiverFrameDiscardPolicy() + + @frame_discard_policy.setter + def frame_discard_policy(self, policy): + self._api.setReceiverFramesDiscardPolicy(policy) + + + @property + def api_compatibility(self): + Compatibility = namedtuple('Compatibility', ['client_detector', 'client_receiver']) + c = Compatibility(self._api.isClientAndDetectorCompatible(), self._api.isClientAndReceiverCompatible()) + return c + + @property + def frame_padding(self): + """ + Padd partial frames in the receiver + """ + return self._api.getPartialFramesPadding() + + @frame_padding.setter + def frame_padding(self, padding): + self._api.setPartialFramesPadding(padding) + + def free_shared_memory(self): + """ + Free the shared memory that contains the detector settings + and reinitialized with 0 detectors so that you can keep + using the same object. + + """ + self._api.freeSharedMemory() + self.__init__(self._api.getMultiDetectorId()) + + @property + def flipped_data_x(self): + """Flips data on x axis. Set for eiger bottom modules""" + return self._flippeddatax + + @property + def flipped_data_y(self): + """Flips data on y axis.""" + return self._flippeddatax + + @property + def high_voltage(self): + """ + High voltage applied to the sensor + """ + return self._api.getDac('vhighvoltage', -1) + + @high_voltage.setter + def high_voltage(self, voltage): + voltage = int(voltage) + if voltage < 0 or voltage > 200: + raise DetectorValueError('High voltage {:d}V is out of range. Should be between 0-200V'.format(voltage)) + self._api.setDac('vhighvoltage', -1, voltage) + + + @property + def hostname(self): + """ + :obj:`list` of :obj:`str`: hostnames of all connected detectors + + Examples + --------- + + :: + + detector.hostname + >> ['beb059', 'beb058'] + + """ + _hm = self._api.getHostname() + if _hm == '': + return [] + return _hm.strip('+').split('+') + + + @hostname.setter + def hostname(self, hn): + if isinstance(hn, str): + self._api.setHostname(hn) + else: + name = ''.join([''.join((h, '+')) for h in hn]) + self._api.setHostname(name) + + @property + def image_size(self): + """ + :py:obj:`collections.namedtuple` with the image size of the detector + Also works setting using a normal tuple + + .. note :: + + Follows the normal convention in Python of (rows, cols) + + Examples + ---------- + + :: + + d.image_size = (512, 1024) + + d.image_size + >> ImageSize(rows=512, cols=1024) + + d.image_size.rows + >> 512 + + d.image_size.cols + >> 1024 + + """ + size = namedtuple('ImageSize', ['rows', 'cols']) + return size(*self._api.getImageSize()) + + @image_size.setter + def image_size(self, size): + self._api.setImageSize(*size) + + + def load_config(self, fname): + """ + Load detector configuration from a configuration file + + Raises + -------- + FileNotFoundError + If the file does not exists + + """ + if os.path.isfile(fname): + self._api.readConfigurationFile(fname) + else: + raise FileNotFoundError('Cannot find configuration file') + + + def load_parameters(self, fname): + """ + Setup detector by executing commands in a parameters file + + + .. note :: + + If you are relying mainly on the Python API it is probably + better to track the settings from Python. This function uses + parameters stored in a text file and the command line commands. + + Raises + -------- + FileNotFoundError + If the file does not exists + + """ + if os.path.isfile(fname): + self._api.readParametersFile(fname) + else: + raise FileNotFoundError('Cannot find parameters file') + + + def load_trimbits(self, fname, idet=-1): + """ + Load trimbit file or files. Either called with detector number or -1 + to try to load detector specific trimbit files + + Parameters + ----------- + fname: + :py:obj:`str` Filename (including path) to the trimbit files + + idet + :py:obj:`int` Detector to load trimbits to, -1 for all + + + :: + + #Assuming 500k consisting of beb049 and beb048 + # 0 is beb049 + # 1 is beb048 + + #Load name.sn049 to beb049 and name.sn048 to beb048 + detector.load_trimbits('/path/to/dir/name') + + #Load one file to a specific detector + detector.load_trimbits('/path/to/dir/name.sn049', 0) + + """ + self._api.loadTrimbitFile(fname, idet) + + + @property + def lock(self): + """Lock the detector to this client + + :: + + detector.lock = True + + """ + return self._api.getServerLock() + + @lock.setter + def lock(self, value): + self._api.setServerLock(value) + + @property + def lock_receiver(self): + """Lock the receivers to this client + + :: + + detector.lock_receiver = True + + """ + + return self._api.getReceiverLock() + + @lock_receiver.setter + def lock_receiver(self, value): + self._api.setReceiverLock(value) + + @property + def module_geometry(self): + """ + :obj:`namedtuple` Geometry(horizontal=nx, vertical=ny) + of the detector modules. + + Examples + --------- + + :: + + detector.module_geometry + >> Geometry(horizontal=1, vertical=2) + + detector.module_geometry.vertical + >> 2 + + detector.module_geometry[0] + >> 1 + + """ + _t = self._api.getDetectorGeometry() + Geometry = namedtuple('Geometry', ['horizontal', 'vertical']) + return Geometry(horizontal=_t[0], vertical=_t[1]) + + @property + def n_frames(self): + """ + :obj:`int` Number of frames per acquisition + """ + return self._api.getNumberOfFrames() + + @n_frames.setter + def n_frames(self, n): + if n >= 1: + self._api.setNumberOfFrames(n) + else: + raise DetectorValueError('Invalid value for n_frames: {:d}. Number of'\ + ' frames should be an integer greater than 0'.format(n)) + + @property + def frames_per_file(self): + return self._api.getFramesPerFile() + + @frames_per_file.setter + def frames_per_file(self, n): + self._api.setFramesPerFile(n) + + @property + def n_cycles(self): + """Number of cycles for the measurement (exp*n_frames)*n_cycles""" + return self._api.getCycles() + + @n_cycles.setter + def n_cycles(self, n_cycles): + if n_cycles > 0: + self._api.setCycles(n_cycles) + else: + raise DetectorValueError('Number of cycles must be positive') + + @property + def n_measurements(self): + """ + Number of times to repeat the programmed measurement. + This is the outer most part. Real time operation is not + guaranteed since this is software controlled. + + Examples + ---------- + + :: + + detector.n_frames = 1 + detector.n_cycles = 1 + detector.n_measurements = 3 + + detector.acq() # 1 frame 3 times + + detector.n_frames = 5 + detector.n_cycles = 3 + detector.n_measurements = 2 + + detector.acq() # 5x3 frames 2 times total 30 frames + + """ + return self._api.getNumberOfMeasurements() + + @n_measurements.setter + def n_measurements(self, value): + if value > 0: + self._api.setNumberOfMeasurements(value) + else: + raise DetectorValueError('Number of measurements must be positive') + + @property + def n_modules(self): + """ + :obj:`int` Number of (half)modules in the detector + + Examples + --------- + + :: + + detector.n_modules + >> 2 + + """ + return self._api.getNumberOfDetectors() + + @property + def online(self): + """Online flag for the detector + + Examples + ---------- + + :: + + d.online + >> False + + d.online = True + + """ + return self._api.getOnline() + + @online.setter + def online(self, value): + self._api.setOnline(value) + + + @property + def last_client_ip(self): + """Returns the ip address of the last client + that accessed the detector + + Returns + ------- + + :obj:`str` last client ip + + Examples + ---------- + + :: + + detector.last_client_ip + >> '129.129.202.117' + + """ + return self._api.getLastClientIP() + + @property + def receiver_last_client_ip(self): + """Returns the ip of the client last talking to the receiver""" + return self._api.getReceiverLastClientIP() + + @property + def receiver_online(self): + """ + Online flag for the receiver. Is set together with detector.online when creating the detector object + + Examples + --------- + + :: + + d.receiver_online + >> True + + d.receiver_online = False + + """ + return self._api.getReceiverOnline() + + @receiver_online.setter + def receiver_online(self, value): + self._api.setReceiverOnline(value) + + @property + def receiver_version(self): + """ + :py:obj:`str` Receiver version as a string. [yearmonthday] + + Examples + ---------- + + :: + + d.receiver_version + >> '20180327' + + """ + v = hex(self._api.getReceiverVersion()) + return v[2:] + + #When returning instance error hadling needs to be done in the + #class that is returned + @property + def register(self): + """Directly manipulate registers on the readout board + + Examples + --------- + + :: + + d.register[0x5d] = 0xf00 + + """ + return self._register + + def reset_frames_caught(self): + """ + Reset the number of frames caught by the receiver. + + .. note :: + + Automatically done when using d.acq() + + """ + self._api.resetFramesCaught() + + @property + def period(self): + """ + :obj:`double` Period between start of frames. Set to 0 for the detector + to choose the shortest possible + """ + _t = self._api.getPeriod() + return _t / 1e9 + + @period.setter + def period(self, t): + ns_time = int(t * 1e9) + if ns_time < 0: + raise ValueError('Period must be 0 or larger') + self._api.setPeriod(ns_time) + + @property + def rate_correction(self): + """ + :obj:`list` of :obj:`double` Rate correction for all modules. + Set to 0 for **disabled** + + .. todo :: + + Should support individual assignments + + Raises + ------- + ValueError + If the passed list is not of the same length as the number of + detectors + + Examples + --------- + + :: + + detector.rate_correction + >> [125.0, 155.0] + + detector.rate_correction = [125, 155] + + + """ + return self._api.getRateCorrection() + + @rate_correction.setter + def rate_correction(self, tau_list): + if len(tau_list) != self.n_modules: + raise ValueError('List of tau needs the same length') + self._api.setRateCorrection(tau_list) + + + @property + def readout_clock(self): + """ + Speed of the readout clock relative to the full speed + + * Full Speed + * Half Speed + * Quarter Speed + * Super Slow Speed + + Examples + --------- + + :: + + d.readout_clock + >> 'Half Speed' + + d.readout_clock = 'Full Speed' + + + """ + speed = self._api.getReadoutClockSpeed() + return self._speed_names[speed] + + @readout_clock.setter + def readout_clock(self, value): + speed = self._speed_int[value] + self._api.setReadoutClockSpeed(speed) + + @property + def receiver_frame_index(self): + return self._api.getReceiverCurrentFrameIndex() + + @property + def rx_datastream(self): + """ + Zmq datastream from receiver. :py:obj:`True` if enabled and :py:obj:`False` + otherwise + + :: + + #Enable data streaming from receiver + detector.rx_datastream = True + + #Check data streaming + detector.rx_datastream + >> True + + """ + return self._api.getRxDataStreamStatus() + + @rx_datastream.setter + def rx_datastream(self, status): + self._api.setRxDataStreamStatus(status) + + + @property + def rx_hostname(self): + """ + Receiver hostname + TODO! setting of individual hostnames, now done with API call + """ + return self._api.getReceiverHostname() + + + @rx_hostname.setter + def rx_hostname(self, name): + self._api.setReceiverHostname(name) + + + @property + def rx_udpip(self): + """ + Receiver UDP ip + """ + return self._api.getReceiverUDPIP(-1) + + + @rx_udpip.setter + def rx_udpip(self, ip): + if isinstance(ip, list): + for i, addr in enumerate(ip): + self._api.setReceiverUDPIP(addr, i) + else: + self._api.setReceiverUDPIP(ip, -1) + + + @property + def rx_udpmac(self): + return self._api.getReceiverUDPMAC(-1) + + @rx_udpmac.setter + def rx_udpmac(self, mac): + if isinstance(mac, list): + for i, m in enumerate(mac): + self._api.setReceiverUDPMAC(m, i) + else: + self._api.setReceiverUDPMAC(mac, -1) + + @property + def rx_tcpport(self): + return self._api.getReceiverPort() + + @rx_tcpport.setter + def rx_tcpport(self, ports): + if len(ports) != len(self): + raise ValueError('Number of ports: {} not equal to number of ' + 'detectors: {}'.format(len(ports), len(self))) + else: + for i, p in enumerate(ports): + self._api.setReceiverPort(i, p) + + @property + def rx_zmqip(self): + """ + ip where the receiver streams data + """ + ip = self._api.getNetworkParameter('rx_zmqip') + return element_if_equal(ip) + + @rx_zmqip.setter + def rx_zmqip(self, ip): + self._api.setNetworkParameter('rx_zmqip', ip, -1) + + + @property + def detectormac(self): + """ + Read detector mac address + """ + mac = self._api.getNetworkParameter('detectormac') + return element_if_equal(mac) + + @property + def detectorip(self): + """ + Read detector ip address + """ + return self._api.getDetectorIp(-1) + + + # @detectorip.setter + # def detectorip(self, ip): + + + @property + def client_zmqip(self): + """ + Ip address where the client listens to zmq stream + """ + ip = self._api.getNetworkParameter('client_zmqip') + return element_if_equal(ip) + + @client_zmqip.setter + + def client_zmqip(self, ip): + self._api.setNetworkParameter('client_zmqip', ip, -1) + + + + @property + def rx_fifodepth(self): + """ + Fifo depth of receiver in number of frames + """ + return self._api.getReceiverFifoDepth() + + @rx_fifodepth.setter + def rx_fifodepth(self, n_frames): + self._api.setReceiverFifoDepth(n_frames) + + + @property + def rx_udpsocksize(self): + """ + UDP buffer size + """ + buffer_size = [int(s) for s in self._api.getNetworkParameter('rx_udpsocksize')] + return element_if_equal(buffer_size) + + @property + def rx_jsonaddheader(self): + """ + UDP buffer size + """ + header = self._api.getNetworkParameter('rx_jsonaddheader') + return element_if_equal(header) + + @rx_jsonaddheader.setter + def rx_jsonaddheader(self, header): + self._api.setNetworkParameter('rx_jsonaddheader', header, -1) + + + + @rx_udpsocksize.setter + def rx_udpsocksize(self, buffer_size): + self._api.setNetworkParameter('rx_udpsocksize', str(buffer_size), -1) + + + @property + def rx_realudpsocksize(self): + """ + UDP buffer size + """ + buffer_size = [int(s) for s in self._api.getNetworkParameter('rx_realudpsocksize')] + return element_if_equal(buffer_size) + + + @property + def rx_zmqport(self): + """ + Return the receiver zmq ports. + + :: + + detector.rx_zmqport + >> [30001, 30002] + + """ + _s = self._api.getNetworkParameter('rx_zmqport') + if _s == '': + return [] + else: + return [int(_p) for _p in _s] + + @rx_zmqport.setter + def rx_zmqport(self, port): + if isinstance(port, Iterable): + for i, p in enumerate(port): + self._api.setNetworkParameter('rx_zmqport', str(p), i) + else: + self._api.setNetworkParameter('rx_zmqport', str(port), -1) + +# Add back when versioning is defined +# @property +# def software_version(self): +# return self._api.getSoftwareVersion(); + + + @property + def user(self): + return self._api.getUserDetails() + + @property + def server_version(self): + """ + :py:obj:`int` On-board server version of the detector + """ + return hex(self._api.getServerVersion()) + + @property + def settings(self): + """ + Detector settings used to control for example calibration or gain + switching. For EIGER almost always standard standard. + + .. warning :: + + For Eiger setting settings should be followed by setting the threshold + otherwise reading of the settings will overwrite the set value + + + """ + return self._api.getSettings() + + @settings.setter + def settings(self, s): + if s in self._settings: + self._api.setSettings(s) + else: + raise DetectorValueError('Settings: {:s}, not defined for {:s}. ' + 'Valid options are: [{:s}]'.format(s, self.detector_type, ', '.join(self._settings))) + + + @property + def settings_path(self): + """ + The path where the slsDetectorSoftware looks for settings/trimbit files + """ + return self._api.getSettingsDir() + + @settings_path.setter + def settings_path(self, path): + if os.path.isdir(path): + self._api.setSettingsDir(path) + else: + raise FileNotFoundError('Settings path does not exist') + + @property + def status(self): + """ + :py:obj:`str` Status of the detector: idle, running, + + .. todo :: + + Check possible values + + """ + return self._api.getRunStatus() + + def start_detector(self): + """ + Non blocking command to star acquisition. Needs to be used in combination + with receiver start. + """ + self._api.startAcquisition() + + def stop_detector(self): + """ + Stop acquisition early or if the detector hangs + """ + self._api.stopAcquisition() + + + def start_receiver(self): + self._api.startReceiver() + + def stop_receiver(self): + self._api.stopReceiver() + + @property + def threaded(self): + """ + Enable parallel execution of commands to the different detector modules + + Examples + ---------- + + :: + + d.threaded + >> True + + d.threaded = False + + """ + return self._api.getThreadedProcessing() + + @threaded.setter + def threaded(self, value): + self._api.setThreadedProcessing(value) + + @property + def threshold(self): + """ + Detector threshold in eV + """ + return self._api.getThresholdEnergy() + + @threshold.setter + def threshold(self, eV): + self._api.setThresholdEnergy(eV) + + @property + def timing_mode(self): + """ + :py:obj:`str` Timing mode of the detector + + * **auto** Something + * **trigger** Something else + + + """ + return self._api.getTimingMode() + + @timing_mode.setter + def timing_mode(self, mode): + self._api.setTimingMode(mode) + + + @property + def trimmed_energies(self): + """ + EIGER: the energies at which the detector was trimmed. This also sets + the range for which the calibration of the detector is valid. + + + :: + + detector.trimmed_energies = [5400, 6400, 8000] + + detector.trimmed_energies + >> [5400, 6400, 8000] + + """ + + return self._api.getTrimEnergies() + + @trimmed_energies.setter + def trimmed_energies(self, energy_list): + self._api.setTrimEnergies(energy_list) + + @property + def vthreshold(self): + """ + Threshold in DAC units for the detector. Sets the individual vcmp of + all chips in the detector. + """ + return self._api.getDac('vthreshold', -1) + + @vthreshold.setter + def vthreshold(self, th): + self._api.setDac('vthreshold', -1, th) + + @property + def trimbits(self): + """ + Set or read trimbits of the detector. + + Examples + --------- + + :: + + #Set all to 32 + d.trimbits = 32 + + d.trimbits + >> 32 + + #if undefined or different + d.trimbits + >> -1 + + """ + return self._api.getAllTrimbits() + + @trimbits.setter + def trimbits(self, value): + if self._trimbit_limits.min <= value <= self._trimbit_limits.max: + self._api.setAllTrimbits(value) + else: + raise DetectorValueError('Trimbit setting {:d} is outside of range:'\ + '{:d}-{:d}'.format(value, self._trimbit_limits.min, self._trimbit_limits.max)) + + @property + def client_zmqport(self): + """zmq port of the client""" + _s = self._api.getNetworkParameter('client_zmqport') + if _s == '': + return [] + return [int(_p)+i for _p in _s for i in range(2)] + + + def _provoke_error(self): + self._api.setErrorMask(1) + + + def config_network(self): + """ + Configures the detector source and destination MAC addresses, IP addresses + and UDP ports, and computes the IP header checksum for such parameters + """ + self._api.configureNetworkParameters() + + +def free_shared_memory(multi_id=0): + """ + Function to free the shared memory but do not initialize with new + 0 size detector + """ + api = DetectorApi(multi_id) + api.freeSharedMemory() diff --git a/python/sls_detector/detector_property.py b/python/sls_detector/detector_property.py new file mode 100755 index 000000000..3b86b1531 --- /dev/null +++ b/python/sls_detector/detector_property.py @@ -0,0 +1,51 @@ +from collections.abc import Iterable +import numpy as np + +class DetectorProperty: + """ + Base class for a detector property that should be accessed by name and index + TODO! Calls are not in parallel and exposes object that can be passes around + """ + def __init__(self, get_func, set_func, nmod_func, name): + self.get = get_func + self.set = set_func + self.get_nmod = nmod_func + self.__name__ = name + + def __getitem__(self, key): + if key == slice(None, None, None): + return [self.get(i) for i in range(self.get_nmod())] + elif isinstance(key, Iterable): + return [self.get(k) for k in key] + else: + return self.get(key) + + def __setitem__(self, key, value): + #operate on all values + if key == slice(None, None, None): + if isinstance(value, (np.integer, int)): + for i in range(self.get_nmod()): + self.set(i, value) + elif isinstance(value, Iterable): + for i in range(self.get_nmod()): + self.set(i, value[i]) + else: + raise ValueError('Value should be int or np.integer not', type(value)) + + #Iterate over some + elif isinstance(key, Iterable): + if isinstance(value, Iterable): + for k,v in zip(key, value): + self.set(k,v) + + elif isinstance(value, int): + for k in key: + self.set(k, value) + + #Set single value + elif isinstance(key, int): + self.set(key, value) + + def __repr__(self): + s = ', '.join(str(v) for v in self[:]) + return '{}: [{}]'.format(self.__name__, s) \ No newline at end of file diff --git a/python/sls_detector/eiger.py b/python/sls_detector/eiger.py new file mode 100755 index 000000000..1d48c2241 --- /dev/null +++ b/python/sls_detector/eiger.py @@ -0,0 +1,597 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Wed Dec 6 11:51:18 2017 + +@author: l_frojdh +""" + +import socket +from collections.abc import Iterable +from collections import namedtuple +from functools import partial + +from .adcs import Adc, DetectorAdcs +from .dacs import DetectorDacs +from .decorators import error_handling +from .detector import Detector +from .detector_property import DetectorProperty +from .utils import element_if_equal +from sls_detector.errors import DetectorValueError, DetectorError + +class EigerVcmp: + """ + Convenience class to be able to loop over vcmp for Eiger + + + .. todo:: + + Support single assignment and perhaps unify with Dac class + + """ + + def __init__(self, detector): + _names = ['vcmp_ll', + 'vcmp_lr', + 'vcmp_rl', + 'vcmp_rr'] + self.set = [] + self.get = [] + for i in range(detector.n_modules): + if i % 2 == 0: + name = _names + else: + name = _names[::-1] + for n in name: + self.set.append(partial(detector._api.setDac, n, i)) + self.get.append(partial(detector._api.getDac, n, i)) + + def __getitem__(self, key): + if key == slice(None, None, None): + return [_d() for _d in self.get] + return self.get[key]() + + def __setitem__(self, i, value): + self.set[i](value) + + def __repr__(self): + return 'vcmp: '+ str(self[:]) + + +class EigerDacs(DetectorDacs): + _dacs = [('vsvp', 0, 4000, 0), + ('vtr', 0, 4000, 2500), + ('vrf', 0, 4000, 3300), + ('vrs', 0, 4000, 1400), + ('vsvn', 0, 4000, 4000), + ('vtgstv', 0, 4000, 2556), + ('vcmp_ll', 0, 4000, 1500), + ('vcmp_lr', 0, 4000, 1500), + ('vcall', 0, 4000, 4000), + ('vcmp_rl', 0, 4000, 1500), + ('rxb_rb', 0, 4000, 1100), + ('rxb_lb', 0, 4000, 1100), + ('vcmp_rr', 0, 4000, 1500), + ('vcp', 0, 4000, 200), + ('vcn', 0, 4000, 2000), + ('vis', 0, 4000, 1550), + ('iodelay', 0, 4000, 660)] + _dacnames = [_d[0] for _d in _dacs] + + +# noinspection PyProtectedMember +class DetectorDelays: + _delaynames = ['frame', 'left', 'right'] + + def __init__(self, detector): + # We need to at least initially know which detector we are connected to + self._detector = detector + + setattr(self, '_frame', DetectorProperty(detector._api.getDelayFrame, + detector._api.setDelayFrame, + detector._api.getNumberOfDetectors, + 'frame')) + + setattr(self, '_left', DetectorProperty(detector._api.getDelayLeft, + detector._api.setDelayLeft, + detector._api.getNumberOfDetectors, + 'left')) + + setattr(self, '_right', DetectorProperty(detector._api.getDelayRight, + detector._api.setDelayRight, + detector._api.getNumberOfDetectors, + 'right')) + # Index to support iteration + self._current = 0 + + def __getattr__(self, name): + return self.__getattribute__('_' + name) + + def __setattr__(self, name, value): + if name in self._delaynames: + return self.__getattribute__('_' + name).__setitem__(slice(None, None, None), value) + else: + super().__setattr__(name, value) + + def __next__(self): + if self._current >= len(self._delaynames): + self._current = 0 + raise StopIteration + else: + self._current += 1 + return self.__getattr__(self._delaynames[self._current-1]) + + def __iter__(self): + return self + + def __repr__(self): + hn = self._detector.hostname + r_str = ['Transmission delay [ns]\n' + '{:11s}{:>8s}{:>8s}{:>8s}'.format('', 'left', 'right', 'frame')] + for i in range(self._detector.n_modules): + r_str.append('{:2d}:{:8s}{:>8d}{:>8d}{:>8d}'.format(i, hn[i], self.left[i], self.right[i], self.frame[i])) + return '\n'.join(r_str) + + +class Eiger(Detector): + """ + Subclassing Detector to set up correct dacs and detector specific + functions. + """ + _detector_dynamic_range = [4, 8, 16, 32] + + + _settings = ['standard', 'highgain', 'lowgain', 'veryhighgain', 'verylowgain'] + """available settings for Eiger, note almost always standard""" + + def __init__(self, id=0): + super().__init__(id) + + self._active = DetectorProperty(self._api.getActive, + self._api.setActive, + self._api.getNumberOfDetectors, + 'active') + + self._vcmp = EigerVcmp(self) + self._dacs = EigerDacs(self) + self._trimbit_limits = namedtuple('trimbit_limits', ['min', 'max'])(0, 63) + self._delay = DetectorDelays(self) + + # Eiger specific adcs + self._temp = DetectorAdcs() + self._temp.fpga = Adc('temp_fpga', self) + self._temp.fpgaext = Adc('temp_fpgaext', self) + self._temp.t10ge = Adc('temp_10ge', self) + self._temp.dcdc = Adc('temp_dcdc', self) + self._temp.sodl = Adc('temp_sodl', self) + self._temp.sodr = Adc('temp_sodr', self) + self._temp.fpgafl = Adc('temp_fpgafl', self) + self._temp.fpgafr = Adc('temp_fpgafr', self) + + @property + def active(self): + """ + Is the detector active? Can be used to enable or disable a detector + module + + Examples + ---------- + + :: + + d.active + >> active: [True, True] + + d.active[1] = False + >> active: [True, False] + """ + return self._active + + @active.setter + def active(self, value): + self._active[:] = value + + @property + def measured_period(self): + return self._api.getMeasuredPeriod() + + @property + def measured_subperiod(self): + return self._api.getMeasuredSubPeriod() + + @property + def add_gappixels(self): + """Enable or disable the (virual) pixels between ASICs + + Examples + ---------- + + :: + + d.add_gappixels = True + + d.add_gappixels + >> True + + """ + return self._api.getGapPixels() + + @add_gappixels.setter + def add_gappixels(self, value): + self._api.setGapPixels(value) + + @property + def dacs(self): + """ + + An instance of DetectorDacs used for accessing the dacs of a single + or multi detector. + + Examples + --------- + + :: + + d = Eiger() + + #Set all vrf to 1500 + d.dacs.vrf = 1500 + + #Check vrf + d.dacs.vrf + >> vrf : 1500, 1500 + + #Set a single vtr + d.dacs.vtr[0] = 1800 + + #Set vrf with multiple values + d.dacs.vrf = [3500,3700] + d.dacs.vrf + >> vrf : 3500, 3700 + + #read into a variable + var = d.dacs.vrf[:] + + #set multiple with multiple values, mostly used for large systems + d.dacs.vcall[0,1] = [3500,3600] + d.dacs.vcall + >> vcall : 3500, 3600 + + d.dacs + >> + ========== DACS ========= + vsvp : 0, 0 + vtr : 4000, 4000 + vrf : 1900, 1900 + vrs : 1400, 1400 + vsvn : 4000, 4000 + vtgstv : 2556, 2556 + vcmp_ll : 1500, 1500 + vcmp_lr : 1500, 1500 + vcall : 4000, 4000 + vcmp_rl : 1500, 1500 + rxb_rb : 1100, 1100 + rxb_lb : 1100, 1100 + vcmp_rr : 1500, 1500 + vcp : 1500, 1500 + vcn : 2000, 2000 + vis : 1550, 1550 + iodelay : 660, 660 + + """ + return self._dacs + + @property + def tx_delay(self): + """ + Transmission delay of the modules to allow running the detector + in a network not supporting the full speed of the detector. + + + :: + + d.tx_delay + >> + Transmission delay [ns] + left right frame + 0:beb048 0 15000 0 + 1:beb049 100 190000 100 + + d.tx_delay.left = [2000,5000] + """ + return self._delay + + def default_settings(self): + """ + reset the detector to some type of standard settings + mostly used when testing + """ + self.n_frames = 1 + self.exposure_time = 1 + self.period = 0 + self.n_cycles = 1 + self.n_measurements = 1 + self.dynamic_range = 16 + + @property + def eiger_matrix_reset(self): + """ + Matrix reset bit for Eiger. + + :py:obj:`True` : Normal operation, the matrix is reset before each acq. + :py:obj:`False` : Matrix reset disabled. Used to not reset before + reading out analog test pulses. + """ + return self._api.getCounterBit() + + @eiger_matrix_reset.setter + def eiger_matrix_reset(self, value): + self._api.setCounterBit(value) + + @property + def flowcontrol_10g(self): + """ + :py:obj:`True` - Flow control enabled :py:obj:`False` flow control disabled. + Sets for all moduels, if for some reason access to a single module is needed + this can be done trough the C++ API. + + """ + fc = self._api.getNetworkParameter('flow_control_10g') + return element_if_equal([bool(int(e)) for e in fc]) + + @flowcontrol_10g.setter + def flowcontrol_10g(self, value): + if value is True: + v = '1' + else: + v = '0' + self._api.setNetworkParameter('flow_control_10g', v, -1) + + def pulse_all_pixels(self, n): + """ + Pulse each pixel of the chip **n** times using the analog test pulses. + The pulse height is set using d.dacs.vcall with 4000 being 0 and 0 being + the highest pulse. + + :: + + #Pulse all pixels ten times + d.pulse_all_pixels(10) + + #Avoid resetting before acq + d.eiger_matrix_reset = False + + d.acq() #take frame + + #Restore normal behaviour + d.eiger_matrix_reset = True + + + """ + self._api.pulseAllPixels(n) + + + def pulse_diagonal(self, n): + """ + Pulse pixels in super colums in a diagonal fashion. Used for calibration + of vcall. Saves time compared to pulsing all pixels. + """ + self._api.pulseDiagonal(n) + + + def pulse_chip(self, n): + """ + Advance the counter by toggling enable. Gives 2*n+2 int the counter + + """ + n = int(n) + if n >= -1: + self._api.pulseChip(n) + else: + raise ValueError('n must be equal or larger than -1') + + @property + def vcmp(self): + """ + Convenience function to get and set the individual vcmp of chips + Used mainly in the calibration code. + + Examples + --------- + + :: + + #Reading + d.vcmp[:] + >> [500, 500, 500, 500, 500, 500, 500, 500] + + #Setting + d.vcmp = [500, 500, 500, 500, 500, 500, 500, 500] + + + """ + + return self._vcmp + + @vcmp.setter + def vcmp(self, values): + if len(values) == len(self._vcmp.set): + for i, v in enumerate(values): + self._vcmp.set[i](v) + else: + raise ValueError('vcmp only compatible with setting all') + + @property + def rx_udpport(self): + """ + UDP port for the receiver. Each module has two ports referred to + as rx_udpport and rx_udpport2 in the command line interface + here they are grouped for each detector + + :: + + [0:rx_udpport, 0:rx_udpport2, 1:rx_udpport ...] + + Examples + ----------- + + :: + + d.rx_udpport + >> [50010, 50011, 50004, 50005] + + d.rx_udpport = [50010, 50011, 50012, 50013] + + """ + p0 = self._api.getReceiverUDPPort() + p1 = self._api.getReceiverUDPPort2() + return [int(val) for pair in zip(p0, p1) for val in pair] + + @rx_udpport.setter + def rx_udpport(self, ports): + """Requires iterating over elements two and two for setting ports""" + a = iter(ports) + for i, p in enumerate(zip(a, a)): + self._api.setReceiverUDPPort(p[0], i) + self._api.setReceiverUDPPort2(p[1], i) + + @property + def rx_zmqport(self): + """ + Return the receiver zmq ports. Note that Eiger has two ports per receiver! + + :: + + detector.rx_zmqport + >> [30001, 30002, 30003, 30004] + + + """ + _s = self._api.getReceiverStreamingPort() + if _s == '': + return [] + else: + return [int(_p) + i for _p in _s for i in range(2)] + + @rx_zmqport.setter + def rx_zmqport(self, port): + if isinstance(port, Iterable): + for i, p in enumerate(port): + self._api.setReceiverStreamingPort(p, i) + else: + self._api.setReceiverStreamingPort(port, -1) + + + @property + def sub_exposure_time(self): + """ + Sub frame exposure time in *seconds* for Eiger in 32bit autosumming mode + + :: + + d.sub_exposure_time + >> 0.0023 + + d.sub_exposure_time = 0.002 + + """ + return self._api.getSubExposureTime() / 1e9 + + + @sub_exposure_time.setter + def sub_exposure_time(self, t): + #TODO! checking here or in the detector? + ns_time = int(t * 1e9) + if ns_time > 0: + self._api.setSubExposureTime(ns_time) + else: + raise DetectorValueError('Sub exposure time must be larger than 0') + + @property + def sub_deadtime(self): + """ + Deadtime between subexposures. Used to mimize noise by delaying the start of the next + subexposure. + """ + return self._api.getSubExposureDeadTime() / 1e9 + + + @sub_deadtime.setter + def sub_deadtime(self, t): + ns_time = int(t * 1e9) + if ns_time >= 0: + self._api.setSubExposureDeadTime(ns_time) + else: + raise ValueError('Sub deadtime time must be larger or equal to 0') + + @property + def temp(self): + """ + An instance of DetectorAdcs used to read the temperature + of different components + + Examples + ----------- + + :: + + detector.temp + >> + temp_fpga : 36.90°C, 45.60°C + temp_fpgaext : 31.50°C, 32.50°C + temp_10ge : 0.00°C, 0.00°C + temp_dcdc : 36.00°C, 36.00°C + temp_sodl : 33.00°C, 34.50°C + temp_sodr : 33.50°C, 34.00°C + temp_fpgafl : 33.81°C, 30.93°C + temp_fpgafr : 27.88°C, 29.15°C + + a = detector.temp.fpga[:] + a + >> [36.568, 45.542] + + + """ + return self._temp + + @property + def tengiga(self): + """Enable 10Gbit/s data output + + Examples + ---------- + + :: + + d.tengiga + >> False + + d.tengiga = True + + """ + return self._api.getTenGigabitEthernet() + + @tengiga.setter + def tengiga(self, value): + self._api.setTenGigabitEthernet(value) + + def set_delays(self, delta): + self.tx_delay.left = [delta*(i*2) for i in range(self.n_modules)] + self.tx_delay.right = [delta*(i*2+1) for i in range(self.n_modules)] + + + def setup500k(self, hostnames): + """ + Setup the Eiger detector to run on the local machine + """ + + self.hostname = hostnames + self.file_write = False + self.image_size = (512, 1024) + self.rx_tcpport = [1954, 1955] + self.rx_udpport = [50010, 50011, 50004, 50005] + self.rx_hostname = socket.gethostname().split('.')[0] + self.rx_datastream = False + self.file_write = False + self.online = True + self.receiver_online = True diff --git a/python/sls_detector/errors.py b/python/sls_detector/errors.py new file mode 100755 index 000000000..f16ceeb9f --- /dev/null +++ b/python/sls_detector/errors.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on Thu Dec 14 17:13:55 2017 + +@author: l_frojdh +""" + + +class DetectorError(Exception): + """ + This error should be used when something fails + on the detector side + """ + pass + + +class DetectorSettingDoesNotExist(Exception): + """This error should be used when the setting does not exist""" + pass + + +class DetectorValueError(Exception): + """This error should be used when the set value is outside the allowed range""" + pass diff --git a/python/sls_detector/experimental.py b/python/sls_detector/experimental.py new file mode 100755 index 000000000..5d0f19a2a --- /dev/null +++ b/python/sls_detector/experimental.py @@ -0,0 +1,16 @@ + +from _sls_detector import multiDetectorApi + +class ExperimentalDetector(multiDetectorApi): + def __init__(self): + super().__init__(0) + + + @property + def rx_udpip(self): + return self._getReceiverUDPIP(-1) + + @rx_udpip.setter + def rx_udpip(self, ip): + self._setReceiverUDPIP(ip, -1) + \ No newline at end of file diff --git a/python/sls_detector/jungfrau.py b/python/sls_detector/jungfrau.py new file mode 100755 index 000000000..3db0e3fea --- /dev/null +++ b/python/sls_detector/jungfrau.py @@ -0,0 +1,260 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Jungfrau detector class and support functions. +Inherits from Detector. +""" +from .adcs import Adc, DetectorAdcs +from .decorators import error_handling +from .detector import Detector +from .dacs import DetectorDacs +from .utils import element_if_equal + + +class JungfrauDacs(DetectorDacs): + _dacs = [('vb_comp', 0, 4000, 1220), + ('vdd_prot', 0, 4000, 3000), + ('vin_com', 0, 4000, 1053), + ('vref_prech', 0, 4000, 1450), + ('vb_pixbuff', 0, 4000, 750), + ('vb_ds', 0, 4000, 1000), + ('vref_ds', 0, 4000, 480), + ('vref_comp', 0, 4000, 420), + ] + _dacnames = [_d[0] for _d in _dacs] + +class Jungfrau(Detector): + """ + Class used to control a Jungfrau detector. Inherits from the Detector class but a specialized + class is needed to provide the correct dacs and unique functions. + + """ + _detector_dynamic_range = [4, 8, 16, 32] + + _settings = ['dynamichg0', + 'dynamicgain', + 'fixgain1', + 'fixgain2', + 'forceswitchg1', + 'forceswitchg2'] + """Available settings for Jungfrau""" + + def __init__(self, multi_id=0): + #Init on base calss + super().__init__(multi_id) + self._dacs = JungfrauDacs(self) + + #Jungfrau specific temps, this can be reduced to a single value? + self._temp = DetectorAdcs() + self._temp.fpga = Adc('temp_fpga', self) + # self._register = Register(self) + + + @property + def dacs(self): + """ + + An instance of DetectorDacs used for accessing the dacs of a single + or multi detector. + + Examples + --------- + + :: + + #Jungfrau + + + """ + return self._dacs + + @property + def power_chip(self): + """Power on or off the ASICs, True for on False for off""" + return self._api.isChipPowered() + + @power_chip.setter + def power_chip(self, value): + self._api.powerChip(value) + + @property + def delay(self): + """Delay after trigger [s]""" + return self._api.getDelay()/1e9 + + @delay.setter + def delay(self, t): + ns_time = int(t * 1e9) + self._api.setDelay(ns_time) + + @property + def n_gates(self): + return self._api.getNumberOfGates() + + @n_gates.setter + def n_gates(self, n): + self._api.setNumberOfGates(n) + + @property + def n_probes(self): + return self._api.getNumberOfProbes() + + @n_probes.setter + def n_probes(self, n): + self._api.setNumberOfProbes(n) + + @property + def storagecell_start(self): + """ + First storage cell + """ + return self._api.getStoragecellStart() + + @storagecell_start.setter + def storagecell_start(self, value): + self._api.setStoragecellStart(value) + + + @property + def n_storagecells(self): + """ + number of storage cells used for the measurements + """ + return self._api.getNumberOfStorageCells() + + @n_storagecells.setter + def n_storagecells(self, value): + self._api.setNumberOfStorageCells(value) + + @property + def temp(self): + """ + An instance of DetectorAdcs used to read the temperature + of different components + + Examples + ----------- + + :: + + detector.temp + >> + temp_fpga : 36.90°C, 45.60°C + + a = detector.temp.fpga[:] + a + >> [36.568, 45.542] + + + """ + return self._temp + + @property + def temperature_threshold(self): + """Threshold for switching of chips""" + return self._api.getThresholdTemperature() + + @temperature_threshold.setter + def temperature_threshold(self, t): + self._api.setThresholdTemperature(t) + + @property + def temperature_control(self): + """ + Monitor the temperature of the detector and switch off chips if temperature_threshold is + crossed + + + Examples + --------- + + :: + + #activate + detector.temperature_control = True + + #deactivate + detector.temperature_control = False + + + """ + return self._api.getTemperatureControl() + + @temperature_control.setter + def temperature_control(self, v): + self._api.setTemperatureControl(v) + + @property + def temperature_event(self): + """Have the temperature threshold been crossed? + + Returns + --------- + + :py:obj:`True` if the threshold have been crossed and temperature_control is active + otherwise :py:obj:`False` + + """ + return self._api.getTemperatureEvent() + + def reset_temperature_event(self): + """Reset the temperature_event. After reset temperature_event is False""" + self._api.resetTemperatureEvent() + + @property + def rx_udpport(self): + """ + UDP port for the receiver. Each module have one port. + Note! Eiger has two ports + + :: + + [0:rx_udpport] + + Examples + ----------- + + :: + + d.rx_udpport + >> [50010] + + d.rx_udpport = [50010] + + """ + return self._api.getNetworkParameter('rx_udpport') + + + @rx_udpport.setter + def rx_udpport(self, ports): + """Requires iterating over elements two and two for setting ports""" + for i, p in enumerate(ports): + self._api.setNetworkParameter('rx_udpport', str(p), i) + + @property + def detector_mac(self): + s = self._api.getNetworkParameter('detectormac') + return element_if_equal(s) + + + @detector_mac.setter + def detector_mac(self, mac): + if isinstance(mac, list): + for i, m in enumerate(mac): + self._api.setNetworkParameter('detectormac', m, i) + else: + self._api.setNetworkParameter('detectormac', mac, -1) + + + @property + def detector_ip(self): + s = self._api.getNetworkParameter('detectorip') + return element_if_equal(s) + + @detector_ip.setter + def detector_ip(self, ip): + if isinstance(ip, list): + for i, addr in enumerate(ip): + self._api.setNetworkParameter('detectorip', addr, i) + else: + self._api.setNetworkParameter('detectorip', ip, -1) diff --git a/python/sls_detector/jungfrau_ctb.py b/python/sls_detector/jungfrau_ctb.py new file mode 100755 index 000000000..8192fe81d --- /dev/null +++ b/python/sls_detector/jungfrau_ctb.py @@ -0,0 +1,179 @@ +from functools import partial +from collections.abc import Iterable +from collections import namedtuple +import socket + +from .detector import Detector +from .utils import element_if_equal +from .adcs import DetectorAdcs, Adc +from .dacs import DetectorDacs +from .detector_property import DetectorProperty +from .decorators import error_handling +from .registers import Register, Adc_register + +class JungfrauCTBDacs(DetectorDacs): + _dacs = [('dac0', 0, 4000, 1400), + ('dac1', 0, 4000, 1200), + ('dac2', 0, 4000, 900), + ('dac3', 0, 4000, 1050), + ('dac4', 0, 4000, 1400), + ('dac5', 0, 4000, 655), + ('dac6', 0, 4000, 2000), + ('dac7', 0, 4000, 1400), + ('dac8', 0, 4000, 850), + ('dac9', 0, 4000, 2000), + ('dac10', 0, 4000, 2294), + ('dac11', 0, 4000, 983), + ('dac12', 0, 4000, 1475), + ('dac13', 0, 4000, 1200), + ('dac14', 0, 4000, 1600), + ('dac15', 0, 4000, 1455), + ('dac16', 0, 4000, 0), + ('dac17', 0, 4000, 1000), + ] + _dacnames = [_d[0] for _d in _dacs] + + + +class JungfrauCTB(Detector): + def __init__(self, id = 0): + super().__init__(id) + self._dacs = JungfrauCTBDacs(self) + self._register = Register(self) + self._adc_register = Adc_register(self) + + @property + def v_a(self): + return self._api.getDac_mV('v_a', -1) + + @v_a.setter + def v_a(self, value): + self._api.setDac_mV('v_a', -1, value) + + @property + def v_b(self): + return self._api.getDac_mV('v_b', -1) + + @v_b.setter + def v_b(self, value): + self._api.setDac_mV('v_b', -1, value) + + + @property + def v_c(self): + return self._api.getDac_mV('v_c', -1) + + @v_c.setter + def v_c(self, value): + self._api.setDac_mV('v_c', -1, value) + + @property + def v_d(self): + return self._api.getDac_mV('v_d', -1) + + @v_d.setter + def v_d(self, value): + self._api.setDac_mV('v_d', -1, value) + + @property + def v_io(self): + return self._api.getDac_mV('v_io', -1) + + @v_io.setter + def v_io(self, value): + self._api.setDac_mV('v_io', -1, value) + + @property + def v_limit(self): + return self._api.getDac_mV('v_limit', -1) + + @v_limit.setter + def v_limit(self, value): + self._api.setDac_mV('v_limit', -1, value) + + @property + def adc_register(self): + return self._adc_register + + # @property + # def register(self): + # return self._register + + def adcOFF(self): + """Switch off the ADC""" + self.adc_register[0x8] = 1 + + + + @property + def dacs(self): + """ + + An instance of DetectorDacs used for accessing the dacs of a single + or multi detector. + + Examples + --------- + + :: + + #JungfrauCTB + + + """ + return self._dacs + + @property + def dbitpipeline(self): + return self._api.getDbitPipeline() + + @dbitpipeline.setter + def dbitpipeline(self, value): + self._api.setDbitPipeline(value) + + + @property + def dbitphase(self): + return self._api.getDbitPhase() + + @dbitphase.setter + def dbitphase(self, value): + self._api.setDbitPhase(value) + + @property + def dbitclock(self): + return self._api.getDbitClock() + + @dbitclock.setter + def dbitclock(self, value): + self._api.setDbitClock(value) + + @property + def samples(self): + return self._api.getJCTBSamples() + + @samples.setter + def samples(self, value): + self._api.setJCTBSamples(value) + + @property + def readout_clock(self): + """ + Speed of the readout clock relative to the full speed + + + Examples + --------- + + :: + + + + + """ + return self._api.getReadoutClockSpeed() + + + @readout_clock.setter + def readout_clock(self, value): + self._api.setReadoutClockSpeed(value) diff --git a/python/sls_detector/registers.py b/python/sls_detector/registers.py new file mode 100755 index 000000000..48e6f2306 --- /dev/null +++ b/python/sls_detector/registers.py @@ -0,0 +1,18 @@ +from .decorators import error_handling, property_error_handling +class Register: + def __init__(self, detector): + self._detector = detector + + @property_error_handling + def __getitem__(self, key): + return self._detector._api.readRegister(key) + + def __setitem__(self, key, value): + self._detector._api.writeRegister(key, value) + +class Adc_register: + def __init__(self, detector): + self._detector = detector + + def __setitem__(self, key, value): + self._detector._api.writeAdcRegister(key, value) \ No newline at end of file diff --git a/python/sls_detector/utils.py b/python/sls_detector/utils.py new file mode 100755 index 000000000..b4f93fb12 --- /dev/null +++ b/python/sls_detector/utils.py @@ -0,0 +1,32 @@ +""" +Utility functions that are useful for testing and troubleshooting +but not directly used in controlling the detector +""" + + +def all_equal(mylist): + """If all elements are equal return true otherwise false""" + return all(x == mylist[0] for x in mylist) + + +def element_if_equal(mylist): + """If all elements are equal return only one element""" + if all_equal(mylist): + if len(mylist) == 0: + return None + else: + return mylist[0] + else: + return mylist + + +def eiger_register_to_time(register): + """ + Decode register value and return time in s. Values are stored in + a 32bit register with bits 2->0 containing the exponent and bits + 31->3 containing the significand (int value) + + """ + clocks = register >> 3 + exponent = register & 0b111 + return clocks*10**exponent / 100e6 diff --git a/python/sphinx/Makefile b/python/sphinx/Makefile new file mode 100755 index 000000000..7b6f690fb --- /dev/null +++ b/python/sphinx/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = python -msphinx +SPHINXPROJ = sls_detector_tools +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/python/sphinx/_static/tp_scurve.png b/python/sphinx/_static/tp_scurve.png new file mode 100755 index 000000000..0ca71c2d9 Binary files /dev/null and b/python/sphinx/_static/tp_scurve.png differ diff --git a/python/sphinx/_static/untrimmed.png b/python/sphinx/_static/untrimmed.png new file mode 100755 index 000000000..86f620800 Binary files /dev/null and b/python/sphinx/_static/untrimmed.png differ diff --git a/python/sphinx/code_quality.rst b/python/sphinx/code_quality.rst new file mode 100755 index 000000000..9fe47c1fe --- /dev/null +++ b/python/sphinx/code_quality.rst @@ -0,0 +1,134 @@ +Code quality +============================= + +For usability and reliability of the software the code needs to be high quality. For this +project it means meeting the four criteria described below. Any addition should pass all of +them. + + +-------------------------------- +Look, read and feel like Python +-------------------------------- + +When using classes and functions from the +package it should feel like you are using Python tools and be forces +to write C++ style code with Python syntax. + +:: + + with xray_box.shutter_open(): + for th in threshold: + d.vthreshold = th + d.acq() + +should be preferred over + +:: + + N = len(threshold) + xray_box.open_shutter() + for i in range(N): + d.dacs.set_dac('vthreshold', threshold[i]) + d.acq() + xray_box.close_shutter() + +even if the difference might seem small. + +-------------------- +Have documentation +-------------------- + +Classes and functions should be documented with doc-strings +in the source code. Preferably with examples. The syntax to be used +is numpy-sphinx. + +:: + + def function(arg): + """ + This is a function that does something + + Parameters + ---------- + arg: int + An argument + + Returns + -------- + value: double + Returns a value + + """ + return np.sin(arg+np.pi) + +--------------------------------- +Pass static analysis with pylint +--------------------------------- + +Yes, anything less than 9/10 just means that you are lazy. If +there is a good reason why to diverge, then we can always +add an exception. + +Currently the following additions are made: + + * good-names: x, y, ax, im etc. + * function arguments 10 + * Whitelist: numpy, _sls + + + +----------------------- +Tested code +----------------------- + +Last but not least... *actually last just because of the long list included.* +All code that goes in should have adequate tests. If a new function does not +have a minimum of one test it does not get added. + +**Unit-tests with pytest and mocker** + +:: + + ----------- coverage: platform linux, python 3.6.4-final-0 ----------- + Name Stmts Miss Cover + ------------------------------------------------ + sls_detector/__init__.py 4 0 100% + sls_detector/decorators.py 14 3 79% + sls_detector/detector.py 461 115 75% + sls_detector/eiger.py 150 64 57% + sls_detector/errors.py 7 0 100% + sls_detector/jungfrau.py 59 26 56% + ------------------------------------------------ + TOTAL 695 208 70% + + + ========= 78 passed in 0.60 seconds ========= + + + +**Simple integration tests** + +These tests require a detector connected. Performs simple tasks like setting +exposure time and reading back to double check the value + +:: + + ----------- coverage: platform linux, python 3.6.4-final-0 ----------- + Name Stmts Miss Cover + ------------------------------------------------ + sls_detector/__init__.py 4 0 100% + sls_detector/decorators.py 14 0 100% + sls_detector/detector.py 461 103 78% + sls_detector/eiger.py 150 20 87% + sls_detector/errors.py 7 0 100% + sls_detector/jungfrau.py 59 26 56% + ------------------------------------------------ + TOTAL 695 149 79% + + + ========= 67 passed, 1 skipped in 16.66 seconds ========= + +**Complex integration test** + +Typical measurements. Might require X-rays. Tests are usually evaluated from +plots \ No newline at end of file diff --git a/python/sphinx/command_line.rst b/python/sphinx/command_line.rst new file mode 100755 index 000000000..a57d68696 --- /dev/null +++ b/python/sphinx/command_line.rst @@ -0,0 +1,370 @@ +Command line to Python +========================= + +If you are already familiar with the command line interface to the +slsDetectorSoftware here is a quick reference translating to Python commands + + + .. note :: + + Commands labeled Mythen only or Gotthard only are currently not implemented in the + Python class. If you need this functionallity please contact the SLS Detector Group + +.. py:currentmodule:: sls_detector + +.. |ro| replace:: *(read only)* +.. |free| replace:: :py:func:`Detector.free_shared_memory` +.. |sub| replace:: :py:attr:`Detector.sub_exposure_time` +.. |mg| replace:: Mythen and Gotthard only +.. |g| replace:: Gotthard only +.. |m| replace:: Mythen only +.. |msp| replace:: :py:attr:`Detector.measured_subperiod` +.. |new_chiptest| replace:: New chip test board only +.. |chiptest| replace:: Chip test board only +.. |dr| replace:: :py:attr:`Detector.dynamic_range` +.. |j| replace:: Jungfrau only +.. |te| replace:: :py:attr:`Detector.trimmed_energies` +.. |temp_fpgaext| replace:: :py:attr:`Detector.temp`.fpgaext +.. |epa| replace:: :py:func:`Eiger.pulse_all_pixels` +.. |rfc| replace:: :py:func:`Detector.reset_frames_caught` +.. |rfi| replace:: :py:attr:`Detector.receiver_frame_index` +.. |ron| replace:: :py:attr:`Detector.receiver_online` +.. |flipy| replace:: :py:attr:`Detector.flipped_data_y` +.. |flipx| replace:: :py:attr:`Detector.flipped_data_x` +.. |adcr| replace:: :py:func:`DetectorApi.writeAdcRegister` +.. |sb| replace:: :py:func:`DetectorApi.setBitInRegister` +.. |cb| replace:: :py:func:`DetectorApi.clearBitInRegister` +.. |tempth| replace:: :py:attr:`Jungfrau.temperature_threshold` +.. |tempev| replace:: :py:attr:`Jungfrau.temperature_event` +.. |tempco| replace:: :py:attr:`Jungfrau.temperature_control` +.. |depr| replace:: *Deprecated/Internal* +.. |nimp| replace:: *Not implemented* +.. |rudp| replace:: :py:attr:`Detector.rx_realudpsocksize` +.. |lci| replace:: :py:attr:`Detector.last_client_ip` +.. |rlci| replace:: :py:attr:`Detector.receiver_last_client_ip` +.. |fdp| replace:: :py:attr:`Detector.frame_discard_policy` +.. |apic| replace:: :py:attr:`Detector.api_compatibility` + + +------------------------ +Commands +------------------------ + +===================== ===================================== ================== ========= +Command Python Implementation Tests +===================== ===================================== ================== ========= +sls_detector_acquire :py:func:`Detector.acq` OK OK +test |depr| \- \- +help help(Detector.acq) \- \- +exitserver |depr| \- \- +exitreceiver |depr| \- \- +flippeddatay |flipy| OK \- +digitest |depr| \- \- +bustest |depr| \- \- +digibittest Which detector? \- \- +reg :py:attr:`Detector.register` OK \- +adcreg |adcr| OK \- +setbit |sb| OK \- +clearbit |cb| OK \- +getbit |nimp| \- \- +r_compression Not implemented in receiver \- \- +acquire :py:func:`Detector.acq` OK \- +busy :py:attr:`Detector.busy` OK Partial +status :py:attr:`Detector.status` OK |ro| \- +status start :py:func:`Detector.start_detector` OK \- +status stop :py:func:`Detector.stop_detector` OK \- +data |depr| \- \- +frame |depr| \- \- +readctr |g| \- \- +resetctr |g| \- \- +resmat :py:attr:`Eiger.eiger_matrix_reset` OK OK +free |free| OK \- +hostname :py:attr:`Detector.hostname` OK OK +add |nimp| \- \- +replace |nimp| \- \- +user |nimp| \- \- +master |nimp| \- \- +sync Which detector? \- \- +online :py:attr:`Detector.online` OK \- +checkonline |nimp| \- \- +activate :py:attr:`Eiger.active` \- \- +nmod :py:attr:`Detector.n_modules` OK \- +maxmod |depr| \- \- +dr |dr| OK OK +roi |g| \- \- +detsizechan :py:attr:`Detector.image_size` OK \- +roimask |nimp| \- \- +flippeddatax |flipx| OK \- +tengiga :py:attr:`Eiger.tengiga` OK \- +gappixels :py:attr:`Eiger.add_gappixels` OK \- +flags :py:attr:`Detector.flags` OK \- +extsig |mg| \- \- +programfpga |j| \- \- +resetfpga |j| \- \- +powerchip :py:attr:`Jungfrau.powerchip` \- \- +led |nimp| \- \- +auto_comp_disable |j| \- \- +pulse Used in |epa| OK \- +pulsenmove Used in |epa| OK \- +pulsechip :py:func:`Eiger.pulse_chip` OK \- +checkdetversion |apic| \- \- +checkrecversion |apic| \- \- +moduleversion |m| \- \- +detectornumber :py:attr:`Detector.detector_number` OK \- +modulenumber |m| \- \- +detectorversion :py:attr:`Detector.firmware_version` OK OK +softwareversion :py:attr:`Detector.server_version` \- \- +thisversion :py:attr:`Detector.client_version` Reads date \- +receiverversion :py:attr:`Detector.receiver_version` Reads date \- +timing :py:attr:`Detector.timing_mode` OK \- +exptime :py:attr:`Detector.exposure_time` OK OK +subexptime |sub| OK OK +period :py:attr:`Detector.period` OK OK +subdeadtime :py:attr:`Eiger.sub_deadtime` OK OK +delay :py:attr:`Jungfrau.delay` OK \- +gates :py:attr:`Jungfrau.n_gates` OK \- +frames :py:attr:`Detector.n_frames` OK OK +cycles :py:attr:`Detector.n_cycles` OK \- +probes :py:attr:`Jungfrau.n_probes` OK \- +measurements :py:attr:`Detector.n_measurements` OK \- +samples Chip test board only (new?) \- \- +storagecells :py:attr:`Jungfrau.n_storagecells` OK \- +storagecell_start :py:attr:`Jungfrau.storagecell_start` OK \- +exptimel |mg| \- \- +periodl |mg| \- \- +delayl |mg| \- \- +gatesl |mg| \- \- +framesl |mg| \- \- +cyclesl |mg| \- \- +probesl |mg| \- \- +now |nimp| \- \- +timestamp |m| \- \- +nframes |nimp| \- \- +measuredperiod :py:attr:`Detector.measured_period` OK \- +measuredsubperiod |msp| \- \- +clkdivider :py:attr:`Detector.readout_clock` OK OK +setlength |m| \- \- +waitstates |m| \- \- +totdivider |m| \- \- +totdutycycle |m| \- \- +phasestep |g| \- \- +oversampling |new_chiptest| \- \- +adcclk |new_chiptest| \- \- +adcphase |new_chiptest| \- \- +adcpipeline |new_chiptest| \- \- +dbitclk |new_chiptest| \- \- +dbitphase |new_chiptest| \- \- +dbitpipeline |new_chiptest| \- \- +config :py:func:`Detector.load_config` OK \- +rx_printconfig |nimp| \- \- +parameters :py:func:`Detector.load_parameters` OK \- +setup |nimp| \- \- +flatfield |nimp| \- \- +ffdir |nimp| \- \- +ratecorr :py:attr:`Detector.rate_correction` OK \- +badchannels |nimp| \- \- +angconv |m| \- \- +globaloff |nimp| \- \- +fineoff |nimp| \- \- +binsize |nimp| \- \- +angdir |nimp| \- \- +moveflag |nimp| \- \- +samplex |nimp| \- \- +sampley |nimp| \- \- +threaded :py:attr:`Detector.threaded` OK \- +darkimage |nimp| \- \- +gainimage |nimp| \- \- +settingsdir :py:attr:`Detector.settings_path` OK \- +trimdir |nimp| \- \- +caldir |nimp| \- \- +trimen :py:attr:`Detector.trimmed_energies` OK \- +settings :py:attr:`Detector.settings` OK \- +threshold :py:attr:`Detector.threshold` OK \- +thresholdnotb |nimp| \- \- +trimbits :py:func:`Detector.load_trimbits` OK \- +trim |nimp| \- \- +trimval :py:attr:`Detector.trimbits` OK OK +pedestal |nimp| \- \- +vthreshold :py:attr:`Detector.vthreshold` OK \- +vcalibration |nimp| \- \- +vtrimbit |nimp| \- \- +vpreamp |nimp| \- \- +vshaper1 |nimp| \- \- +vshaper2 |nimp| \- \- +vhighvoltage :py:attr:`Detector.high_voltage` OK \- +vapower |nimp| \- \- +vddpower |nimp| \- \- +vshpower |nimp| \- \- +viopower |nimp| \- \- +vref_ds :py:attr:`Jungfrau.dacs.vref_ds` OK \- +vcascn_pb |nimp| \- \- +vcascp_pb |nimp| \- \- +vout_cm |nimp| \- \- +vcasc_out |nimp| \- \- +vin_cm |nimp| \- \- +vref_comp |nimp| \- \- +ib_test_c |nimp| \- \- +dac0 |nimp| \- \- +dac1 |nimp| \- \- +dac2 |nimp| \- \- +dac3 |nimp| \- \- +dac4 |nimp| \- \- +dac5 |nimp| \- \- +dac6 |nimp| \- \- +dac7 |nimp| \- \- +vsvp :py:attr:`Eiger.dacs.vsvp` OK \- +vsvn :py:attr:`Eiger.dacs.vsvn` OK \- +vtr :py:attr:`Eiger.dacs.vtr` OK \- +vrf :py:attr:`Eiger.dacs.vrf` OK \- +vrs :py:attr:`Eiger.dacs.vrs` OK \- +vtgstv :py:attr:`Eiger.dacs.vtgstv` OK \- +vcmp_ll :py:attr:`Eiger.dacs.vcmp_ll` OK \- +vcmp_ll :py:attr:`Eiger.dacs.vcmp_ll` OK \- +vcall :py:attr:`Eiger.dacs.vcall` OK \- +vcmp_rl :py:attr:`Eiger.dacs.vcmp_rl` OK \- +vcmp_rr :py:attr:`Eiger.dacs.vcmp_rr` OK \- +rxb_rb :py:attr:`Eiger.dacs.rxb_rb` OK \- +rxb_lb :py:attr:`Eiger.dacs.rxb_lb` OK \- +vcp :py:attr:`Eiger.dacs.vcp` OK \- +vcn :py:attr:`Eiger.dacs.vcn` OK \- +vis :py:attr:`Eiger.dacs.vis` OK \- +iodelay :py:attr:`Eiger.dacs.iodelay` OK \- +dac |nimp| \- \- +adcvpp |nimp| \- \- +v_a |nimp| \- \- +v_b |nimp| \- \- +v_c |nimp| \- \- +v_d |nimp| \- \- +v_io |nimp| \- \- +v_chip |nimp| \- \- +v_limit |nimp| \- \- +vIpre |nimp| \- \- +VcdSh |nimp| \- \- +Vth1 |nimp| \- \- +Vth2 |nimp| \- \- +Vth3 |nimp| \- \- +VPL |nimp| \- \- +Vtrim |nimp| \- \- +vIbias |nimp| \- \- +vIinSh |nimp| \- \- +cas |nimp| \- \- +casSh |nimp| \- \- +vIbiasSh |nimp| \- \- +vIcin |nimp| \- \- +vIpreOut |nimp| \- \- +temp_adc |nimp| \- \- +temp_fpga :py:attr:`Detector.temp`.fpga OK \- +temp_fpgaext |temp_fpgaext| OK \- +temp_10ge :py:attr:`Detector.temp`.t10ge OK \- +temp_dcdc :py:attr:`Detector.temp`.dcdc OK \- +temp_sodl :py:attr:`Detector.temp`.sodl OK \- +temp_sodr :py:attr:`Detector.temp`.sodr OK \- +adc |nimp| \- \- +temp_fpgafl :py:attr:`Detector.temp`.fpgafl OK \- +temp_fpgafr :py:attr:`Detector.temp`.fpgafr OK \- +i_a |nimp| \- \- +i_b |nimp| \- \- +i_c |nimp| \- \- +i_d |nimp| \- \- +i_io |nimp| \- \- +vm_a |nimp| \- \- +vm_b |nimp| \- \- +vm_c |nimp| \- \- +vm_d |nimp| \- \- +vm_io |nimp| \- \- +temp_threshold |tempth| \- \- +temp_control |tempco| \- \- +temp_event |tempev| \- \- +outdir :py:attr:`Detector.file_path` OK OK +fname :py:attr:`Detector.file_name` OK OK +index :py:attr:`Detector.file_index` OK OK +enablefwrite :py:attr:`Detector.file_write` OK OK +overwrite :py:attr:`Detector.file_overwrite` OK \- +currentfname |nimp| \- \- +fileformat :py:attr:`Detector.file_format` OK \- +positions |depr| \- \- +startscript |depr| \- \- +startscriptpar |depr| \- \- +stopscript |depr| \- \- +stopscriptpar |depr| \- \- +scriptbefore |depr| \- \- +scriptbeforepar |depr| \- \- +scriptafter |depr| \- \- +scriptafterpar |depr| \- \- +headerafter |depr| \- \- +headerbefore |depr| \- \- +headerbeforepar |depr| \- \- +headerafterpar |depr| \- \- +encallog |depr| \- \- +angcallog |depr| \- \- +scan0script |depr| \- \- +scan0par |depr| \- \- +scan0prec |depr| \- \- +scan0steps |depr| \- \- +scan0range |depr| \- \- +scan1script |depr| \- \- +scan1par |depr| \- \- +scan1prec |depr| \- \- +scan1steps |depr| \- \- +scan1range |depr| \- \- +rx_hostname :py:attr:`Detector.rx_hostname` OK \- +rx_udpip :py:attr:`Detector.rx_udpip` OK \- +rx_udpmac :py:attr:`Detector.rx_udpmac` OK \- +rx_udpport :py:attr:`Detector.rx_udpport` OK \- +rx_udpport2 :py:attr:`Detector.rx_udpport` OK \- +rx_udpsocksize :py:attr:`Detector.rx_udpsocksize` OK \- +rx_realudpsocksize |rudp| OK +detectormac :py:attr:`Detector.detector_mac` OK \- +detectorip :py:attr:`Detector.detector_ip` OK \- +txndelay_left :py:attr:`Eiger.delay`.left OK \- +txndelay_right :py:attr:`Eiger.delay`.right OK \- +txndelay_frame :py:attr:`Eiger.delay`.frame OK \- +flowcontrol_10g :py:attr:`Eiger.flowcontrol_10g` OK \- +zmqport :py:attr:`Detector.client_zmqport` Read \- +rx_zmqport :py:attr:`Detector.rx_zmqport` Read \- +rx_datastream :py:attr:`Detector.rx_datastream` OK \- +zmqip :py:attr:`Detector.client_zmqip` OK \- +rx_zmqip :py:attr:`Detector.rx_zmqip` Read \- +rx_jsonaddheader :py:attr:`Detector.rx_jsonaddheader` OK \- +configuremac :py:attr:`Detector.config_network` OK \- +rx_tcpport :py:attr:`Detector.rx_tcpport` +port |nimp| \- \- +stopport |nimp| \- \- +lock :py:attr:`Detector.lock` OK \- +lastclient :py:attr:`Detector.last_client_ip` OK \- +receiver start :py:func:`Detector.start_receiver` OK \- +receiver stop :py:func:`Detector.stop_receiver` \- \- +r_online |ron| OK \- +r_checkonline |nimp| \- \- +framescaught :py:attr:`Detector.frames_caught` OK \- +resetframescaught |rfc| OK \- +frameindex |rfi| OK \- +r_lock :py:attr:`Detector.lock_receiver` OK \- +r_lastclient |rlci| OK \- +r_readfreq |nimp| \- \- +rx_fifodepth :py:attr:`Detector.rx_fifodepth` OK \- +r_silent |nimp| \- \- +r_framesperfile :py:attr:`Detector.n_frames_per_file` OK \- +r_discardpolicy |fdp| OK \- +r_padding :py:attr:`Detector.file_padding` OK \- +adcinvert |chiptest| \- \- +adcdisable |chiptest| \- \- +pattern |chiptest| \- \- +patword |chiptest| \- \- +patioctrl |chiptest| \- \- +patclkctrl |chiptest| \- \- +patlimits |chiptest| \- \- +patloop0 |chiptest| \- \- +patnloop0 |chiptest| \- \- +patwait0 |chiptest| \- \- +patwaittime0 |chiptest| \- \- +patloop1 |chiptest| \- \- +patnloop1 |chiptest| \- \- +patwait1 |chiptest| \- \- +patwaittime1 |chiptest| \- \- +patloop2 |chiptest| \- \- +patnloop2 |chiptest| \- \- +patwait2 |chiptest| \- \- +patwaittime2 |chiptest| \- \- +dut_clk |chiptest| \- \- +===================== ===================================== ================== ========= \ No newline at end of file diff --git a/python/sphinx/conf.py b/python/sphinx/conf.py new file mode 100755 index 000000000..bb228ce4c --- /dev/null +++ b/python/sphinx/conf.py @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# sls_detector_tools documentation build configuration file, created by +# sphinx-quickstart on Wed Nov 1 10:17:29 2017. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys +sys.path.insert(0, os.path.abspath('..')) + + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = ['sphinx.ext.autodoc', + 'sphinx.ext.doctest', + 'sphinx.ext.coverage', + 'sphinx.ext.mathjax', + 'sphinx.ext.viewcode', + 'sphinx.ext.napoleon', + 'sphinx.ext.todo', + 'sphinx.ext.autosummary'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'sls_detector' +copyright = '2019, Sls Detector Group' +author = 'Erik Frojdh' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '4.0.1' +# The full version, including alpha/beta/rc tags. +release = '4.0.1' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = "sphinx_rtd_theme" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Custom sidebar templates, must be a dictionary that maps document names +# to template names. +# +# This is required for the alabaster theme +# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars +html_sidebars = { + '**': [ + 'about.html', + 'navigation.html', + 'relations.html', # needs 'show_related': True theme option to display + 'searchbox.html', + 'donate.html', + ] +} + + +# -- Options for HTMLHelp output ------------------------------------------ + +# Output file base name for HTML help builder. +htmlhelp_basename = 'sls_detector_doc' +napoleon_use_ivar = True + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'sls_detector.tex', 'sls_detector Documentation', + 'Erik Frojdh', 'manual'), +] + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'sls_detector_tools', 'sls_detector_tools Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'py_sls', 'py_sls Documentation', + author, 'py_sls', 'One line description of project.', + 'Miscellaneous'), +] + + diff --git a/python/sphinx/cpp_api.rst b/python/sphinx/cpp_api.rst new file mode 100755 index 000000000..839dbac3f --- /dev/null +++ b/python/sphinx/cpp_api.rst @@ -0,0 +1,12 @@ +C++ API +===================================================== + + +.. py:currentmodule:: _sls_detector + +.. autoclass:: DetectorApi + :members: + :undoc-members: + + + diff --git a/python/sphinx/error-handling.rst b/python/sphinx/error-handling.rst new file mode 100755 index 000000000..56b3ddd46 --- /dev/null +++ b/python/sphinx/error-handling.rst @@ -0,0 +1,67 @@ +Error handling +========================= + + +Check input in Python +---------------------- + +As far as possible we try to check the input on the Python side +before calling the slsDeteectorsSoftware. Errors should not pass +silently but raise an exception + +:: + + #Trimbit range for Eiger is 0-63 + detector.trimbits = 98 + (...) + ValueError: Trimbit setting 98 is outside of range:0-63 + +Errors in slsDetectorsSoftware +------------------------------- + +The slsDetectorsSoftware uses a mask to record errors from the different +detectors. If an error is found we raise a RuntimeError at the end of the +call using the error message from slsDetectorsSoftware + +.. todo :: + + Implement this for all functions + +:: + + detector.settings = 'bananas' + (...) + RuntimeError: Detector 0: + Could not set settings. + Detector 1: + Could not set settings. + Detector 2: + Could not set settings. + + +Using decorators +------------------- + +Using decorators we can reset the error mask before the command and then +check it after the command + +.. code-block:: python + + #add decorator to check the error mask + @error_handling + def some_function(): + a = 1+1 + return a + +Communication with the detector is usually the biggest overhead so +this does not impact performance. + +:: + + %timeit d.exposure_time + >> 1.52 ms ± 5.42 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) + + %timeit d.decorated_exposure_time + >> 1.53 ms ± 3.18 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) + + diff --git a/python/sphinx/examples.rst b/python/sphinx/examples.rst new file mode 100755 index 000000000..f3bc7d478 --- /dev/null +++ b/python/sphinx/examples.rst @@ -0,0 +1,143 @@ +Examples +================ + +Some short hints on how to use the detector + +------------------------ +Simple threshold scan +------------------------ + +Assuming you have set up your detector with exposure time, period, enabled +file writing etc. + +.. code-block:: python + + from sls_detector import Eiger + + d = Eiger() + threshold = range(0, 2000, 200) + for th in threshold: + d.vthreshold = th + d.acq() + + +If we want to control the shutter of for example, the big X-ray box we can add +this line in our code. It then opens the shutter just before the measurement +and closes is afterwards. + +:: + + with xrf_shutter_open(box, 'Fe'): + for th in threshold: + d.vthreshold = th + d.acq() + + +----------------------- +Reading temperatures +----------------------- + +:: + + d.temp + >> + temp_fpga : 43.19°C, 51.83°C + temp_fpgaext : 38.50°C, 38.50°C + temp_10ge : 39.50°C, 39.50°C + temp_dcdc : 42.50°C, 42.50°C + temp_sodl : 39.50°C, 40.50°C + temp_sodr : 39.50°C, 40.50°C + temp_fpgafl : 40.87°C, 37.61°C + temp_fpgafr : 34.51°C, 35.63°C + + d.temp.fpga + >> temp_fpga : 40.84°C, 39.31°C + + t = d.temp.fpga[0] + t + >> 40.551 + + t = d.temp.fpga[:] + t + >> [40.566, 39.128] + + +----------------------- +Non blocking acquire +----------------------- + +There are mainly two ways to achieve a non blocking acquire when calling from the Python API. One is to manually start +the detector and the second one is to launch the normal acquire from a different process. Depending on your measurement +it might also be better to run the other task in a seperate process and use acq in the main thread. +But lets start looking at the at the manual way: + +:: + + import time + from sls_detector import Eiger + d = Eiger() + + n = 10 + t = 1 + + d.exposure_time = t + d.n_frames = n + d.reset_frames_caught() + + #Start the measurement + t0 = time.time() + d.start_receiver() + d.start_detector() + + #Wait for the detector to be ready or do other important stuff + time.sleep(t*n) + + #check if the detector is ready otherwise wait a bit longer + while d.status != 'idle': + time.sleep(0.1) + + #Stop the receiver after we got the frames + #Detector is already idle so we don't need to stop it + d.stop_receiver() + + lost = d.frames_caught - n + print(f'{n} frames of {t}s took {time.time()-t0:{.3}}s with {lost} frames lost ') + + #Reset to not interfere with a potential next measurement + d.reset_frames_caught() + +Instead launching d.acq() from a different process is a bit easier since the control of receiver and detector +is handled in the acq call. However, you need to join the process used otherwise a lot of zombie processes would +hang around until the main process exits. + +:: + + import time + from multiprocessing import Process + from sls_detector import Eiger + + def acquire(): + """ + Create a new Eiger object that still referes to the same actual detector + and same shared memory. Then launch acq. + """ + detector = Eiger() + detector.acq() + + #This is the detector we use throughout the session + d = Eiger() + + #Process to run acquire + p = Process(target=acquire) + + #Start the thread and short sleep to allow the acq to start + p.start() + time.sleep(0.01) + + #Do some other work + while d.busy is True: + print(d.busy) + time.sleep(0.1) + + #Join the process + p.join() \ No newline at end of file diff --git a/python/sphinx/getting_started.rst b/python/sphinx/getting_started.rst new file mode 100755 index 000000000..b5b464474 --- /dev/null +++ b/python/sphinx/getting_started.rst @@ -0,0 +1,122 @@ +Getting started +================ + + +------------------------ +Setting up the detector +------------------------ + +All configuration of the detector can either be done from the Python +API (including loading config file) or externally. The detector setup is +discovered from the shared memory when launching a new script. Because the +detector usually should remain online longer than a specific script it is +recommended to run the receivers seperate. + +--------------------------------- +Setting and getting attributes +--------------------------------- + +Most of the detector and software setting are implemented as attributes +in the Detector class. When something is assigned it is also set +in the detector and when the attribute is called using dot notation it +it looked up from the detector. + +:: + + #Currently Eiger and Jungfrau but Detector should work for all + from sls_detector import Eiger() + d = Eiger() + + d.file_write = True + d.vthreshold = 1500 + + d.frame_index + >> 12 + + d.file_name + >> 'run' + +--------------------------------- +Working with DACs +--------------------------------- + +The following examples assumes an Eiger500k detector. But the same syntax +works for other detector sizes and models. + +:: + + d.dacs + >> + ========== DACS ========= + vsvp : 0, 0 + vtr : 4000, 4000 + vrf : 2000, 2300 + vrs : 1400, 1400 + vsvn : 4000, 4000 + vtgstv : 2556, 2556 + vcmp_ll : 1500, 1500 + vcmp_lr : 1500, 1500 + vcall : 3500, 3600 + vcmp_rl : 1500, 1500 + rxb_rb : 1100, 1100 + rxb_lb : 1100, 1100 + vcmp_rr : 1500, 1500 + vcp : 1500, 1500 + vcn : 2000, 2000 + vis : 1550, 1550 + iodelay : 660, 660 + + #Read dac values to a variable + vrf = d.dacs.vrf[:] + + #Set a dac in a module + d.dacs.vrf[0] = 1500 + d.dacs.vrf[0] + >> 1500 + + #Set vrf to the same value in all moduels + d.dacs.vrf = 1500 + + #Set a dac using an iterable + d.dacs.vrf = [1500, 1600] + d.dacs.vrf + >> vrf : 1500, 1600 + + #Set dacs iterating on index and values + d.dacs.vrf[0,1] = 1300,1400 + + +--------------------------------- +Operating multiple detectors +--------------------------------- + +Operating multiple detectors is supported by assigning an id when creating the object. If no id is +set it defaults to 0. + +:: + + d0 = Eiger() #id is now 0 + d1 = Jungfrau(1) + + #Or explicitly + d1 = Jungfrau(id = 0) + +The detectors now operate independently of each other but can be synchronized using a hardware trigger. + +:: + + from sls_detector import Eiger + + d0 = Eiger(0) + d1 = Eiger(1) + + d0.load_config('/some/path/T45.config') + d1.load_config('/some/path/T62.config') + + d0.n_frames = 1 + d0.exposure_time = 1 + d0.timing_mode = 'trigger' + + d1.n_frames = 5 + d1.exposure_time = 0.2 + d1.timing_mode = 'trigger' \ No newline at end of file diff --git a/python/sphinx/index.rst b/python/sphinx/index.rst new file mode 100755 index 000000000..ae114adac --- /dev/null +++ b/python/sphinx/index.rst @@ -0,0 +1,30 @@ +sls_detector - Python interface for the slsDetectorsPackage +============================================================== + +sls_detector provide Python bindings to the slsDetectorsPackage using mainly the +multiSlsDetector API. This module contains two parts, a compiled C module to +expose the API and a Python class to offer a more Pythonic interface. + + +.. toctree:: + :maxdepth: 3 + :caption: Contents: + + installation + getting_started + code_quality + command_line + examples + error-handling + + sls_detector + cpp_api + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/python/sphinx/installation.rst b/python/sphinx/installation.rst new file mode 100755 index 000000000..f17920876 --- /dev/null +++ b/python/sphinx/installation.rst @@ -0,0 +1,90 @@ +Installation +========================= + +The easiest way to install the Python API and the slsDetectorPackage is using conda. But other +methods are also available. + +--------------------- +Install using conda +--------------------- +If you don't have it installed get the latest version of `Miniconda`_ + +.. _Miniconda: https://conda.io/miniconda.html + +:: + + wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh + sh Miniconda3-latest-Linux-x86_64.sh + + +Install sls_detector and sls_detector_lib using: + +:: + + #Add conda channels + conda config --add channels conda-forge + conda config --add channels slsdetectorgroup + + #Install latest version + conda install sls_detector + + #Install specific version + conda install sls_detector=3.0.1 + +------------------------------ +Local build using conda-build +------------------------------ + +Needs the `sls_detector_lib`_ installed in order to automatically find headers +and shared libraries. Make sure that the branch of sls_detector matches the lib +version installed. + +.. _sls_detector_lib: https://github.com/slsdetectorgroup/sls_detector_lib + +:: + + #Clone source code + git clone https://github.com/slsdetectorgroup/sls_detector.git + + #Checkout the branch needed + git checkout 3.0.1 + + #Build and install the local version + conda-build sls_detector + conda install --use-local sls_detector + + +----------------------- +Developer build +----------------------- + +IF you if you are developing and are making constant changes to the code it's a bit cumbersome +to build with conda and install. Then an easier way is to build the C/C++ parts in the package +directory and temporary add this to the path + +:: + + #in path/to/sls_detector + python setup.py build_ext --inplace + +Then in your Python script + +:: + + import sys + sys.path.append('/path/to/sls_detector') + from sls_detector import Detector + + + +-------------- +Prerequisites +-------------- + +All dependencies are manged trough conda but for a stand alone build you would need + + * gcc 4.8+ + * Qwt 6 + * Qt 4.8 + * numpy + * slsDetectorPackage diff --git a/python/sphinx/makedocs.sh b/python/sphinx/makedocs.sh new file mode 100755 index 000000000..b3773381f --- /dev/null +++ b/python/sphinx/makedocs.sh @@ -0,0 +1,6 @@ +make clean +make html +rm -rf ../docs/ +mv _build/html/ ../docs/ +touch ../docs/.nojekyll +rm -rf _build diff --git a/python/sphinx/modules.rst b/python/sphinx/modules.rst new file mode 100755 index 000000000..731034e95 --- /dev/null +++ b/python/sphinx/modules.rst @@ -0,0 +1,8 @@ +sls_detector +================== + +.. toctree:: + :maxdepth: 4 + + sls_detector + diff --git a/python/sphinx/sls_detector.rst b/python/sphinx/sls_detector.rst new file mode 100755 index 000000000..15df97e89 --- /dev/null +++ b/python/sphinx/sls_detector.rst @@ -0,0 +1,33 @@ +Python classes +===================================================== + + +.. py:currentmodule:: sls_detector + +Detector +---------- + +.. autoclass:: Detector + :members: + :undoc-members: + :show-inheritance: + + + +Eiger +------- + +.. autoclass:: Eiger + :members: + :undoc-members: + :show-inheritance: + + + +Jungfrau +---------- + +.. autoclass:: Jungfrau + :members: + :undoc-members: + :show-inheritance: diff --git a/python/src/Detector.h b/python/src/Detector.h new file mode 100755 index 000000000..ea9225642 --- /dev/null +++ b/python/src/Detector.h @@ -0,0 +1,964 @@ +#ifndef DETECTOR_H +#define DETECTOR_H +#include +#include +#include +#include + +#include + +#include "error_defs.h" +#include "multiSlsDetector.h" +#include "slsDetector.h" +// #include "slsDetectorUtils.h" +#include "sls_detector_defs.h" +// #include "sls_receiver_defs.h" + +class Detector { + public: + Detector(int i) : det(i), multi_detector_id(i) { + // Disable output from std::cout + // std::cout.setstate(std::ios_base::failbit); + } + + int getMultiDetectorId() { return multi_detector_id; } + + // get image size as [nrow, ncols] return as a pair of ints + std::pair getImageSize() { + std::pair image_size{0, 0}; + image_size.first = det.getMaxNumberOfChannelsPerDetector( + slsDetectorDefs::dimension::Y); + image_size.second = det.getMaxNumberOfChannelsPerDetector( + slsDetectorDefs::dimension::X); + return image_size; + } + + void setImageSize(const int rows, const int cols) { + det.setMaxNumberOfChannelsPerDetector(slsDetectorDefs::dimension::Y, + rows); + det.setMaxNumberOfChannelsPerDetector(slsDetectorDefs::dimension::X, + cols); + } + + // blocking command, acquire set number of frames + void acquire() { det.acquire(); } + + // for Eiger check status of the module + // true active false deactivated + bool getActive(int i) { return det.activate(-1, i); } + // activate or deactivate a module + void setActive(int i, bool value) { det.activate(value, i); } + + int getFramesCaughtByReceiver() { + return det.getFramesCaughtByReceiver(); + // return det.getFramesCaughtByReceiver(); + } + int getFramesCaughtByReceiver(int i) { + return det.getFramesCaughtByReceiver(i); + } + + void setReceiverFifoDepth(int n_frames) { + det.setReceiverFifoDepth(n_frames); + } + + void setNumberOfStorageCells(const int64_t num) { + det.setTimer(slsDetectorDefs::timerIndex::STORAGE_CELL_NUMBER, num); + } + int getNumberOfStorageCells() { + return det.setTimer(slsDetectorDefs::timerIndex::STORAGE_CELL_NUMBER, + -1); + } + + void setStoragecellStart(int cell) { det.setStoragecellStart(cell); } + + int getStoragecellStart() { return det.setStoragecellStart(); } + + int getReceiverFifoDepth() { return det.setReceiverFifoDepth(); } + + void resetFramesCaught() { det.resetFramesCaught(); } + + int getReceiverCurrentFrameIndex() { + return det.getReceiverCurrentFrameIndex(); + } + + std::string getReceiverHostname(int det_id = -1) const { + return det.getReceiverHostname(det_id); + } + + void setReceiverHostname(std::string hostname, int det_id = -1) { + det.setReceiverHostname(hostname, det_id); + } + + std::string getReceiverUDPIP(int det_id = -1) const { + return det.getReceiverUDPIP(det_id); + } + + void setReceiverUDPIP(std::string ip, int det_id = -1) { + det.setReceiverUDPIP(ip, det_id); + } + + std::string getReceiverUDPMAC(int det_id = -1) { + return det.getReceiverUDPMAC(det_id); + } + + void setReceiverUDPMAC(std::string mac, int det_id = -1) { + det.setReceiverUDPMAC(mac, det_id); + } + + void startReceiver() { det.startReceiver(); } + void stopReceiver() { det.stopReceiver(); } + + bool getTenGigabitEthernet() { return det.enableTenGigabitEthernet(); } + void setTenGigabitEthernet(bool value) { + det.enableTenGigabitEthernet(value); + } + + void setFileFormat(const std::string &format); + std::string getFileFormat(); + + std::string checkOnline() { return det.checkOnline(); } + + bool getReceiverOnline() { return det.setReceiverOnline(); } + void setReceiverOnline(const bool status) { det.setReceiverOnline(status); } + + bool getOnline() { return det.setOnline(); } + void setOnline(const bool status) { det.setOnline(status); } + + bool isChipPowered() { return det.powerChip(); } + void powerChip(const bool value) { det.powerChip(value); } + + // read register from readout system, used for low level control + uint32_t readRegister(const uint32_t addr) { + return det.readRegister(addr); + } + + // directly write to register in readout system + void writeRegister(const uint32_t addr, const uint32_t value) { + det.writeRegister(addr, value); + } + + // directly write to the ADC register + // should this also be unsigned? Probably... + void writeAdcRegister(const int addr, const int value) { + det.writeAdcRegister(addr, value); + } + + void setBitInRegister(const uint32_t reg_addr, const int bit_number) { + det.setBit(reg_addr, bit_number); + } + void clearBitInRegister(const uint32_t reg_addr, const int bit_number) { + det.clearBit(reg_addr, bit_number); + } + + bool getAcquiringFlag() { return det.getAcquiringFlag(); } + + void setAcquiringFlag(const bool flag) { det.setAcquiringFlag(flag); } + + bool getCounterBit() { return det.setCounterBit(); } + void setCounterBit(bool b) { det.setCounterBit(b); } + + slsDetectorDefs::dacIndex dacNameToEnum(std::string dac_name); + + std::pair getDetectorGeometry() { + std::pair g; + det.getNumberOfDetectors(g.first, g.second); + return g; + } + + int getNumberOfDetectors() { return det.getNumberOfDetectors(); } + + std::string getRunStatus() { + auto s = det.getRunStatus(); + return det.runStatusType(s); + } + + void startAcquisition() { det.startAcquisition(); } + void stopAcquisition() { det.stopAcquisition(); } + + std::string getHostname() { return det.getHostname(); } + + void setHostname(std::string hostname) { + det.setHostname(hostname.c_str()); + } + + int getDynamicRange() { return det.setDynamicRange(-1); } + void setDynamicRange(const int dr) { det.setDynamicRange(dr); } + + void pulseChip(const int n) { det.pulseChip(n); } + void pulseAllPixels(const int n); + void pulseDiagonal(const int n); + + void readConfigurationFile(std::string fname) { + det.readConfigurationFile(fname); + } + void readParametersFile(std::string fname) { + det.retrieveDetectorSetup(fname); + } + + int64_t getFirmwareVersion() { + return det.getId(slsDetectorDefs::DETECTOR_FIRMWARE_VERSION); + } + int64_t getServerVersion() { + return det.getId(slsDetectorDefs::DETECTOR_SOFTWARE_VERSION); + } + int64_t getClientVersion() { + return det.getId(slsDetectorDefs::THIS_SOFTWARE_VERSION); + } + int64_t getReceiverVersion() { + return det.getId(slsDetectorDefs::RECEIVER_VERSION); + } + + std::vector getDetectorNumber() { return det.getDetectorNumber(); } + + int getReadoutClockSpeed() { + return det.setSpeed(slsDetectorDefs::CLOCK_DIVIDER, -1); + } + void setReadoutClockSpeed(const int speed) { + det.setSpeed(slsDetectorDefs::CLOCK_DIVIDER, speed); + } + + void setDbitPipeline(const int value) { + det.setSpeed(slsDetectorDefs::DBIT_PIPELINE, value); + } + int getDbitPipeline() { + return det.setSpeed(slsDetectorDefs::DBIT_PIPELINE, -1); + } + void setDbitPhase(const int value) { + det.setSpeed(slsDetectorDefs::DBIT_PHASE, value); + } + int getDbitPhase() { return det.setSpeed(slsDetectorDefs::DBIT_PHASE, -1); } + void setDbitClock(const int value) { + det.setSpeed(slsDetectorDefs::DBIT_CLOCK, value); + } + int getDbitClock() { return det.setSpeed(slsDetectorDefs::DBIT_CLOCK, -1); } + std::vector getReceiverPort() const { return det.getReceiverPort(); } + + void setReceiverPort(int det_id, int value) { + det.setReceiverPort(value, det_id); + } + + void setRateCorrection(std::vector tau) { + for (int i = 0; i < det.getNumberOfDetectors(); ++i) + det.setRateCorrection(tau[i], i); + } + + std::vector getRateCorrection(); + + bool getFlippedDataX(int i) { + return det.getFlippedData(slsDetectorDefs::dimension::X, i); + } + + bool getFlippedDataY(int i) { + return det.getFlippedData(slsDetectorDefs::dimension::Y, i); + } + + void setFlippedDataX(int i, bool value) { + det.setFlippedData(slsDetectorDefs::dimension::X, value, i); + } + + void setFlippedDataY(int i, bool value) { + det.setFlippedData(slsDetectorDefs::dimension::Y, value, i); + } + + /*** Frame and file settings ***/ + void setFileName(std::string fname) { det.setFileName(fname); } + std::string getFileName() { return det.getFileName(); } + void setFilePath(std::string path) { det.setFilePath(path); } + void setFilePath(std::string path, int i) { det.setFilePath(path, i); } + std::string getFilePath() { return det.getFilePath(); } + std::string getFilePath(int i) { return det.getFilePath(i); } + + std::string getUserDetails() { return det.getUserDetails(); } + + void setFramesPerFile(const int n_frames) { + det.setFramesPerFile(n_frames); + } + int getFramesPerFile() { return det.setFramesPerFile(); } + + std::string getReceiverFrameDiscardPolicy() { + return det.getReceiverFrameDiscardPolicy( + det.setReceiverFramesDiscardPolicy()); + } + void setReceiverFramesDiscardPolicy(std::string f) { + auto fdp = det.getReceiverFrameDiscardPolicy(f); + if (fdp == slsDetectorDefs::GET_FRAME_DISCARD_POLICY) { + throw std::invalid_argument("Coult not decode policy: nodiscard, " + "discardempty, discardpartial"); + } + det.setReceiverFramesDiscardPolicy(fdp); + } + + void setPartialFramesPadding(bool padding) { + det.setPartialFramesPadding(padding); + } + + bool getPartialFramesPadding() { return det.getPartialFramesPadding(); } + + std::vector getMeasuredPeriod() { + std::vector mp; + for (int i = 0; i < det.getNumberOfDetectors(); ++i) { + auto t = det.getTimeLeft(slsDetectorDefs::MEASURED_PERIOD, i); + mp.push_back(static_cast(t) * 1E-9); + } + return mp; + } + std::vector getMeasuredSubPeriod() { + std::vector mp; + for (int i = 0; i < det.getNumberOfDetectors(); ++i) { + auto t = det.getTimeLeft(slsDetectorDefs::MEASURED_SUBPERIOD, i); + mp.push_back(static_cast(t) * 1E-9); + } + return mp; + } + + bool isClientAndDetectorCompatible() { + auto r = det.checkDetectorVersionCompatibility(); + if (r == 0) + return true; + else + return false; + } + bool isClientAndReceiverCompatible() { + auto r = det.checkReceiverVersionCompatibility(); + if (r == 0) + return true; + else + return false; + } + + /*** END Frame and file settings ***/ + + void loadTrimbitFile(std::string fname, const int idet) { + det.loadSettingsFile(fname, idet); + } + + // Eiger: set the energies where the detector is trimmed + void setTrimEnergies(std::vector energy) { det.setTrimEn(energy); } + + std::vector getTrimEnergies() { return det.getTrimEn(); } + + /*** Temperature control functions for Jungfrau ***/ + void setThresholdTemperature(float t) { + det.setThresholdTemperature(static_cast(t * 1000), -1); + } + + float getThresholdTemperature() { + return static_cast(det.setThresholdTemperature(-1, -1)) / + 1000.0; + } + + void setTemperatureControl(bool v) { det.setTemperatureControl(v); } + bool getTemperatureControl() { return det.setTemperatureControl(); } + + bool getTemperatureEvent() { return det.setTemperatureEvent(); } + void resetTemperatureEvent() { det.setTemperatureEvent(0); } + /*** END Temperature control functions for Jungfrau ***/ + + void setThresholdEnergy(const int eV) { det.setThresholdEnergy(eV); } + + std::string getSettingsDir() { return det.getSettingsDir(); } + void setSettingsDir(std::string dir) { det.setSettingsDir(dir); } + + int getThresholdEnergy() { return det.getThresholdEnergy(); } + + std::string getSettings() { + return det.getDetectorSettings(det.getSettings()); + } + + void setSettings(std::string s) { + det.setSettings(det.getDetectorSettings(s)); + } + + // name to enum translation on the c++ side + // should we instead expose the enum to Python? + int getDac(std::string dac_name, const int mod_id) { + int val = -1; + auto dac = dacNameToEnum(dac_name); + return det.setDAC(val, dac, 0, mod_id); + } + + void setDac(std::string dac_name, const int mod_id, int val) { + auto dac = dacNameToEnum(dac_name); + det.setDAC(val, dac, 0, mod_id); + } + + int getDac_mV(std::string dac_name, const int mod_id) { + int val = -1; + auto dac = dacNameToEnum(dac_name); + return det.setDAC(val, dac, 1, mod_id); + } + + void setDac_mV(std::string dac_name, const int mod_id, int value) { + auto dac = dacNameToEnum(dac_name); + det.setDAC(value, dac, 1, mod_id); + } + + // Intended for the JungfrauCTB should we name dacs instead + int getDacFromIndex(const int index, const int mod_id) { + int val = -1; + auto dac = static_cast(0); + return det.setDAC(val, dac, 0, mod_id); + } + // Intended for the JungfrauCTB should we name dacs instead + int setDacFromIndex(const int index, const int mod_id, int value) { + auto dac = static_cast(0); + return det.setDAC(value, dac, 0, mod_id); + } + + // Calling multi do we have a need to lock/unlock a single det? + bool getServerLock() { return det.lockServer(-1); } + void setServerLock(const bool value) { det.lockServer(value); } + bool getReceiverLock() { return det.lockReceiver(-1); } + void setReceiverLock(const bool value) { det.lockReceiver(value); } + + int getAdc(std::string adc_name, int mod_id) { + auto adc = dacNameToEnum(adc_name); + return det.getADC(adc, mod_id); + } + + std::vector getReadoutFlags(); + + // note singular + void setReadoutFlag(const std::string flag_name); + + // name to enum transltion of dac + int getDacVthreshold() { + int val = -1; + auto dac = slsDetectorDefs::dacIndex::THRESHOLD; + return det.setDAC(val, dac, 0, -1); + } + + void setDacVthreshold(const int val) { + auto dac = slsDetectorDefs::dacIndex::THRESHOLD; + det.setDAC(val, dac, 0, -1); + } + + void setFileIndex(const int i) { det.setFileIndex(i); } + + int getFileIndex() { return det.getFileIndex(); } + + // time in ns + void setExposureTime(const int64_t t) { + det.setTimer(slsDetectorDefs::timerIndex::ACQUISITION_TIME, t); + } + + // time in ns + int64_t getExposureTime() { + return det.setTimer(slsDetectorDefs::timerIndex::ACQUISITION_TIME, -1); + } + + void setSubExposureTime(const int64_t t) { + det.setTimer(slsDetectorDefs::timerIndex::SUBFRAME_ACQUISITION_TIME, t); + } + + int64_t getSubExposureTime() { + // time in ns + return det.setTimer( + slsDetectorDefs::timerIndex::SUBFRAME_ACQUISITION_TIME, -1); + } + + void setSubExposureDeadTime(const int64_t t) { + det.setTimer(slsDetectorDefs::timerIndex::SUBFRAME_DEADTIME, t); + } + + int64_t getSubExposureDeadTime() { + // time in ns + return det.setTimer(slsDetectorDefs::timerIndex::SUBFRAME_DEADTIME, -1); + } + + int64_t getCycles() { + return det.setTimer(slsDetectorDefs::timerIndex::CYCLES_NUMBER, -1); + } + + void setCycles(const int64_t n_cycles) { + det.setTimer(slsDetectorDefs::timerIndex::CYCLES_NUMBER, n_cycles); + } + + void setNumberOfMeasurements(const int n_measurements) { + det.setTimer(slsDetectorDefs::timerIndex::MEASUREMENTS_NUMBER, + n_measurements); + } + int getNumberOfMeasurements() { + return det.setTimer(slsDetectorDefs::timerIndex::MEASUREMENTS_NUMBER, + -1); + } + + int getNumberOfGates() { + return det.setTimer(slsDetectorDefs::timerIndex::GATES_NUMBER, -1); + } + void setNumberOfGates(const int t) { + det.setTimer(slsDetectorDefs::timerIndex::GATES_NUMBER, t); + } + + // time in ns + int64_t getDelay() { + return det.setTimer(slsDetectorDefs::timerIndex::DELAY_AFTER_TRIGGER, + -1); + } + // time in ns + void setDelay(const int64_t t) { + det.setTimer(slsDetectorDefs::timerIndex::DELAY_AFTER_TRIGGER, t); + } + // time in ns + int64_t getPeriod() { + return det.setTimer(slsDetectorDefs::timerIndex::FRAME_PERIOD, -1); + } + // time in ns + void setPeriod(const int64_t t) { + det.setTimer(slsDetectorDefs::timerIndex::FRAME_PERIOD, t); + } + + int64_t getNumberOfFrames() { + return det.setTimer(slsDetectorDefs::timerIndex::FRAME_NUMBER, -1); + } + + void setNumberOfFrames(const int64_t nframes) { + det.setTimer(slsDetectorDefs::timerIndex::FRAME_NUMBER, nframes); + } + + std::string getTimingMode() { + return det.externalCommunicationType( + det.setExternalCommunicationMode()); + } + void setTimingMode(const std::string mode) { + det.setExternalCommunicationMode(det.externalCommunicationType(mode)); + } + + void freeSharedMemory() { det.freeSharedMemory(); } + + std::vector getDetectorType() { + std::vector detector_type; + for (int i = 0; i < det.getNumberOfDetectors(); ++i) { + detector_type.push_back(det.getDetectorTypeAsString(i)); + } + return detector_type; + } + + void setFileWrite(bool value) { det.setFileWrite(value); } + bool getFileWrite() { return det.getFileWrite(); } + + void setFileOverWrite(bool value) { det.setFileOverWrite(value); } + + bool getFileOverWrite() { return det.getFileOverWrite(); } + + void setAllTrimbits(int tb) { det.setAllTrimbits(tb); } + int getAllTrimbits() { return det.setAllTrimbits(-1); } + bool getRxDataStreamStatus() { + return det.enableDataStreamingFromReceiver(); + } + + void setRxDataStreamStatus(bool state) { + det.enableDataStreamingFromReceiver(state); + } + + // Get a network parameter for all detectors, looping over individual + // detectors return a vector of strings + std::vector getReceiverStreamingPort() { + std::vector vec; + vec.reserve(det.getNumberOfDetectors()); + for (int i = 0; i < det.getNumberOfDetectors(); ++i) { + vec.push_back(det.getReceiverStreamingPort(i)); + } + return vec; + } + + void setReceiverStreamingPort(int value, int det_id) { + det.setReceiverDataStreamingOutPort(value, det_id); + } + + std::vector getReceiverUDPPort() { + std::vector vec; + vec.reserve(det.getNumberOfDetectors()); + for (int i = 0; i < det.getNumberOfDetectors(); ++i) { + vec.push_back(det.getReceiverUDPPort(i)); + } + return vec; + } + + std::vector getReceiverUDPPort2() { + std::vector vec; + vec.reserve(det.getNumberOfDetectors()); + for (int i = 0; i < det.getNumberOfDetectors(); ++i) { + vec.push_back(det.getReceiverUDPPort2(i)); + } + return vec; + } + + void setReceiverUDPPort(int port, int det_id) { + det.setReceiverUDPPort(port, det_id); + } + void setReceiverUDPPort2(int port, int det_id) { + det.setReceiverUDPPort2(port, det_id); + } + + // //Set network parameter for all modules if det_id == -1 otherwise the + // module + // //specified with det_id. + // void setDetectorNetworkParameter(std::string par_name, std::string par, + // const int det_id) { + // auto p = networkNameToEnum(par_name); + // if (det_id == -1) { + // det.setDetectorNetworkParameter(p, par); + // } else { + // det.setDetectorNetworkParameter(p, par, det_id); + // } + // } + + void configureNetworkParameters() { det.configureMAC(); } + + std::string getLastClientIP() { return det.getLastClientIP(); } + std::string getReceiverLastClientIP() { + return det.getReceiverLastClientIP(); + } + + // get frame delay of module (det_id) in ns + int getDelayFrame(int det_id) { + auto r = det.setDetectorNetworkParameter( + slsDetectorDefs::networkParameter::DETECTOR_TXN_DELAY_FRAME, -1, + det_id); + return r; + } + // set frame delay of module (det_id) in ns + void setDelayFrame(int det_id, int delay) { + // auto delay_str = std::to_string(delay); + det.setDetectorNetworkParameter( + slsDetectorDefs::networkParameter::DETECTOR_TXN_DELAY_FRAME, delay, + det_id); + } + + // get delay left of module (det_id) in ns + int getDelayLeft(int det_id) { + auto r = det.setDetectorNetworkParameter( + slsDetectorDefs::networkParameter::DETECTOR_TXN_DELAY_LEFT, -1, + det_id); + return r; + } + // set delay left of module (det_id) in ns + void setDelayLeft(int det_id, int delay) { + // auto delay_str = std::to_string(delay); + det.setDetectorNetworkParameter( + slsDetectorDefs::networkParameter::DETECTOR_TXN_DELAY_LEFT, delay, + det_id); + } + + // get delay right of module (det_id) in ns + int getDelayRight(const int det_id) { + auto r = det.setDetectorNetworkParameter( + slsDetectorDefs::networkParameter::DETECTOR_TXN_DELAY_RIGHT, -1, + det_id); + return r; + } + + // set delay right of module (det_id) in ns + void setDelayRight(int det_id, int delay) { + // auto delay_str = std::to_string(delay); + det.setDetectorNetworkParameter( + slsDetectorDefs::networkParameter::DETECTOR_TXN_DELAY_RIGHT, delay, + det_id); + } + + // Check if detector if filling in gap pixels in module + // return true if so, currently only in developer + bool getGapPixels() { return det.enableGapPixels(-1); } + + // Set to true to have the detector filling in gap pixels + // false to disable, currently only in developer + void setGapPixels(bool val) { det.enableGapPixels(val); } + + slsDetectorDefs::networkParameter networkNameToEnum(std::string par_name); + + private: + multiSlsDetector det; + slsDetector *getSlsDetector(int i) const; + int multi_detector_id = 0; +}; + +void Detector::setFileFormat(const std::string &format) { + if (format == "binary") { + det.setFileFormat(slsDetectorDefs::fileFormat::BINARY); + } else if (format == "ascii") { + det.setFileFormat(slsDetectorDefs::fileFormat::ASCII); + } else if (format == "hdf5") { + det.setFileFormat(slsDetectorDefs::fileFormat::HDF5); + } +} + +std::string Detector::getFileFormat() { + auto format = + det.setFileFormat(slsDetectorDefs::fileFormat::GET_FILE_FORMAT, -1); + switch (format) { + case slsDetectorDefs::fileFormat::BINARY: + return "binary"; + case slsDetectorDefs::fileFormat::ASCII: + return "ascii"; + case slsDetectorDefs::fileFormat::HDF5: + return "hdf5"; + default: + return "unknown"; + } +} + +slsDetectorDefs::networkParameter +Detector::networkNameToEnum(std::string par_name) { + + if (par_name == "detectormac") { + return slsDetectorDefs::networkParameter::DETECTOR_MAC; + } else if (par_name == "detectorip") { + return slsDetectorDefs::networkParameter::DETECTOR_IP; + } else if (par_name == "rx_hostname") { + return slsDetectorDefs::networkParameter::RECEIVER_HOSTNAME; + } else if (par_name == "rx_udpip") { + return slsDetectorDefs::networkParameter::RECEIVER_UDP_IP; + } else if (par_name == "rx_udpport") { + return slsDetectorDefs::networkParameter::RECEIVER_UDP_PORT; + } else if (par_name == "rx_udpmac") { + return slsDetectorDefs::networkParameter::RECEIVER_UDP_MAC; + } else if (par_name == "rx_udpport2") { + return slsDetectorDefs::networkParameter::RECEIVER_UDP_PORT2; + } else if (par_name == "rx_udpsocksize") { + return slsDetectorDefs::networkParameter::RECEIVER_UDP_SCKT_BUF_SIZE; + } else if (par_name == "rx_realudpsocksize") { + return slsDetectorDefs::networkParameter:: + RECEIVER_REAL_UDP_SCKT_BUF_SIZE; + } else if (par_name == "rx_jsonaddheader") { + return slsDetectorDefs::networkParameter::ADDITIONAL_JSON_HEADER; + } else if (par_name == "delay_left") { + return slsDetectorDefs::networkParameter::DETECTOR_TXN_DELAY_LEFT; + } else if (par_name == "delay_right") { + return slsDetectorDefs::networkParameter::DETECTOR_TXN_DELAY_RIGHT; + } else if (par_name == "delay_frame") { + return slsDetectorDefs::networkParameter::DETECTOR_TXN_DELAY_FRAME; + } else if (par_name == "flow_control_10g") { + return slsDetectorDefs::networkParameter::FLOW_CONTROL_10G; + } else if (par_name == "client_zmqport") { + return slsDetectorDefs::networkParameter::CLIENT_STREAMING_PORT; + } else if (par_name == "rx_zmqport") { + return slsDetectorDefs::networkParameter::RECEIVER_STREAMING_PORT; + } else if (par_name == "rx_zmqip") { + return slsDetectorDefs::networkParameter::RECEIVER_STREAMING_SRC_IP; + } else if (par_name == "client_zmqip") { + return slsDetectorDefs::networkParameter::CLIENT_STREAMING_SRC_IP; + } + + throw std::runtime_error("Could not decode network parameter"); +}; + +// slsDetectorDefs::fileFormat Detector::file/// + +slsDetectorDefs::dacIndex Detector::dacNameToEnum(std::string dac_name) { + // to avoid uninitialised + slsDetectorDefs::dacIndex dac = slsDetectorDefs::dacIndex::E_SvP; + + if (dac_name == "vsvp") { + dac = slsDetectorDefs::dacIndex::E_SvP; + } else if (dac_name == "vtr") { + dac = slsDetectorDefs::dacIndex::E_Vtr; + } else if (dac_name == "vthreshold") { + dac = slsDetectorDefs::dacIndex::THRESHOLD; + } else if (dac_name == "vrf") { + dac = slsDetectorDefs::dacIndex::E_Vrf; + } else if (dac_name == "vrs") { + dac = slsDetectorDefs::dacIndex::E_Vrs; + } else if (dac_name == "vsvn") { + dac = slsDetectorDefs::dacIndex::E_SvN; + } else if (dac_name == "vtgstv") { + dac = slsDetectorDefs::dacIndex::E_Vtgstv; + } else if (dac_name == "vcmp_ll") { + dac = slsDetectorDefs::dacIndex::E_Vcmp_ll; + } else if (dac_name == "vcmp_lr") { + dac = slsDetectorDefs::dacIndex::E_Vcmp_lr; + } else if (dac_name == "vcall") { + dac = slsDetectorDefs::dacIndex::E_cal; + } else if (dac_name == "vcmp_rl") { + dac = slsDetectorDefs::dacIndex::E_Vcmp_rl; + } else if (dac_name == "rxb_rb") { + dac = slsDetectorDefs::dacIndex::E_rxb_rb; + } else if (dac_name == "rxb_lb") { + dac = slsDetectorDefs::dacIndex::E_rxb_lb; + } else if (dac_name == "vcmp_rr") { + dac = slsDetectorDefs::dacIndex::E_Vcmp_rr; + } else if (dac_name == "vcp") { + dac = slsDetectorDefs::dacIndex::E_Vcp; + } else if (dac_name == "vcn") { + dac = slsDetectorDefs::dacIndex::E_Vcn; + } else if (dac_name == "vis") { + dac = slsDetectorDefs::dacIndex::E_Vis; + } else if (dac_name == "iodelay") { + dac = slsDetectorDefs::dacIndex::IO_DELAY; + } else if (dac_name == "v_a") { + dac = slsDetectorDefs::dacIndex::V_POWER_A; + } else if (dac_name == "v_b") { + dac = slsDetectorDefs::dacIndex::V_POWER_B; + } else if (dac_name == "v_c") { + dac = slsDetectorDefs::dacIndex::V_POWER_C; + } else if (dac_name == "v_d") { + dac = slsDetectorDefs::dacIndex::V_POWER_D; + } else if (dac_name == "v_io") { + dac = slsDetectorDefs::dacIndex::V_POWER_IO; + } else if (dac_name == "v_chip") { + dac = slsDetectorDefs::dacIndex::V_POWER_CHIP; + } else if (dac_name == "v_limit") { + dac = slsDetectorDefs::dacIndex::V_LIMIT; + } else if (dac_name == "temp_fpga") { + dac = slsDetectorDefs::dacIndex::TEMPERATURE_FPGA; + } else if (dac_name == "temp_fpgaext") { + dac = slsDetectorDefs::dacIndex::TEMPERATURE_FPGAEXT; + } else if (dac_name == "temp_10ge") { + dac = slsDetectorDefs::dacIndex::TEMPERATURE_10GE; + } else if (dac_name == "temp_dcdc") { + dac = slsDetectorDefs::dacIndex::TEMPERATURE_DCDC; + } else if (dac_name == "temp_sodl") { + dac = slsDetectorDefs::dacIndex::TEMPERATURE_SODL; + } else if (dac_name == "temp_sodr") { + dac = slsDetectorDefs::dacIndex::TEMPERATURE_SODR; + } else if (dac_name == "temp_fpgafl") { + dac = slsDetectorDefs::dacIndex::TEMPERATURE_FPGA2; + } else if (dac_name == "temp_fpgafr") { + dac = slsDetectorDefs::dacIndex::TEMPERATURE_FPGA3; + } else if (dac_name == "vhighvoltage") { + dac = slsDetectorDefs::dacIndex::HIGH_VOLTAGE; + } else if (dac_name == "vb_comp") { + dac = static_cast(0); + } else if (dac_name == "vdd_prot") { + dac = static_cast(1); + } else if (dac_name == "vin_com") { + dac = static_cast(2); + } else if (dac_name == "vref_prech") { + dac = static_cast(3); + } else if (dac_name == "vb_pixbuff") { + dac = static_cast(4); + } else if (dac_name == "vb_ds") { + dac = static_cast(5); + } else if (dac_name == "vref_ds") { + dac = static_cast(6); + } else if (dac_name == "vref_comp") { + dac = static_cast(7); + } else if (dac_name == "dac0") { + dac = static_cast(0); + } else if (dac_name == "dac1") { + dac = static_cast(1); + } else if (dac_name == "dac2") { + dac = static_cast(2); + } else if (dac_name == "dac3") { + dac = static_cast(3); + } else if (dac_name == "dac4") { + dac = static_cast(4); + } else if (dac_name == "dac5") { + dac = static_cast(5); + } else if (dac_name == "dac6") { + dac = static_cast(6); + } else if (dac_name == "dac7") { + dac = static_cast(7); + } else if (dac_name == "dac8") { + dac = static_cast(8); + } else if (dac_name == "dac9") { + dac = static_cast(9); + } else if (dac_name == "dac10") { + dac = static_cast(10); + } else if (dac_name == "dac11") { + dac = static_cast(11); + } else if (dac_name == "dac12") { + dac = static_cast(12); + } else if (dac_name == "dac13") { + dac = static_cast(13); + } else if (dac_name == "dac14") { + dac = static_cast(14); + } else if (dac_name == "dac15") { + dac = static_cast(15); + } else if (dac_name == "dac16") { + dac = static_cast(16); + } else if (dac_name == "dac17") { + dac = static_cast(17); + } + + return dac; +} + +std::vector Detector::getReadoutFlags() { + std::vector flags; + auto r = det.setReadOutFlags(); + if (r & slsDetectorDefs::readOutFlags::STORE_IN_RAM) + flags.push_back("storeinram"); + if (r & slsDetectorDefs::readOutFlags::TOT_MODE) + flags.push_back("tot"); + if (r & slsDetectorDefs::readOutFlags::CONTINOUS_RO) + flags.push_back("continous"); + if (r & slsDetectorDefs::readOutFlags::PARALLEL) + flags.push_back("parallel"); + if (r & slsDetectorDefs::readOutFlags::NONPARALLEL) + flags.push_back("nonparallel"); + if (r & slsDetectorDefs::readOutFlags::SAFE) + flags.push_back("safe"); + if (r & slsDetectorDefs::readOutFlags::DIGITAL_ONLY) + flags.push_back("digital"); + if (r & slsDetectorDefs::readOutFlags::ANALOG_AND_DIGITAL) + flags.push_back("analog_digital"); + if (r & slsDetectorDefs::readOutFlags::NOOVERFLOW) + flags.push_back("nooverflow"); + if (r & slsDetectorDefs::readOutFlags::SHOW_OVERFLOW) + flags.push_back("overflow"); + return flags; +} + +// note singular +void Detector::setReadoutFlag(const std::string flag_name) { + if (flag_name == "none") + det.setReadOutFlags(slsDetectorDefs::readOutFlags::NORMAL_READOUT); + else if (flag_name == "storeinram") + det.setReadOutFlags(slsDetectorDefs::readOutFlags::STORE_IN_RAM); + else if (flag_name == "tot") + det.setReadOutFlags(slsDetectorDefs::readOutFlags::TOT_MODE); + else if (flag_name == "continous") + det.setReadOutFlags(slsDetectorDefs::readOutFlags::CONTINOUS_RO); + else if (flag_name == "parallel") + det.setReadOutFlags(slsDetectorDefs::readOutFlags::PARALLEL); + else if (flag_name == "nonparallel") + det.setReadOutFlags(slsDetectorDefs::readOutFlags::NONPARALLEL); + else if (flag_name == "safe") + det.setReadOutFlags(slsDetectorDefs::readOutFlags::SAFE); + else if (flag_name == "digital") + det.setReadOutFlags(slsDetectorDefs::readOutFlags::DIGITAL_ONLY); + else if (flag_name == "analog_digital") + det.setReadOutFlags(slsDetectorDefs::readOutFlags::ANALOG_AND_DIGITAL); + else if (flag_name == "nooverflow") + det.setReadOutFlags(slsDetectorDefs::readOutFlags::NOOVERFLOW); + else if (flag_name == "overflow") + det.setReadOutFlags(slsDetectorDefs::readOutFlags::SHOW_OVERFLOW); + else + throw std::runtime_error("Flag name not recognized"); +} + +std::vector Detector::getRateCorrection() { + std::vector rate_corr; + for (int i = 0; i < det.getNumberOfDetectors(); ++i) { + rate_corr.push_back(det.getRateCorrection(i)); + } + return rate_corr; +} + +void Detector::pulseAllPixels(int n) { + // int pulsePixelNMove(int n=0,int x=0,int y=0); + // int pulsePixel(int n=0,int x=0,int y=0); + + for (int j = 0; j < 8; ++j) { + det.pulsePixel(0, -255 + j, 0); + for (int i = 0; i < 256; ++i) { + det.pulsePixelNMove(n, 0, 1); + } + } + return; +} +void Detector::pulseDiagonal(int n) { + // int pulsePixelNMove(int n=0,int x=0,int y=0); + // int pulsePixel(int n=0,int x=0,int y=0); + + for (int j = 20; j < 232; j += 16) { + det.pulsePixel(0, -255, j); + for (int i = 0; i < 8; ++i) { + det.pulsePixelNMove(n, 1, 1); + } + } + return; +} + +#endif // DETECTOR_H diff --git a/python/src/main.cpp b/python/src/main.cpp new file mode 100755 index 000000000..094ab8e48 --- /dev/null +++ b/python/src/main.cpp @@ -0,0 +1,297 @@ +#include +#include + +#include "Detector.h" +#include "mythenFileIO.h" + +namespace py = pybind11; + +PYBIND11_MODULE(_sls_detector, m) +{ + m.doc() = R"pbdoc( + C/C++ API + ----------------------- + .. warning :: + + This is the compiled c extension. You probably want to look at the + interface provided by sls instead. + + )pbdoc"; + + py::class_ DetectorApi(m, "DetectorApi", R"pbdoc( + Interface to the multiSlsDetector class through Detector.h These functions + are used by the python classes Eiger and Jungfrau and normally it is better + to use them than to directly access functions here. + + However it is possible to access these functions... + + :: + + #Using the python class + from sls_detector import Eiger + d = Eiger() + d._api.getThresholdEnergy() + + #creating a DetectorApi object (remember to set online flags) + from _sls_detector import DetectorApi + api = DetectorApi(0) + api.setOnline(True) + api.setReceiverOnline(True) + api.getNumberOfFrames() + + #But the Pythonic way is almost alway simpler + d = Eiger() + d.n_frames + >> 10 + + )pbdoc"); + DetectorApi + .def(py::init()) + .def("freeSharedMemory", &Detector::freeSharedMemory) + .def("getMultiDetectorId", &Detector::getMultiDetectorId) + .def("acq", &Detector::acquire) + .def("getAcquiringFlag", &Detector::getAcquiringFlag) + .def("setAcquiringFlag", &Detector::setAcquiringFlag) + + .def("setAllTrimbits", &Detector::setAllTrimbits) + .def("getAllTrimbits", &Detector::getAllTrimbits) + .def("setCounterBit", &Detector::setCounterBit) + .def("getCounterBit", &Detector::getCounterBit) + + .def("getAdc", &Detector::getAdc) + .def("getDac", &Detector::getDac) + .def("getDac_mV", &Detector::getDac_mV) + .def("setDac", &Detector::setDac) + .def("setDac_mV", &Detector::setDac_mV) + .def("getDacFromIndex", &Detector::getDacFromIndex) + .def("setDacFromIndex", &Detector::setDacFromIndex) + + .def("getDbitPipeline", &Detector::getDbitPipeline) + .def("setDbitPipeline", &Detector::setDbitPipeline) + .def("getDbitPhase", &Detector::getDbitPhase) + .def("setDbitPhase", &Detector::setDbitPhase) + .def("getDbitClock", &Detector::getDbitClock) + .def("setDbitClock", &Detector::setDbitClock) + + .def("setThresholdEnergy", &Detector::setThresholdEnergy) + .def("getThresholdEnergy", &Detector::getThresholdEnergy) + + .def("getSettings", &Detector::getSettings) + .def("setSettings", &Detector::setSettings) + .def("getSettingsDir", &Detector::getSettingsDir) + .def("setSettingsDir", &Detector::setSettingsDir) + + .def("loadTrimbitFile", &Detector::loadTrimbitFile) + .def("setTrimEnergies", &Detector::setTrimEnergies) + .def("getTrimEnergies", &Detector::getTrimEnergies) + + .def("pulseChip", &Detector::pulseChip) + .def("pulseAllPixels", &Detector::pulseAllPixels) + .def("pulseDiagonal", &Detector::pulseDiagonal) + .def("getRunStatus", &Detector::getRunStatus) + .def("readConfigurationFile", &Detector::readConfigurationFile) + .def("readParametersFile", &Detector::readParametersFile) + .def("checkOnline", &Detector::checkOnline) + .def("setReadoutClockSpeed", &Detector::setReadoutClockSpeed) + .def("getReadoutClockSpeed", &Detector::getReadoutClockSpeed) + .def("getHostname", &Detector::getHostname) + .def("setHostname", &Detector::setHostname) + + .def("getOnline", &Detector::getOnline) + .def("setOnline", &Detector::setOnline) + .def("getReceiverOnline", &Detector::getReceiverOnline) + .def("setReceiverOnline", &Detector::setReceiverOnline) + + .def("getReceiverPort", &Detector::getReceiverPort) + .def("setReceiverPort", &Detector::setReceiverPort) + + .def("isChipPowered", &Detector::isChipPowered) + .def("powerChip", &Detector::powerChip) + + .def("readRegister", &Detector::readRegister) + .def("writeRegister", &Detector::writeRegister) + .def("writeAdcRegister", &Detector::writeAdcRegister) + .def("setBitInRegister", &Detector::setBitInRegister) + .def("clearBitInRegister", &Detector::clearBitInRegister) + + .def("setDynamicRange", &Detector::setDynamicRange) + .def("getDynamicRange", &Detector::getDynamicRange) + .def("getFirmwareVersion", &Detector::getFirmwareVersion) + .def("getServerVersion", &Detector::getServerVersion) + .def("getClientVersion", &Detector::getClientVersion) + .def("getReceiverVersion", &Detector::getReceiverVersion) + .def("getDetectorNumber", &Detector::getDetectorNumber) + .def("getRateCorrection", &Detector::getRateCorrection) + .def("setRateCorrection", &Detector::setRateCorrection) + + .def("startAcquisition", &Detector::startAcquisition) + .def("stopAcquisition", &Detector::stopAcquisition) + .def("startReceiver", &Detector::startReceiver) + .def("stopReceiver", &Detector::stopReceiver) + + .def("getFilePath", (std::string(Detector::*)()) & Detector::getFilePath, "Using multiSlsDetector") + .def("getFilePath", (std::string(Detector::*)(int)) & Detector::getFilePath, "File path for individual detector") + .def("setFilePath", (void (Detector::*)(std::string)) & Detector::setFilePath) + .def("setFilePath", (void (Detector::*)(std::string, int)) & Detector::setFilePath) + + .def("setFileName", &Detector::setFileName) + .def("getFileName", &Detector::getFileName) + .def("setFileIndex", &Detector::setFileIndex) + .def("getFileIndex", &Detector::getFileIndex) + + .def("setExposureTime", &Detector::setExposureTime) + .def("getExposureTime", &Detector::getExposureTime) + .def("setSubExposureTime", &Detector::setSubExposureTime) + .def("getSubExposureTime", &Detector::getSubExposureTime) + .def("setPeriod", &Detector::setPeriod) + .def("getPeriod", &Detector::getPeriod) + .def("setSubExposureDeadTime", &Detector::setSubExposureDeadTime) + .def("getSubExposureDeadTime", &Detector::getSubExposureDeadTime) + + .def("getCycles", &Detector::getCycles) + .def("setCycles", &Detector::setCycles) + .def("setNumberOfMeasurements", &Detector::setNumberOfMeasurements) + .def("getNumberOfMeasurements", &Detector::getNumberOfMeasurements) + .def("getNumberOfGates", &Detector::getNumberOfGates) + .def("setNumberOfGates", &Detector::setNumberOfGates) + .def("getDelay", &Detector::getDelay) + .def("setDelay", &Detector::setDelay) + + + .def("setStoragecellStart", &Detector::setStoragecellStart) + .def("getStoragecellStart", &Detector::getStoragecellStart) + .def("setNumberOfStorageCells", &Detector::setNumberOfStorageCells) + .def("getNumberOfStorageCells", &Detector::getNumberOfStorageCells) + + .def("getTimingMode", &Detector::getTimingMode) + .def("setTimingMode", &Detector::setTimingMode) + + .def("getDetectorType", &Detector::getDetectorType) + + .def("setThresholdTemperature", &Detector::setThresholdTemperature) + .def("getThresholdTemperature", &Detector::getThresholdTemperature) + .def("setTemperatureControl", &Detector::setTemperatureControl) + .def("getTemperatureControl", &Detector::getTemperatureControl) + .def("getTemperatureEvent", &Detector::getTemperatureEvent) + .def("resetTemperatureEvent", &Detector::resetTemperatureEvent) + + .def("getRxDataStreamStatus", &Detector::getRxDataStreamStatus) + .def("setRxDataStreamStatus", &Detector::setRxDataStreamStatus) + + //Network stuff + .def("getReceiverHostname", &Detector::getReceiverHostname) + .def("setReceiverHostname", &Detector::setReceiverHostname) + .def("getReceiverStreamingPort", &Detector::getReceiverStreamingPort) + .def("setReceiverStreamingPort", &Detector::setReceiverStreamingPort) + .def("getReceiverUDPPort", &Detector::getReceiverUDPPort) + .def("getReceiverUDPPort2", &Detector::getReceiverUDPPort2) + .def("setReceiverUDPPort", &Detector::setReceiverUDPPort) + .def("setReceiverUDPPort2", &Detector::setReceiverUDPPort2) + .def("setReceiverUDPIP", &Detector::setReceiverUDPIP) + .def("getReceiverUDPIP", &Detector::getReceiverUDPIP) + .def("getReceiverUDPMAC", &Detector::getReceiverUDPMAC) + .def("setReceiverUDPMAC", &Detector::setReceiverUDPMAC) + + .def("getReceiverPort", &Detector::getReceiverPort) + .def("setReceiverPort", &Detector::setReceiverPort) + + .def("configureNetworkParameters", &Detector::configureNetworkParameters) + .def("getDelayFrame", &Detector::getDelayFrame) + .def("setDelayFrame", &Detector::setDelayFrame) + .def("getDelayLeft", &Detector::getDelayLeft) + .def("setDelayLeft", &Detector::setDelayLeft) + .def("getDelayRight", &Detector::getDelayRight) + .def("setDelayRight", &Detector::setDelayRight) + .def("getLastClientIP", &Detector::getLastClientIP) + .def("getReceiverLastClientIP", &Detector::getReceiverLastClientIP) + + .def("setFramesPerFile", &Detector::setFramesPerFile) + .def("getFramesPerFile", &Detector::getFramesPerFile) + .def("setReceiverFifoDepth", &Detector::setReceiverFifoDepth) + .def("getReceiverFifoDepth", &Detector::getReceiverFifoDepth) + + .def("getReceiverFrameDiscardPolicy", &Detector::getReceiverFrameDiscardPolicy) + .def("setReceiverFramesDiscardPolicy", &Detector::setReceiverFramesDiscardPolicy) + .def("setPartialFramesPadding", &Detector::setPartialFramesPadding) + .def("getPartialFramesPadding", &Detector::getPartialFramesPadding) + + .def("getUserDetails", &Detector::getUserDetails) + .def("isClientAndDetectorCompatible", &Detector::isClientAndDetectorCompatible) + .def("isClientAndReceiverCompatible", &Detector::isClientAndReceiverCompatible) + .def("getMeasuredPeriod", &Detector::getMeasuredPeriod) + .def("getMeasuredSubPeriod", &Detector::getMeasuredSubPeriod) + + + .def("setFileWrite", &Detector::setFileWrite) + .def("getFileWrite", &Detector::getFileWrite) + .def("setFileOverWrite", &Detector::setFileOverWrite) + .def("getFileOverWrite", &Detector::getFileOverWrite) + .def("getDacVthreshold", &Detector::getDacVthreshold) + .def("setDacVthreshold", &Detector::setDacVthreshold) + .def("setNumberOfFrames", &Detector::setNumberOfFrames) + .def("getNumberOfFrames", &Detector::getNumberOfFrames) + + //Overloaded calls + .def("getFramesCaughtByReceiver", (int (Detector::*)() ) & Detector::getFramesCaughtByReceiver) + .def("getFramesCaughtByReceiver", (int (Detector::*)(int)) & Detector::getFramesCaughtByReceiver) + + + .def("resetFramesCaught", &Detector::resetFramesCaught) + .def("getReceiverCurrentFrameIndex", &Detector::getReceiverCurrentFrameIndex) + .def("getGapPixels", &Detector::getGapPixels) + .def("setGapPixels", &Detector::setGapPixels) + .def("getFlippedDataX", &Detector::getFlippedDataX) + .def("getFlippedDataY", &Detector::getFlippedDataY) + .def("setFlippedDataX", &Detector::setFlippedDataX) + .def("setFlippedDataY", &Detector::setFlippedDataY) + + .def("getServerLock", &Detector::getServerLock) + .def("setServerLock", &Detector::setServerLock) + .def("getReceiverLock", &Detector::getReceiverLock) + .def("setReceiverLock", &Detector::setReceiverLock) + + .def("getReadoutFlags", &Detector::getReadoutFlags) + .def("setReadoutFlag", &Detector::setReadoutFlag) + + .def("setFileFormat", &Detector::setFileFormat) + .def("getFileFormat", &Detector::getFileFormat) + + .def("getActive", &Detector::getActive) + .def("setActive", &Detector::setActive) + + .def("getTenGigabitEthernet", &Detector::getTenGigabitEthernet) + .def("setTenGigabitEthernet", &Detector::setTenGigabitEthernet) + + .def("getImageSize", &Detector::getImageSize) + .def("setImageSize", &Detector::setImageSize) + .def("getNumberOfDetectors", &Detector::getNumberOfDetectors) + .def("getDetectorGeometry", &Detector::getDetectorGeometry); + + + +//Experimental API to use the multi directly and inherit from to reduce +//code duplication need to investigate how to handle documentation +py::class_ multiDetectorApi(m, "multiDetectorApi"); + multiDetectorApi + .def(py::init()) + .def_property("busy", + py::cpp_function(&multiSlsDetector::getAcquiringFlag), + py::cpp_function(&multiSlsDetector::setAcquiringFlag)) + .def_property_readonly("rx_tcpport", + py::cpp_function(&multiSlsDetector::getReceiverPort)) + .def_property_readonly("detectornumber", + py::cpp_function(&multiSlsDetector::getDetectorNumber)) + .def("_getReceiverUDPIP", &multiSlsDetector::getReceiverUDPIP) + .def("_setReceiverUDPIP", &multiSlsDetector::setReceiverUDPIP) + ; + + py::module io = m.def_submodule("io", "Submodule for io"); + io.def("read_ctb_file", &read_ctb_file, "some"); + + +#ifdef VERSION_INFO + m.attr("__version__") = VERSION_INFO; +#else + m.attr("__version__") = "dev"; +#endif +} diff --git a/python/src/mythenFileIO.h b/python/src/mythenFileIO.h new file mode 100644 index 000000000..c0660c9bc --- /dev/null +++ b/python/src/mythenFileIO.h @@ -0,0 +1,85 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +namespace py = pybind11; + +template +std::vector ExtractBits(const std::vector &data, int dr = 24) { + constexpr int mask0 = (1 << bit_index0); + constexpr int mask1 = (1 << bit_index1); + constexpr int NumStrips = 2; + const int NumCompleteSamples = data.size() / dr; + const int NumCounters = NumCompleteSamples * NumStrips; + + std::vector result(NumCounters); + + auto ptr = data.data(); + + auto strip0 = result.data(); + auto strip1 = strip0 + NumCompleteSamples; + + for (int j = 0; j != NumCompleteSamples; ++j) { + for (int i = 0; i != dr; ++i) { + int bit0 = (*ptr & mask0) >> bit_index0; + int bit1 = (*ptr++ & mask1) >> bit_index1; + *strip0 |= bit0 << i; + *strip1 |= bit1 << i; + } + strip0++; + strip1++; + } + return result; +} + +template +std::vector ExtractBits(const std::vector &data, int dr = 24) { + constexpr int mask = (1 << bit_index); + const int NumCompleteSamples = data.size() / dr; + std::vector result(NumCompleteSamples); + auto ptr = data.data(); + for (auto &r : result) { + for (int i = 0; i != dr; ++i) { + int bit = (*ptr++ & mask) >> bit_index; + r |= bit << i; + } + } + return result; +} + +std::vector ReadFile(const std::string &fname, int offset = 8, + int dr = 24) { + const int element_size = static_cast(sizeof(uint64_t)); + const int byte_offset = element_size * offset; + const int expected_size = dr * element_size * 32 * 3; + std::ifstream fs(fname, std::ios::binary | std::ios::ate); + if (!fs.is_open()) { + throw std::runtime_error("File not found: " + std::string(fname)); + } + auto data_size = static_cast(fs.tellg()) - byte_offset; + if (data_size != expected_size) { + auto diff = data_size - expected_size; + std::cout << "WARNING: data size is: " << data_size + << " expected size is: " << expected_size << ", " + << std::abs(diff) << " bytes " + << ((diff < 0) ? "missing" : "too many") << '\n'; + } + std::vector data(expected_size / element_size); + fs.seekg(byte_offset, std::ios::beg); + fs.read(reinterpret_cast(data.data()), expected_size); + return data; +} + +py::array_t read_ctb_file(const std::string &fname, int offset = 8, + int dr = 24) { + auto data = ExtractBits<17, 6>(ReadFile(fname, offset, dr)); + return py::array(data.size(), data.data()); +} diff --git a/python/unit-tests/__pycache__/dac_test.cpython-37-PYTEST.pyc b/python/unit-tests/__pycache__/dac_test.cpython-37-PYTEST.pyc new file mode 100755 index 000000000..cb42d5d0f Binary files /dev/null and b/python/unit-tests/__pycache__/dac_test.cpython-37-PYTEST.pyc differ diff --git a/python/unit-tests/__pycache__/detector_test.cpython-37-PYTEST.pyc b/python/unit-tests/__pycache__/detector_test.cpython-37-PYTEST.pyc new file mode 100755 index 000000000..21d549630 Binary files /dev/null and b/python/unit-tests/__pycache__/detector_test.cpython-37-PYTEST.pyc differ diff --git a/python/unit-tests/__pycache__/test_detector_property.cpython-37-PYTEST.pyc b/python/unit-tests/__pycache__/test_detector_property.cpython-37-PYTEST.pyc new file mode 100755 index 000000000..c2f3580c0 Binary files /dev/null and b/python/unit-tests/__pycache__/test_detector_property.cpython-37-PYTEST.pyc differ diff --git a/python/unit-tests/__pycache__/test_utils.cpython-37-PYTEST.pyc b/python/unit-tests/__pycache__/test_utils.cpython-37-PYTEST.pyc new file mode 100755 index 000000000..845dc2c2b Binary files /dev/null and b/python/unit-tests/__pycache__/test_utils.cpython-37-PYTEST.pyc differ diff --git a/python/unit-tests/dac_test.py b/python/unit-tests/dac_test.py new file mode 100755 index 000000000..90341fcaa --- /dev/null +++ b/python/unit-tests/dac_test.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Testing setting and getting dacs from the detector +""" +from unittest.mock import Mock, call +import pytest +from pytest_mock import mocker +import numpy as np + +from sls_detector import Eiger +from sls_detector import DetectorApi + + +def test_get_vrf_for_three_mod(mocker): + m2= mocker.patch.object(DetectorApi, 'getNumberOfDetectors', autospec=True) + m2.return_value = 3 + m = mocker.patch.object(DetectorApi, 'getDac', autospec=True) + m.return_value = 1560 + d = Eiger() + vrf = d.dacs.vrf[:] + assert vrf == [1560, 1560, 1560] + +def test_set_vrf_for_three_mod_same_value(mocker): + m2= mocker.patch.object(DetectorApi, 'getNumberOfDetectors', autospec=True) + m2.return_value = 3 + m = mocker.patch.object(DetectorApi, 'setDac', autospec=True) +# m.return_value = 1560 + d = Eiger() + d.dacs.vrf[:] = 1500 + calls = [call('vrf', 0, 1500), call('vrf', 1, 1500), call('vrf', 2, 1500)] + m.assert_has_calls(calls) + assert m.call_count == 3 + +def test_set_vrf_for_four_mod_different_value(mocker): + m2= mocker.patch.object(DetectorApi, 'getNumberOfDetectors', autospec=True) + m2.return_value = 4 + m = mocker.patch.object(DetectorApi, 'setDac', autospec=True) +# m.return_value = 1560 + d = Eiger() + d.dacs.vrf = [1500, 1600, 1800, 1502] + calls = [call('vrf', 0, 1500), + call('vrf', 1, 1600), + call('vrf', 2, 1800), + call('vrf', 3, 1502)] + m.assert_has_calls(calls) + assert m.call_count == 4 + +def test_set_vrf_for_four_mod_different_value_slice(mocker): + m2= mocker.patch.object(DetectorApi, 'getNumberOfDetectors', autospec=True) + m2.return_value = 4 + m = mocker.patch.object(DetectorApi, 'setDac', autospec=True) +# m.return_value = 1560 + d = Eiger() + d.dacs.vrf[:] = [1500, 1600, 1800, 1502] + calls = [call('vrf', 0, 1500), + call('vrf', 1, 1600), + call('vrf', 2, 1800), + call('vrf', 3, 1502)] + m.assert_has_calls(calls) + assert m.call_count == 4 + +def test_set_vcp_single_call(mocker): + m2= mocker.patch.object(DetectorApi, 'getNumberOfDetectors', autospec=True) + m2.return_value = 2 + m = mocker.patch.object(DetectorApi, 'setDac', autospec=True) +# m.return_value = 1560 + d = Eiger() + d.dacs.vcp[1] = 1637 + m.assert_called_once_with('vcp', 1, 1637) + +def test_iterate_on_index_call_vcn(mocker): + m2= mocker.patch.object(DetectorApi, 'getNumberOfDetectors', autospec=True) + m2.return_value = 10 + m = mocker.patch.object(DetectorApi, 'setDac', autospec=True) +# m.return_value = 1560 + d = Eiger() + d.dacs.vcn[0,3,8] = 1532 + calls = [call('vcn', 0, 1532), + call('vcn', 3, 1532), + call('vcn', 8, 1532)] + m.assert_has_calls(calls) + assert m.call_count == 3 + +def test_set_dac_from_element_in_numpy_array(mocker): + m2= mocker.patch.object(DetectorApi, 'getNumberOfDetectors', autospec=True) + m2.return_value = 2 + m = mocker.patch.object(DetectorApi, 'setDac', autospec=True) + d = Eiger() + + vrf = np.array((1600,1700,1800)) + d.dacs.vrf = vrf[0] + calls = [call('vrf', 0, 1600), + call('vrf', 1, 1600),] + m.assert_has_calls(calls) + assert m.call_count == 2 + +def test_set_dac_from_element_in_numpy_array_using_slice(mocker): + m2= mocker.patch.object(DetectorApi, 'getNumberOfDetectors', autospec=True) + m2.return_value = 2 + m = mocker.patch.object(DetectorApi, 'setDac', autospec=True) + d = Eiger() + + vrf = np.array((1600,1700,1800)) + d.dacs.vrf[:] = vrf[0] + calls = [call('vrf', 0, 1600), + call('vrf', 1, 1600),] + m.assert_has_calls(calls) + assert m.call_count == 2 + +def test_set_eiger_default(mocker): + m2= mocker.patch.object(DetectorApi, 'getNumberOfDetectors', autospec=True) + m2.return_value = 2 + m = mocker.patch.object(DetectorApi, 'setDac', autospec=True) +# m.return_value = 1560 + d = Eiger() + d.dacs.set_default() + calls = [call('vsvp', 0, 0), + call('vsvp', 1, 0), + call('vtr', 0, 2500), + call('vtr', 1, 2500), + call('vrf', 0, 3300), + call('vrf', 1, 3300), + call('vrs', 0, 1400), + call('vrs', 1, 1400), + call('vsvn', 0, 4000), + call('vsvn', 1, 4000), + call('vtgstv', 0, 2556), + call('vtgstv', 1, 2556), + call('vcmp_ll', 0, 1500), + call('vcmp_ll', 1, 1500), + call('vcmp_lr', 0, 1500), + call('vcmp_lr', 1, 1500), + call('vcall', 0, 4000), + call('vcall', 1, 4000), + call('vcmp_rl', 0, 1500), + call('vcmp_rl', 1, 1500), + call('rxb_rb', 0, 1100), + call('rxb_rb', 1, 1100), + call('rxb_lb', 0, 1100), + call('rxb_lb', 1, 1100), + call('vcmp_rr', 0, 1500), + call('vcmp_rr', 1, 1500), + call('vcp', 0, 200), + call('vcp', 1, 200), + call('vcn', 0, 2000), + call('vcn', 1, 2000), + call('vis', 0, 1550), + call('vis', 1, 1550), + call('iodelay', 0, 660), + call('iodelay', 1, 660)] + + m.assert_has_calls(calls) + assert m.call_count == 17*2 + +def test_set_eiger_set_from_array_call_count(mocker): + import numpy as np + m2= mocker.patch.object(DetectorApi, 'getNumberOfDetectors', autospec=True) + m2.return_value = 3 + m = mocker.patch.object(DetectorApi, 'setDac', autospec=True) +# m.return_value = 1560 + d = Eiger() + d.dacs.set_from_array( np.zeros((17,3))) + assert m.call_count == 17*3 + +def test_get_fpga_temp(mocker): + m2= mocker.patch.object(DetectorApi, 'getNumberOfDetectors', autospec=True) + m2.return_value = 2 + m = mocker.patch.object(DetectorApi, 'getAdc', autospec=True) + m.return_value = 34253 + d = Eiger() + t = d.temp.fpga[:] + assert t == [34.253, 34.253] \ No newline at end of file diff --git a/python/unit-tests/detector_eiger.py b/python/unit-tests/detector_eiger.py new file mode 100755 index 000000000..e17127636 --- /dev/null +++ b/python/unit-tests/detector_eiger.py @@ -0,0 +1,489 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Testing parameters and methods of the Detector class using mocks +""" +from unittest.mock import Mock +import pytest +from pytest_mock import mocker + + + +@pytest.fixture +def d(): + from sls_detector import Eiger + return Eiger() + + +def test_acq_call(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.acq') + d.acq() + m.assert_called_once_with() + +def test_busy_call(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getAcquiringFlag') + m.return_value = False + assert d.busy == False + + +def test_assign_to_detector_type(d): + with pytest.raises(AttributeError): + d.detector_type = 'Eiger' + +def test_det_type(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getDetectorType') + m.return_value = 'Eiger' + assert d.detector_type == 'Eiger' + +def test_set_dynamic_range_4(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setDynamicRange') + d.dynamic_range = 4 + m.assert_called_with(4) + +def test_set_dynamic_range_8(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setDynamicRange') + d.dynamic_range = 8 + m.assert_called_with(8) + + +def test_set_dynamic_range_16(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setDynamicRange') + d.dynamic_range = 16 + m.assert_called_with(16) + +def test_set_dynamic_range_32(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setDynamicRange') + d.dynamic_range = 32 + m.assert_called_with(32) + +def test_set_dynamic_range_raises_exception(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setDynamicRange') + with pytest.raises(ValueError): + d.dynamic_range = 17 + +def test_get_dynamic_range_32(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getDynamicRange') + m.return_value = 32 + dr = d.dynamic_range + assert dr == 32 + +def test_eiger_matrix_reset(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getCounterBit') + m.return_value = True + assert d.eiger_matrix_reset == True + +def test_set_eiger_matrix_reset(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setCounterBit') + d.eiger_matrix_reset = True + m.assert_called_once_with(True) + + +def test_get_exposure_time(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getExposureTime') + m.return_value = 100000000 + assert d.exposure_time == 0.1 + +def test_set_exposure_time(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setExposureTime') + d.exposure_time = 1.5 + m.assert_called_once_with(1500000000) + +def test_set_exposure_time_less_than_zero(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setExposureTime') + with pytest.raises(ValueError): + d.exposure_time = -7 + + +def test_get_file_index(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getFileIndex') + m.return_value = 8 + assert d.file_index == 8 + +def test_set_file_index(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setFileIndex') + d.file_index = 9 + m.assert_called_with(9) + + +def test_set_file_index_raises_on_neg(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setFileIndex') + with pytest.raises(ValueError): + d.file_index = -9 + + +def test_get_file_name(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getFileName') + d.file_name + m.assert_called_once_with() + +def test_set_file_name(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setFileName') + d.file_name = 'hej' + m.assert_called_once_with('hej') + +def test_get_file_path(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getFilePath') + d.file_path + m.assert_called_once_with() + +def test_set_file_path_when_path_exists(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setFilePath') + #To avoid raising an exception because path is not there + mock_os = mocker.patch('os.path.exists') + mock_os.return_value = True + d.file_path = '/path/to/something/' + m.assert_called_once_with('/path/to/something/') + +def test_set_file_path_raises_when_not_exists(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setFilePath') + mock_os = mocker.patch('os.path.exists') + mock_os.return_value = False + with pytest.raises(FileNotFoundError): + d.file_path = '/path/to/something/' + +def test_get_file_write(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getFileWrite') + m.return_value = False + assert d.file_write == False + +def test_set_file_write(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setFileWrite') + d.file_write = True + m.assert_called_once_with(True) + + +def test_get_firmware_version(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getFirmwareVersion') + m.return_value = 20 + assert d.firmware_version == 20 + +def test_cannot_set_fw_version(d): + with pytest.raises(AttributeError): + d.firmware_version = 20 + +def test_get_high_voltage_call_signature(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getDac') + d.high_voltage + m.assert_called_once_with('vhighvoltage', -1) + +def test_get_high_voltage(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getDac') + m.return_value = 80 + assert d.high_voltage == 80 + +#self._api.setDac('vhighvoltage', -1, voltage) +def test_set_high_voltage(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setDac') + d.high_voltage = 80 + m.assert_called_once_with('vhighvoltage', -1, 80) + +def test_decode_hostname_two_names(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getHostname') + m.return_value = 'beb059+beb048+' + assert d.hostname == ['beb059', 'beb048'] + +def test_decode_hostname_four_names(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getHostname') + m.return_value = 'beb059+beb048+beb120+beb153+' + assert d.hostname == ['beb059', 'beb048', 'beb120', 'beb153'] + +def test_decode_hostname_blank(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getHostname') + m.return_value = '' + assert d.hostname == [] + +def test_get_image_size_gives_correct_size(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getImageSize') + m.return_value = (512,1024) + im_size = d.image_size + assert im_size.rows == 512 + assert im_size.cols == 1024 + + + +def test_load_config(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.readConfigurationFile') + #To avoid raising an exception because path is not there + mock_os = mocker.patch('os.path.isfile') + mock_os.return_value = True + d.load_config('/path/to/my/file.config') + m.assert_called_once_with('/path/to/my/file.config') + +def test_load_config_raises_when_file_is_not_found(d, mocker): + mocker.patch('_sls_detector.DetectorApi.readConfigurationFile') + mock_os = mocker.patch('os.path.isfile') + mock_os.return_value = False + with pytest.raises(FileNotFoundError): + d.load_config('/path/to/my/file.config') + +def test_load_parameters(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.readParametersFile') + #To avoid raising an exception because path is not there + mock_os = mocker.patch('os.path.isfile') + mock_os.return_value = True + d.load_parameters('/path/to/my/file.par') + m.assert_called_once_with('/path/to/my/file.par') + +def test_load_parameters_raises_when_file_is_not_found(d, mocker): + mocker.patch('_sls_detector.DetectorApi.readParametersFile') + mock_os = mocker.patch('os.path.isfile') + mock_os.return_value = False + with pytest.raises(FileNotFoundError): + d.load_parameters('/path/to/my/file.par') + +#getDetectorGeometry +def test_get_module_geometry_gives_correct_size(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getDetectorGeometry') + m.return_value = (13,7) + g = d.module_geometry + assert g.vertical == 7 + assert g.horizontal == 13 + +def test_get_module_geometry_access(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getDetectorGeometry') + m.return_value = (12,3) + assert d.module_geometry[0] == 12 + assert d.module_geometry[1] == 3 + assert d.module_geometry.vertical == 3 + assert d.module_geometry.horizontal == 12 + +def test_get_n_frames(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getNumberOfFrames') + m.return_value = 3 + assert d.n_frames == 3 + +def test_set_n_frames(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames') + d.n_frames = 9 + m.assert_called_once_with(9) + +def test_set_n_frames_raises_on_neg(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames') + with pytest.raises(ValueError): + d.n_frames = -1 + +def test_set_n_frames_raises_on_zero(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames') + with pytest.raises(ValueError): + d.n_frames = 0 + +def test_get_n_modules(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors') + m.return_value = 12 + assert d.n_modules == 12 + +def test_get_period_time(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getPeriod') + m.return_value = 130000000 + assert d.period == 0.13 + +def test_set_period_time(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setPeriod') + d.period = 1.953 + m.assert_called_once_with(1953000000) + +def test_set_period_time_less_than_zero(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setPeriod') + with pytest.raises(ValueError): + d.period = -7 + +def test_pulse_chip_call(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.pulseChip') + d.pulse_chip(15) + m.assert_called_once_with(15) + +def test_pulse_chip_call_minus_one(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.pulseChip') + d.pulse_chip(-1) + m.assert_called_once_with(-1) + +def test_pulse_chip_asserts_on_smaller_than_minus_one(d, mocker): + mocker.patch('_sls_detector.DetectorApi.pulseChip') + with pytest.raises(ValueError): + d.pulse_chip(-3) +#--------------------------------------------------------------------subexptime +def test_get_sub_exposure_time(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getSubExposureTime') + m.return_value = 2370000 + assert d.sub_exposure_time == 0.00237 + + +def test_set_sub_exposure_time(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setSubExposureTime') + d.sub_exposure_time = 0.002 + m.assert_called_once_with(2000000) + +def test_set_sub_exposure_time_raises_on_zero(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setSubExposureTime') + with pytest.raises(ValueError): + d.sub_exposure_time = 0 + +#-------------------------------------------------------------Rate correction +def test_get_rate_correction(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getRateCorrection') + m.return_value = [132,129] + assert d.rate_correction == [132,129] + +def test_set_rate_correction(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setRateCorrection') + mock_n = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors') + mock_n.return_value = 3 + d.rate_correction = [123,90,50] + m.assert_called_once_with([123,90,50]) + +def test_set_rate_correction_raises_on_wrong_number_of_values(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setRateCorrection') + mock_n = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors') + mock_n.return_value = 4 + with pytest.raises(ValueError): + d.rate_correction = [123,90,50] + +#----------------------------------------------------------------Readout clock +def test_get_readout_clock_0(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') + m.return_value = 0 + assert d.readout_clock == 'Full Speed' + +def test_get_readout_clock_1(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') + m.return_value = 1 + assert d.readout_clock == 'Half Speed' + +def test_get_readout_clock_2(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') + m.return_value = 2 + assert d.readout_clock == 'Quarter Speed' + +def test_get_readout_clock_3(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') + m.return_value = 3 + assert d.readout_clock == 'Super Slow Speed' + +def test_set_readout_clock_0(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') + d.readout_clock = 'Full Speed' + m.assert_called_once_with(0) + +def test_set_readout_clock_1(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') + d.readout_clock = 'Half Speed' + m.assert_called_once_with(1) + +def test_set_readout_clock_2(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') + d.readout_clock = 'Quarter Speed' + m.assert_called_once_with(2) + +def test_set_readout_clock_3(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') + d.readout_clock = 'Super Slow Speed' + m.assert_called_once_with(3) + +#----------------------------------------------------------------rx_datastream +def test_get_rx_datastream(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getRxDataStreamStatus') + m.return_value = False + assert d.rx_datastream == False + +def test_set_rx_datastream(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setRxDataStreamStatus') + d.rx_datastream = True + m.assert_called_once_with(True) + +def test_get_rx_zmqip(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') + d.rx_zmqip + m.assert_called_once_with('rx_zmqip') + +def test_get_rx_zmqport_call(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') + d.rx_zmqport + m.assert_called_once_with('rx_zmqport') + +def test_get_rx_zmqport_decode(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') + m.return_value = '30001+30003+' + assert d.rx_zmqport == [30001, 30002, 30003, 30004] + +def test_get_rx_zmqport_empty(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') + m.return_value = '' + assert d.rx_zmqport == [] + + +#--------------------------------------------------------------------status +def test_status_call(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getRunStatus') + d.status + m.assert_called_once_with() + +def test_start_acq_call(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.startAcquisition') + d.start_acq() + m.assert_called_once_with() + +def test_stop_acq_call(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.stopAcquisition') + d.stop_acq() + m.assert_called_once_with() + +#--------------------------------------------------------------------subexptime +def test_get_sub_exposure_time(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getSubExposureTime') + m.return_value = 2370000 + assert d.sub_exposure_time == 0.00237 + + +def test_set_sub_exposure_time(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setSubExposureTime') + d.sub_exposure_time = 0.002 + m.assert_called_once_with(2000000) + +def test_set_sub_exposure_time_raises_on_zero(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setSubExposureTime') + with pytest.raises(ValueError): + d.sub_exposure_time = 0 + +#------------------------------------------------------------------timing mode +def test_get_timing_mode(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getTimingMode') + d.timing_mode + m.assert_called_once_with() + +def test_set_timing_mode(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setTimingMode') + d.timing_mode = 'auto' + m.assert_called_once_with('auto') + +#----------------------------------------------------------------vthreshold +def test_get_vthreshold(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getDac') + d.vthreshold + m.assert_called_once_with('vthreshold', -1) + +def test_set_vthreshold(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setDac') + d.vthreshold = 1675 + m.assert_called_once_with('vthreshold', -1, 1675) + +#----------------------------------------------------------------trimbits +def test_get_trimbits(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getAllTrimbits') + d.trimbits + m.assert_called_once_with() + +def test_set_trimbits(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setAllTrimbits') + d.trimbits = 15 + m.assert_called_once_with(15) + +def test_set_trimbits_raises_outside_range(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setAllTrimbits') + + with pytest.raises(ValueError): + d.trimbits = 69 + + with pytest.raises(ValueError): + d.trimbits = -5 + + diff --git a/python/unit-tests/detector_test.py b/python/unit-tests/detector_test.py new file mode 100755 index 000000000..55de8c801 --- /dev/null +++ b/python/unit-tests/detector_test.py @@ -0,0 +1,472 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Testing parameters and methods of the Detector class using mocks +""" +from unittest.mock import Mock +import pytest +from pytest_mock import mocker + +import sys +sys.path.append('/home/l_frojdh/slsdetectorgrup/sls_detector') + +import _sls_detector +from sls_detector.errors import DetectorValueError, DetectorError +from sls_detector.utils import all_equal, element_if_equal +@pytest.fixture +def d(): + from sls_detector import Detector + return Detector() + + +def test_length_zero(d): + assert len(d) == 0 + +def test_acq_call(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.acq') + d.acq() + m.assert_called_once_with() + + + +def test_busy_call(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getAcquiringFlag') + m.return_value = False + assert d.busy == False + +def test_set_busy(d): + d.busy = True + assert d.busy == True + assert d._api.getAcquiringFlag() == True + d.busy = False + assert d.busy == False + assert d._api.getAcquiringFlag() == False + +def test_error_mask(d): + d._api.setErrorMask(1) + assert d.error_mask == 1 + d.clear_errors() + +def test_error_handling(d): + with pytest.raises(DetectorError): + d._provoke_error() + +def test_assign_to_detector_type(d): + with pytest.raises(AttributeError): + d.detector_type = 'Eiger' + +def test_det_type(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getDetectorType') + m.return_value = 'Eiger' + assert d.detector_type == 'Eiger' + + +def test_get_exposure_time(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getExposureTime') + m.return_value = 100000000 + assert d.exposure_time == 0.1 + +def test_set_exposure_time(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setExposureTime') + d.exposure_time = 1.5 + m.assert_called_once_with(1500000000) + +def test_set_exposure_time_less_than_zero(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setExposureTime') + with pytest.raises(DetectorValueError): + d.exposure_time = -7 + + +def test_get_file_index(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getFileIndex') + m.return_value = 8 + assert d.file_index == 8 + +def test_set_file_index(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setFileIndex') + d.file_index = 9 + m.assert_called_with(9) + + +def file_index_with_no_detector(d): + assert d.file_index == -100 + +def dr_with_no_detector(d): + assert d.dynamic_range == -100 + +def test_set_file_index_raises_on_neg(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setFileIndex') + with pytest.raises(ValueError): + d.file_index = -9 + + +def test_get_file_name(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getFileName') + d.file_name + m.assert_called_once_with() + +def test_set_file_name(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setFileName') + d.file_name = 'hej' + m.assert_called_once_with('hej') + +def test_get_file_path(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getFilePath') + d.file_path + m.assert_called_once_with() + +def test_set_file_path_when_path_exists(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setFilePath') + #To avoid raising an exception because path is not there + mock_os = mocker.patch('os.path.exists') + mock_os.return_value = True + d.file_path = '/path/to/something/' + m.assert_called_once_with('/path/to/something/') + +def test_set_file_path_raises_when_not_exists(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setFilePath') + mock_os = mocker.patch('os.path.exists') + mock_os.return_value = False + with pytest.raises(FileNotFoundError): + d.file_path = '/path/to/something/' + +def test_get_file_write(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getFileWrite') + m.return_value = False + assert d.file_write == False + +def test_set_file_write(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setFileWrite') + d.file_write = True + m.assert_called_once_with(True) + + +def test_get_firmware_version(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getFirmwareVersion') + m.return_value = 20 + assert d.firmware_version == 20 + +def test_cannot_set_fw_version(d): + with pytest.raises(AttributeError): + d.firmware_version = 20 + +def test_get_high_voltage_call_signature(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getDac') + d.high_voltage + m.assert_called_once_with('vhighvoltage', -1) + +def test_get_high_voltage(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getDac') + m.return_value = 80 + assert d.high_voltage == 80 + +#self._api.setDac('vhighvoltage', -1, voltage) +def test_set_high_voltage(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setDac') + d.high_voltage = 80 + m.assert_called_once_with('vhighvoltage', -1, 80) + +def test_decode_hostname_two_names(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getHostname') + m.return_value = 'beb059+beb048+' + assert d.hostname == ['beb059', 'beb048'] + +def test_decode_hostname_four_names(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getHostname') + m.return_value = 'beb059+beb048+beb120+beb153+' + assert d.hostname == ['beb059', 'beb048', 'beb120', 'beb153'] + +def test_decode_hostname_blank(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getHostname') + m.return_value = '' + assert d.hostname == [] + +def test_get_image_size_gives_correct_size(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getImageSize') + m.return_value = (512,1024) + im_size = d.image_size + assert im_size.rows == 512 + assert im_size.cols == 1024 + + + +def test_load_config(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.readConfigurationFile') + #To avoid raising an exception because path is not there + mock_os = mocker.patch('os.path.isfile') + mock_os.return_value = True + d.load_config('/path/to/my/file.config') + m.assert_called_once_with('/path/to/my/file.config') + +def test_load_config_raises_when_file_is_not_found(d, mocker): + mocker.patch('_sls_detector.DetectorApi.readConfigurationFile') + mock_os = mocker.patch('os.path.isfile') + mock_os.return_value = False + with pytest.raises(FileNotFoundError): + d.load_config('/path/to/my/file.config') + +def test_load_parameters(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.readParametersFile') + #To avoid raising an exception because path is not there + mock_os = mocker.patch('os.path.isfile') + mock_os.return_value = True + d.load_parameters('/path/to/my/file.par') + m.assert_called_once_with('/path/to/my/file.par') + +def test_load_parameters_raises_when_file_is_not_found(d, mocker): + mocker.patch('_sls_detector.DetectorApi.readParametersFile') + mock_os = mocker.patch('os.path.isfile') + mock_os.return_value = False + with pytest.raises(FileNotFoundError): + d.load_parameters('/path/to/my/file.par') + +#getDetectorGeometry +def test_get_module_geometry_gives_correct_size(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getDetectorGeometry') + m.return_value = (13,7) + g = d.module_geometry + assert g.vertical == 7 + assert g.horizontal == 13 + +def test_get_module_geometry_access(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getDetectorGeometry') + m.return_value = (12,3) + assert d.module_geometry[0] == 12 + assert d.module_geometry[1] == 3 + assert d.module_geometry.vertical == 3 + assert d.module_geometry.horizontal == 12 + +def test_module_geometry_without_detectors(d): + t = d.module_geometry + assert t.horizontal == 0 + assert t.vertical == 0 + +def test_get_n_frames(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getNumberOfFrames') + m.return_value = 3 + assert d.n_frames == 3 + +def test_set_n_frames(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames') + d.n_frames = 9 + m.assert_called_once_with(9) + +def test_nframes_without_detector(d): + assert d.n_frames == -100 + +def test_set_n_frames_raises_on_neg(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames') + with pytest.raises(DetectorValueError): + d.n_frames = -1 + +def test_set_n_frames_raises_on_zero(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setNumberOfFrames') + with pytest.raises(DetectorValueError): + d.n_frames = 0 + +def test_n_cycles_without_detector(d): + assert d.n_cycles == -100 + +def test_set_n_cycles_raises_on_zero(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setCycles') + with pytest.raises(DetectorValueError): + d.n_cycles = 0 + +def test_set_n_cycles(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setCycles') + d.n_cycles = 56 + m.assert_called_once_with(56) + + + +def test_n_measurements_without_detector(d): + assert d.n_measurements == -100 + +def test_set_n_measurements_raises_on_zero(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setNumberOfMeasurements') + with pytest.raises(DetectorValueError): + d.n_measurements = 0 + +def test_set_n_measurements(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setNumberOfMeasurements') + d.n_measurements = 560 + m.assert_called_once_with(560) + +def test_get_n_modules_no_detector(d): + assert d.n_modules == 0 + +def test_get_n_modules(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors') + m.return_value = 12 + assert d.n_modules == 12 + +def test_get_period_time(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getPeriod') + m.return_value = 130000000 + assert d.period == 0.13 + +def test_set_period_time(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setPeriod') + d.period = 1.953 + m.assert_called_once_with(1953000000) + +def test_set_period_time_less_than_zero(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setPeriod') + with pytest.raises(ValueError): + d.period = -7 + + +def test_get_online(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getOnline') + d.online + m.assert_called_once_with() + +def test_set_online(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setOnline') + d.online = True + m.assert_called_once_with(True) + +def test_last_client_ip_no_detector(d): + assert d.last_client_ip == '' + +def test_last_cliten_ip_call(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getLastClientIP') + d.last_client_ip + m.assert_called_once_with() + +#-------------------------------------------------------------Rate correction +def test_get_rate_correction(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getRateCorrection') + m.return_value = [132,129] + assert d.rate_correction == [132,129] + +def test_set_rate_correction(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setRateCorrection') + mock_n = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors') + mock_n.return_value = 3 + d.rate_correction = [123,90,50] + m.assert_called_once_with([123,90,50]) + +def test_set_rate_correction_raises_on_wrong_number_of_values(d, mocker): + mocker.patch('_sls_detector.DetectorApi.setRateCorrection') + mock_n = mocker.patch('_sls_detector.DetectorApi.getNumberOfDetectors') + mock_n.return_value = 4 + with pytest.raises(ValueError): + d.rate_correction = [123,90,50] + +#----------------------------------------------------------------Readout clock +def test_get_readout_clock_0(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') + m.return_value = 0 + assert d.readout_clock == 'Full Speed' + +def test_get_readout_clock_1(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') + m.return_value = 1 + assert d.readout_clock == 'Half Speed' + +def test_get_readout_clock_2(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') + m.return_value = 2 + assert d.readout_clock == 'Quarter Speed' + +def test_get_readout_clock_3(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getReadoutClockSpeed') + m.return_value = 3 + assert d.readout_clock == 'Super Slow Speed' + +def test_set_readout_clock_0(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') + d.readout_clock = 'Full Speed' + m.assert_called_once_with(0) + +def test_set_readout_clock_1(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') + d.readout_clock = 'Half Speed' + m.assert_called_once_with(1) + +def test_set_readout_clock_2(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') + d.readout_clock = 'Quarter Speed' + m.assert_called_once_with(2) + +def test_set_readout_clock_3(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setReadoutClockSpeed') + d.readout_clock = 'Super Slow Speed' + m.assert_called_once_with(3) + +#----------------------------------------------------------------rx_datastream +def test_get_rx_datastream(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getRxDataStreamStatus') + m.return_value = False + assert d.rx_datastream == False + +def test_set_rx_datastream(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setRxDataStreamStatus') + d.rx_datastream = True + m.assert_called_once_with(True) + +def test_get_rx_zmqip(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') + d.rx_zmqip + m.assert_called_once_with('rx_zmqip') + +def test_get_rx_zmqport_call(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') + d.rx_zmqport + m.assert_called_once_with('rx_zmqport') + +def test_get_rx_zmqport_decode(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') + m.return_value = ['30001', '30003'] + assert d.rx_zmqport == [30001, 30003] + +def test_get_rx_zmqport_empty(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getNetworkParameter') + m.return_value = '' + assert d.rx_zmqport == [] + + +#--------------------------------------------------------------------status +def test_status_call(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getRunStatus') + d.status + m.assert_called_once_with() + +def test_start_detecor(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.startAcquisition') + d.start_detector() + m.assert_called_once_with() + +def test_stop_acq_call(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.stopAcquisition') + d.stop_detector() + m.assert_called_once_with() + + + +#------------------------------------------------------------------timing mode +def test_get_timing_mode(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getTimingMode') + d.timing_mode + m.assert_called_once_with() + +def test_set_timing_mode(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setTimingMode') + d.timing_mode = 'auto' + m.assert_called_once_with('auto') + +#----------------------------------------------------------------vthreshold +def test_get_vthreshold(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.getDac') + d.vthreshold + m.assert_called_once_with('vthreshold', -1) + +def test_set_vthreshold(d, mocker): + m = mocker.patch('_sls_detector.DetectorApi.setDac') + d.vthreshold = 1675 + m.assert_called_once_with('vthreshold', -1, 1675) + + + + diff --git a/python/unit-tests/test_detector_property.py b/python/unit-tests/test_detector_property.py new file mode 100755 index 000000000..c647c4efc --- /dev/null +++ b/python/unit-tests/test_detector_property.py @@ -0,0 +1,76 @@ +import pytest +from sls_detector.detector_property import DetectorProperty + +class Holder: + """ + This class does nothing except hold values + for testing of the DetectorProperty class + """ + def __init__(self, N): + self.values = [i for i in range(N)] + def get(self, i): + return self.values[i] + def set(self, i,v): + self.values[i] = v + def nmod(self): + return len(self.values) + +@pytest.fixture +def p(): + h = Holder(5) + return DetectorProperty(h.get, h.set, h.nmod, 'prop') + +def test_initialization(): + def getf(i): + return 5 + def setf(): + return + def nmod(): + return 3 + name = 'a property' + p = DetectorProperty(getf, setf, nmod, name) + assert p.get == getf + assert p.set == setf + assert p.get_nmod == nmod + assert p.__name__ == name + +def test_get_single_value(p): + assert p[2] == 2 + +def test_get_all_values(p): + assert p[:] == [0, 1, 2, 3, 4] + +def test_get_values_by_iterable(p): + vals = p[1,3] + assert vals == [1,3] + +def test_set_single_value(p): + p[2] = 7 + assert p[:] == [0,1,7,3,4] + +def test_set_all(p): + p[:] = 10 + assert p[:] == [10,10,10,10,10] + +def test_set_all_by_list(p): + p[:] = [7,8,9,10,11] + assert p[:] == [7,8,9,10,11] + +def test_set_all_bool(p): + p[:] = True + assert p[:] == [True]*5 + +def test_set_by_iter(p): + keys = [2,4] + vals = [18,23] + p[keys] = vals + assert p[:] == [0,1,18,3,23] + +def test_set_by_iter_single_val(p): + keys = [2,4] + val = 9 + p[keys] = val + assert p[:] == [0,1,9,3,9] + +def test_print_values(p): + assert repr(p) == 'prop: [0, 1, 2, 3, 4]' diff --git a/python/unit-tests/test_utils.py b/python/unit-tests/test_utils.py new file mode 100755 index 000000000..e759f6cb4 --- /dev/null +++ b/python/unit-tests/test_utils.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Testing parameters and methods of the Detector class using mocks +""" + +import pytest +from sls_detector.utils import eiger_register_to_time +from sls_detector.utils import all_equal, element_if_equal + +def test_convert_zero(): + assert eiger_register_to_time(0) == 0 + +def test_convert_smallest_unit(): + assert pytest.approx(eiger_register_to_time(0b1000), 1e-9) == 1e-8 + +def test_convert_second_smallest_unit(): + assert pytest.approx(eiger_register_to_time(0b10000), 1e-9) == 2e-8 + +def test_convert_one_ms_using_exponent(): + assert pytest.approx(eiger_register_to_time(0b1101), 1e-9) == 1e-3 + +def test_convert_five_seconds(): + assert pytest.approx(eiger_register_to_time(0b1001110001000101), 1e-9) == 5.0 + +def test_all_equal_int(): + assert all_equal([5,5]) == True + +def test_all_equal_fails(): + assert all_equal([5,6]) == False + +def test_all_equal_tuple(): + assert all_equal(('a', 'a', 'a')) == True + +def test_all_equal_str(): + assert all_equal('aaa') == True + +def test_all_equal_str_fails(): + assert all_equal('aaab') == False + + + +def test_element_if_equal_int(): + assert element_if_equal([5,5]) == 5 + +def test_element_if_equal_str(): + assert element_if_equal('hhh') == 'h' + +def test_element_if_equal_int_fails(): + assert element_if_equal([5, 6, 7]) == [5, 6, 7] \ No newline at end of file diff --git a/recipe/meta.yaml b/recipe/meta.yaml deleted file mode 100644 index 3bbea1e83..000000000 --- a/recipe/meta.yaml +++ /dev/null @@ -1,89 +0,0 @@ - -package: - name: sls_detector_software - version: "developer" - -source: - - path: .. - -build: - number: 0 - rpaths: - - lib/ - -requirements: - build: - - {{ compiler('c') }} - - {{compiler('cxx')}} - - cmake - - qwt 6.* - - qt=4.8.7=7 - - zeromq=4.2.5=hfc679d8_5 - - pyzmq - - xorg-libx11 - - xorg-libice - - xorg-libxext - - xorg-libsm - - xorg-libxau - - xorg-libxrender - - xorg-libxfixes - - {{ cdt('mesa-libgl-devel') }} # [linux] - - {{ cdt('mesa-libegl-devel') }} # [linux] - - {{ cdt('mesa-dri-drivers') }} # [linux] - - {{ cdt('libselinux') }} # [linux] - - {{ cdt('libxdamage') }} # [linux] - - {{ cdt('libxxf86vm') }} # [linux] - - host: - - libstdcxx-ng - - libgcc-ng - - libpng >=1.6.32,<1.6.35 - - xorg-libx11 - - xorg-libice - - xorg-libxext - - xorg-libsm - - xorg-libxau - - xorg-libxrender - - xorg-libxfixes - - run: - - libstdcxx-ng - - libgcc-ng - -outputs: - - name: sls_detector_lib - version: "developer" - script: copy_lib.sh - requirements: - build: - - {{ compiler('c') }} - - {{compiler('cxx')}} - - name: sls_detector_gui - version: "developer" - script: copy_gui.sh - requirements: - build: - - {{ compiler('c') }} - - {{compiler('cxx')}} - - cmake - - qwt 6.* - - qt=4.8.7=7 - - zeromq=4.2.5=hfc679d8_5 - - pyzmq - - xorg-libx11 - - xorg-libice - - xorg-libxext - - xorg-libsm - - xorg-libxau - - xorg-libxrender - - xorg-libxfixes - - {{ cdt('mesa-libgl-devel') }} # [linux] - - {{ cdt('mesa-libegl-devel') }} # [linux] - - {{ cdt('mesa-dri-drivers') }} # [linux] - - {{ cdt('libselinux') }} # [linux] - - {{ cdt('libxdamage') }} # [linux] - - {{ cdt('libxxf86vm') }} # [linux] - run: - - sls_detector_lib=developer - - qwt 6.* - - qt=4.8.7=7 diff --git a/serverBin/eigerDetectorServerv4.0.0.22.0 b/serverBin/eigerDetectorServerv4.0.0.22.0 new file mode 120000 index 000000000..7e15d70e8 --- /dev/null +++ b/serverBin/eigerDetectorServerv4.0.0.22.0 @@ -0,0 +1 @@ +../slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv4.0.0.22.0 \ No newline at end of file diff --git a/serverBin/eigerDetectorServerv4.0.1.22.1 b/serverBin/eigerDetectorServerv4.0.1.22.1 deleted file mode 120000 index 04312328b..000000000 --- a/serverBin/eigerDetectorServerv4.0.1.22.1 +++ /dev/null @@ -1 +0,0 @@ -../slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServerv4.0.1.22.1 \ No newline at end of file diff --git a/serverBin/gotthardDetectorServerv4.0.0.3 b/serverBin/gotthardDetectorServerv4.0.0.3 new file mode 120000 index 000000000..d98581ea5 --- /dev/null +++ b/serverBin/gotthardDetectorServerv4.0.0.3 @@ -0,0 +1 @@ +../slsDetectorSoftware/gotthardDetectorServer/gotthardDetectorServerv4.0.0.3 \ No newline at end of file diff --git a/serverBin/gotthardDetectorServerv4.0.1.4 b/serverBin/gotthardDetectorServerv4.0.1.4 deleted file mode 120000 index bfc7b6c24..000000000 --- a/serverBin/gotthardDetectorServerv4.0.1.4 +++ /dev/null @@ -1 +0,0 @@ -../slsDetectorSoftware/gotthardDetectorServer/gotthardDetectorServerv4.0.1.4 \ No newline at end of file diff --git a/serverBin/jungfrauDetectorServerv4.0.0.0 b/serverBin/jungfrauDetectorServerv4.0.0.0 new file mode 120000 index 000000000..cfdfe7458 --- /dev/null +++ b/serverBin/jungfrauDetectorServerv4.0.0.0 @@ -0,0 +1 @@ +../slsDetectorSoftware/jungfrauDetectorServer/bin/jungfrauDetectorServerv4.0.0.0 \ No newline at end of file diff --git a/serverBin/jungfrauDetectorServerv4.0.1.0 b/serverBin/jungfrauDetectorServerv4.0.1.0 deleted file mode 120000 index 807c9b778..000000000 --- a/serverBin/jungfrauDetectorServerv4.0.1.0 +++ /dev/null @@ -1 +0,0 @@ -../slsDetectorSoftware/jungfrauDetectorServer/bin/jungfrauDetectorServerv4.0.1.0 \ No newline at end of file diff --git a/settingsdir/eiger/highgain/calibration.snbeb045 b/settingsdir/eiger/highgain/calibration.snbeb045 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/highgain/highgain.cal b/settingsdir/eiger/highgain/highgain.cal old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/highgain/highgain.trim b/settingsdir/eiger/highgain/highgain.trim old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/highgain/settings.snbeb045 b/settingsdir/eiger/highgain/settings.snbeb045 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/lowgain/calibration.snbeb045 b/settingsdir/eiger/lowgain/calibration.snbeb045 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/lowgain/lowgain.cal b/settingsdir/eiger/lowgain/lowgain.cal old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/lowgain/lowgain.trim b/settingsdir/eiger/lowgain/lowgain.trim old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/lowgain/settings.snbeb045 b/settingsdir/eiger/lowgain/settings.snbeb045 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/standard/4500eV/noise.sn031 b/settingsdir/eiger/standard/4500eV/noise.sn031 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/standard/4500eV/noise.sn032 b/settingsdir/eiger/standard/4500eV/noise.sn032 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/standard/5400eV/noise.sn031 b/settingsdir/eiger/standard/5400eV/noise.sn031 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/standard/5400eV/noise.sn032 b/settingsdir/eiger/standard/5400eV/noise.sn032 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/standard/6400eV/noise.sn031 b/settingsdir/eiger/standard/6400eV/noise.sn031 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/standard/6400eV/noise.sn032 b/settingsdir/eiger/standard/6400eV/noise.sn032 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/standard/calibration.sn031 b/settingsdir/eiger/standard/calibration.sn031 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/standard/calibration.sn032 b/settingsdir/eiger/standard/calibration.sn032 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/standard/eigernoise.sn049 b/settingsdir/eiger/standard/eigernoise.sn049 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/standard/noise.sn031 b/settingsdir/eiger/standard/noise.sn031 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/standard/noise.sn032 b/settingsdir/eiger/standard/noise.sn032 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/standard/standard.cal b/settingsdir/eiger/standard/standard.cal old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/standard/standard.trim b/settingsdir/eiger/standard/standard.trim old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/veryhighgain/calibration.sn031 b/settingsdir/eiger/veryhighgain/calibration.sn031 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/veryhighgain/calibration.sn032 b/settingsdir/eiger/veryhighgain/calibration.sn032 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/veryhighgain/noise.sn031 b/settingsdir/eiger/veryhighgain/noise.sn031 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/veryhighgain/noise.sn032 b/settingsdir/eiger/veryhighgain/noise.sn032 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/veryhighgain/veryhighgain.cal b/settingsdir/eiger/veryhighgain/veryhighgain.cal old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/veryhighgain/veryhighgain.trim b/settingsdir/eiger/veryhighgain/veryhighgain.trim old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/verylowgain/calibration.sn031 b/settingsdir/eiger/verylowgain/calibration.sn031 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/verylowgain/calibration.sn032 b/settingsdir/eiger/verylowgain/calibration.sn032 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/verylowgain/noise.sn031 b/settingsdir/eiger/verylowgain/noise.sn031 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/verylowgain/noise.sn032 b/settingsdir/eiger/verylowgain/noise.sn032 old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/verylowgain/verylowgain.cal b/settingsdir/eiger/verylowgain/verylowgain.cal old mode 100644 new mode 100755 diff --git a/settingsdir/eiger/verylowgain/verylowgain.trim b/settingsdir/eiger/verylowgain/verylowgain.trim old mode 100644 new mode 100755 diff --git a/settingsdir/mythen/fast/noise.snxxx b/settingsdir/mythen/fast/noise.snxxx old mode 100644 new mode 100755 diff --git a/settingsdir/mythen/highgain/noise.snxxx b/settingsdir/mythen/highgain/noise.snxxx old mode 100644 new mode 100755 diff --git a/settingsdir/mythen/standard/noise.snxxx b/settingsdir/mythen/standard/noise.snxxx old mode 100644 new mode 100755 diff --git a/settingsdir/mythen/standard/standard.trim b/settingsdir/mythen/standard/standard.trim old mode 100644 new mode 100755 diff --git a/slsDetectorCalibration/.gitignore b/slsDetectorCalibration/.gitignore deleted file mode 100644 index 5f41dcb88..000000000 --- a/slsDetectorCalibration/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -*.o -*.*~ diff --git a/slsDetectorCalibration/MovingStat.h b/slsDetectorCalibration/MovingStat.h deleted file mode 100755 index 35249b1c9..000000000 --- a/slsDetectorCalibration/MovingStat.h +++ /dev/null @@ -1,156 +0,0 @@ -#ifndef MOVINGSTAT_H -#define MOVINGSTAT_H - -#include - - -class MovingStat - { - - /** @short approximated moving average structure */ - public: - - - /** constructor - \param nn number of samples parameter to be used - */ - MovingStat(int nn=1000) : n(nn), m_n(0) {} - - /** - clears the moving average number of samples parameter, mean and standard deviation - */ - void Clear() - { - m_n = 0; - m_newM=0; - m_newM2=0; - } - - /** - clears the moving average number of samples parameter, mean and standard deviation - */ - void Set(double val, double rms=0, int m=-1) - { - if (m>=0) m_n = m; else m_n = n; - m_newM=val*m_n; - SetRMS(rms); - } - /** - clears the moving average number of samples parameter, mean and standard deviation - */ - void SetRMS(double rms) - { - if (rms<=0) { - m_newM2=m_newM*m_newM/n; - m_n=0; - } else { - if (m_n>0) - m_newM2=(m_n*rms*rms+m_newM*m_newM/m_n); - else { - m_newM2=(m_n*rms*rms+m_newM*m_newM/n); - m_n=0; - } - } - } - - /** sets number of samples parameter - \param i number of samples parameter to be set - */ - - int SetN(int i) {if (i>=1) n=i; return n;}; - - /** - gets number of samples parameter - \returns actual number of samples parameter - */ - int GetN() {return m_n;}; - - /** calculates the moving average i.e. adds if number of elements is lower than number of samples parameter, pushes otherwise - \param x value to calculate the moving average - */ - inline void Calc(double x) { - if (m_n 0) ? m_newM/m_n : 0.0; - } - - /** returns the squared mean, 0 if no elements are inside - \returns returns the squared average - */ - double M2() const - { - return ( (m_n > 1) ? m_newM2/m_n : 0.0 ); - } - - /** returns the variance, 0 if no elements are inside - \returns returns the variance - */ - inline double Variance() const - { - return ( (m_n > 1) ? (M2()-Mean()*Mean()) : 0.0 ); - } - - /** returns the standard deviation, 0 if no elements are inside - \returns returns the standard deviation - */ - inline double StandardDeviation() const - { - return ( (Variance() > 0) ? sqrt( Variance() ) : -1 ); - } - - private: - int n; /**< number of samples parameter */ - int m_n; /**< current number of elements */ - double m_newM; /**< accumulated average */ - double m_newM2; /**< accumulated squared average */ - }; -#endif diff --git a/slsDetectorCalibration/RunningStat.h b/slsDetectorCalibration/RunningStat.h deleted file mode 100755 index 1197ffc0f..000000000 --- a/slsDetectorCalibration/RunningStat.h +++ /dev/null @@ -1,55 +0,0 @@ - class RunningStat - { - public: - RunningStat() : m_n(0) {} - - void Clear() - { - m_n = 0; - } - - void Push(double x) - { - m_n++; - - // See Knuth TAOCP vol 2, 3rd edition, page 232 - if (m_n == 1) - { - m_oldM = m_newM = x; - m_oldS = 0.0; - } - else - { - m_newM = m_oldM + (x - m_oldM)/m_n; - m_newS = m_oldS + (x - m_oldM)*(x - m_newM); - - // set up for next iteration - m_oldM = m_newM; - m_oldS = m_newS; - } - } - - int NumDataValues() const - { - return m_n; - } - - double Mean() const - { - return (m_n > 0) ? m_newM : 0.0; - } - - double Variance() const - { - return ( (m_n > 1) ? m_newS/(m_n - 1) : 0.0 ); - } - - double StandardDeviation() const - { - return sqrt( Variance() ); - } - - private: - int m_n; - double m_oldM, m_newM, m_oldS, m_newS; - }; diff --git a/slsDetectorCalibration/Stat.h b/slsDetectorCalibration/Stat.h deleted file mode 100644 index 196f5bbb7..000000000 --- a/slsDetectorCalibration/Stat.h +++ /dev/null @@ -1,45 +0,0 @@ -class Stat - { - public: - - Stat() : n(0), m(0.), m2(0.) {} - - void Clear() - { - n = 0; - m=0; - m2=0; - } - - void Push(double x) - { - - m+=x; - m2+=x*x; - n++; - } - - int NumDataValues() const - { - return n; - } - - double Mean() const - { - return (n > 0) ? m/n : 0.0; - } - - double Variance() const - { - return ( (n >0 ) ? (m2/n-m*m/(n*n)) : 0.0 ); - } - - double StandardDeviation() const - { - return sqrt( Variance() ); - } - - private: - int n; - double m, m2; - }; diff --git a/slsDetectorCalibration/analogDetector.h b/slsDetectorCalibration/analogDetector.h deleted file mode 100644 index 65eaa651c..000000000 --- a/slsDetectorCalibration/analogDetector.h +++ /dev/null @@ -1,1164 +0,0 @@ -#ifndef ANALOGDETECTOR_H -#define ANALOGDETECTOR_H - -//#include - -#include -#include "slsDetectorData.h" -#include "pedestalSubtraction.h" -#include "commonModeSubtraction.h" -#include "tiffIO.h" -#include "slsInterpolation.h" - - -#ifdef ROOTSPECTRUM -#include -#include -#include -#include -#include -#include -#include -#include -#endif - -using namespace std; - -#ifndef FRAMEMODE_DEF -#define FRAMEMODE_DEF -/** -enum to define the flags of the data set, which are needed to seect the type of processing it should undergo: frame, pedestal, flat -*/ - enum frameMode { eFrame, ePedestal, eFlat }; -/** -enum to define the detector mode -*/ - enum detectorMode { eAnalog, ePhotonCounting, eInterpolating }; -#endif - - -template class analogDetector { - - /** @short class to perform pedestal subtraction etc. for an analog detector */ - - public: - - - - /** - - Constructor (no error checking if datasize and offsets are compatible!) - \param d detector data structure to be used - if null it is assumed that the data are in ordered ip=iy*nx+ix - \param sign is the sign of the data - \param nped number of samples for pedestal averaging - \param cm common mode subtraction algorithm, if any. Defaults to NULL i.e. none - \param nnx detector size in x - must be specified if no data structure is defined, otherwise defaults to the size of the data structure. - \param nny detector size in y - must be specified if no data structure is defined, otherwise defaults to the size of the data structure. - \param gm pointer to tha gain map matrix - - - */ - - - analogDetector(slsDetectorData *d, int sign=1, - commonModeSubtraction *cm=NULL, int nped=1000, int nnx=-1, int nny=-1, double *gm=NULL) : det(d), nx(nnx), ny(nny), stat(NULL), cmSub(cm), iframe(-1), dataSign(sign), gmap(gm), id(0) { - - if (det) - det->getDetectorSize(nx,ny); - - stat=new pedestalSubtraction*[ny]; - for (int i=0; idet; - nx=orig->nx; - ny=orig->ny; - dataSign=orig->dataSign; - iframe=orig->iframe; - gmap=orig->gmap; - cmSub=orig->cmSub; - id=orig->id; - xmin=orig->xmin; - xmax=orig->xmax; - ymin=orig->ymin; - ymax=orig->ymax; - thr=orig->thr; - // nSigma=orig->nSigma; - fMode=orig->fMode; - myFile=orig->myFile; - - - stat=new pedestalSubtraction*[ny]; - for (int i=0; iSetNPedestals(); - //cout << nped << " " << orig->getPedestal(ix,iy) << orig->getPedestalRMS(ix,iy) << endl; - for (int iy=0; iygetPedestal(ix,iy),orig->getPedestalRMS(ix,iy),orig->GetNPedestals(ix,iy)); - } - } - image=new int[nx*ny]; -#ifdef ROOTSPECTRUM - hs=(TH2F*)(orig->hs)->Clone();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); -#ifdef ROOTCLUST - hs3=(TH2F*)(orig->hs3)->Clone();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); - hs5=(TH2F*)(orig->hs5)->Clone();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); - hs7=(TH2F*)(orig->hs7)->Clone();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); - hs9=(TH2F*)(orig->hs9)->Clone();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); -#endif -#endif - - } - - - /** - clone. Must be virtual! - \returns a clone of the original analog detector - */ - virtual analogDetector *Clone() { - return new analogDetector(this); - } - - /** - Gives an id to the structure. For debugging purposes in case of multithreading. - \param i is to be set - \returns current id - */ - int setId(int i){id=i; return id;}; - - /** - Returns id of the structure. For debugging purposes in case of multithreading. - \returns current id - */ - int getId() {return id; }; - /** - Returns data size of the detector data structure - \returns data size of the detector data structurein bytes - */ - int getDataSize(){return det->getDataSize();}; - /** - Returns data size of the detector image matrix - \param nnx reference to image size in x - \param nny reference to image size in y - \param nns reference to number of subpixels for interpolating detector, will always be 1 in this case - \returns number of pixels of the detector image - */ - virtual int getImageSize(int &nnx, int &nny, int &nns){nnx=nx; nny=ny; nns=1; return nx*ny;}; - /** - Returns data size of the detector image matrix - \param nnx reference to pixel size in x - \param nny reference to pixel size in y - \returns number of pixels of the detector image - */ - virtual int getDetectorSize(int &nnx, int &nny){nnx=nx; nny=ny; return nx*ny;}; - - /** - set gain map - \param gm pointer to gain map matrix to be set - NULL unsets - \returns pointer to current gain map - */ - double *setGainMap(double *gm) {gmap=gm; return gmap;}; - - /** - return gain map - \returns pointer to current gain map - */ - double *getGainMap() {return gmap;}; - /** - reads a 32 bit tiff file of the size of the detector and sets its values as gain map for the detector. If file does not exist returns NULL, but does not change gainmap compared to previous settings. - \param imgname complete name of the file containing the gain map data - \returns pointer to current gain map is file reading succeeded, NULL is file reading didn't work. - */ - double *readGainMap(const char * imgname) { - uint32 nnx, nny; - float *gm=ReadFromTiff( imgname, nny, nnx); - if (gm) { - if (gmap) delete [] gmap; - gmap=new double[nnx*nny]; - for (int iy=0; iyClear(); -#ifdef ROOTSPECTRUM - hs->Reset(); -#ifdef ROOTCLUST - hs3->Reset();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); - hs5->Reset();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); - hs7->Reset();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); - hs9->Reset();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); -#endif -#endif - }; - - /** resets the commonModeSubtraction and increases the frame index */ - virtual void newFrame(){iframe++; if (cmSub) cmSub->newFrame();}; - - - /** sets the commonModeSubtraction algorithm to be used - \param cm commonModeSubtraction algorithm to be used (NULL unsets) - \returns pointer to the actual common mode subtraction algorithm - */ - commonModeSubtraction *setCommonModeSubtraction(commonModeSubtraction *cm) {cmSub=cm; return cmSub;}; -/** - gets the commonModeSubtraction algorithm to be used - \returns pointer to the actual common mode subtraction algorithm - */ - commonModeSubtraction *getCommonModeSubtraction() {return cmSub;}; - - - /** - sets the sign of the data - \param sign 1 means positive values for photons, -1 negative, 0 gets - \returns current sign for the data - */ - int setDataSign(int sign=0) {if (sign==1 || sign==-1) dataSign=sign; return dataSign;}; - - - /** - adds value to pedestal (and common mode) for the given pixel - \param val value to be added - \param ix pixel x coordinate - \param iy pixel y coordinate - \param cm 1 adds the value to common mod, 0 skips it. Defaults to 0. - not properly implemented - */ - virtual void addToPedestal(double val, int ix, int iy=0, int cm=0){ - if (ix>=0 && ix=0 && iy0) { - val-= getCommonMode(ix, iy); - } - stat[iy][ix].addToPedestal(val); - /* if (cmSub && cm>0) { */ - /* if (det) if (det->isGood(ix, iy)==0) return; */ - /* cmSub->addToCommonMode(val, ix, iy); */ - /* }; */ - }; - } - - double getCommonMode(int ix, int iy) { - if (cmSub) return cmSub->getCommonMode(ix, iy); - else return 0; - } - - - virtual void addToCommonMode(char *data){ - if (cmSub) { - for (int iy=ymin; iy0) - if (det->isGood(ix,iy)) - addToCommonMode(data, ix, iy); - } - } - //cout << "cm " << getCommonMode(0,0) << " " << getCommonMode(1,0) << endl; - } - } - virtual void addToCommonMode(char *data, int ix, int iy=0){ - if (cmSub) { - if (det) if (det->isGood(ix, iy)==0) return; - if (getNumpedestals(ix,iy)>0){ - cmSub->addToCommonMode(subtractPedestal(data,ix,iy,0), ix, iy); - // cout << ix << " " <=0 && ix=0 && iy0) - return stat[iy][ix].getPedestal()+getCommonMode(ix,iy); - else return stat[iy][ix].getPedestal(); - else return -1; - }; - - - /** - gets pedestal rms (i.e. noise) - \param ix pixel x coordinate - \param iy pixel y coordinate - \returns pedestal rms - */ - virtual double getPedestalRMS(int ix, int iy){ - if (ix>=0 && ix=0 && iy=0 && ix=0 && iy=0 && ix=0 && iy=0 && ix=0 && iySetBinContent(ix+1, iy+1,image[iy*nx+ix]); -#endif - } - } - ret=WriteToTiff(gm, imgname, ny, nx); - delete [] gm; -#ifdef ROOTSPECTRUM - char rootfn[10000]; - sprintf(rootfn,"%s.root",imgname); - TFile *f=new TFile(rootfn,"RECREATE"); - hs->Write("hs"); -#ifdef ROOTCLUST - hs3->Write("hs3"); - hs5->Write("hs5"); - hs7->Write("hs7"); - hs9->Write("hs9"); -#endif - hmap->Write("hmap"); - - - f->Close(); - delete f; - delete hmap; -#endif - return ret; - } -#ifdef ROOTSPECTRUM - TH2F *getSpectrum(){return hs;}; -#endif - /** - write 32bit tiff file containing the pedestals - \param imgname file name to be written - \returns NULL if file writing didn't succed, otherwise a pointer - */ - - virtual void *writePedestals(const char * imgname) { - float *gm=NULL; - void *ret; - gm=new float[nx*ny]; -#ifdef ROOTSPECTRUM - - TH2F *hmap=new TH2F("hmap","hmap",nx, -0.5,nx-0.5, ny, -0.5, ny-0.5); - -#endif - for (int iy=0; iygetCommonMode(); */ - /* else */ - gm[iy*nx+ix]=stat[iy][ix].getPedestal(); -#ifdef ROOTSPECTRUM - hmap->SetBinContent(ix+1, iy+1,gm[iy*nx+ix]); -#endif - } - } - ret=WriteToTiff(gm, imgname, ny, nx); - delete [] gm; - -#ifdef ROOTSPECTRUM - char rootfn[10000]; - sprintf(rootfn,"%s.root",imgname); - TFile *f=new TFile(rootfn,"RECREATE"); - hs->Write("hs"); -#ifdef ROOTCLUST - hs3->Write("hs3"); - hs5->Write("hs5"); - hs7->Write("hs7"); - hs9->Write("hs9"); -#endif - hmap->Write("hmap"); - f->Close(); - delete f; - delete hmap; -#endif - return ret; - } - - /** - read 32bit tiff file containing the pedestals - \param imgname file name to be read - \returns 0 if file reading didn't succed, otherwise 1 - */ - int readPedestals(const char * imgname) { - uint32 nnx, nny; - float *gm=ReadFromTiff( imgname, nny, nnx); - if (nnx>nx) nnx=nx; - if (nny>ny) nny=ny; - - - - if (gm) { - for (int iy=0; iynx) nnx=nx; - if (nny>ny) nny=ny; - - - - if (gm) { - for (int iy=0; iynx) nnx=nx; - if (nny>ny) nny=ny; - if (gm) { - for (int iy=0; iyisGood(ix,iy)) { - addToPedestal(data,ix,iy,1); - //if (ix==10 && iy==10) - // cout <=0 && xmi<=nx) xmin=xmi; - if (xma>=0 && xma<=nx) xmax=xma; - if (xmax=0 && ymi<=ny) ymin=ymi; - if (yma>=0 && yma<=ny) ymax=yma; - if (ymax=0 && ix=0 && iygetValue(data, ix, iy); - else - val=((double*)data)[iy*nx+ix]; - - /* if (ix==10 && iy==10) */ - /* cout << ix << " " << iy << " " << val ; */ - /* if (ix==100 && iy==100) */ - /* cout << ix << " " << iy << " " << val; */ - addToPedestal(val,ix,iy); - /* if (ix==10 && iy==10) */ - /* cout <<" " << getPedestal(ix,iy)<< endl; */ - /* if (ix==100 && iy==100) */ - /* cout << " " << getPedestal(ix,iy)<< endl; */ - } - return ; - - }; - - - /** - Subtracts pedestal from the data array in the region of interest - \param data pointer to the data - \param val pointer where the pedestal subtracted data should be added. If NULL, the internal image is used - \returns pointer to the pedestal subtracted data - */ - // virtual int *subtractPedestal(char *data, int *val=NULL) { - - virtual int *subtractPedestal(char *data, int *val=NULL, int cm=0) { - - newFrame(); - - if (val==NULL) - val=image;//new double[nx*ny]; - - for (int iy=ymin; iyisGood(ix,iy)) - val[iy*nx+ix]+=subtractPedestal(data, ix, iy,cm); - } - } - return val; - }; - - - - - /** - Subtracts pedestal from the data for a selected pixel - \param data pointer to the data - \param ix pixel x coordinate - \param iy pixel y coordinate - \returns pedestal subtracted value - */ - - - - virtual double subtractPedestal(char *data, int ix, int iy=0, int cm=0) { - double g=1.; - double val; - if (ix>=0 && ix=0 && iygetValue(data, ix, iy)-getPedestal(ix,iy,cm))/g; - else - val= (((double*)data)[iy*nx+ix]-getPedestal(ix,iy))/g; - -#ifdef ROOTSPECTRUM - hs->Fill(val,(iy-ymin)*(xmax-xmin)+(ix-xmin)); -#ifdef ROOTCLUST - double v3=0,v5=0,v7=0,v9=0; - for (int iix=-4; iix<5; iix++) - for (int iiy=-4; iiy<5; iiy++) { - if (det) - val= (dataSign*det->getValue(data, ix+iix, iy+iiy)-getPedestal(ix+iix,iy+iiy,cm))/g; - else - val= (((double*)data)[(iy+iiy)*nx+ix+iix]-getPedestal(ix+iix,iy+iiy,cm))/g; - - if (iix>-4 && iiy>-4 && iix<4 && iiy<4) { - if (iix>-3 && iiy>-3 && iix<3 && iiy<3){ - if (iix>-2 && iiy>-2 && iix<2 && iiy<2){ - v3+=val; - } - v5+=val; - } - v7+=val; - } - v9+=val; - } - hs3->Fill(v3,(iy-ymin)*(xmax-xmin)+(ix-xmin)); - hs5->Fill(v5,(iy-ymin)*(xmax-xmin)+(ix-xmin)); - hs7->Fill(v7,(iy-ymin)*(xmax-xmin)+(ix-xmin)); - hs9->Fill(v9,(iy-ymin)*(xmax-xmin)+(ix-xmin)); - -#endif -#endif - return val; - } - }; - - - /** - sets threshold value for conversion into number of photons - \param t threshold to be set - \returns threshold value - */ - double setThreshold(double t){thr=t; return thr;}; - - /** - gets threshold value for conversion into number of photons - \returns threshold value - */ - double getThreshold(){return thr;}; - /** - converts the data into number of photons for the selected pixel - \param data pointer to the data - \param ix pixel x coordinate - \param iy pixel y coordinate - \returns converted number of photons. If no threshold is set, returns gain converted pedestal subtracted data. - */ - - virtual int getNPhotons(char *data, int ix, int iy=0) { - int nph=0; - double v; - if (ix>=0 && ix=0 && iyFill(v,(iy-ymin)*(xmax-xmin)+(ix-xmin)); */ -/* #endif */ - if (thr>0) { - v+=0.5*thr; - nph=v/thr; - if (nph>0) - return nph; - return 0; - } - return v; - } - return 0; - }; - - /** - converts the data into number of photons for all pixels - \param data pointer to the data - \param nph pointer where the photons should added. If NULL,the internal image is used - \returns pointer to array containing the number of photons - */ - int *getNPhotons(char *data, int *nph=NULL) { - - double val; - if (nph==NULL) - nph=image; - newFrame(); - - addToCommonMode(data); - - for (int iy=ymin; iyisGood(ix,iy)) - nph[iy*nx+ix]+=getNPhotons(data, ix, iy); - } - } - return nph; - - } - - /** - clears the image array - - */ - virtual void clearImage(){ - for (int iy=0; iyReset(); -#ifdef ROOTCLUST - - if (hs3) - hs3->Reset(); - if (hs5) - hs5->Reset(); - if (hs7) - hs7->Reset(); - if (hs9) - hs9->Reset(); -#endif - //cout << "done " << endl; -#endif - }; - - /** sets/gets number of samples for moving average pedestal calculation - \param i number of samples to be set (0 or negative gets) - \returns actual number of samples - */ - int SetNPedestals(int i=-1) { - int ix=0, iy=0; - if (i>0) - for (iy=0; iy=0 && ix=0 && iyisGood(ix,iy)) { - if (ix>=0 && ix=0 && iy *det; /**< slsDetectorData to be used */ - int nx; /**< Size of the detector in x direction */ - int ny; /**< Size of the detector in y direction */ - pedestalSubtraction **stat; /**< pedestalSubtraction class */ - commonModeSubtraction *cmSub;/**< commonModeSubtraction class */ - int dataSign; /**< sign of the data i.e. 1 if photon is positive, -1 if negative */ - int iframe; /**< frame number (not from file but incremented within the dataset every time newFrame is called */ - double *gmap; - int *image; - int id; - //int xmin, xmax, ymin, ymax; int xmin; /**< minimum x of the region of interest */ - int xmin; /**< minimum x of the region of interest */ - int xmax; /**< maximum x of the region of interest */ - int ymin;/**< minimum y of the region of interest */ - int ymax;/**< maximum y of the region of interest */ - double thr; /**< threshold to be used for conversion into number of photons */ - // int nSigma; /**< number of sigma to be used for conversion into number of photons if threshold is undefined */ - frameMode fMode; /**< current detector frame mode */ - detectorMode dMode; /**< current detector frame mode */ - FILE *myFile; /**< file pointer to write to */ -#ifdef ROOTSPECTRUM - TH2F *hs; -#ifdef ROOTCLUST - TH2F *hs3; - TH2F *hs5; - TH2F *hs7; - TH2F *hs9; -#endif -#endif -}; - -#endif diff --git a/slsDetectorCalibration/commonModeSubtraction.h b/slsDetectorCalibration/commonModeSubtraction.h deleted file mode 100644 index 0484e6746..000000000 --- a/slsDetectorCalibration/commonModeSubtraction.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef COMMONMODESUBTRACTION_H -#define COMMONMODESUBTRACTION_H - -#include "MovingStat.h" - - - - -class commonModeSubtraction { - - /** @short class to calculate the common mode of the pedestals based on an approximated moving average*/ - - public: - - /** constructor - \param nn number of samples for the moving average to calculate the average common mode - \param iroi number of regions on which one can calculate the common mode separately. Defaults to 1 i.e. whole detector - - */ - commonModeSubtraction(int nn=1000, int iroi=1) : cmStat(NULL), cmPed(NULL), nCm(NULL), nROI(iroi) {cmStat=new MovingStat[nROI]; for (int i=0; i0) cmStat[i].Calc(cmPed[i]/nCm[i]); - nCm[i]=0; - cmPed[i]=0; - }}; - - /** adds the pixel to the sum of pedestals -- virtual func must be overloaded to define the regions of interest - \param val value to add - \param ix pixel x coordinate - \param iy pixel y coordinate - */ - virtual void addToCommonMode(double val, int ix=0, int iy=0) { - (void) ix; (void) iy; - - //if (isc>=0 && isc0) return cmPed[0]/nCm[0]-cmStat[0].Mean(); - return 0;}; - - - - - - protected: - MovingStat *cmStat; /** - -class commonModeSubtraction { - - /** @short class to calculate the common mode of the pedestals based on an approximated moving average*/ - - public: - - /** constructor - \param nn number of samples for the moving average to calculate the average common mode - \param iroi number of regions on which one can calculate the common mode separately. Defaults to 1 i.e. whole detector - - */ - commonModeSubtraction(int iroi=1, int ns=3) : nROI(iroi), nsigma(ns) { - mean=new double[nROI]; - mean2=new double[nROI]; - nCm=new double[nROI]; - }; - - /** destructor - deletes the moving average(s) and the sum of pedestals calculator(s) */ - virtual ~commonModeSubtraction() {delete [] mean; delete [] mean2; delete [] nCm;}; - - - /** clears the moving average and the sum of pedestals calculation - virtual func*/ - virtual void Clear(){ - for (int i=0; i0) cmStat[i].Calc(cmPed[i]/nCm[i]); - nCm[i]=0; - mean[i]=0; - mean2[i]=0; - }}; - - /** adds the pixel to the sum of pedestals -- virtual func must be overloaded to define the regions of interest - \param val value to add - \param ix pixel x coordinate - \param iy pixel y coordinate - */ - virtual void addToCommonMode(double val, int ix=0, int iy=0) { - - int iroi=getROI(ix,iy); - // if (iroi==0) val=100; - // else val=-100; - // if (isc>=0 && isc=0 && iroi=0 && iroi0) - return mean[iroi]/nCm[iroi]; - } - return 0; - }; - - /** gets the common mode i.e. the difference between the current average sum of pedestals mode and the average pedestal - \param ix pixel x coordinate - \param iy pixel y coordinate - \return the difference between the current average sum of pedestals and the average pedestal - */ - virtual double getCommonModeRMS(int ix=0, int iy=0) { - int iroi=getROI(ix,iy); - if (iroi>=0 && iroi0) - return sqrt(mean2[iroi]/nCm[iroi]-(mean[iroi]/nCm[iroi])*(mean[iroi]/nCm[iroi])); - } - return 0; - }; - - /** - gets the common mode ROI for pixel ix, iy -should be overloaded! - */ - virtual int getROI(int ix, int iy){ (void) ix; (void) iy; return 0;}; - - - - protected: - double *mean; /** { - - - public: - mythen3_01_jctbData( int nch=64*3,int dr=24, int off=5): slsDetectorData(64*3,1,dr*8*nch,NULL,NULL,NULL), dynamicRange(dr), serialOffset(off), frameNumber(0), numberOfCounters(nch) {}; - - virtual void getPixel(int ip, int &x, int &y) {x=-1; y=-1;}; - - virtual short unsigned int getChannel(char *data, int ix, int iy=0) { - int ret=-1; - short unsigned int *val=mythen03_frame(data,dynamicRange,numberOfCounters,serialOffset); - if (ix>=0 && ix=0) frameNumber=f; return frameNumber; }; - virtual int setDynamicRange(int d=-1) {if (d>0 && d<=24) dynamicRange=d; return dynamicRange;}; - virtual int setSerialOffset(int d=-1) {if (d>=0) serialOffset=d; return serialOffset;}; - virtual int setNumberOfCounters(int d=-1) {if (d>=0) numberOfCounters=d; return numberOfCounters;}; - - - private: - - int dynamicRange; - int serialOffset; - int frameNumber; - int numberOfCounters; - - - - -}; - -#endif diff --git a/slsDetectorCalibration/dataStructures/Mythen3_02_jctbData.h b/slsDetectorCalibration/dataStructures/Mythen3_02_jctbData.h deleted file mode 100644 index a76e2cbaf..000000000 --- a/slsDetectorCalibration/dataStructures/Mythen3_02_jctbData.h +++ /dev/null @@ -1,130 +0,0 @@ -#ifndef MYTHEN302JCTBDATA_H -#define MYTHEN302JCTBDATA_H - - -#include "Mythen3_01_jctbData.h" -//class mythen3_02_jctbData : public slsDetectorData { -class mythen3_02_jctbData : public mythen3_01_jctbData { - - - public: - mythen3_02_jctbData( int nch=64*3,int dr=24, int off=5): mythen3_01_jctbData( nch,dr, off) - //slsDetectorData(64*3,1,dr*8*nch,NULL,NULL,NULL), dynamicRange(dr), serialOffset(off), frameNumber(0), numberOfCounters(nch) - {}; - - /* virtual void getPixel(int ip, int &x, int &y) {x=-1; y=-1;}; */ - - /* virtual short unsigned int getChannel(char *data, int ix, int iy=0) { */ - /* int ret=-1; */ - /* short unsigned int *val=mythen03_frame(data,dynamicRange,numberOfCounters,serialOffset); */ - /* if (ix>=0 && ix=0) frameNumber=f; return frameNumber; }; */ - /* virtual int setDynamicRange(int d=-1) {if (d>0 && d<=24) dynamicRange=d; return dynamicRange;}; */ - /* virtual int setSerialOffset(int d=-1) {if (d>=0) serialOffset=d; return serialOffset;}; */ - /* virtual int setNumberOfCounters(int d=-1) {if (d>=0) numberOfCounters=d; return numberOfCounters;}; */ - - - /* private: */ - - /* int dynamicRange; */ - /* int serialOffset; */ - /* int frameNumber; */ - /* int numberOfCounters; */ - - - - -}; - -#endif diff --git a/slsDetectorCalibration/dataStructures/adcSar2_jctbData.h b/slsDetectorCalibration/dataStructures/adcSar2_jctbData.h deleted file mode 100644 index 0b0665aaf..000000000 --- a/slsDetectorCalibration/dataStructures/adcSar2_jctbData.h +++ /dev/null @@ -1,63 +0,0 @@ -#ifndef ADCSAR2_JCTBDATA_H -#define ADCSAR2_JCTBDATA_H - - -class adcSar2_jctbData : public slsDetectorData { - - - public: - adcSar2_jctbData(int nsamples=1000): slsDetectorData(nsamples,1,nsamples*8,NULL,NULL,NULL){}; - - virtual void getPixel(int ip, int &x, int &y) {x=ip/8; y=1;}; - - virtual short unsigned int getChannel(char *data, int ix, int iy=0) { - int adcvalue=0; - int vv1= *((int16_t*) (data+8*ix)); - int vv2= *((int16_t*) (data+8*ix+2)); - for (int jj=0;jj<8;jj++){ - adcvalue=adcvalue+ (((vv1>>(jj*2)) & 0x1)<<(jj)); - } - for (int jj=0;jj<4;jj++){ - adcvalue=adcvalue+ (((vv2>>(jj*2)) & 0x1)<<(jj+8)); - } - return adcvalue; - }; - - virtual int getFrameNumber(char *buff) {return frameNumber;}; - - virtual char *findNextFrame(char *data, int &ndata, int dsize) { - ndata=dsize; - return data; - } - - virtual char *readNextFrame(ifstream &filebin) { - char *data=NULL; - if (filebin.is_open()) { - data=new char[dataSize]; - filebin.read(data,dataSize); - } - return data; - } - - /* virtual int **getData(char *ptr, int dsize=-1) { */ - /* int **val; */ - /* val=new int*[1]; */ - /* val[0]=mythen03_frame(ptr,dynamicRange,nx,serialOffset); */ - /* return val; */ - - /* } */ - - - - virtual int setFrameNumber(int f=0) {if (f>=0) frameNumber=f; return frameNumber; }; - - private: - - int frameNumber; - - - - -}; - -#endif diff --git a/slsDetectorCalibration/dataStructures/chiptestBoardData.h b/slsDetectorCalibration/dataStructures/chiptestBoardData.h deleted file mode 100644 index 0ef633c44..000000000 --- a/slsDetectorCalibration/dataStructures/chiptestBoardData.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef CHIPTESTDATA_H -#define CHIPTESTDATA_H - -#include "slsDetectorData.h" - -class chiptestBoardData : public slsDetectorData { - - - public: - - /** - chiptestBoard data structure. Works for data acquired using the chiptestBoard. - Inherits and implements slsDetectorData. - - Constructor (no error checking if datasize and offsets are compatible!) - \param npx number of pixels in the x direction - \param npy number of pixels in the y direction (1 for strips) - \param nadc number of adcs - \param offset offset at the beginning of the pattern - \param dMap array of size nx*ny storing the pointers to the data in the dataset (as offset) - \param dMask Array of size nx*ny storing the polarity of the data in the dataset (should be 0 if no inversion is required, 0xffffffff is inversion is required) - \param dROI Array of size nx*ny. The elements are 1s if the channel is good or in the ROI, 0 is bad or out of the ROI. NULL (default) means all 1s. - - */ - chiptestBoardData(int npx, int npy, int nadc, int offset, int **dMap=NULL, uint16_t **dMask=NULL, int **dROI=NULL): slsDetectorData(npx, npy, nadc*(npx*npy)+offset, dMap, dMask, dROI), nAdc(nadc), offSize(offset), iframe(0) {}; // should be? nadc*(npx*npy+offset) - - - - /** - - Returns the frame number for the given dataset. Virtual func: works for slsDetectorReceiver data (also for each packet), but can be overloaded. - \param buff pointer to the dataset - \returns frame number - - */ - - virtual int getFrameNumber(char *buff){(void)buff; return iframe;}; - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! - \param data pointer to the memory to be analyzed - \param ndata size of frame returned - \param dsize size of the memory slot to be analyzed - \returns always return the pointer to data (no frame loss!) - */ - - virtual char *findNextFrame(char *data, int &ndata, int dsize) {ndata=dsize;setDataSize(dsize); return data;}; - - /** - Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! - \param filebin input file stream (binary) - \returns pointer to the first packet of the last good frame, NULL if no frame is found or last frame is incomplete - */ - - virtual char *readNextFrame(ifstream &filebin) { - - int afifo_length=0; - uint16_t *afifo_cont; - - if (filebin.is_open()) { - if (filebin.read((char*)&afifo_length,sizeof(uint32_t))) { - setDataSize(afifo_length*nAdc*sizeof(uint16_t)); - afifo_cont=new uint16_t[afifo_length*nAdc]; - if (filebin.read((char*)afifo_cont,afifo_length*sizeof(uint16_t)*nAdc)) { - iframe++; - return (char*)afifo_cont; - } else { - delete [] afifo_cont; - return NULL; - } - } else { - return NULL; - } - } - return NULL; - }; - - private: - const int nAdc; /** { -public: - - - - - /** - Implements the slsReceiverData structure for the eiger prototype read out by a half module i.e. using the slsReceiver - (256*256 pixels, 512 packets for 16 bit mode, 256 for 8, 128 for 4, 1024 for 32, 1040 etc.) - \param d dynamic range - \param c crosstalk parameter for the output buffer - - */ - - - eigerHalfModuleData(bool t, bool l, int dr, int tg, int psize, int dsize, int npf, int x, int y, double c=0): - slsReceiverData(x, y, npf, psize), - top(t), left(l), - dynamicRange(dr), tenGiga(tg), - packetSize(psize), onepacketdataSize(dsize), numberofPacketsPerFrame(npf), - xtalk(c), - header_t(0), footer_t(0){ - - - int **dMap; - uint32_t **dMask; - - dMap=new int*[ny]; - dMask=new uint32_t*[ny]; - - - for (int i = 0; i < ny; i++) { - dMap[i] = new int[nx]; - dMask[i] = new uint32_t[nx]; - } - - //Map - int totalNumberOfBytes = numberofPacketsPerFrame * packetSize; - int iPacket = 8; - int iData = 0; - int increment = (dynamicRange/8); - int ic_increment = 1; - if (dynamicRange == 4) { - increment = 1; - ic_increment = 2; - } - - if(top){ - for (int ir=0; ir= onepacketdataSize){ - iPacket += 16; - iData = 0; - } - - } - } - } - - //bottom - else{ - iData = 0; - int numbytesperline; - switch(dynamicRange){ - case 4: numbytesperline = 256; break; - case 8: numbytesperline = 512; break; - case 16:numbytesperline = 1024; break; - case 32:numbytesperline = 2048; break; - } - iPacket = totalNumberOfBytes - numbytesperline - 8; - if((dynamicRange == 32) && (!tenGiga)) - iPacket -= 16; - - for (int ir=0; irpacketnum)); - }; - - - - /** - returns the pixel value as double correcting for the output buffer crosstalk - \param data pointer to the memory - \param ix coordinate in the x direction - \param iy coordinate in the y direction - \returns channel value as double - - */ - double getValue(char *data, int ix, int iy=0) { - // cout << "##" << (void*)data << " " << ix << " " <=0 && ix=0 && iy=0 && dataMap[iy][ix]missingpacket); - - if(identifier==deactivatedPacketValue){ - // cprintf(RED,"deactivated packet\n"); - return -2; - } - // -----END OF CHECK ------------------------------------------------------------- - - - }else{ - cprintf(RED,"outside limits\n"); - return -99; - } - - //get proper data - n = ((uint32_t)(*((uint32_t*)(((char*)data)+(dataMap[iy][ix]))))); - - //each byte is shared by 2 pixels for 4 bit mode - if(dynamicRange == 4){ - if(ix != origX) - return ((n & 0xf0)>>4)^m; - return (n & 0xf)^m; - } - else if(dynamicRange == 8) return (n & 0xff)^m; - else if(dynamicRange == 16) return (n & 0xffff)^m; - else return (n & 0xffffffff)^m; - - - }; - - - /** sets the output buffer crosstalk correction parameter - \param c output buffer crosstalk correction parameter to be set - \returns current value for the output buffer crosstalk correction parameter - - */ - double setXTalk(double c) {xtalk=c; return xtalk;} - - - /** gets the output buffer crosstalk parameter - \returns current value for the output buffer crosstalk correction parameter - */ - double getXTalk() {return xtalk;} - - void getChannelArray(double* data, char* buffer){ - for(int iy = 0; iy < ny; iy++){ - for(int ix = 0; ix < nx; ix++){ - data[iy*nx+ix] = getValue((char*)buffer,ix,iy); - //cprintf(BLUE,"%d,%d :%f\n",ix,iy,value); - } - } - } - - - int* decodeData(int *datain) { - - int dataBytes = numberofPacketsPerFrame * onepacketdataSize; - int nch = nx*ny; - int* dataout = new int [nch]; - char *ptr=(char*)datain; - char iptr; - - const int bytesize=8; - int ival=0; - int ipos=0, ichan=0, ibyte; - - switch (dynamicRange) { - case 4: - for (ibyte=0; ibyte>(ipos*4))&0xf; //pick the right 4bit - dataout[ichan]=ival; - ichan++; - } - } - break; - case 8: - for (ichan=0; ichan { - - private: - const int nModules; - const int offset; - int iframe; - - -public: - - - - /** - Implements the slsReceiverData structure for the gotthard read out by a module i.e. using the slsReceiver - (1x1280 pixels, 2 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - gotthardDoubleModuleDataNew(int off=24*2, int nmod=2): slsDetectorData(1280*nmod, 1, nmod*(1280*2+off)), nModules(nmod), offset(off),iframe(0) { - - - - -#ifdef BCHIP074_BCHIP075 - cout << "This is a bchip074-bchip075 system " << endl; -#endif - - - uint16_t **dMask; - int **dMap; - int ix, iy; - int ypixels=1; - int xpixels=1280*nmod; - int imod, ipix; - dMask=new uint16_t*[1]; - dMap=new int*[1]; - dMap[0] = new int[1280*nmod]; - dMask[0] = new uint16_t[1280*nmod]; - - for(int ix=0; ix=128*4 && ibad<128*5) || (ibad>=9*128 && ibad<10*128) || (ibad>=(1280+128*4) && ibad=(1280+128*6))) - dataROIMask[0][ix]=0; -#endif - } - - setDataMap(dMap); - setDataMask(dMask); - - }; - - - /** - - Returns the frame number for the given dataset. - \param buff pointer to the dataset - \returns frame number - - */ - - - int getFrameNumber(char *buff){if (offset>=sizeof(sls_detector_header)) return ((sls_detector_header*)buff)->frameNumber; return iframe;};//*((int*)(buff+5))&0xffffff;}; - - - - /** - gets the packets number (last packet is labelled with 0 and is replaced with 40) - \param buff pointer to the memory - \returns packet number - - */ - - int getPacketNumber(char *buff){if (offset>=sizeof(sls_detector_header))return ((sls_detector_header*)buff)->packetNumber;}; - - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - np=getPacketNumber(data); - return data; - } - } - return NULL; - - - - }; - - - - -}; - - - - - -#endif diff --git a/slsDetectorCalibration/dataStructures/gotthardModuleData.h b/slsDetectorCalibration/dataStructures/gotthardModuleData.h deleted file mode 100644 index 3f674af57..000000000 --- a/slsDetectorCalibration/dataStructures/gotthardModuleData.h +++ /dev/null @@ -1,148 +0,0 @@ -#ifndef GOTTHARDMODULEDATA_H -#define GOTTHARDMODULEDATA_H -#include "slsReceiverData.h" - - - - - -#define FRAMEMASK 0xFFFFFFFE -#define PACKETMASK 1 -#define FRAMEOFFSET 0x1 - - -class gotthardModuleData : public slsReceiverData { -public: - - - - - /** - Implements the slsReceiverData structure for the gotthard read out by a module i.e. using the slsReceiver - (1x1280 pixels, 2 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - gotthardModuleData(double c=0): slsReceiverData(xpixels, ypixels, npackets, buffersize), xtalk(c) { - - uint16_t **dMask; - int **dMap; - int ix, iy; - int initial_offset = 2; - int offset = initial_offset; - - dMask=new uint16_t*[ypixels]; - dMap=new int*[ypixels]; - for (int i = 0; i < ypixels; i++) { - dMap[i] = new int[xpixels]; - dMask[i] = new uint16_t[xpixels]; - } - - for(ix=0; ix>FRAMEOFFSET); - }; - - - - /** - gets the packets number (last packet is labelled with 0 and is replaced with 40) - \param buff pointer to the memory - \returns packet number - - */ - - int getPacketNumber(char *buff){ - int np=(*(int*)buff); - //gotthards frame header must be incremented - ++np; - //packet index should be 1 or 2 - return ((np&PACKETMASK)+1); - }; - - - /** - returns the pixel value as double correcting for the output buffer crosstalk - \param data pointer to the memory - \param ix coordinate in the x direction - \param iy coordinate in the y direction - \returns channel value as double - - */ - double getValue(char *data, int ix, int iy=0) { - //check how it is for gotthard - if (xtalk==0) - return slsDetectorData::getValue(data, ix, iy); - else - return slsDetectorData::getValue(data, ix, iy)-xtalk*slsDetectorData::getValue(data, ix-1, iy); - }; - - - - /** sets the output buffer crosstalk correction parameter - \param c output buffer crosstalk correction parameter to be set - \returns current value for the output buffer crosstalk correction parameter - - */ - double setXTalk(double c) {xtalk=c; return xtalk;} - - - /** gets the output buffer crosstalk parameter - \returns current value for the output buffer crosstalk correction parameter - */ - double getXTalk() {return xtalk;} - - - - - - - -private: - - double xtalk; /** { - - private: - - int iframe; - const int offset; - - -public: - - - - /** - Implements the slsReceiverData structure for the gotthard read out by a module i.e. using the slsReceiver - (1x1280 pixels, 2 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - gotthardModuleDataNew(int off=24*2, int nch=1280): slsDetectorData(nch, 1, nch*2+off), offset(off) { - - uint16_t **dMask; - int **dMap; - int ix, iy; - int ypixels=1; - int xpixels=nch; - - dMask=new uint16_t*[1]; - dMap=new int*[1]; - dMap[0] = new int[nch]; - dMask[0] = new uint16_t[nch]; - - for(int ix=0; ix=sizeof(sls_detector_header)) return ((sls_detector_header*)buff)->frameNumber; return iframe;};//*((int*)(buff+5))&0xffffff;}; - - - - /** - gets the packets number (last packet is labelled with 0 and is replaced with 40) - \param buff pointer to the memory - \returns packet number - - */ - - int getPacketNumber(char *buff){if (offset>=sizeof(sls_detector_header))return ((sls_detector_header*)buff)->packetNumber;}; - - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - np=getPacketNumber(data); - return data; - } - } - return NULL; - - - - }; - - - - -}; - - - - - -#endif diff --git a/slsDetectorCalibration/dataStructures/gotthardShortModuleData.h b/slsDetectorCalibration/dataStructures/gotthardShortModuleData.h deleted file mode 100644 index 4d853c7b0..000000000 --- a/slsDetectorCalibration/dataStructures/gotthardShortModuleData.h +++ /dev/null @@ -1,127 +0,0 @@ -#ifndef GOTTHARDSHORTMODULEDATA_H -#define GOTTHARDSHORTMODULEDATA_H -#include "slsReceiverData.h" - - - - - - -class gotthardShortModuleData : public slsReceiverData { -public: - - - - - /** - Implements the slsReceiverData structure for the gotthard short read out by a module i.e. using the slsReceiver - (1x256 pixels, 1 packet 256 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - gotthardShortModuleData(double c=0): slsReceiverData(xpixels, ypixels, npackets, buffersize), xtalk(c){ - - uint16_t **dMask; - int **dMap; - int ix, iy; - int offset = 2; - - dMask=new uint16_t*[ypixels]; - dMap=new int*[ypixels]; - for (int i = 0; i < ypixels; i++) { - dMap[i] = new int[xpixels]; - dMask[i] = new uint16_t[xpixels]; - } - - for(ix=0; ix::getValue(data, ix, iy); - else - return slsDetectorData::getValue(data, ix, iy)-xtalk*slsDetectorData::getValue(data, ix-1, iy); - }; - - - - /** sets the output buffer crosstalk correction parameter - \param c output buffer crosstalk correction parameter to be set - \returns current value for the output buffer crosstalk correction parameter - - */ - double setXTalk(double c) {xtalk=c; return xtalk;} - - - /** gets the output buffer crosstalk parameter - \returns current value for the output buffer crosstalk correction parameter - */ - double getXTalk() {return xtalk;} - - - - - - - -private: - - double xtalk; /**=0 && ix=0 && iy=0 && dataMap[iy][ix]8000) //exchange if gainBits==2 is returned! - d|=(1<<14); // gain bit 1 - if (*((uint16_t*)(data)+dataMap[iy][ix]+1)>8000) //exchange if gainBits==2 is returned! - d|=(1<<15); // gain bit 0 - - } - - } - return d^m; - }; - - /** - returns the pixel value as double correcting for the output buffer crosstalk - \param data pointer to the memory - \param ix coordinate in the x direction - \param iy coordinate in the y direction - \returns channel value as double - - */ - double getValue(char *data, int ix, int iy=0) { - // cout << "##" << (void*)data << " " << ix << " " < the gain bits are read out the wrong way around (i.e. GB0 and GB1 have to be reversed!) - \param data pointer to the memory - \param ix coordinate in the x direction - \param iy coordinate in the y direction - \returns gain bits as int - */ - int getGainBits(char *data, int ix, int iy=0) { - uint16_t d=getChannel(data, ix, iy); - return ((d&0xc000)>>14); - }; - //*/ - - - - - /** sets the output buffer crosstalk correction parameter - \param c output buffer crosstalk correction parameter to be set - \returns current value for the output buffer crosstalk correction parameter - - */ - double setXTalk(double c) {xtalk=c; return xtalk;} - - - /** gets the output buffer crosstalk parameter - \returns current value for the output buffer crosstalk correction parameter - */ - double getXTalk() {return xtalk;} - - - - - - - - private: - - double xtalk; /** { - - private: - - typedef struct { - uint64_t frameNumber; /**< is the frame number */ - uint32_t expLength; /**< is the subframe number (32 bit eiger) or real time exposure time in 100ns (others) */ - uint32_t packetNumber; /**< is the packet number */ - uint64_t bunchId; /**< is the bunch id from beamline */ - uint64_t timestamp; /**< is the time stamp with 10 MHz clock */ - uint16_t modId; /**< is the unique module id (unique even for left, right, top, bottom) */ - uint16_t xCoord; /**< is the x coordinate in the complete detector system */ - uint16_t yCoord; /**< is the y coordinate in the complete detector system */ - uint16_t zCoord; /**< is the z coordinate in the complete detector system */ - uint32_t debug; /**< is for debugging purposes */ - uint16_t roundRNumber; /**< is the round robin set number */ - uint8_t detType; /**< is the detector type see :: detectorType */ - uint8_t version; /**< is the version number of this structure format */ - } sls_detector_header; - - - int iframe; - int nadc; - int sc_width; - int sc_height; - public: - - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - jungfrau10ModuleData(int ns=16384): slsDetectorData(256*4, 256*2, 256*256*8*2+48, NULL, NULL, NULL) , iframe(0) { - - - - int row, col; - - int isample; - int iadc; - int ix, iy; - - int ichip; - - // cout << sizeof(uint16_t) << endl; - int ip=0; - for (int iy=0; iy<256*2; iy++) { - for (int ix=0; ix<256*4; ix++){ - dataMap[iy][ix]=ip*2+48; - ip++; - } - } - - - /* for (iadc=0; iadc=ny || col<0 || col>=nx) { */ -/* cout << "Wrong row, column " << row << " " << col << " " << iadc << " " << i << endl; */ -/* } else */ -/* dataMap[row][col]=(nadc*i+iadc)*2; */ - /* if (dataMap[row][col]<0 || dataMap[row][col]>=dataSize) */ - /* cout << "Error: pointer " << dataMap[row][col] << " out of range " << row << " " << col <<" " << iadc << " " << i << endl; */ - /* else { */ - /* xmap[nadc*i+iadc]=col; */ - /* ymap[nadc*i+iadc]=row; */ - - /* } */ - /* } */ - - // } - - - - }; - - - - /** - - Returns the frame number for the given dataset. Purely virtual func. - \param buff pointer to the dataset - \returns frame number - - */ - - - int getFrameNumber(return (sls_detector_header*)buff)->frameNumber;}; - - /** - - Returns the packet number for the given dataset. purely virtual func - \param buff pointer to the dataset - \returns packet number number - - - virtual int getPacketNumber(char *buff)=0; - - */ - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; - - - /** - - Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! - \param filebin input file stream (binary) - \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete - - */ - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[dataSize]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - // char *readNextFrame(ifstream &filebin){ - // int afifo_length=0; - /* uint16_t *afifo_cont; */ - /* int ib=0; */ - /* if (filebin.is_open()) { */ - /* afifo_cont=new uint16_t[dataSize/2]; */ - /* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ - /* ib+=2; */ - /* if (ib==dataSize) break; */ - /* } */ - /* if (ib>0) { */ - /* iframe++; */ - /* // cout << ib << "-" << endl; */ - /* return (char*)afifo_cont; */ - /* } else { */ - /* delete [] afifo_cont; */ - /* return NULL; */ - /* } */ - /* } */ - /* return NULL; */ - /* }; */ - - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn; - - // cout << dataSize << endl; - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - np=getPacketNumber(data); - return data; - } - } - return NULL; - - - -}; - - - -#endif diff --git a/slsDetectorCalibration/dataStructures/moench02Ctb10GbData.h b/slsDetectorCalibration/dataStructures/moench02Ctb10GbData.h deleted file mode 100644 index a36090496..000000000 --- a/slsDetectorCalibration/dataStructures/moench02Ctb10GbData.h +++ /dev/null @@ -1,246 +0,0 @@ -#ifndef MOENCH02CTB10GBDATA_H -#define MOENCH02CTB10GBDATA_H -#include -#include "slsDetectorData.h" -#include "slsReceiverData.h" - - -class moench02Ctb10GbData : public slsReceiverData { - - private: - - int iframe; - // int *xmap, *ymap; - int nadc; - int sc_width; - int sc_height; - - int maplength; - - - - public: - - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - moench02Ctb10GbData(int ns=6400): slsReceiverData(160, 160, 50, 8208) , nadc(4), sc_width(40), sc_height(160) { - - - int adc_nr[4]={120,0,80,40}; - int row, col; - - int isample; - int iadc; - int ix, iy; - int i; - int npackets=50; - maplength = 8208*npackets; - //this->setDataSize(maplength); - /* maplength=this->getDataSize()/2; */ - - for (int ip=0; ip=8208*npackets) { - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - - } - } - } - } - int ibyte; - int ii=0; - - for (int ipacket=0; ipacket=2 && iadc<=5){ - xmap[i]=adc_nr[iadc-2]+ix; - ymap[i]=iy; - }else{ - xmap[i]=-1; - ymap[i]=-1; - } - ii++; - } - }//end loop on bytes - }//end loop on packets - - iframe=0; - cout << "data struct created" << endl; - }; - - void getPixel(int ip, int &x, int &y) { - if(ip>=0 && ip0) { */ - /* iframe++; */ - /* //cout << ib << "-" << endl; */ - /* return (char*)afifo_cont; */ - /* } else { */ - /* delete [] afifo_cont; */ - /* return NULL; */ - /* } */ - /* } */ - /* return NULL; */ - /* }; */ - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[packetSize*nPackets]; - char *retval=0; - int nd; - np=0; - int pn; - char aa[8224]={0}; - char *packet=(char *)aa; - int fnum = -1; - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - - - cout << "+"; - - while(filebin.read((char*)packet, 8208)){ - - pn=getPacketNumber(packet); - if (fnum<0) - fnum= getFrameNumber(packet); - - - if (fnum>=0) { - if (getFrameNumber(packet) !=fnum) { - - if (np==0){ - cout << "-"; - delete [] data; - return NULL; - } else - filebin.seekg(-8208,ios_base::cur); - return data; - } - - memcpy(data+(pn-1)*packetSize, packet, packetSize); - - np++; - if (np==nPackets) - break; - if (pn==nPackets) - break; - } - } - }else{ - cerr< { - - private: - - int iframe; - // int *xmap, *ymap; - int nadc; - int sc_width; - int sc_height; - - int maplength; - - - - public: - - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - moench02CtbData(int ns=6400): slsDetectorData(160, 160, ns*2*32, NULL, NULL) , nadc(32), sc_width(40), sc_height(160) { - - - int adc_off[4]={40,0,120,80}; - int adc_nr[4]={8,10,20,22}; - int row, col; - - int isample; - int iadc, iiadc; - int ix, iy; - maplength=this->getDataSize()/2; - //cout << maplength << endl; - - for (iiadc=0; iiadc<4; iiadc++) { - - iadc=adc_nr[iiadc]; - //cout << iiadc << endl; - for (int i=0; i=dataSize) { - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - - } - } - - for (int i=0; i=0){ - xmap[i]=adc_off[iadc]+ix; - ymap[i]=iy; - }else{ - xmap[i]=-1; - ymap[i]=-1; - } - } - iframe=0; - cout << "data struct created" << endl; - }; - - void getPixel(int ip, int &x, int &y) { - if(ip>=0 && ip0) { - iframe++; - //cout << ib/2 << "-" << endl; - //for (int i=0; i { - - private: - - int iframe; - // int *xmap, *ymap; - //int nadc; - int sc_width; - int sc_height; - - int maplength; - - - - public: - - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - moench02CtbDataDGS(int ns=6400): slsDetectorData(160, 160, ns*(2*32+8), NULL, NULL) , sc_width(40), sc_height(160) { - - - int adc_off[4]={40,0,120,80}; - int adc_nr[4]={8,10,20,23}; - int row, col; - - int isample; - int iadc, iiadc; - int ix, iy; - maplength=this->getDataSize()/2; - //cout << maplength << endl; - - for (iiadc=0; iiadc<4; iiadc++) { - - iadc=adc_nr[iiadc]; - //cout << iiadc << endl; - for (int i=0; i=dataSize) { - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - - } - } - - for (int i=0; i=0){ - xmap[i]=adc_off[iadc]+ix; - ymap[i]=iy; - }else{ - xmap[i]=-1; - ymap[i]=-1; - } - } - iframe=0; - cout << "data struct created" << endl; - }; - - void getPixel(int ip, int &x, int &y) { - if(ip>=0 && ip>31)) return 1; - return 0; - } - return 0; //not yet implemented for 4th supercolumn - } - - - /** - - Returns the frame number for the given dataset. Purely virtual func. - \param buff pointer to the dataset - \returns frame number - - */ - - - virtual int getFrameNumber(char *buff){(void)buff; return iframe;}; - - /** - - Returns the packet number for the given dataset. purely virtual func - \param buff pointer to the dataset - \returns packet number number - - - virtual int getPacketNumber(char *buff)=0; - - */ - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; - - - /** - - Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! - \param filebin input file stream (binary) - \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete - - */ - virtual char *readNextFrame(ifstream &filebin){ - // int afifo_length=0; - uint16_t *afifo_cont; - int ib=0; - if (filebin.is_open()) { - afifo_cont=new uint16_t[dataSize/2]; - while (filebin.read(((char*)afifo_cont)+ib,2)) { - ib+=2; - if (ib==dataSize) break; - } - if (ib>0) { - iframe++; - //cout << ib/2 << "-" << endl; - //for (int i=0; i { - public: - - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - moench02ModuleData(double c=0): slsReceiverData(160, 160, 40, 1286), - xtalk(c) { - - - - - uint16_t **dMask; - int **dMap; - int ix, iy; - - - - dMask=new uint16_t*[160]; - dMap=new int*[160]; - for (int i = 0; i < 160; i++) { - dMap[i] = new int[160]; - dMask[i] = new uint16_t[160]; - } - - for (int isc=0; isc<4; isc++) { - for (int ip=0; ip<10; ip++) { - - for (int ir=0; ir<16; ir++) { - for (int ic=0; ic<40; ic++) { - - ix=isc*40+ic; - iy=ip*16+ir; - - dMap[iy][ix]=1286*(isc*10+ip)+2*ir*40+2*ic+4; - // cout << ix << " " << iy << " " << dMap[ix][iy] << endl; - } - } - } - } - - for (ix=0; ix<120; ix++) { - for (iy=0; iy<160; iy++) - dMask[iy][ix]=0x3fff; - } - for (ix=120; ix<160; ix++) { - for (iy=0; iy<160; iy++) - dMask[iy][ix]=0x0; - } - - - setDataMap(dMap); - setDataMask(dMask); - - - - - }; - - - - /** - gets the packets number (last packet is labelled with 0 and is replaced with 40) - \param buff pointer to the memory - \returns packet number - - */ - - int getPacketNumber(char *buff){ - int np=(*(int*)buff)&0xff; - if (np==0) - np=40; - return np; - }; - - - /** - returns the pixel value as double correcting for the output buffer crosstalk - \param data pointer to the memory - \param ix coordinate in the x direction - \param iy coordinate in the y direction - \returns channel value as double - - */ - double getValue(char *data, int ix, int iy=0) { - // cout << "##" << (void*)data << " " << ix << " " <::getValue(data, ix, iy); - else - return slsDetectorData::getValue(data, ix, iy)-xtalk*slsDetectorData::getValue(data, ix-1, iy); - }; - - - - /** sets the output buffer crosstalk correction parameter - \param c output buffer crosstalk correction parameter to be set - \returns current value for the output buffer crosstalk correction parameter - - */ - double setXTalk(double c) {xtalk=c; return xtalk;} - - - /** gets the output buffer crosstalk parameter - \returns current value for the output buffer crosstalk correction parameter - */ - double getXTalk() {return xtalk;} - - - - - - - - private: - - double xtalk; /** { - - protected: - - int iframe; - int nadc; - int sc_width; - int sc_height; - - public: - - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - // moench03Ctb10GbData(int ns=5000): slsDetectorData(400, 400, 8208*40, NULL, NULL) , nadc(32), sc_width(25), sc_height(200) { - moench03Ctb10GbData(int ns=5000): slsReceiverData(400, 400, 40, 8208), nadc(32), sc_width(25), sc_height(200) { - - int adc_nr[32]={200,225,250,275,300,325,350,375,\ - 0,25,50,75,100,125,150,175,\ - 175,150,125,100,75,50,25,0,\ - 375,350,325,300,275,250,225,200}; - int row, col; - - int isample; - int iadc; - int ix, iy; - - int npackets=40; - int i; - - - for (int ip=0; ip=8208*40) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - } - } - } - - int ipacket; - int ibyte; - int ii=0; - for (int ipacket=0; ipacket0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ - - - virtual char *readNextFrame(ifstream &filebin, int& fnum, char *data=NULL) { - int dd=0; - if (data==NULL) { - data=new char[packetSize*nPackets]; - dd=1; - } - char *retval=0; - int np=0, nd; - fnum = -1; - int pn; - char aa[8224]; - char *packet=(char *)aa; - int place; - - if (filebin.is_open()) { - - - - place=filebin.tellg(); - while(filebin.read((char*)packet, 8208) && np=0) { - if (getFrameNumber(packet) !=fnum) { - cout << "-"<=0) { */ -/* if (getFrameNumber(packet) !=fnum) { */ - -/* if (np==0){ */ -/* delete [] data; */ -/* return NULL; */ -/* } else */ -/* return data; */ -/* } */ - -/* memcpy(data+(pn-1)*packetSize, packet, packetSize); */ -/* np++; */ - -/* } */ -/* } */ - -/* } */ - -/* if (np==0){ */ -/* delete [] data; */ -/* return NULL; */ -/* } */ - -/* }; */ - -int getPacketNumber(int x, int y) {return dataMap[y][x]/8208;}; - - -}; - - - - -#endif diff --git a/slsDetectorCalibration/dataStructures/moench03Ctb10GbT1Data.h b/slsDetectorCalibration/dataStructures/moench03Ctb10GbT1Data.h deleted file mode 100644 index 415bb82ac..000000000 --- a/slsDetectorCalibration/dataStructures/moench03Ctb10GbT1Data.h +++ /dev/null @@ -1,287 +0,0 @@ -#ifndef MOENCH03CTB10GBT1DATA_H -#define MOENCH03CTB10GBT1DATA_H -#include "slsReceiverData.h" - - - -class moench03Ctb10GbT1Data : public slsReceiverData { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - public: - - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - moench03Ctb10GbT1Data(int ns=5000): slsReceiverData(400, 400, 40, 8208), nadc(32), sc_width(25), sc_height(200) { - - - - int adc_nr[32]={300,325,350,375,300,325,350,375, \ - 200,225,250,275,200,225,250,275,\ - 100,125,150,175,100,125,150,175,\ - 0,25,50,75,0,25,50,75}; - - int row, col; - - int isample; - int iadc; - int ix, iy; - - int npackets=40; - int i; - int adc4(0); - - for (int ip=0; ip=8208*40) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - } - } - } - - int ipacket; - int ibyte; - int ii=0; - for (int ipacket=0; ipacket0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ - - - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[packetSize*nPackets]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - - } - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn, po=0; - char aa[8224]; - char *packet=(char *)aa; - // cout << packetSize*nPackets << endl; - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - - - - - while(filebin.read((char*)packet, 8208) ){ - pn=getPacketNumber(packet); - - if (fnum<0) - fnum= getFrameNumber(packet); - - // cout << "fn: " << fnum << "\t pn: " << pn << endl; - if (fnum>=0) { - if (getFrameNumber(packet) !=fnum || pnnPackets) { - cout << "Bad packet number " << pn << endl; - } - - memcpy(data+(pn-1)*packetSize, packet, packetSize); - np++; - po =pn; - - if (np==nPackets) - break; - - if (pn==nPackets) - break; - - } - } - - } - - if (np==0){ - // delete [] data; - return NULL; - } - - ff=fnum; - return data; - - }; - - - - - - - - - - - - - - - - - - -int getPacketNumber(int x, int y) {return dataMap[y][x]/8208;}; - - -}; - - - - -#endif diff --git a/slsDetectorCalibration/dataStructures/moench03CtbData.h b/slsDetectorCalibration/dataStructures/moench03CtbData.h deleted file mode 100644 index 66ae0cbda..000000000 --- a/slsDetectorCalibration/dataStructures/moench03CtbData.h +++ /dev/null @@ -1,157 +0,0 @@ -#ifndef MOENCH03CTBDATA_H -#define MOENCH03CTBDATA_H -#include "slsDetectorData.h" - - - -class moench03CtbData : public slsDetectorData { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - public: - - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - moench03CtbData(int ns=5000): slsDetectorData(400, 400, ns*2*32, NULL, NULL) , nadc(32), sc_width(25), sc_height(200) { - - - int row, col; - - int isample; - int iadc; - int ix, iy; - - int adc_nr[32]={200,225,250,275,300,325,350,375,\ - 0,25,50,75,100,125,150,175,\ - 175,150,125,100,75,50,25,0,\ - 375,350,325,300,275,250,225,200}; - - /* int adc_nr[32]={300,325,350,375,300,325,350,375, \ */ - /* 200,225,250,275,200,225,250,275,\ */ - /* 100,125,150,175,100,125,150,175,\ */ - /* 0,25,50,75,0,25,50,75}; */ - - - for (iadc=0; iadc=2*400*400) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - - } - } - for (int i=0; i0) { - iframe++; - // cout << ib << "-" << endl; - return (char*)afifo_cont; - } else { - delete [] afifo_cont; - return NULL; - } - } - return NULL; - }; - - - - -}; - - - -#endif diff --git a/slsDetectorCalibration/dataStructures/moench03T1CtbData.h b/slsDetectorCalibration/dataStructures/moench03T1CtbData.h deleted file mode 100644 index 4a99d3746..000000000 --- a/slsDetectorCalibration/dataStructures/moench03T1CtbData.h +++ /dev/null @@ -1,158 +0,0 @@ -#ifndef MOENCH03T1CTBDATA_H -#define MOENCH03T1CTBDATA_H -#include "slsDetectorData.h" - - - -class moench03T1CtbData : public slsDetectorData { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - public: - - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - moench03T1CtbData(int ns=5000): slsDetectorData(400, 400, ns*2*32, NULL, NULL) , nadc(32), sc_width(25), sc_height(200) { - - - int adc_nr[32]={300,325,350,375,300,325,350,375, \ - 200,225,250,275,200,225,250,275,\ - 100,125,150,175,100,125,150,175,\ - 0,25,50,75,0,25,50,75}; - - int row, col; - - int isample; - int iadc; - int ix, iy; - - - - - - for (iadc=0; iadc=2*400*400) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - - } - } - int adc4; - for (int i=0; i0) { - iframe++; - // cout << ib << "-" << endl; - return (char*)afifo_cont; - } else { - delete [] afifo_cont; - return NULL; - } - } - return NULL; - }; - - - - -}; - - - -#endif diff --git a/slsDetectorCalibration/dataStructures/moench03T1ReceiverData.h b/slsDetectorCalibration/dataStructures/moench03T1ReceiverData.h deleted file mode 100644 index 855bfb7c4..000000000 --- a/slsDetectorCalibration/dataStructures/moench03T1ReceiverData.h +++ /dev/null @@ -1,285 +0,0 @@ -#ifndef MOENCH03T1ZMQDATA_H -#define MOENCH03T1ZMQDATA_H -#include "slsDetectorData.h" - - /** - @short structure for a Detector Packet or Image Header - @li frameNumber is the frame number - @li expLength is the subframe number (32 bit eiger) or real time exposure time in 100ns (others) - @li packetNumber is the packet number - @li bunchId is the bunch id from beamline - @li timestamp is the time stamp with 10 MHz clock - @li modId is the unique module id (unique even for left, right, top, bottom) - @li xCoord is the x coordinate in the complete detector system - @li yCoord is the y coordinate in the complete detector system - @li zCoord is the z coordinate in the complete detector system - @li debug is for debugging purposes - @li roundRNumber is the round robin set number - @li detType is the detector type see :: detectorType - @li version is the version number of this structure format - */ - typedef struct { - uint64_t frameNumber; /**< is the frame number */ - uint32_t expLength; /**< is the subframe number (32 bit eiger) or real time exposure time in 100ns (others) */ - uint32_t packetNumber; /**< is the packet number */ - uint64_t bunchId; /**< is the bunch id from beamline */ - uint64_t timestamp; /**< is the time stamp with 10 MHz clock */ - uint16_t modId; /**< is the unique module id (unique even for left, right, top, bottom) */ - uint16_t xCoord; /**< is the x coordinate in the complete detector system */ - uint16_t yCoord; /**< is the y coordinate in the complete detector system */ - uint16_t zCoord; /**< is the z coordinate in the complete detector system */ - uint32_t debug; /**< is for debugging purposes */ - uint16_t roundRNumber; /**< is the round robin set number */ - uint8_t detType; /**< is the detector type see :: detectorType */ - uint8_t version; /**< is the version number of this structure format */ - } sls_detector_header; - - - - -class moench03T1ReceiverData : public slsDetectorData { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - const int nPackets; /**(400, 400, ps*npackets+sizeof(sls_detector_header)), packetSize(ps), nPackets(npackets) { - - int nadc=32; - int sc_width=25; - int sc_height=200; - - int adc_nr[32]={300,325,350,375,300,325,350,375, \ - 200,225,250,275,200,225,250,275,\ - 100,125,150,175,100,125,150,175,\ - 0,25,50,75,0,25,50,75}; - - int row, col; - - int isample; - int iadc; - int ix, iy; - - // int npackets=40; - int i; - int adc4(0); - - for (int ip=0; ip=8192*40) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - } - } - } - - int ipacket; - int ibyte; - int ii=0; - for (ibyte=0; ibyteframeNumber;};//*((int*)(buff+5))&0xffffff;}; - - /** - - Returns the packet number for the given dataset. purely virtual func - \param buff pointer to the dataset - \returns packet number number - - - - */ - int getPacketNumber(char *buff){((sls_detector_header*)buff)->packetNumber;}//((*(((int*)(buff+4))))&0xff)+1;}; - -/* /\** */ - -/* Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func */ -/* \param data pointer to the memory to be analyzed */ -/* \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot */ -/* \param dsize size of the memory slot to be analyzed */ -/* \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found */ - -/* *\/ */ -/* virtual char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; */ - - -/* /\** */ - -/* Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! */ -/* \param filebin input file stream (binary) */ -/* \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete */ - -/* *\/ */ -/* virtual char *readNextFrame(ifstream &filebin){ */ -/* // int afifo_length=0; */ -/* uint16_t *afifo_cont; */ -/* int ib=0; */ -/* if (filebin.is_open()) { */ -/* afifo_cont=new uint16_t[dataSize/2]; */ -/* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ -/* ib+=2; */ -/* if (ib==dataSize) break; */ -/* } */ -/* if (ib>0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ - - - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[dataSize]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn; - - // cout << dataSize << endl; - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - np=getPacketNumber(data); - return data; - } - } - return NULL; - - - - }; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - const int nSamples; - - - public: - - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - moench03T1ReceiverDataNew(int ns=5000): slsDetectorData(400, 400, ns*2*32+sizeof(sls_detector_header)), nSamples(ns) { - - int nadc=32; - int sc_width=25; - int sc_height=200; - - int adc_nr[32]={300,325,350,375,300,325,350,375, \ - 200,225,250,275,200,225,250,275,\ - 100,125,150,175,100,125,150,175,\ - 0,25,50,75,0,25,50,75}; - - int row, col; - - int isample; - int iadc; - int ix, iy; - - int npackets=40; - int i; - int adc4(0); - - for (int ip=0; ip=nSamples*2*32) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - } - } - } - - int ipacket; - int ibyte; - int ii=0; - for (ibyte=0; ibyteframeNumber;};//*((int*)(buff+5))&0xffffff;}; - - /** - - Returns the packet number for the given dataset. purely virtual func - \param buff pointer to the dataset - \returns packet number number - - - - */ - int getPacketNumber(char *buff){return ((sls_detector_header*)buff)->packetNumber;}//((*(((int*)(buff+4))))&0xff)+1;}; - -/* /\** */ - -/* Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func */ -/* \param data pointer to the memory to be analyzed */ -/* \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot */ -/* \param dsize size of the memory slot to be analyzed */ -/* \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found */ - -/* *\/ */ -/* virtual char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; */ - - -/* /\** */ - -/* Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! */ -/* \param filebin input file stream (binary) */ -/* \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete */ - -/* *\/ */ -/* virtual char *readNextFrame(ifstream &filebin){ */ -/* // int afifo_length=0; */ -/* uint16_t *afifo_cont; */ -/* int ib=0; */ -/* if (filebin.is_open()) { */ -/* afifo_cont=new uint16_t[dataSize/2]; */ -/* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ -/* ib+=2; */ -/* if (ib==dataSize) break; */ -/* } */ -/* if (ib>0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ - - - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[dataSize]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn; - - // cout << dataSize << endl; - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - np=getPacketNumber(data); - return data; - } - } - return NULL; - - - - }; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - const int nSamples; - - - public: - - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ -#ifdef HOR - moench03T1ReceiverDataNew(int ns=5000): slsDetectorData(800, 200, ns*2*32+sizeof(sls_detector_header)), nSamples(ns) { -#endif -#ifdef VERT - moench03T1ReceiverDataNew(int ns=5000): slsDetectorData(200, 800, ns*2*32+sizeof(sls_detector_header)), nSamples(ns) { -#endif - int nadc=32; - int sc_width=25; - int sc_height=200; - - int adc_nr[32]={300,325,350,375,300,325,350,375, \ - 200,225,250,275,200,225,250,275,\ - 100,125,150,175,100,125,150,175,\ - 0,25,50,75,0,25,50,75}; - - int row, col; - - int isample; - int iadc; - int ix, iy; - - int npackets=40; - int i; - int adc4(0); - int pix; - - - int off=0; -#ifdef OFF_1 - off=1; -#endif - cout << "This is a MOENCH with rectangular pixels!" << endl; - - for (int ip=0; ip=nSamples*2*32+sizeof(sls_detector_header)) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - ix=col; - iy=row; -#ifdef HOR - if (row%2==off) { - ix=2*col; - iy=row/2; - } else { - ix=2*col+1; - iy=row/2; - } -#endif - -#ifdef VERT - if (col%2==off) { - ix=col/2; - iy=row*2+1; - } else { - ix=col/2; - iy=row*2; - } -#endif - dataMap[iy][ix]=pix; - } - } - } - } - - /* int ipacket; */ - /* int ibyte; */ - /* int ii=0; */ - /* for (ibyte=0; ibyteframeNumber;};//*((int*)(buff+5))&0xffffff;}; - - /** - - Returns the packet number for the given dataset. purely virtual func - \param buff pointer to the dataset - \returns packet number number - - - - */ - int getPacketNumber(char *buff){return ((sls_detector_header*)buff)->packetNumber;}//((*(((int*)(buff+4))))&0xff)+1;}; - -/* /\** */ - -/* Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func */ -/* \param data pointer to the memory to be analyzed */ -/* \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot */ -/* \param dsize size of the memory slot to be analyzed */ -/* \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found */ - -/* *\/ */ -/* virtual char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; */ - - -/* /\** */ - -/* Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! */ -/* \param filebin input file stream (binary) */ -/* \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete */ - -/* *\/ */ -/* virtual char *readNextFrame(ifstream &filebin){ */ -/* // int afifo_length=0; */ -/* uint16_t *afifo_cont; */ -/* int ib=0; */ -/* if (filebin.is_open()) { */ -/* afifo_cont=new uint16_t[dataSize/2]; */ -/* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ -/* ib+=2; */ -/* if (ib==dataSize) break; */ -/* } */ -/* if (ib>0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ - - - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[dataSize]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn; - - // cout << dataSize << endl; - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - np=getPacketNumber(data); - return data; - } - } - return NULL; - - - - }; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - const int nPackets; /**(400, 400, ps*npackets), packetSize(ps), nPackets(npackets) { - - int nadc=32; - int sc_width=25; - int sc_height=200; - - int adc_nr[32]={300,325,350,375,300,325,350,375, \ - 200,225,250,275,200,225,250,275,\ - 100,125,150,175,100,125,150,175,\ - 0,25,50,75,0,25,50,75}; - - int row, col; - - int isample; - int iadc; - int ix, iy; - - // int npackets=40; - int i; - int adc4(0); - - for (int ip=0; ip=8192*40) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - } - } - } - - int ipacket; - int ibyte; - int ii=0; - for (int ipacket=0; ipacket0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ - - - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[packetSize*nPackets]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn; - - - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, packetSize*nPackets) ){ - iframe++; - ff=iframe; - return data; - } - } - return NULL; - - - - }; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize { - - private: - - // int iframe; - int nadc; - int sc_width; - int sc_height; - const int nSamples; - const int offset; - - public: - - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - moench03T1ZmqDataNew(int ns=5000): slsDetectorData(400, 400, ns*32*2+sizeof(int)), nSamples(ns), offset(sizeof(int)) { - - int nadc=32; - int sc_width=25; - int sc_height=200; - - int adc_nr[32]={300,325,350,375,300,325,350,375, \ - 200,225,250,275,200,225,250,275,\ - 100,125,150,175,100,125,150,175,\ - 0,25,50,75,0,25,50,75}; - - int row, col; - - int isample; - int iadc; - int ix, iy; - - int npackets=40; - int i; - int adc4(0); - - for (int ip=0; ip=dataSize) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - } - } - } - - - int ii=0; - - for (i=0; i< dataSize; i++) { - if (i0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ - - - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[32*2*nSamples]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn; - - - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, 32*2*nSamples) ){ - // iframe++; - //ff=iframe; - return data; - } - } - return NULL; - - - - }; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize<32*2*nSamples) ndata=dsize; - else ndata=32*2*nSamples; - return data; - - } - - - - - - - // virtual int setFrameNumber(int ff){iframe=ff}; - - - - - - - - - - -int getPacketNumber(int x, int y) {return 0;}; - -}; - - - - -#endif diff --git a/slsDetectorCalibration/dataStructures/moench03TCtb10GbData.h b/slsDetectorCalibration/dataStructures/moench03TCtb10GbData.h deleted file mode 100644 index 989012991..000000000 --- a/slsDetectorCalibration/dataStructures/moench03TCtb10GbData.h +++ /dev/null @@ -1,285 +0,0 @@ -#ifndef MOENCH03TCTB10GBDATA_H -#define MOENCH03TCTB10GBDATA_H -#include "moench03Ctb10GbData.h" - - - -class moench03TCtb10GbData : public moench03Ctb10GbData { //slsReceiverData { - - - public: - - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - // moench03TCtb10GbData(int ns=5000): slsDetectorData(400, 400, 8208*40, NULL, NULL) , nadc(32), sc_width(25), sc_height(200) { - moench03TCtb10GbData(int ns=5000): moench03Ctb10GbData(ns) {//slsReceiverData(400, 400, 40, 8208), nadc(32), sc_width(25), sc_height(200) { - // cout <<"constructor"<< endl; - // nadc=32; - int adc_nr[32]={300,325,350,375,300,325,350,375, \ - 200,225,250,275,200,225,250,275,\ - 100,125,150,175,100,125,150,175,\ - 0,25,50,75,0,25,50,75}; - int row, col; - - int isample; - int iadc; - int ix, iy; - - int npackets=40; - int i; - int adc4(0); - - for (int ip=0; ip=8208*40) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - } - } - } - // cout <<"map"<< endl; - int ipacket; - int ibyte; - int ii=0; - for (int ipacket=0; ipacket0) { *\/ */ -/* /\* iframe++; *\/ */ -/* /\* // cout << ib << "-" << endl; *\/ */ -/* /\* return (char*)afifo_cont; *\/ */ -/* /\* } else { *\/ */ -/* /\* delete [] afifo_cont; *\/ */ -/* /\* return NULL; *\/ */ -/* /\* } *\/ */ -/* /\* } *\/ */ -/* /\* return NULL; *\/ */ -/* /\* }; *\/ */ - - -/* virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { */ -/* char *data=new char[packetSize*nPackets]; */ -/* char *retval=0; */ -/* int nd; */ -/* np=0; */ -/* int pn; */ -/* char aa[8224]={0}; */ -/* char *packet=(char *)aa; */ -/* int fnum = -1; */ - -/* if (ff>=0) */ -/* fnum=ff; */ - -/* if (filebin.is_open()) { */ - - -/* cout << "+"; */ - -/* while(filebin.read((char*)packet, 8208)){ */ - -/* pn=getPacketNumber(packet); */ - -/* if (fnum<0) */ -/* fnum= getFrameNumber(packet); */ - -/* if (fnum>=0) { */ -/* if (getFrameNumber(packet) !=fnum) { */ - -/* if (np==0){ */ -/* cout << "-"; */ -/* delete [] data; */ -/* return NULL; */ -/* } else */ -/* filebin.seekg(-8208,ios_base::cur); */ - -/* return data; */ -/* } */ - -/* memcpy(data+(pn-1)*packetSize, packet, packetSize); */ -/* np++; */ -/* if (np==nPackets) */ -/* break; */ -/* if (pn==nPackets) */ -/* break; */ -/* } */ -/* } */ - -/* } */ - -/* if (np==0){ */ -/* cout << "?"; */ -/* delete [] data; */ -/* return NULL; */ -/* }// else if (np { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - public: - - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - moench03TCtbData(int ns=5000): slsDetectorData(400, 400, ns*2*32, NULL, NULL) , nadc(32), sc_width(25), sc_height(200) { - - - int row, col; - - int isample; - int iadc; - int ix, iy; - - - - int adc_nr[32]={300,325,350,375,300,325,350,375, \ - 200,225,250,275,200,225,250,275,\ - 100,125,150,175,100,125,150,175,\ - 0,25,50,75,0,25,50,75}; - - - - /* int adc_nr[32]={200,225,250,275,300,325,350,375,\ */ - /* 0,25,50,75,100,125,150,175,\ */ - /* 175,150,125,100,75,50,25,0,\ */ - /* 375,350,325,300,275,250,225,200}; */ - - - for (iadc=0; iadc=2*400*400) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - - } - } - int adc4; - for (int i=0; i0) { - iframe++; - // cout << ib << "-" << endl; - return (char*)afifo_cont; - } else { - delete [] afifo_cont; - return NULL; - } - } - return NULL; - }; - - - - -}; - - - -#endif diff --git a/slsDetectorCalibration/doxy.config b/slsDetectorCalibration/doxy.config deleted file mode 100644 index 7f1241be0..000000000 --- a/slsDetectorCalibration/doxy.config +++ /dev/null @@ -1,85 +0,0 @@ -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. -# Private class members and static file members will be hidden unless -# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES - -EXTRACT_ALL = YES - -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class -# will be included in the documentation. - -EXTRACT_PRIVATE = NO - - - -# If the EXTRACT_STATIC tag is set to YES all static members of a file -# will be included in the documentation. - -EXTRACT_STATIC = YES - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) -# defined locally in source files will be included in the documentation. -# If set to NO only classes defined in header files are included. - -EXTRACT_LOCAL_CLASSES = YES - -# This flag is only useful for Objective-C code. When set to YES local -# methods, which are defined in the implementation section but not in -# the interface are included in the documentation. -# If set to NO (the default) only methods in the interface are included. - -EXTRACT_LOCAL_METHODS = YES - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base -# name of the file that contains the anonymous namespace. By default -# anonymous namespace are hidden. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all -# undocumented members of documented classes, files or namespaces. -# If set to NO (the default) these members will be included in the -# various overviews, but no documentation section is generated. -# This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. -# If set to NO (the default) these classes will be included in the various -# overviews. This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all -# friend (class|struct|union) declarations. -# If set to NO (the default) these declarations will be included in the -# documentation. - -HIDE_FRIEND_COMPOUNDS = NO - -INTERNAL_DOCS = NO - -SHOW_INCLUDE_FILES = NO - -SHOW_FILES = NO - -SHOW_NAMESPACES = NO - -COMPACT_LATEX = YES - -PAPER_TYPE = a4 - -PDF_HYPERLINKS = YES - -USE_PDFLATEX = YES - -LATEX_HIDE_INDICES = YES - -PREDEFINED = __cplusplus - -INPUT = MovingStat.h slsDetectorData.h slsReceiverData.h moench02ModuleData.h pedestalSubtraction.h commonModeSubtraction.h moenchCommonMode.h singlePhotonDetector.h energyCalibration.h moenchReadData.C single_photon_hit.h chiptestBoardData.h jungfrau02Data.h jungfrauReadData.C jungfrau02CommonMode.h -OUTPUT_DIRECTORY = docs - diff --git a/slsDetectorCalibration/energyCalibration.cpp b/slsDetectorCalibration/energyCalibration.cpp deleted file mode 100644 index 596d9a0e4..000000000 --- a/slsDetectorCalibration/energyCalibration.cpp +++ /dev/null @@ -1,534 +0,0 @@ -#include "energyCalibration.h" - -#ifdef __CINT -#define MYROOT -#endif - - -#ifdef MYROOT -#include -#include -#include -#include -#endif - -#include - -#define max(a,b) ((a) > (b) ? (a) : (b)) -#define min(a,b) ((a) < (b) ? (a) : (b)) -#define ELEM_SWAP(a,b) { register int t=(a);(a)=(b);(b)=t; } - - -using namespace std; - -#ifdef MYROOT - -Double_t energyCalibrationFunctions::pedestal(Double_t *x, Double_t *par) { - return par[0]-par[1]*sign*x[0]; -} - - -Double_t energyCalibrationFunctions::gaussChargeSharing(Double_t *x, Double_t *par) { - Double_t f, arg=0; - if (par[3]!=0) arg=sign*(x[0]-par[2])/par[3]; - f=TMath::Exp(-1*arg*arg/2.); - f=f+par[5]/2.*(TMath::Erfc(arg/(TMath::Sqrt(2.)))); - return par[4]*f+pedestal(x,par); -} - -Double_t energyCalibrationFunctions::gaussChargeSharingPixel(Double_t *x, Double_t *par) { - Double_t f; - if (par[3]<=0 || par[2]*(*x)<=0 || par[5]<0 || par[4]<=0) return 0; - - Double_t pp[3]; - - pp[0]=0; - pp[1]=par[2]; - pp[2]=par[3]; - - - f=(par[5]-par[6]*(TMath::Log(*x/par[2])))*erfBox(x,pp); - f+=par[4]*TMath::Gaus(*x, par[2], par[3], kTRUE); - return f+pedestal(x,par); -} - -Double_t energyCalibrationFunctions::erfBox(Double_t *z, Double_t *par) { - - - - Double_t m=par[0]; - Double_t M=par[1]; - - if (par[0]>par[1]) { - m=par[1]; - M=par[0]; - } - - if (m==M) - return 0; - - - if (par[2]<=0) { - if (*z>=m && *z<=M) - return 1./(M-m); - else - return 0; - - } - - return (TMath::Erfc((z[0]-M)/par[2])-TMath::Erfc((z[0]-m)/par[2]))*0.5/(M-m); - -} - - -// basic erf function -Double_t energyCalibrationFunctions::erfFunction(Double_t *x, Double_t *par) { - double arg=0; - if (par[1]!=0) arg=(par[0]-x[0])/par[1]; - return ((par[2]/2.*(1+TMath::Erf(sign*arg/(TMath::Sqrt(2)))))); -}; - - -Double_t energyCalibrationFunctions::erfFunctionChargeSharing(Double_t *x, Double_t *par) { - Double_t f; - - f=erfFunction(x, par+2)*(1+par[5]*(par[2]-x[0]))+par[0]-par[1]*x[0]*sign; - return f; -}; - - -Double_t energyCalibrationFunctions::erfFuncFluo(Double_t *x, Double_t *par) { - Double_t f; - f=erfFunctionChargeSharing(x, par)+erfFunction(x, par+6)*(1+par[9]*(par[6]-x[0])); - return f; -}; -#endif - -double energyCalibrationFunctions::median(double *x, int n){ - // sorts x into xmed array and returns median - // n is number of values already in the xmed array - double xmed[n]; - int k,i,j; - - for (i=0; i*(x+j)) - k++; - if (*(x+i)==*(x+j)) { - if (i>j) - k++; - } - } - xmed[k]=*(x+i); - } - k=n/2; - return xmed[k]; -} - - -int energyCalibrationFunctions::quick_select(int arr[], int n){ - int low, high ; - int median; - int middle, ll, hh; - - low = 0 ; high = n-1 ; median = (low + high) / 2; - for (;;) { - if (high <= low) /* One element only */ - return arr[median] ; - - if (high == low + 1) { /* Two elements only */ - if (arr[low] > arr[high]) - ELEM_SWAP(arr[low], arr[high]) ; - return arr[median] ; - } - - /* Find median of low, middle and high items; swap into position low */ - middle = (low + high) / 2; - if (arr[middle] > arr[high]) ELEM_SWAP(arr[middle], arr[high]) ; - if (arr[low] > arr[high]) ELEM_SWAP(arr[low], arr[high]) ; - if (arr[middle] > arr[low]) ELEM_SWAP(arr[middle], arr[low]) ; - - /* Swap low item (now in position middle) into position (low+1) */ - ELEM_SWAP(arr[middle], arr[low+1]) ; - - /* Nibble from each end towards middle, swapping items when stuck */ - ll = low + 1; - hh = high; - for (;;) { - do ll++; while (arr[low] > arr[ll]) ; - do hh--; while (arr[hh] > arr[low]) ; - - if (hh < ll) - break; - - ELEM_SWAP(arr[ll], arr[hh]) ; - } - - /* Swap middle item (in position low) back into correct position */ - ELEM_SWAP(arr[low], arr[hh]) ; - - /* Re-set active partition */ - if (hh <= median) - low = ll; - if (hh >= median) - high = hh - 1; - } -} - -int energyCalibrationFunctions::kth_smallest(int *a, int n, int k){ - register int i,j,l,m ; - register double x ; - - l=0 ; m=n-1 ; - while (lSetParNames("Background Offset","Background Slope","Inflection Point","Noise RMS", "Number of Photons","Charge Sharing Slope"); - - fspectrum=new TF1("fspectrum",funcs,&energyCalibrationFunctions::spectrum,0,1000,6,"energyCalibrationFunctions","spectrum"); - fspectrum->SetParNames("Background Pedestal","Background slope", "Peak position","Noise RMS", "Number of Photons","Charge Sharing Pedestal"); - - fspixel=new TF1("fspixel",funcs,&energyCalibrationFunctions::spectrumPixel,0,1000,7,"energyCalibrationFunctions","spectrumPixel"); - fspixel->SetParNames("Background Pedestal","Background slope", "Peak position","Noise RMS", "Number of Photons","Charge Sharing Pedestal","Corner"); - -#endif - - -} - - - -void energyCalibration::fixParameter(int ip, Double_t val){ - - fscurve->FixParameter(ip, val); - fspectrum->FixParameter(ip, val); -} - - -void energyCalibration::releaseParameter(int ip){ - - fscurve->ReleaseParameter(ip); - fspectrum->ReleaseParameter(ip); -} - - - - - - - -energyCalibration::~energyCalibration(){ -#ifdef MYROOT - delete fscurve; - delete fspectrum; -#endif - -} - -#ifdef MYROOT - - - - - -TH1F* energyCalibration::createMedianHistogram(TH2F* h2, int ch0, int nch, int direction) { - - if (h2==NULL || nch==0) - return NULL; - - double *x=new double[nch]; - TH1F *h1=NULL; - - double val=-1; - - if (direction==0) { - h1=new TH1F("median","Median",h2->GetYaxis()->GetNbins(),h2->GetYaxis()->GetXmin(),h2->GetYaxis()->GetXmax()); - for (int ib=0; ibGetXaxis()->GetNbins(); ib++) { - for (int ich=0; ichGetBinContent(ch0+ich+1,ib+1); - } - val=energyCalibrationFunctions::median(x, nch); - h1->SetBinContent(ib+1,val); - } - } else if (direction==1) { - h1=new TH1F("median","Median",h2->GetXaxis()->GetNbins(),h2->GetXaxis()->GetXmin(),h2->GetXaxis()->GetXmax()); - for (int ib=0; ibGetYaxis()->GetNbins(); ib++) { - for (int ich=0; ichGetBinContent(ib+1,ch0+ich+1); - } - val=energyCalibrationFunctions::median(x, nch); - h1->SetBinContent(ib+1,val); - } - } - delete [] x; - - return h1; - -} - - - - - - - - - - - - - - -void energyCalibration::setStartParameters(Double_t *par){ - bg_offset=par[0]; - bg_slope=par[1]; - flex=par[2]; - noise=par[3]; - ampl=par[4]; - cs_slope=par[5]; -} - - -void energyCalibration::getStartParameters(Double_t *par){ - par[0]=bg_offset; - par[1]=bg_slope; - par[2]=flex; - par[3]=noise; - par[4]=ampl; - par[5]=cs_slope; -} - -#endif -int energyCalibration::setChargeSharing(int p) { - if (p>=0) { - cs_flag=p; -#ifdef MYROOT - if (p) { - fscurve->ReleaseParameter(5); - fspectrum->ReleaseParameter(1); - } else { - fscurve->FixParameter(5,0); - fspectrum->FixParameter(1,0); - } -#endif - } - - return cs_flag; -} - - -#ifdef MYROOT -void energyCalibration::initFitFunction(TF1 *fun, TH1 *h1) { - - Double_t min=fit_min, max=fit_max; - - Double_t mypar[6]; - - if (max==-1) - max=h1->GetXaxis()->GetXmax(); - - if (min==-1) - min=h1->GetXaxis()->GetXmin(); - - - if (bg_offset==-1) - mypar[0]=0; - else - mypar[0]=bg_offset; - - - if (bg_slope==-1) - mypar[1]=0; - else - mypar[1]=bg_slope; - - - if (flex==-1) - mypar[2]=(min+max)/2.; - else - mypar[2]=flex; - - - if (noise==-1) - mypar[3]=0.1; - else - mypar[3]=noise; - - if (ampl==-1) - mypar[4]=h1->GetBinContent(h1->GetXaxis()->FindBin(0.5*(max+min))); - else - mypar[4]=ampl; - - if (cs_slope==-1) - mypar[5]=0; - else - mypar[5]=cs_slope; - - fun->SetParameters(mypar); - - fun->SetRange(min,max); - -} - - -TF1* energyCalibration::fitFunction(TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar) { - - - TF1* fitfun; - - char fname[100]; - - strcpy(fname, fun->GetName()); - - if (plot_flag) { - h1->Fit(fname,"R0Q"); - } else - h1->Fit(fname,"R0Q"); - - - fitfun= h1->GetFunction(fname); - fitfun->GetParameters(mypar); - for (int ip=0; ip<6; ip++) { - emypar[ip]=fitfun->GetParError(ip); - } - return fitfun; -} - -TF1* energyCalibration::fitSCurve(TH1 *h1, Double_t *mypar, Double_t *emypar) { - initFitFunction(fscurve,h1); - return fitFunction(fscurve, h1, mypar, emypar); -} - - - - - -TF1* energyCalibration::fitSpectrum(TH1 *h1, Double_t *mypar, Double_t *emypar) { - initFitFunction(fspectrum,h1); - return fitFunction(fspectrum, h1, mypar, emypar); -} - - - -TF1* energyCalibration::fitSpectrumPixel(TH1 *h1, Double_t *mypar, Double_t *emypar) { - initFitFunction(fspixel,h1); - return fitFunction(fspixel, h1, mypar, emypar); -} - - - -TGraphErrors* energyCalibration::linearCalibration(int nscan, Double_t *en, Double_t *een, Double_t *fl, Double_t *efl, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff) { - - TGraphErrors *gr; - - Double_t mypar[2]; - - gr = new TGraphErrors(nscan,en,fl,een,efl); - - if (plot_flag) { - gr->Fit("pol1"); - gr->SetMarkerStyle(20); - } else - gr->Fit("pol1","0Q"); - - TF1 *fitfun= gr->GetFunction("pol1"); - fitfun->GetParameters(mypar); - - egain=fitfun->GetParError(1); - eoff=fitfun->GetParError(0); - - gain=funcs->setScanSign()*mypar[1]; - - off=mypar[0]; - - return gr; -} - - -TGraphErrors* energyCalibration::calibrate(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff, int integral) { - - TH1F *h; - - Double_t mypar[6], emypar[6]; - Double_t fl[nscan], efl[nscan]; - - - for (int ien=0; ien -#include -class TH1F; -class TH2F; -class TGraphErrors; -#endif - - -using namespace std; - - - - -const double conven=1000./3.6; /**< electrons/keV */ -const double el=1.67E-4; /**< electron charge in fC */ - - - -/** - \mainpage Common Root library for SLS detectors data analysis - * - * \section intro_sec Introduction - We know very well s-curves etc. but at the end everybody uses different functions ;-). - - * \subsection mot_sec Motivation - It would be greate to use everybody the same functions... - -*/ - - -/** - * - * -@libdoc The energiCalibration class contains all the necessary functions for s-curve fitting and linear calibration of the threshold. - * - * @short Energy calibration functions - * @author Anna Bergamaschi - * @version 0.1alpha - - - */ - -/** - class containing all the possible energy calibration functions (scurves with and without charge sharing, gaussian spectrum with and without charge sharing, possibility of chosing the sign of the X-axis) - -*/ -class energyCalibrationFunctions { - - public: - - energyCalibrationFunctions(int s=-1) {setScanSign(s);}; - - /** sets scan sign - \param s can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) otherwise gets - \returns current scan sign can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) - */ - int setScanSign(int s=0) {if (s==1 || s==-1) sign=s; return sign;};; - - -#ifdef MYROOT - /** - Gaussian Function with charge sharing pedestal - par[0] is the absolute height of the background pedestal - par[1] is the slope of the background pedestal - */ - Double_t pedestal(Double_t *x, Double_t *par); - - /** - Gaussian Function with charge sharing pedestal - par[0] is the absolute height of the background pedestal - par[1] is the slope of the background pedestal - par[2] is the gaussian peak position - par[3] is the RMS of the gaussian (and of the pedestal) - par[4] is the height of the function - par[5] is the fractional height of the charge sharing pedestal (scales with par[3]) - */ - Double_t gaussChargeSharing(Double_t *x, Double_t *par); - /** - Gaussian Function with charge sharing pedestal - par[0] is the absolute height of the background pedestal - par[1] is the slope of the background pedestal - par[2] is the gaussian peak position - par[3] is the RMS of the gaussian (and of the pedestal) - par[4] is the height of the function - par[5] is the fractional height of the charge sharing pedestal (scales with par[3]) - */ - Double_t gaussChargeSharingPixel(Double_t *x, Double_t *par); - - /** - Basic erf function - par[0] is the inflection point - par[1] is the RMS - par[2] is the amplitude - */ -Double_t erfFunction(Double_t *x, Double_t *par) ; - Double_t erfBox(Double_t *z, Double_t *par); - /** Erf function with charge sharing slope - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point - par[3] is the RMS - par[4] is the amplitude - par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) - */ -Double_t erfFunctionChargeSharing(Double_t *x, Double_t *par); - - /** Double Erf function with charge sharing slope - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point of the first energy - par[3] is the RMS of the first energy - par[4] is the amplitude of the first energy - par[5] is the angual coefficient of the charge sharing slope of the first energy (scales with par[3]) - par[6] is the inflection point of the second energy - par[7] is the RMS of the second energy - par[8] is the amplitude of the second energy - par[9] is the angual coefficient of the charge sharing slope of the second energy (scales with par[8]) - */ - -Double_t erfFuncFluo(Double_t *x, Double_t *par); - - - /** - static function Gaussian with charge sharing pedestal with the correct scan sign - par[0] is the absolute height of the background pedestal - par[1] is the slope of the pedestal - par[2] is the gaussian peak position - par[3] is the RMS of the gaussian (and of the pedestal) - par[4] is the height of the function - par[5] is the fractional height of the charge sharing pedestal (scales with par[4] - */ - Double_t spectrum(Double_t *x, Double_t *par); - - /** - static function Gaussian with charge sharing pedestal with the correct scan sign - par[0] is the absolute height of the background pedestal - par[1] is the slope of the pedestal - par[2] is the gaussian peak position - par[3] is the RMS of the gaussian (and of the pedestal) - par[4] is the height of the function - par[5] is the fractional height of the charge sharing pedestal (scales with par[4] - */ - Double_t spectrumPixel(Double_t *x, Double_t *par); - - - /** Erf function with charge sharing slope with the correct scan sign - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point - par[3] is the RMS - par[4] is the amplitude - par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) - */ - Double_t scurve(Double_t *x, Double_t *par); - - - - /** Double Erf function with charge sharing slope - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point of the first energy - par[3] is the RMS of the first energy - par[4] is the amplitude of the first energy - par[5] is the angual coefficient of the charge sharing slope of the first energy (scales with par[3]) - par[6] is the inflection point of the second energy - par[7] is the RMS of the second energy - par[8] is the amplitude of the second energy - par[9] is the angual coefficient of the charge sharing slope of the second energy (scales with par[8]) - */ - Double_t scurveFluo(Double_t *x, Double_t *par); - -#endif - -/** Calculates the median of an array of n elements */ - static double median(double *x, int n); -/** Calculates the median of an array of n elements (swaps the arrays!)*/ - static int quick_select(int arr[], int n); -/** Calculates the median of an array of n elements (swaps the arrays!)*/ - static int kth_smallest(int *a, int n, int k); - - private: - int sign; - - -}; - -/** - class alowing the energy calibration of photon counting and anlogue detectors - -*/ - -class energyCalibration { - - - public: - /** - default constructor - creates the function with which the s-curves will be fitted - */ - energyCalibration(); - - /** - default destructor - deletes the function with which the s-curves will be fitted - */ - ~energyCalibration(); - - /** sets plot flag - \param p plot flag (-1 gets, 0 unsets, >0 plot) - \returns current plot flag - */ - int setPlotFlag(int p=-1) {if (p>=0) plot_flag=p; return plot_flag;}; - - /** sets scan sign - \param s can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) otherwise gets - \returns current scan sign can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) - */ - int setScanSign(int s=0) {return funcs->setScanSign(s);}; - - /** sets plot flag - \param p plot flag (-1 gets, 0 unsets, >0 plot) - \returns current plot flag - */ - int setChargeSharing(int p=-1); - - - void fixParameter(int ip, Double_t val); - - void releaseParameter(int ip); - -#ifdef MYROOT - - /** - Creates an histogram with the median of nchannels starting from a specified one. the direction on which it is mediated can be selected (defaults to x=0) - \param h2 2D histogram on which the median will be calculated - \param ch0 starting channel - \param nch number of channels to be mediated - \param direction can be either 0 (x, default) or 1 (y) - \returns a TH1F histogram with the X-axis as a clone of the h2 Y (if direction=0) or X (if direction=0) axis, and on the Y axis the median of the counts of the mediated channels f h2 - */ - static TH1F* createMedianHistogram(TH2F* h2, int ch0, int nch, int direction=0); - - - /** sets the s-curve fit range - \param mi minimum of the fit range (-1 is histogram x-min) - \param ma maximum of the fit range (-1 is histogram x-max) - */ - void setFitRange(Double_t mi, Double_t ma){fit_min=mi; fit_max=ma;}; - - /** gets the s-curve fit range - \param mi reference for minimum of the fit range (-1 is histogram x-min) - \param ma reference for maximum of the fit range (-1 is histogram x-max) - */ - void getFitRange(Double_t &mi, Double_t &ma){mi=fit_min; ma=fit_max;}; - - -/** set start parameters for the s-curve function - \param par parameters, -1 sets to auto-calculation - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point - par[3] is the RMS - par[4] is the amplitude - par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) -- always positive - */ - void setStartParameters(Double_t *par); - -/** get start parameters for the s-curve function - \param par parameters, -1 means auto-calculated - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point - par[3] is the RMS - par[4] is the amplitude - par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) -- always positive - */ - void getStartParameters(Double_t *par); - - /** - fits histogram with the s-curve function - \param h1 1d-histogram to be fitted - \param mypar pointer to fit parameters array - \param emypar pointer to fit parameter errors - \returns the fitted function - can be used e.g. to get the Chi2 or similar - */ - TF1 *fitSCurve(TH1 *h1, Double_t *mypar, Double_t *emypar); - - - /** - fits histogram with the spectrum - \param h1 1d-histogram to be fitted - \param mypar pointer to fit parameters array - \param emypar pointer to fit parameter errors - \returns the fitted function - can be used e.g. to get the Chi2 or similar - */ - TF1 *fitSpectrum(TH1 *h1, Double_t *mypar, Double_t *emypar); - - - /** - fits histogram with the spectrum - \param h1 1d-histogram to be fitted - \param mypar pointer to fit parameters array - \param emypar pointer to fit parameter errors - \returns the fitted function - can be used e.g. to get the Chi2 or similar - */ - TF1 *fitSpectrumPixel(TH1 *h1, Double_t *mypar, Double_t *emypar); - - - /** - calculates gain and offset for the set of inflection points - \param nscan number of energy scans - \param en array of energies (nscan long) - \param een array of errors on energies (nscan long) - can be NULL! - \param fl array of inflection points (nscan long) - \param efl array of errors on the inflection points (nscan long) - \param gain reference to gain resulting from the fit - \param off reference to offset resulting from the fit - \param egain reference to error on the gain resulting from the fit - \param eoff reference to the error on the offset resulting from the fit - \returns graph energy vs inflection point - */ - TGraphErrors* linearCalibration(int nscan, Double_t *en, Double_t *een, Double_t *fl, Double_t *efl, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff); - - /** - calculates gain and offset for the set of energy scans - \param nscan number of energy scans - \param en array of energies (nscan long) - \param een array of errors on energies (nscan long) - can be NULL! - \param h1 array of TH1 - \param gain reference to gain resulting from the fit - \param off reference to offset resulting from the fit - \param egain reference to error on the gain resulting from the fit - \param eoff reference to the error on the offset resulting from the fit - \returns graph energy vs inflection point - */ - TGraphErrors* calibrateScurves(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff){return calibrate(nscan, en, een, h1, gain, off, egain, eoff, 1);}; - - /** - calculates gain and offset for the set of energy spectra - \param nscan number of energy scans - \param en array of energies (nscan long) - \param een array of errors on energies (nscan long) - can be NULL! - \param h1 array of TH1 - \param gain reference to gain resulting from the fit - \param off reference to offset resulting from the fit - \param egain reference to error on the gain resulting from the fit - \param eoff reference to the error on the offset resulting from the fit - \returns graph energy vs peak - */ - TGraphErrors* calibrateSpectra(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff){return calibrate(nscan, en, een, h1, gain, off, egain, eoff, 0);}; - - -#endif - private: - -#ifdef MYROOT - /** - calculates gain and offset for the set of energies - \param nscan number of energy scans - \param en array of energies (nscan long) - \param een array of errors on energies (nscan long) - can be NULL! - \param h1 array of TH1 - \param gain reference to gain resulting from the fit - \param off reference to offset resulting from the fit - \param egain reference to error on the gain resulting from the fit - \param eoff reference to the error on the offset resulting from the fit - \param integral 1 is an s-curve set (default), 0 spectra - \returns graph energy vs peak/inflection point - */ - TGraphErrors* calibrate(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff, int integral=1); - - - /** - Initializes the start parameters and the range of the fit depending on the histogram characteristics and/or on the start parameters specified by the user - \param fun pointer to function to be initialized - \param h1 histogram from which to extract the range and start parameters, if not already specified by the user - -*/ - - void initFitFunction(TF1 *fun, TH1 *h1); - - - /** - Performs the fit according to the flags specified and returns the fitted function - \param fun function to fit - \param h1 histogram to fit - \param mypar pointer to fit parameters array - \param emypar pointer to fit parameter errors - \returns the fitted function - can be used e.g. to get the Chi2 or similar - */ - TF1 *fitFunction(TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar); - -#endif - -#ifdef MYROOT - Double_t fit_min; /**< minimum of the s-curve fitting range, -1 is histogram x-min */ - Double_t fit_max; /**< maximum of the s-curve fitting range, -1 is histogram x-max */ - - Double_t bg_offset; /**< start value for the background pedestal */ - Double_t bg_slope; /**< start value for the background slope */ - Double_t flex; /**< start value for the inflection point */ - Double_t noise; /**< start value for the noise */ - Double_t ampl; /**< start value for the number of photons */ - Double_t cs_slope; /**< start value for the charge sharing slope */ - - - TF1 *fscurve; /**< function with which the s-curve will be fitted */ - - TF1 *fspectrum; /**< function with which the spectrum will be fitted */ - - TF1 *fspixel; /**< function with which the spectrum will be fitted */ - -#endif - - energyCalibrationFunctions *funcs; - int plot_flag; /**< 0 does not plot, >0 plots (flags?) */ - - int cs_flag; /**< 0 functions without charge sharing contribution, >0 with charge sharing contribution */ - -}; - -#endif - - - - - - - - - - - - - - - - - - - diff --git a/slsDetectorCalibration/gotthardDoubleModuleCommonModeSubtractionNew.h b/slsDetectorCalibration/gotthardDoubleModuleCommonModeSubtractionNew.h deleted file mode 100644 index 2960cabd4..000000000 --- a/slsDetectorCalibration/gotthardDoubleModuleCommonModeSubtractionNew.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef GOTTHARDDOUBLECOMMONMODESUBTRACTION_H -#define GOTTHARDDOUBLECOMMONMODESUBTRACTION_H - - -#include "commonModeSubtractionNew.h" - -class gotthardDoubleModuleCommonModeSubtraction : public commonModeSubtraction { - - /** @short class to calculate the common mode of the pedestals based on an approximated moving average*/ - - public: - - /** constructor - \param nn number of samples for the moving average to calculate the average common mode - \param iroi number of regions on which one can calculate the common mode separately. Defaults to 1 i.e. whole detector - - */ - gotthardDoubleModuleCommonModeSubtraction(int ns=3) : commonModeSubtraction(2, ns) {}; - - /** - gets the common mode ROI for pixel ix, iy - */ - virtual int getROI(int ix, int iy){return ix%2;}; - - -}; - - - -#endif diff --git a/slsDetectorCalibration/gotthardExecutables/Makefile.onTheFly b/slsDetectorCalibration/gotthardExecutables/Makefile.onTheFly deleted file mode 100644 index da6e994ef..000000000 --- a/slsDetectorCalibration/gotthardExecutables/Makefile.onTheFly +++ /dev/null @@ -1,22 +0,0 @@ - -CBFLIBDIR=/afs/psi.ch/project/sls_det_software/CBFlib-0.9.5 -LIBRARYCBF=$(CBFLIBDIR)/lib/*.o ../tiffIO.cpp -ZMQLIB=../../slsReceiverSoftware/include -INCDIR=-I.. -I../../slsReceiverSoftware/include -I$(CBFLIBDIR)/include/ -I. -I../interpolations -I../dataStructures -LIBHDF5=-L$(CBFLIBDIR)/lib/ -lhdf5 -LDFLAG= -L/usr/lib64/ -lpthread -#-L../../bin -MAIN=gotthard25umZmqAnalysis.C - -#DESTDIR?=../bin - -all: gotthard25umOnTheFlyAnalysis gotthard25umZmq - -gotthard25umOnTheFlyAnalysis: $(MAIN) $(INCS) clean - g++ -o gotthard25umOnTheAnalysis $(MAIN) -lm -ltiff -lstdc++ $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) - -gotthard25umZmq: $(MAIN) $(INCS) clean - g++ -o gotthard25umZmq $(MAIN) -lm -ltiff -lstdc++ $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DZMQ -L$(ZMQLIB) -lzmq - -clean: - rm -f gotthard25umOnTheFlyAnalysis diff --git a/slsDetectorCalibration/gotthardExecutables/gotthard25umZmqAnalysis.C b/slsDetectorCalibration/gotthardExecutables/gotthard25umZmqAnalysis.C deleted file mode 100644 index 49987b07b..000000000 --- a/slsDetectorCalibration/gotthardExecutables/gotthard25umZmqAnalysis.C +++ /dev/null @@ -1,517 +0,0 @@ -#include "sls_receiver_defs.h" -//#ifdef ZMQ -#include "ZmqSocket.h" -//#endif -#include -#include -#include -#include -#include -#include -//#include -//#include -//#include -#include -#include - -//#define BCHIP074_BCHIP075 - -#include "gotthardModuleDataNew.h" -#include "gotthardDoubleModuleDataNew.h" -#include "gotthardDoubleModuleCommonModeSubtractionNew.h" - -#include "singlePhotonDetector.h" -//#include "interpolatingDetector.h" -//#include "linearInterpolation.h" -#include "multiThreadedAnalogDetector.h" - -#include - -#define NC 1280 -#define NR 1 - -//#include "tiffIO.h" - - - - - -#define SLS_DETECTOR_JSON_HEADER_VERSION 0x2 -int main(int argc, char *argv[]){ - //void *gotthardProcessFrame() { - - - - int fifosize=1000; - int nthreads=1; - int nph, nph1; - int etabins=550; - double etamin=-1, etamax=2; - int nsubpix=1; - float *etah=new float[etabins*etabins]; - int *heta, *himage; - int offset=48; - #ifdef ZMQ - offset=0; - #endif - #ifndef ZMQ - offset=48; - #endif - - //commonModeSubtraction *cm=NULL; - - gotthardDoubleModuleCommonModeSubtraction *cm=new gotthardDoubleModuleCommonModeSubtraction(); - gotthardModuleDataNew *decoder=new gotthardModuleDataNew(); - gotthardDoubleModuleDataNew *det=new gotthardDoubleModuleDataNew(offset); - singlePhotonDetector *filter=new singlePhotonDetector(det,3, 5, 1, cm, 1000, 100); - // analogDetector *filter=new analogDetector(det, 1, cm, 1000); - // analogDetector *filter_nocm=new analogDetector(det, 1, NULL, 1000); - filter->setROI(0,2560,0,1); - char *buff;//[2*(48+1280*2)]; - char *buff0; - char *buff1; - multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); - mt->setFrameMode(eFrame); - // mt->setFrameMode(eFrame); - // mt->setFrameMode(ePedestal); - mt->StartThreads(); - mt->popFree(buff); - buff0=buff; - buff1=buff+offset*2+1280*2; - int photons[1280*2]; - int nf=0; - int ok=0; - std::time_t end_time; - //int16_t dout[1280*2]; - int iFrame=-1; - int np=-1; - nph=0; - nph1=0; - //int np; - int iph; - int data_ready=1; - int *image; - - - - int length; - int nnx, nny,nns; - int nix, niy,nis; - // infinite loop - int ix, iy, isx, isy; - - filter->getImageSize(nnx, nny,nns); - int16_t *dout=new int16_t [nnx*nny]; - - - -#ifdef ZMQ - if (argc < 3 ) { - cprintf(RED, "Help: %s [receive socket ip] [receive starting port number] [send_socket ip] [send starting port number]\n",argv[0]); - return EXIT_FAILURE; - } - - // receive parameters - bool send = false; - char* socketip=argv[1]; - uint32_t portnum = atoi(argv[2]); - int size = nnx*nny*2; - - // send parameters if any - char* socketip2 = 0; - uint32_t portnum2 = 0; - if (argc > 3) { - send = true; - socketip2 = argv[3]; - portnum2 = atoi(argv[4]); - } - cout << "\nrx socket ip : " << socketip << - "\nrx port num : " << portnum ; - if (send) { - cout << "\nsd socket ip : " << socketip2 << - "\nsd port num : " << portnum2; - } - cout << endl; - - - - // receive socket - ZmqSocket* zmqsocket0 = new ZmqSocket(socketip,portnum); - if (zmqsocket0->IsError()) { - cprintf(RED, "Error: Could not create Zmq socket on port %d with ip %s\n", portnum, socketip); - delete zmqsocket0; - return EXIT_FAILURE; - } - - ZmqSocket* zmqsocket1 = new ZmqSocket(socketip,portnum+1); - if (zmqsocket1->IsError()) { - cprintf(RED, "Error: Could not create Zmq socket on port %d with ip %s\n", portnum+1, socketip); - delete zmqsocket1; - delete zmqsocket0; - return EXIT_FAILURE; - } - - - zmqsocket0->Connect(); - printf("Zmq Client 0 at %s\n", zmqsocket0->GetZmqServerAddress()); - zmqsocket1->Connect(); - printf("Zmq Client 1 at %s\n", zmqsocket1->GetZmqServerAddress()); - - // send socket - ZmqSocket* zmqsocket2 = 0; - ZmqSocket* zmqsocket3 = 0; - if (send) { - zmqsocket2 = new ZmqSocket(portnum2, socketip2); - if (zmqsocket2->IsError()) { - bprintf(RED, "Error: Could not create Zmq socket server on port %d and ip %s\n", portnum2, socketip2); - delete zmqsocket2; - delete zmqsocket1; - delete zmqsocket0; - return EXIT_FAILURE; - } - - zmqsocket3 = new ZmqSocket(portnum2+1, socketip2); - if (zmqsocket3->IsError()) { - bprintf(RED, "Error: Could not create Zmq socket server on port %d and ip %s\n", portnum2+1, socketip2); - delete zmqsocket3; - delete zmqsocket2; - delete zmqsocket1; - delete zmqsocket0; - return EXIT_FAILURE; - } - - zmqsocket2->Connect(); - printf("Zmq Server 0 started at %s\n", zmqsocket2->GetZmqServerAddress()); - zmqsocket3->Connect(); - printf("Zmq Server 1 started at %s\n", zmqsocket3->GetZmqServerAddress()); - } - - - - - - - - uint64_t acqIndex1 = -1; - uint64_t frameIndex1 = -1; - uint32_t subframeIndex1 = -1; - uint64_t fileindex1 = -1; - string filename1 = ""; - - uint64_t acqIndex0 = -1; - uint64_t frameIndex0 = -1; - uint32_t subframeIndex0 = -1; - uint64_t fileindex0 = -1; - string filename0 = ""; - - - int eoa0=0; - int eoa1=0; - - - - - - #endif - - - - - - - - - - - - - char ofname[10000]; - char fn0[10000], fn1[10000]; - FILE *fout=NULL; - FILE *fclust=NULL; - for (int i=0; ireadNextFrame(filebin0, iFrame, np, buff0)) && (decoder->readNextFrame(filebin1, iFrame, np, buff1))) { -#endif - - - - - -#ifdef ZMQ - - int end_of_acquisition; - while(1) { - end_of_acquisition=0; - eoa0=0; - eoa1=0; - - // cout << "Receive header " << nf << endl; - if (!zmqsocket0->ReceiveHeader(0, acqIndex0, frameIndex0, subframeIndex0, filename0, fileindex0)) { - - // cout << "************************************************************************** packet0!*****************************"<< endl; - eoa0=1; - end_of_acquisition++; - } - if (!zmqsocket1->ReceiveHeader(0, acqIndex1, frameIndex1, subframeIndex1, filename1, fileindex1)) { - //cout << "************************************************************************** packet1!*****************************"<< endl; - eoa1=1; - end_of_acquisition++; - } - - - - - - // if ((!zmqsocket0->ReceiveHeader(0, acqIndex0, frameIndex0, subframeIndex0, filename0, fileindex0)) && (!zmqsocket1->ReceiveHeader(0, acqIndex1, frameIndex1, subframeIndex1, filename1, fileindex1))){ - if (end_of_acquisition==0) { - - if (acqIndex0!=acqIndex1) - cout << "different acquisition indexes " << acqIndex0 << " and " << acqIndex1 << endl; - if (frameIndex0!=frameIndex1) - cout << "different frame indexes " << frameIndex0 << " and " << frameIndex1 << endl; - - - while (frameIndex0ReceiveData(0, buff0, size/2); - if (!zmqsocket0->ReceiveHeader(0, acqIndex0, frameIndex0, subframeIndex0, filename0, fileindex0)) { - end_of_acquisition++; - eoa0=1; - break; - } - } - - while (frameIndex1ReceiveData(0, buff1, size/2); - if (!zmqsocket1->ReceiveHeader(0, acqIndex1, frameIndex1, subframeIndex1, filename1, fileindex1)) { - end_of_acquisition++; - eoa1=1; - break; - } - } - } - - - - if (eoa0!=eoa1) { - - while (eoa0<1) { - length = zmqsocket0->ReceiveData(0, buff0, size/2); - if (!zmqsocket0->ReceiveHeader(0, acqIndex0, frameIndex0, subframeIndex0, filename0, fileindex0)) { - end_of_acquisition++; - eoa0=1; - } - } - - - while (eoa1<1) { - length = zmqsocket1->ReceiveData(0, buff1, size/2); - if (!zmqsocket1->ReceiveHeader(0, acqIndex1, frameIndex1, subframeIndex1, filename1, fileindex1)) { - end_of_acquisition++; - eoa1=1; - } - } - } - - - - - - - if (end_of_acquisition) { - // cout << "************************************************************************** END OF FRAME" << end_of_acquisition << " !*****************************"<< endl; - // return 0; - - sprintf(ofname,"%s_%d.ph",fn0,irun); - while (mt->isBusy()) {;} - image=filter->getImage(); - if (image) { - fout=fopen(ofname,"w"); - cout << nf << "*****************" << endl; - for (int i=0; i<2560; i++) { - fprintf(fout,"%d %d\n",i,image[i]); - dout[i]=image[i]; - if (dout[i]<0) - dout[i]=0; - } - fclose(fout); - } - - - if (send) { - - zmqsocket2->SendHeaderData(0, false, SLS_DETECTOR_JSON_HEADER_VERSION,0,0,0,0,0, 0,0,fn0, 0, 0,0,0,0,0,0,0,0,0,0,0,1); - zmqsocket3->SendHeaderData(0, false, SLS_DETECTOR_JSON_HEADER_VERSION,0,0,0,0,0, 0,0,fn1, 0, 0,0,0,0,0,0,0,0,0,0,0,1); - - zmqsocket2->SendData((char*)dout,size/2); - zmqsocket3->SendData(((char*)dout)+size/2,size/2); - // // cprintf(GREEN, "Sent Data\n"); - - - zmqsocket2->SendHeaderData(0, true, SLS_DETECTOR_JSON_HEADER_VERSION); - zmqsocket3->SendHeaderData(0, true, SLS_DETECTOR_JSON_HEADER_VERSION); - } - - - //mt->setFrameMode(eFrame); - filter->clearImage(); - // std::time(&end_time); - // cout << std::ctime(&end_time) << " " << nf << endl; - fclose(fclust); - fclust=NULL; - - - - continue; - } - - if (fclust==NULL) { - - strcpy(fn0,filename0.c_str()); - strcpy(fn1,filename1.c_str()); - sprintf(ofname,"%s_%d.clust",fn0,irun); - fclust=fopen(ofname,"w"); - while (mt->isBusy()) {;} - mt->setFilePointer(fclust); - } - - // strcpy(fn0,filename0.c_str()); - // strcpy(fn1,filename1.c_str()); - - // cout << "Receive data " << nf << endl; - length = zmqsocket0->ReceiveData(0, buff0, size/2); - length += zmqsocket1->ReceiveData(0, buff1, size/2); - - irun=fileindex0; - - - - // // if (nf>100) - // // mt->setFrameMode(eFrame); - // //filter->clearImage(); - - -#endif - - - mt->pushData(buff); - mt->nextThread(); - // cout << "==" << nf << endl; - - // while (mt->isBusy()) {;} - // image=filter->getImage(); - // if (image) { - // for (int i=0; i<2560; i++) { - // // if (i<512) - - // // fprintf(fout,"%d %d\n",i,image[i]); - // dout[i]=filter->subtractPedestal(buff,i,0,1);//image[i];//filter->getPedestal(i,0);// - // if (dout[i]<0) - // dout[i]=0; - // // cout << i << " " << image[i] << " " << dout[i] << endl; - // } - // } - - - // if (send) { - // strcpy(fname0,filename0.c_str()); - // strcpy(fname1,filename1.c_str()); - // // zmqsocket2->SendHeaderData(0, false, SLS_DETECTOR_JSON_HEADER_VERSION,16,fileindex,400,400,400*400, acqIndex,frameIndex,fname, acqIndex, 0,0,0,0,0,0,0,0,0,0,0,1); - // zmqsocket2->SendHeaderData(0, false, SLS_DETECTOR_JSON_HEADER_VERSION,0,0,0,0,0, 0,0,fname0, 0, 0,0,0,0,0,0,0,0,0,0,0,1); - // zmqsocket3->SendHeaderData(0, false, SLS_DETECTOR_JSON_HEADER_VERSION,0,0,0,0,0, 0,0,fname1, 0, 0,0,0,0,0,0,0,0,0,0,0,1); - - // zmqsocket2->SendData((char*)dout,size/2); - // zmqsocket3->SendData(((char*)dout)+size/2,size/2); - // // cprintf(GREEN, "Sent Data\n"); - - - // // zmqsocket2->SendHeaderData(0, true, SLS_DETECTOR_JSON_HEADER_VERSION); - // // zmqsocket3->SendHeaderData(0, true, SLS_DETECTOR_JSON_HEADER_VERSION); - - // // cprintf(RED, "Received %d frames\n", nf); - - // } - - - mt->popFree(buff); - buff0=buff; - buff1=buff+offset*2+1280*2; - - - - nf++; - - - - -#ifndef ZMQ - - - - - while (mt->isBusy()) {;} - image=filter->getImage(); - if (image) { - fout=fopen(ofname,"w"); - //cout << nf << "*****************" << endl; - for (int i=0; i<512; i++) { - fprintf(fout,"%d %d\n",i,image[i]); - } - fclose(fout); - } - filter->clearImage(); - - - - iFrame=-1; - } - - filebin0.close(); - filebin1.close(); - } - else - cout << "Could not open file " << fname0<< " or " << fname1 << endl; -#endif - - } - return NULL; - - - -} diff --git a/slsDetectorCalibration/interpolatingDetector.h b/slsDetectorCalibration/interpolatingDetector.h deleted file mode 100644 index f5ce437bd..000000000 --- a/slsDetectorCalibration/interpolatingDetector.h +++ /dev/null @@ -1,275 +0,0 @@ -#ifndef INTERPOLATINGDETECTOR_H -#define INTERPOLATINGDETECTOR_H - - -#include "singlePhotonDetector.h" - -#include "slsInterpolation.h" - -//#define M015 - -#ifdef MYROOT1 -#include - -#endif - - -#include - -using namespace std; - - -class interpolatingDetector : public singlePhotonDetector { - - /** @short class to perform pedestal subtraction etc. and find single photon clusters for an analog detector */ - - public: - - - /** - - Constructor (no error checking if datasize and offsets are compatible!) - \param d detector data structure to be used - \param csize cluster size (should be an odd number). Defaults to 3 - \param nsigma number of rms to discriminate from the noise. Defaults to 5 - \param sign 1 if photons are positive, -1 if negative - \param cm common mode subtraction algorithm, if any. Defaults to NULL i.e. none - \param nped number of samples for pedestal averaging - \param nd number of dark frames to average as pedestals without photon discrimination at the beginning of the measurement - - - */ - - - interpolatingDetector(slsDetectorData *d, slsInterpolation *inte, - double nsigma=5, - int sign=1, - commonModeSubtraction *cm=NULL, - int nped=1000, - int nd=100, int nnx=-1, int nny=-1) : - singlePhotonDetector(d, 3,nsigma,sign, cm, nped, nd, nnx, nny) , interp(inte), id(0) { - //cout << "**"<< xmin << " " << xmax << " " << ymin << " " << ymax << endl; - fi=new pthread_mutex_t ; - -}; - - - - interpolatingDetector(interpolatingDetector *orig) : singlePhotonDetector(orig) { - // if (orig->interp) - // interp=(orig->interp)->Clone(); - // else - - interp=orig->interp; - - id=orig->id; - fi=orig->fi; - } - - - virtual interpolatingDetector *Clone() { - return new interpolatingDetector(this); - } - - virtual int setId(int i) { - id=i; - // interp->setId(id); - return id; - }; - - virtual void prepareInterpolation(int &ok) { - /* cout << "*"<< endl; */ -/* #ifdef SAVE_ALL */ -/* char tit[1000]; */ -/* sprintf(tit,"/scratch/ped_%d.tiff",id); */ -/* writePedestals(tit); */ -/* sprintf(tit,"/scratch/ped_rms_%d.tiff",id); */ -/* writePedestalRMS(tit); */ -/* if (gmap) { */ -/* sprintf(tit,"/scratch/gmap_%d.tiff",id); */ -/* writeGainMap(tit); */ -/* } */ -/* #endif */ - if (interp){ - pthread_mutex_lock(fi); - interp->prepareInterpolation(ok); - pthread_mutex_unlock(fi); - } - } - - - void clearImage() { - if (interp) { - pthread_mutex_lock(fi); - interp->clearInterpolatedImage(); - pthread_mutex_unlock(fi); - } else - singlePhotonDetector::clearImage(); - }; - - int getImageSize(int &nnx, int &nny, int &ns) { - if (interp) - return interp->getImageSize(nnx, nny, ns); - else - return analogDetector::getImageSize(nnx, nny, ns); - }; - - - #ifdef MYROOT1 - virtual TH2F *getImage() -#endif -#ifndef MYROOT1 - virtual int *getImage() -#endif - { - // cout << "image " << endl; - if (interp) - return interp->getInterpolatedImage(); - else - return analogDetector::getImage(); - } - -#ifdef MYROOT1 - virtual TH2F *addToInterpolatedImage(char *data, int *val, int &nph) -#endif -#ifndef MYROOT1 - virtual int *addToInterpolatedImage(char *data, int *val, int &nph) -#endif - { - nph=addFrame(data,val,0); - if (interp) - return interp->getInterpolatedImage(); - else - singlePhotonDetector::getImage(); - //return NULL; - }; - - -#ifdef MYROOT1 - virtual TH2F *addToFlatField(char *data, int *val, int &nph) -#endif -#ifndef MYROOT1 - virtual int *addToFlatField(char *data, int *val, int &nph) -#endif - { - nph=addFrame(data,val,1); - if (interp) - return interp->getFlatField(); - else - return NULL; - }; - - void *writeImage(const char * imgname) { - // cout << id << "=" << imgname<< endl; - if (interp) - interp->writeInterpolatedImage(imgname); - else - analogDetector::writeImage(imgname); - return NULL; - } - - - -int addFrame(char *data, int *ph=NULL, int ff=0) { - - singlePhotonDetector::processData(data,ph); - int nph=0; - - double int_x, int_y; - double eta_x, eta_y; - if (interp) { - // cout << "int" << endl; - pthread_mutex_lock(fi); - for (nph=0; nphaddToFlatField((clusters+nph)->quadTot,(clusters+nph)->quad,(clusters+nph)->get_cluster(),eta_x, eta_y); - } else { - interp->getInterpolatedPosition((clusters+nph)->x, (clusters+nph)->y, (clusters+nph)->quadTot,(clusters+nph)->quad,(clusters+nph)->get_cluster(),int_x, int_y); - interp->addToImage(int_x, int_y); - } - } - pthread_mutex_unlock(fi); - } - return nphFrame; - -}; - - virtual void processData(char *data, int *val=NULL) { - switch (dMode) { - case eAnalog: - // cout << "an" << endl; - analogDetector::processData(data,val); - break; - case ePhotonCounting: - // cout << "spc" << endl; - singlePhotonDetector::processData(data,val); - break; - default: - //cout << "int" << endl; - switch(fMode) { - case ePedestal: - addToPedestal(data); - break; - case eFlat: - if (interp) - addFrame(data,val,1); - else - singlePhotonDetector::processData(data,val); - break; - default: - if (interp) - addFrame(data,val,0); - else - singlePhotonDetector::processData(data,val); - } - } - - }; - - - - virtual slsInterpolation *getInterpolation(){ - return interp; - }; - - virtual slsInterpolation *setInterpolation(slsInterpolation *ii){ - int ok; - interp=ii; - /* pthread_mutex_lock(fi); - if (interp) - interp->prepareInterpolation(ok); - pthread_mutex_unlock(fi); */ - // cout << "det" << endl; - return interp; - }; - - virtual void resetFlatField() { if (interp) { - pthread_mutex_lock(fi); - interp->resetFlatField(); - pthread_mutex_unlock(fi); - } - } - - virtual int getNSubPixels(){ if (interp) return interp->getNSubPixels(); else return 1;} - virtual int setNSubPixels(int ns) { - if (interp) { - pthread_mutex_lock(fi); - interp->getNSubPixels(); - pthread_mutex_unlock(fi); - } - return getNSubPixels(); - } - - protected: - - - slsInterpolation *interp; - int id; - pthread_mutex_t *fi; -}; - - - - - -#endif diff --git a/slsDetectorCalibration/interpolations/.__afs3A48 b/slsDetectorCalibration/interpolations/.__afs3A48 deleted file mode 100755 index efa6b3d16..000000000 Binary files a/slsDetectorCalibration/interpolations/.__afs3A48 and /dev/null differ diff --git a/slsDetectorCalibration/interpolations/eta2InterpolationBase.h b/slsDetectorCalibration/interpolations/eta2InterpolationBase.h deleted file mode 100644 index d6c4a81dc..000000000 --- a/slsDetectorCalibration/interpolations/eta2InterpolationBase.h +++ /dev/null @@ -1,403 +0,0 @@ -#ifndef ETA2_INTERPOLATION_BASE_H -#define ETA2_INTERPOLATION_BASE_H - -#ifdef MYROOT1 -#include -#include -#include -#include -#endif - -#include "etaInterpolationBase.h" - -class eta2InterpolationBase : public virtual etaInterpolationBase { - - public: - eta2InterpolationBase(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationBase(nx,ny, ns, nb, emin, emax) { - - /* if (etamin>=etamax) { */ - /* etamin=-1; */ - /* etamax=2; */ - /* // cout << ":" <2) - calcEta(totquad, sDum, etax, etay); - getInterpolatedPosition(x,y,etax,etay,corner,int_x,int_y); - - return; - }; - - - virtual void getInterpolatedPosition(int x, int y, double *data, double &int_x, double &int_y) - { - double sDum[2][2]; - double tot, totquad; - double etax,etay; - - int corner; - corner=calcQuad(data, tot, totquad, sDum); - if (nSubPixels>2) - calcEta(totquad, sDum, etax, etay); - getInterpolatedPosition(x,y,etax,etay,corner,int_x,int_y); - - return; - }; - - - - - - - - - - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,double *cl,double &int_x, double &int_y) { - - double cc[2][2]; - int xoff, yoff; - switch (quad) { - case BOTTOM_LEFT: - xoff=0; - yoff=0; - break; - case BOTTOM_RIGHT: - xoff=1; - yoff=0; - break; - case TOP_LEFT: - xoff=0; - yoff=1; - break; - case TOP_RIGHT: - xoff=1; - yoff=1; - break; - default: - ; - } - double etax, etay; - if (nSubPixels>2) { - cc[0][0]=cl[xoff+3*yoff]; - cc[1][0]=cl[xoff+3*(yoff+1)]; - cc[0][1]=cl[xoff+1+3*yoff]; - cc[1][1]=cl[xoff+1+3*(yoff+1)]; - calcEta(totquad,cc,etax,etay); - } - return getInterpolatedPosition(x,y,etax, etay,quad,int_x,int_y); - - } - - - - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,int *cl,double &int_x, double &int_y) { - - double cc[2][2]; - int xoff, yoff; - - switch (quad) { - case BOTTOM_LEFT: - xoff=0; - yoff=0; - break; - case BOTTOM_RIGHT: - xoff=1; - yoff=0; - break; - case TOP_LEFT: - xoff=0; - yoff=1; - break; - case TOP_RIGHT: - xoff=1; - yoff=1; - break; - default: - ; - } - double etax, etay; - if (nSubPixels>2) { - cc[0][0]=cl[xoff+3*yoff]; - cc[1][0]=cl[xoff+3*(yoff+1)]; - cc[0][1]=cl[xoff+1+3*yoff]; - cc[1][1]=cl[xoff+1+3*(xoff+1)]; - calcEta(totquad,cc,etax,etay); - } - return getInterpolatedPosition(x,y,etax, etay,quad,int_x,int_y); - - } - - - - - - - virtual void getInterpolatedPosition(int x, int y, double etax, double etay, int corner, double &int_x, double &int_y) - { - - - double xpos_eta=0,ypos_eta=0; - double dX,dY; - int ex,ey; - switch (corner) - { - case TOP_LEFT: - dX=-1.; - dY=0; - break; - case TOP_RIGHT: - ; - dX=0; - dY=0; - break; - case BOTTOM_LEFT: - dX=-1.; - dY=-1.; - break; - case BOTTOM_RIGHT: - dX=0; - dY=-1.; - break; - default: - cout << "bad quadrant" << endl; - dX=0.; - dY=0.; - } - - - if (nSubPixels>2) { - - ex=(etax-etamin)/etastep; - ey=(etay-etamin)/etastep; - if (ex<0) { - cout << "x*"<< ex << endl; - ex=0; - } - if (ex>=nbeta) { - cout << "x?"<< ex << endl; - ex=nbeta-1; - } - if (ey<0) { - cout << "y*"<< ey << endl; - ey=0; - } - if (ey>=nbeta) { - cout << "y?"<< ey << endl; - ey=nbeta-1; - } - - - - xpos_eta=(((double)hhx[(ey*nbeta+ex)]))+dX ;///((double)nSubPixels); - ypos_eta=(((double)hhy[(ey*nbeta+ex)]))+dY ;///((double)nSubPixels); - - } else { - xpos_eta=0.5*dX+0.25; - ypos_eta=0.5*dY+0.25; - } - - int_x=((double)x) + xpos_eta+0.5; - int_y=((double)y) + ypos_eta+0.5; - - - } - - - - virtual int addToFlatField(double totquad,int quad,int *cl,double &etax, double &etay) { - double cc[2][2]; - int xoff, yoff; - - switch (quad) { - case BOTTOM_LEFT: - xoff=0; - yoff=0; - break; - case BOTTOM_RIGHT: - xoff=1; - yoff=0; - break; - case TOP_LEFT: - xoff=0; - yoff=1; - break; - case TOP_RIGHT: - xoff=1; - yoff=1; - break; - default: - ; - } - cc[0][0]=cl[xoff+3*yoff]; - cc[1][0]=cl[xoff+3*(yoff+1)]; - cc[0][1]=cl[xoff+1+3*yoff]; - cc[1][1]=cl[xoff+1+3*(yoff+1)]; - - //calcMyEta(totquad,quad,cl,etax, etay); - calcEta(totquad, cc,etax, etay); - - // cout <<"******"<< etax << " " << etay << endl; - - - return addToFlatField(etax,etay); - } - - virtual int addToFlatField(double totquad,int quad,double *cl,double &etax, double &etay) { - double cc[2][2]; - int xoff, yoff; - - switch (quad) { - case BOTTOM_LEFT: - xoff=0; - yoff=0; - break; - case BOTTOM_RIGHT: - xoff=1; - yoff=0; - break; - case TOP_LEFT: - xoff=0; - yoff=1; - break; - case TOP_RIGHT: - xoff=1; - yoff=1; - break; - default: - ; - } - cc[0][0]=cl[xoff+3*yoff]; - cc[1][0]=cl[(yoff+1)*3+xoff]; - cc[0][1]=cl[yoff*3+xoff+1]; - cc[1][1]=cl[(yoff+1)*3+xoff+1]; - - /* cout << cl[0] << " " << cl[1] << " " << cl[2] << endl; */ - /* cout << cl[3] << " " << cl[4] << " " << cl[5] << endl; */ - /* cout << cl[6] << " " << cl[7] << " " << cl[8] << endl; */ - /* cout <<"******"<Fill(etax,etay); -#endif -#ifndef MYROOT1 - int ex,ey; - ex=(etax-etamin)/etastep; - ey=(etay-etamin)/etastep; - if (ey=0 && ey>=0) - heta[ey*nbeta+ex]++; -#endif - return 0; - }; - - virtual int *getInterpolatedImage(){ - int ipx, ipy; - // cout << "ff" << endl; - calcDiff(1, hhx, hhy); //get flat - double avg=0; - for (ipx=0; ipx0) - hintcorr[ibx+iby*nSubPixels*nPixelsX]=hint[ibx+iby*nSubPixels*nPixelsX]*(avg/flat[ipx+ipy*nSubPixels]); - else - hintcorr[ibx+iby*nSubPixels*nPixelsX]=hint[ibx+iby*nSubPixels*nPixelsX]; - - - } - } - - - - return hintcorr; - }; - -/* protected: */ - -/* #ifdef MYROOT1 */ -/* TH2D *heta; */ -/* TH2D *hhx; */ -/* TH2D *hhy; */ -/* #endif */ -/* #ifndef MYROOT1 */ -/* int *heta; */ -/* float *hhx; */ -/* float *hhy; */ -/* #endif */ -/* int nbeta; */ -/* double etamin, etamax, etastep; */ - -}; - -#endif diff --git a/slsDetectorCalibration/interpolations/eta3InterpolationBase.h b/slsDetectorCalibration/interpolations/eta3InterpolationBase.h deleted file mode 100644 index 516b4a535..000000000 --- a/slsDetectorCalibration/interpolations/eta3InterpolationBase.h +++ /dev/null @@ -1,294 +0,0 @@ -#ifndef ETA3_INTERPOLATION_BASE_H -#define ETA3_INTERPOLATION_BASE_H - -#ifdef MYROOT1 -#include -#include -#include -#include -#endif - -#include "etaInterpolationBase.h" - -class eta3InterpolationBase : public virtual etaInterpolationBase { - - public: - eta3InterpolationBase(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationBase(nx, ny, ns, nb, emin, emax) { - // cout << "e3ib " << nb << " " << emin << " " << emax << endl; - /* if (nbeta<=0) { */ - /* nbeta=nSubPixels*10; */ - /* } */ - if (etamin>=etamax) { - etamin=-1; - etamax=1; - } - - etastep=(etamax-etamin)/nbeta; -#ifdef MYROOT1 - delete heta; - delete hhx; - delete hhy; - heta=new TH2D("heta","heta",nbeta,etamin,etamax,nbeta,etamin,etamax); - hhx=new TH2D("hhx","hhx",nbeta,etamin,etamax,nbeta,etamin,etamax); - hhy=new TH2D("hhy","hhy",nbeta,etamin,etamax,nbeta,etamin,etamax); -#endif -#ifndef MYROOT1 - /* delete [] heta; */ - /* delete [] hhx; */ - /* delete [] hhy; */ - - /* heta=new int[nbeta*nbeta]; */ - /* hhx=new float[nbeta*nbeta]; */ - /* hhy=new float[nbeta*nbeta]; */ - -#endif - // cout << nbeta << " " << etamin << " " << etamax << endl; -}; - - eta3InterpolationBase(eta3InterpolationBase *orig): etaInterpolationBase(orig){ }; - - /* virtual eta3InterpolationBase* Clone()=0; */ - - - - - // virtual void prepareInterpolation(int &ok){}; - - - ////////////////////////////////////////////////////////////////////////////// - //////////// /*It return position hit for the event in input */ ////////////// - virtual void getInterpolatedPosition(int x, int y, int *data, double &int_x, double &int_y) - { - double tot, totquad; - double etax,etay; - - int corner=calcEta3(data,etax,etay, totquad); - - getInterpolatedPosition(x,y,etax,etay,corner,int_x,int_y); - - return; - }; - - - virtual void getInterpolatedPosition(int x, int y, double *data, double &int_x, double &int_y) - { - double sDum[2][2]; - double tot, totquad; - double etax,etay; - - int corner=calcEta3(data,etax,etay, totquad); - - getInterpolatedPosition(x,y,etax,etay,corner,int_x,int_y); - - return; - }; - - - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,double *cl,double &int_x, double &int_y) { - - - double etax, etay; - if (nSubPixels>2) { - calcEta3(cl,etax,etay, totquad); - } - return getInterpolatedPosition(x,y,etax, etay,quad,int_x,int_y); - - } - - - - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,int *cl,double &int_x, double &int_y) { - - - double etax, etay; - if (nSubPixels>2) { - calcEta3(cl,etax,etay, totquad); - } - return getInterpolatedPosition(x,y,etax, etay,quad,int_x,int_y); - - } - - - - virtual void getInterpolatedPosition(int x, int y, double etax, double etay, int corner, double &int_x, double &int_y) - { - - - double xpos_eta=0,ypos_eta=0; - int ex,ey; - - if (nSubPixels>2) { - -#ifdef MYROOT1 - xpos_eta=(hhx->GetBinContent(hhx->GetXaxis()->FindBin(etax),hhy->GetYaxis()->FindBin(etay)))/((double)nSubPixels); - ypos_eta=(hhy->GetBinContent(hhx->GetXaxis()->FindBin(etax),hhy->GetYaxis()->FindBin(etay)))/((double)nSubPixels); -#endif -#ifndef MYROOT1 - ex=(etax-etamin)/etastep; - ey=(etay-etamin)/etastep; - if (ex<0) { - /* cout << etax << " " << etamin << " "; */ - /* cout << "3x*"<< ex << endl; */ - ex=0; - } - if (ex>=nbeta) { - /* cout << etax << " " << etamin << " "; */ - /* cout << "3x?"<< ex << endl; */ - ex=nbeta-1; - } - if (ey<0) { - /* cout << etay << " " << etamin << " "; */ - /* cout << "3y*"<< ey << endl; */ - ey=0; - } - if (ey>=nbeta) { - /* cout << etay << " " << etamin << " "; */ - /* cout << "3y?"<< ey << endl; */ - ey=nbeta-1; - - } - xpos_eta=(((double)hhx[(ey*nbeta+ex)]));///((double)nSubPixels); - ypos_eta=(((double)hhy[(ey*nbeta+ex)]));///((double)nSubPixels); - -#endif - - } else { - switch (corner) { - case BOTTOM_LEFT: - xpos_eta=-0.25; - ypos_eta=-0.25; - break; - case BOTTOM_RIGHT: - xpos_eta=0.25; - ypos_eta=-0.25; - break; - case TOP_LEFT: - xpos_eta=-0.25; - ypos_eta=0.25; - break; - case TOP_RIGHT: - xpos_eta=0.25; - ypos_eta=0.25; - break; - default: - xpos_eta=0; - ypos_eta=0; - } - - } - int_x=((double)x) + xpos_eta; - int_y=((double)y) + ypos_eta; - // int_x=5. + xpos_eta; - // int_y=5. + ypos_eta; - - - } - - - - - - -/* ///////////////////////////////////////////////////////////////////////////////////////////////// */ -/* virtual void getPositionETA3(int x, int y, double *data, double &int_x, double &int_y) */ -/* { */ -/* double sDum[2][2]; */ -/* double tot, totquad; */ -/* double eta3x,eta3y; */ -/* double ex,ey; */ - -/* calcQuad(data, tot, totquad, sDum); */ -/* calcEta3(data,eta3x, eta3y,tot); */ - -/* double xpos_eta,ypos_eta; */ - -/* #ifdef MYROOT1 */ -/* xpos_eta=((hhx->GetBinContent(hhx->GetXaxis()->FindBin(eta3x),hhy->GetYaxis()->FindBin(eta3y))))/((double)nSubPixels); */ -/* ypos_eta=((hhy->GetBinContent(hhx->GetXaxis()->FindBin(eta3x),hhy->GetYaxis()->FindBin(eta3y))))/((double)nSubPixels); */ - -/* #endif */ -/* #ifndef MYROOT1 */ -/* ex=(eta3x-etamin)/etastep; */ -/* ey=(eta3y-etamin)/etastep; */ - -/* if (ex<0) ex=0; */ -/* if (ex>=nbeta) ex=nbeta-1; */ -/* if (ey<0) ey=0; */ -/* if (ey>=nbeta) ey=nbeta-1; */ - -/* xpos_eta=(((double)hhx[(int)(ey*nbeta+ex)]))/((double)nSubPixels); */ -/* ypos_eta=(((double)hhy[(int)(ey*nbeta+ex)]))/((double)nSubPixels); */ -/* #endif */ - -/* int_x=((double)x) + xpos_eta; */ -/* int_y=((double)y) + ypos_eta; */ - -/* return; */ -/* }; */ - - virtual int addToFlatField(double totquad,int quad,int *cl,double &etax, double &etay) { - - calcEta3(cl, etax, etay, totquad); - return addToFlatField(etax,etay); - } - - virtual int addToFlatField(double totquad,int quad,double *cl,double &etax, double &etay) { - - - calcEta3(cl, etax, etay, totquad); - return addToFlatField(etax,etay); - } - - - - ////////////////////////////////////////////////////////////////////////////////////// - virtual int addToFlatField(double *cluster, double &etax, double &etay){ - double totquad; - calcEta3(cluster, etax, etay, totquad); - return addToFlatField(etax,etay); - - }; - - virtual int addToFlatField(int *cluster, double &etax, double &etay){ - - double totquad; - - calcEta3(cluster, etax, etay, totquad); - return addToFlatField(etax,etay); - - }; - - - virtual int addToFlatField(double etax, double etay){ -#ifdef MYROOT1 - heta->Fill(etax,etay); -#endif -#ifndef MYROOT1 - int ex,ey; - ex=(etax-etamin)/etastep; - ey=(etay-etamin)/etastep; - if (ey=0 && ey>=0) - heta[ey*nbeta+ex]++; -#endif - return 0; - }; - - -/* protected: */ - -/* #ifdef MYROOT1 */ -/* TH2D *heta; */ -/* TH2D *hhx; */ -/* TH2D *hhy; */ -/* #endif */ -/* #ifndef MYROOT1 */ -/* int *heta; */ -/* float *hhx; */ -/* float *hhy; */ -/* #endif */ -/* int nbeta; */ -/* double etamin, etamax, etastep; */ - -}; - -#endif diff --git a/slsDetectorCalibration/interpolations/etaInterpolationAdaptiveBins.h b/slsDetectorCalibration/interpolations/etaInterpolationAdaptiveBins.h deleted file mode 100644 index feef0d3a9..000000000 --- a/slsDetectorCalibration/interpolations/etaInterpolationAdaptiveBins.h +++ /dev/null @@ -1,285 +0,0 @@ -#ifndef ETA_INTERPOLATION_ADAPTIVEBINS_H -#define ETA_INTERPOLATION_ADAPTIVEBINS_H - -#include -#include "tiffIO.h" -//#include "etaInterpolationBase.h" -#include "etaInterpolationPosXY.h" - - - -class etaInterpolationAdaptiveBins : public etaInterpolationPosXY { - - // protected: - - - private: - - virtual void iterate(float *newhhx, float *newhhy) { - - double bsize=1./nSubPixels; - - double hy[nSubPixels][nbeta]; //profile y - double hx[nSubPixels][nbeta]; //profile x - double hix[nSubPixels][nbeta]; //integral of projection x - double hiy[nSubPixels][nbeta]; //integral of projection y - int ipy, ipx; - double tot_eta_x[nSubPixels]; - double tot_eta_y[nSubPixels]; - //for (int ipy=0; ipy=nSubPixels) ipy=nSubPixels-1; - hx[ipy][ibx]+=heta[ibx+iby*nbeta]; - - - ipx=hhx[ibx+iby*nbeta]*nSubPixels; - if (ipx<0) ipx=0; - if (ipx>=nSubPixels) ipx=nSubPixels-1; - hy[ipx][iby]+=heta[ibx+iby*nbeta]; - } - } - - - - for (ipy=0; ipy=((ipy)*bsize) && hhy[ibx+iby*nbeta]<=((ipy+1)*bsize)) { - ipy=hhy[ibx+iby*nbeta]*nSubPixels; - - if (ipy<0) ipy=0; - if (ipy>=nSubPixels) ipy=nSubPixels-1; - - if (ipy>=0 && ipy0) - newhhx[ibx+iby*nbeta]=hix[ipy][ibx]/(tot_eta_x[ipy]); - else - cout << "Bad tot_etax " << ipy << " " << tot_eta_x[ipy] << endl; - else - cout << "** Bad value ipy " << ibx << " " << iby << " "<< ipy << " " << hhy[ibx+iby*nbeta]*nSubPixels << endl; - // if (newhhx[ibx+iby*nbeta]>=1 || newhhx[ibx+iby*nbeta]<0 ) cout << "***"<< ibx << " " << iby << newhhx[ibx+iby*nbeta] << endl; - // if (ipy==3 && ibx==10) cout << newhhx[ibx+iby*nbeta] << " " << hix[ibx] << " " << ibx+iby*nbeta << endl; - // } - ipy=hhx[ibx+iby*nbeta]*nSubPixels; - //if (hhx[ibx+iby*nbeta]>=((ipy)*bsize) && hhx[ibx+iby*nbeta]<=((ipy+1)*bsize)) { - if (ipy<0) ipy=0; - if (ipy>=nSubPixels) ipy=nSubPixels-1; - - if (ipy>=0 && ipy0) - newhhy[ibx+iby*nbeta]=hiy[ipy][iby]/(tot_eta_y[ipy]); - else - cout << "Bad tot_etay " << ipy << " " << tot_eta_y[ipy] << endl; - else - cout << "** Bad value ipx " << ibx << " " << iby << " "<< ipy << " " << hhx[ibx+iby*nbeta]*nSubPixels << endl; - // if (newhhy[ibx+iby*nbeta]>=1 || newhhy[ibx+iby*nbeta]<0 ) cout << "***"<< ibx << " " << iby << newhhy[ibx+iby*nbeta] << endl; - // if (ipy==3 && iby==10) cout << newhhy[ibx+iby*nbeta] << " " << hiy[iby] << " " << ibx+iby*nbeta << endl; - // } - } - } - // } - - - } - - - public: - etaInterpolationAdaptiveBins(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationPosXY(nx,ny,ns, nb, emin,emax){ - // flat=new double[nSubPixels*nSubPixels]; flat_x=new double[nSubPixels]; flat_y=new double[nSubPixels]; - // flat=new double[nSubPixels*nSubPixels]; -}; - - etaInterpolationAdaptiveBins(etaInterpolationAdaptiveBins *orig): etaInterpolationPosXY(orig){hintcorr=new int[nPixelsX*nPixelsY*nSubPixels];}; - - virtual etaInterpolationAdaptiveBins* Clone()=0; - - /* return new etaInterpolationAdaptiveBins(this); */ - - /* }; */ - - - - virtual void prepareInterpolation(int &ok) { - prepareInterpolation(ok, 1000); - } - - virtual void prepareInterpolation(int &ok, int nint) - { - ok=1; - - ///*Eta Distribution Rebinning*/// - double bsize=1./nSubPixels; //precision - // cout<<"nPixelsX = "< rms) { - -/* #ifdef SAVE_ALL */ -/* if (iint%10==0) */ -/* debugSaveAll(iint); */ -/* #endif */ - // cout << "Iteration " << iint << endl; - iterate(newhhx,newhhy); - new_diff=calcDiff(avg, newhhx, newhhy); - // cout << " chi2= " << new_diff << " (rms= " << sqrt(tot_eta) << ")"< -#include -#include -#include -#endif - -#include "slsInterpolation.h" -#include "tiffIO.h" - -class etaInterpolationBase : public slsInterpolation { - - public: - - etaInterpolationBase(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : slsInterpolation(nx,ny,ns), hhx(NULL), hhy(NULL), heta(NULL), nbeta(nb), etamin(emin), etamax(emax) { - // cout << "eb " << nb << " " << emin << " " << emax << endl; - // cout << nb << " " << etamin << " " << etamax << endl; - if (nbeta<=0) { - //cout << "aaa:" <=etamax) { - etamin=-1; - etamax=2; - } - etastep=(etamax-etamin)/nbeta; - heta=new int[nbeta*nbeta]; - hhx=new float[nbeta*nbeta]; - hhy=new float[nbeta*nbeta]; - rangeMin=etamin; - rangeMax=etamax; - flat= new double[nSubPixels*nSubPixels]; - hintcorr=new int [nSubPixels*nSubPixels*nPixelsX*nPixelsY]; - - }; - - etaInterpolationBase(etaInterpolationBase *orig): slsInterpolation(orig){ - nbeta=orig->nbeta; - etamin=orig->etamin; - etamax=orig->etamax; - rangeMin=orig->rangeMin; - rangeMax=orig->rangeMax; - - - etastep=(etamax-etamin)/nbeta; - heta=new int[nbeta*nbeta]; - memcpy(heta,orig->heta,nbeta*nbeta*sizeof(int)); - hhx=new float[nbeta*nbeta]; - memcpy(hhx,orig->hhx,nbeta*nbeta*sizeof(float)); - hhy=new float[nbeta*nbeta]; - memcpy(hhy,orig->hhy,nbeta*nbeta*sizeof(float)); - hintcorr=new int [nSubPixels*nSubPixels*nPixelsX*nPixelsY]; - - }; - - - - - - virtual void resetFlatField() { - for (int ibx=0; ibx=etamax) { - etamin=-1; - etamax=2; - } - rangeMin=etamin; - rangeMax=etamax; - etastep=(etamax-etamin)/nbeta; - } - return heta; - }; - - int *setFlatField(int *h, int nb=-1, double emin=1, double emax=0) - { - return setEta(h, nb, emin, emax); - }; - - - - int *getFlatField(){return setEta(NULL);}; - - int *getFlatField(int &nb, double &emin, double &emax){ - nb=nbeta; - emin=etamin; - emax=etamax; - return getFlatField(); - }; - - - void *writeFlatField(const char * imgname) { - float *gm=NULL; - gm=new float[nbeta*nbeta]; - for (int ix=0; ix=1) etamax=emax; - if (emin<=0) etamin=emin; - - if (etamin>=etamax) { - etamin=-1; - etamax=2; - } - - etastep=(etamax-etamin)/nbeta; - uint32 nnx; - uint32 nny; - float *gm=ReadFromTiff(imgname, nnx, nny); - if (nnx!=nny) { - cout << "different number of bins in x " << nnx << " and y " << nny<< " !"<< endl; - cout << "Aborting read"<< endl; - return 0; - } - nbeta=nnx; - if (gm) { - if (heta) { - delete [] heta; - delete [] hhx; - delete [] hhy; - } - - heta=new int[nbeta*nbeta]; - hhx=new float[nbeta*nbeta]; - hhy=new float[nbeta*nbeta]; - - for (int ix=0; ixScale((double)nSubPixels); - return hhx; - }; - - float *gethhy() - { - // hhy->Scale((double)nSubPixels); - return hhy; - }; - virtual int addToFlatField(double etax, double etay){ - int ex,ey; - ex=(etax-etamin)/etastep; - ey=(etay-etamin)/etastep; - if (ey=0 && ey>=0) - heta[ey*nbeta+ex]++; - return 0; - }; - - - // virtual void prepareInterpolation(int &ok)=0; - - - void debugSaveAll(int ind=0) { - int ib, ibx, iby; - char tit[10000]; - - float tot_eta=0; - - float *etah=new float[nbeta*nbeta]; - int etabins=nbeta; - int ibb=0; - - for (int ii=0; ii=nSubPixels) ibx=nSubPixels-1; - if (iby>=nSubPixels) iby=nSubPixels-1; - - - if (ibx>=0 && ibx=0 && iby0 && iby>0) cout << ibx << " " << iby << " " << ii << endl; - ftest[ibx+iby*nSubPixels]+=heta[ii]; - } else - cout << "Bad interpolation "<< ii << " " << ibx << " " << iby<< endl; - - } - - sprintf(tit,"/scratch/ftest_%d.tiff",ind); - WriteToTiff(ftest, tit, nSubPixels, nSubPixels); - - //int ibx=0, iby=0; - tot_eta/=nSubPixels*nSubPixels; - int nbad=0; - for (int ii=0; iitot_eta*2.){ - etah[ii]=2; - nbad++; - } else - etah[ii]=0; - } - sprintf(tit,"/scratch/eta_bad_%d.tiff",ind); - WriteToTiff(etah, tit, etabins, etabins); - // cout << "Index: " << ind << "\t Bad bins: "<< nbad << endl; - //int ibx=0, iby=0; - - delete [] ftest; - delete [] etah; - - } - - - protected: - - - double calcDiff(double avg, float *hx, float *hy) { - //double p_tot=0; - double diff=0, d; - double bsize=1./nSubPixels; - int nbad=0; - double p_tot_x[nSubPixels], p_tot_y[nSubPixels], p_tot[nSubPixels*nSubPixels]; - double maxdiff=0, mindiff=avg*nSubPixels*nSubPixels; - - int ipx, ipy; - for (ipy=0; ipy=nSubPixels) ipx=nSubPixels-1; - - ipy=hy[ibx+iby*nbeta]*nSubPixels; - if (ipy<0) ipy=0; - if (ipy>=nSubPixels) ipy=nSubPixels-1; - - p_tot[ipx+ipy*nSubPixels]+=heta[ibx+iby*nbeta]; - p_tot_y[ipy]+=heta[ibx+iby*nbeta]; - p_tot_x[ipx]+=heta[ibx+iby*nbeta]; - - - } - } - - - // cout << endl << endl; - for (ipy=0; ipy5*sqrt(avg) ) - nbad++; - diff+=d*d; - if (dmaxdiff) maxdiff=d; - // cout << setprecision(4) << p_tot[ipx+nSubPixels*ipy] << " "; - } - - /* cout << "** " << setprecision(4) << flat_y[ipy]; */ - //cout << "\n"; - } - /* cout << "**" << endl; cout.width(5); */ - /* for (ipx=0; ipx -#include "tiffIO.h" -//#include "etaInterpolationBase.h" -#include "etaInterpolationAdaptiveBins.h" - - -//#define HSIZE 1 - - -class etaInterpolationCleverAdaptiveBins : public etaInterpolationAdaptiveBins { - - private: - - - // double *gradientX, *gradientY, *gradientXY; - - - virtual void iterate(float *newhhx, float *newhhy) { - - double bsize=1./nSubPixels; - - /* double hy[nSubPixels*HSIZE][nbeta]; //profile y */ - /* double hx[nSubPixels*HSIZE][nbeta]; //profile x */ - // double hix[nSubPixels*HSIZE][nbeta]; //integral of projection x - // double hiy[nSubPixels*HSIZE][nbeta]; //integral of projection y - int ipy, ipx, ippx, ippy; - // double tot_eta_x[nSubPixels*HSIZE]; - //double tot_eta_y[nSubPixels*HSIZE]; - - double mean=0; - double maxflat=0, minflat=0, maxgradX=0, mingradX=0, maxgradY=0, mingradY=0, maxgr=0, mingr=0; - - int ix_maxflat, iy_maxflat, ix_minflat, iy_minflat, ix_maxgrX, iy_maxgrX, ix_mingrX, iy_mingrX,ix_maxgrY, iy_maxgrY, ix_mingrY, iy_mingrY, ix_mingr, iy_mingr, ix_maxgr, iy_maxgr; - int maskMin[nSubPixels*nSubPixels], maskMax[nSubPixels*nSubPixels]; - - - //for (int ipy=0; ipymean+3.*sqrt(mean)) maskMax[ipx+nSubPixels*ipy]=1; else maskMax[ipx+nSubPixels*ipy]=0; - if (ipx>0 && ipy>0) { - if (flat[ipx+nSubPixels*ipy]flat[ipx-1+nSubPixels*(ipy-1)]) maskMin[ipx+nSubPixels*ipy]=0; - } - if (ipx>0 && ipyflat[ipx-1+nSubPixels*(ipy+1)]) maskMin[ipx+nSubPixels*ipy]=0; - } - if (ipy>0 && ipxflat[ipx+1+nSubPixels*(ipy-1)]) maskMin[ipx+nSubPixels*ipy]=0; - } - if (ipyflat[ipx+1+nSubPixels*(ipy+1)]) maskMin[ipx+nSubPixels*ipy]=0; - } - if (ipyflat[ipx+nSubPixels*(ipy+1)]) maskMin[ipx+nSubPixels*ipy]=0; - } - if (ipxflat[ipx+1+nSubPixels*(ipy)]) maskMin[ipx+nSubPixels*ipy]=0; - } - - if (ipy>0 ) { - if (flat[ipx+nSubPixels*ipy]flat[ipx+nSubPixels*(ipy-1)]) maskMin[ipx+nSubPixels*ipy]=0; - } - - if (ipx>0 ) { - if (flat[ipx+nSubPixels*ipy]flat[ipx-1+nSubPixels*(ipy)]) maskMin[ipx+nSubPixels*ipy]=0; - } - - // if (maskMin[ipx+nSubPixels*ipy]) cout << ipx << " " << ipy << " is a local minimum " << flat[ipx+nSubPixels*ipy] << endl; - // if (maskMax[ipx+nSubPixels*ipy]) cout << ipx << " " << ipy << " is a local maximum "<< flat[ipx+nSubPixels*ipy] << endl; - - } - } - int is_a_border=0; - - //initialize the new partition to the previous one - // int ibx_p, iby_p, ibx_n, iby_n; - int ibbx, ibby; - - - memcpy(newhhx,hhx,nbeta*nbeta*sizeof(float)); - memcpy(newhhy,hhy,nbeta*nbeta*sizeof(float)); - - for (int ibx=0; ibxnbeta-1) ibbx=nbeta-1; - for (int iy=-1; iy<2; iy++) { - ibby=iby+iy; - if (ibby<0) ibby=0; - if (ibby>nbeta-1) ibby=nbeta-1; - - - ipy=hhy[ibbx+ibby*nbeta]*nSubPixels; - ipx=hhx[ibbx+ibby*nbeta]*nSubPixels; - - - if (ipx!=ippx || ipy!=ippy) { - is_a_border=1; - if (maskMin[ippx+nSubPixels*ippy]) { - //increase the region - newhhx[ibbx+ibby*nbeta]=((double)ippx+0.5)/((double)nSubPixels); - newhhy[ibbx+ibby*nbeta]=((double)ippy+0.5)/((double)nSubPixels); - } - if (maskMax[ippx+nSubPixels*ippy]) { - //reduce the region - newhhx[ibx+iby*nbeta]=((double)ipx+0.5)/((double)nSubPixels); - newhhy[ibx+iby*nbeta]=((double)ipy+0.5)/((double)nSubPixels); - } - - // cout << ippx << " " << ippy << " " << ibx << " " << iby << " * " << ipx << " " << ipy << " " << ibbx << " " << ibby << endl; - } - - - } - } - } - - - - } - - } - - - //Check that the resulting histograms are monotonic and they don't have holes! - - for (int ibx=0; ibxipx) - newhhx[ibx+1+iby*nbeta]=newhhx[ibx+iby*nbeta]; - else if (ipx >ippx+1) - newhhx[ibx+1+iby*nbeta]=((double)(ippx+1+0.5))/((double)nSubPixels); - - if ( ippy>ipy) - newhhy[ibx+(iby+1)*nbeta]=newhhy[ibx+iby*nbeta]; - else if (ipy >ippy+1) - newhhy[ibx+(iby+1)*nbeta]=((double)(ippy+1+0.5))/((double)nSubPixels); - - } - } - - - } - - - public: - etaInterpolationCleverAdaptiveBins(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationAdaptiveBins(nx,ny,ns, nb, emin,emax){ - - - }; - - etaInterpolationCleverAdaptiveBins(etaInterpolationCleverAdaptiveBins *orig): etaInterpolationAdaptiveBins(orig){}; - - virtual etaInterpolationCleverAdaptiveBins* Clone()=0; - - /* return new etaInterpolationCleverAdaptiveBins(this); */ - - /* }; */ - - -}; - -class eta2InterpolationCleverAdaptiveBins : public virtual eta2InterpolationBase, public virtual etaInterpolationCleverAdaptiveBins { - public: - eta2InterpolationCleverAdaptiveBins(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationBase(nx,ny,ns, nb, emin,emax),eta2InterpolationBase(nx,ny,ns, nb, emin,emax),etaInterpolationCleverAdaptiveBins(nx,ny,ns, nb, emin,emax){ - }; - - eta2InterpolationCleverAdaptiveBins(eta2InterpolationCleverAdaptiveBins *orig): etaInterpolationBase(orig), etaInterpolationCleverAdaptiveBins(orig) {}; - - virtual eta2InterpolationCleverAdaptiveBins* Clone() { return new eta2InterpolationCleverAdaptiveBins(this);}; - - // virtual int *getInterpolatedImage(){return eta2InterpolationBase::getInterpolatedImage();}; - - /* virtual int *getInterpolatedImage(){ */ - /* int ipx, ipy; */ - /* cout << "ff" << endl; */ - /* calcDiff(1, hhx, hhy); //get flat */ - /* double avg=0; */ - /* for (ipx=0; ipx0) */ - /* hintcorr[ibx+iby*nSubPixels*nPixelsX]=hint[ibx+iby*nSubPixels*nPixelsX]*(avg/flat[ipx+ipy*nSubPixels]); */ - /* else */ - /* hintcorr[ibx+iby*nSubPixels*nPixelsX]=hint[ibx+iby*nSubPixels*nPixelsX]; */ - - - /* } */ - /* } */ - - - - /* return hintcorr; */ - /* }; */ - - -}; - - - -class eta3InterpolationCleverAdaptiveBins : public virtual eta3InterpolationBase, public virtual etaInterpolationCleverAdaptiveBins { - public: - eta3InterpolationCleverAdaptiveBins(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationBase(nx,ny,ns, nb, emin,emax),eta3InterpolationBase(nx,ny,ns, nb, emin,emax), etaInterpolationCleverAdaptiveBins(nx,ny,ns, nb, emin,emax){ - - }; - - eta3InterpolationCleverAdaptiveBins(eta3InterpolationCleverAdaptiveBins *orig): etaInterpolationBase(orig), etaInterpolationCleverAdaptiveBins(orig) {}; - - virtual eta3InterpolationCleverAdaptiveBins* Clone() { return new eta3InterpolationCleverAdaptiveBins(this);}; -}; - -#endif diff --git a/slsDetectorCalibration/interpolations/etaInterpolationGlobal.h b/slsDetectorCalibration/interpolations/etaInterpolationGlobal.h deleted file mode 100644 index 615b7c04b..000000000 --- a/slsDetectorCalibration/interpolations/etaInterpolationGlobal.h +++ /dev/null @@ -1,85 +0,0 @@ -#ifndef ETA_INTERPOLATION_GLOBAL_H -#define ETA_INTERPOLATION_GLOBAL_H - - -#include "etaInterpolationBase.h" - -class etaInterpolationGlobal : public etaInterpolationBase{ - public: - globalEtaInterpolation(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationBase(nx,ny,ns, nb, emin,emax){}; - - - - virtual void prepareInterpolation(int &ok) - { - ok=1; -#ifdef MYROOT1 - if (hhx) delete hhx; - if (hhy) delete hhy; - - hhx=new TH2D("hhx","hhx",heta->GetNbinsX(),heta->GetXaxis()->GetXmin(),heta->GetXaxis()->GetXmax(), heta->GetNbinsY(),heta->GetYaxis()->GetXmin(),heta->GetYaxis()->GetXmax()); - hhy=new TH2D("hhy","hhy",heta->GetNbinsX(),heta->GetXaxis()->GetXmin(),heta->GetXaxis()->GetXmax(), heta->GetNbinsY(),heta->GetYaxis()->GetXmin(),heta->GetYaxis()->GetXmax()); - -#endif - - - ///*Eta Distribution Rebinning*/// - double bsize=1./nSubPixels; //precision - // cout<<"nPixelsX = "<(ib+1)*tot_eta*bsize) ib++; - for (int iby=0; ibySetBinContent(ibx+1,iby+1,ib); -#endif -#ifndef MYROOT1 - hhx[ibx+iby*nbeta]=ib; -#endif - } - } - ib=0; - for (int iby=0; iby(ib+1)*tot_eta*bsize) ib++; - for (int ibx=0; ibxSetBinContent(ibx+1,iby+1,ib); -#endif -#ifndef MYROOT1 - hhy[ibx+iby*nbeta]=ib; -#endif - } - } - - return ; - }; - -}; - -#endif diff --git a/slsDetectorCalibration/interpolations/etaInterpolationPosXY.h b/slsDetectorCalibration/interpolations/etaInterpolationPosXY.h deleted file mode 100644 index 1f775782d..000000000 --- a/slsDetectorCalibration/interpolations/etaInterpolationPosXY.h +++ /dev/null @@ -1,184 +0,0 @@ -#ifndef ETA_INTERPOLATION_POSXY_H -#define ETA_INTERPOLATION_POSXY_H - - -//#include "tiffIO.h" -#include "etaInterpolationBase.h" -#include "eta2InterpolationBase.h" -#include "eta3InterpolationBase.h" - -class etaInterpolationPosXY : public virtual etaInterpolationBase{ - public: - etaInterpolationPosXY(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationBase(nx,ny,ns, nb, emin,emax){ - // cout << "epxy " << nb << " " << emin << " " << emax << endl; cout << nbeta << " " << etamin << " " << etamax << endl; - }; - - etaInterpolationPosXY(etaInterpolationPosXY *orig): etaInterpolationBase(orig) {}; - - virtual etaInterpolationPosXY* Clone()=0; /* { */ - - /* return new etaInterpolationPosXY(this); */ - - /* }; */ - - virtual void prepareInterpolation(int &ok) - { - ok=1; -#ifdef MYROOT1 - if (hhx) delete hhx; - if (hhy) delete hhy; - - hhx=new TH2D("hhx","hhx",heta->GetNbinsX(),heta->GetXaxis()->GetXmin(),heta->GetXaxis()->GetXmax(), heta->GetNbinsY(),heta->GetYaxis()->GetXmin(),heta->GetYaxis()->GetXmax()); - hhy=new TH2D("hhy","hhy",heta->GetNbinsX(),heta->GetXaxis()->GetXmin(),heta->GetXaxis()->GetXmax(), heta->GetNbinsY(),heta->GetYaxis()->GetXmin(),heta->GetYaxis()->GetXmax()); - -#endif - - - ///*Eta Distribution Rebinning*/// - double bsize=1./nSubPixels; //precision - // cout<<"nPixelsX = "<=0 && etax<=1) - hx[iby]=heta[iby+ib*nbeta]; - else { - hx[iby]=0; - } - // tot_eta_x+=hx[iby]; - if (etax>=0 && etax<=1) - hy[iby]=heta[ib+iby*nbeta]; - else - hy[iby]=0; - // tot_eta_y+=hy[iby]; - } - - hix[0]=hx[0]; - hiy[0]=hy[0]; - - for (int iby=1; iby(ii+1)*tot_eta_x*bsize) - { - //if (hix[ibx]>tot_eta_x*(ii+1)/nSubPixels) ii++; - hhx[ibx+ib*nbeta]=hix[ibx]/tot_eta_x; - } - } - /* if (ii!=(nSubPixels-1)) */ - /* cout << ib << " x " << tot_eta_x << " " << (ii+1)*tot_eta_x*bsize << " " << ii << " " << hix[nbeta-1]<< endl; */ - - ii=0; - - for (int ibx=0; ibxtot_eta_y*(ii+1)/nSubPixels) ii++; - hhy[ib+ibx*nbeta]=hiy[ibx]/tot_eta_y; - } - } - } - - - int ibx, iby, ib; - - iby=0; - while (hhx[iby*nbeta+nbeta/2]<0) iby++; - for (ib=0; ib -#include -//#include -#include // std::abs - -#define PI 3.14159265 -#define TWOPI 2.*PI - -using namespace std; - -class etaInterpolationRandomBins : public etaInterpolationPosXY { - - private: - double calcDiff(double avg, float *hx, float *hy) { - double p_tot=0; - double diff=0; - double bsize=1./nSubPixels; - - for (int ipx=0; ipx=((ipx)*bsize) && hx[ibx+iby*nbeta]<((ipx+1)*bsize) && hy[ibx+iby*nbeta]>=((ipy)*bsize) && hy[ibx+iby*nbeta]<((ipy+1)*bsize)) { - p_tot+=heta[ibx+iby*nbeta]; - } - } - } - - // cout << p_tot << " \t "; - - - - diff+=(p_tot-avg)*(p_tot-avg); - - } - // cout << "\n"; - } - return diff; - } - - double iterate(float *newhhx, float *newhhy, double avg) { - - double bsize=1./nSubPixels; - - double hy[nbeta]; //profile y - double hx[nbeta]; //profile x - double hix[nbeta]; //integral of projection x - double hiy[nbeta]; //integral of projection y - - double tot_eta_x=0; - double tot_eta_y=0; - - int p0; - int vx[(nSubPixels+1)*(nSubPixels+1)], vy[(nSubPixels+1)*(nSubPixels+1)]; - - int arrx[nSubPixels+1], arry[nSubPixels+1]; - - int bad=1; - - - int isby, isbx; - int ii=0; - - - // using default comparison (operator <): - // std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33 - - for (isby=0; isby<(nSubPixels+1)/2+1; isby++) { - - for (isbx=0; isbx<(nSubPixels+1)/2+1; isbx++) { - p0=isby*(nSubPixels+1)+isbx; - // for (int iv=0; iv<(nSubPixels+1)*(nSubPixels+1); iv++) { - if (isbx==0) { - vy[p0]=isby*nbeta/nSubPixels; - vx[p0]=0; - } else if ( isby==0 ) { - vy[p0]=0; - vx[p0]=isbx*nbeta/nSubPixels; - } - else { - vy[p0]=rand()%(nbeta/2); - vx[p0]=rand()%(nbeta/2); - if (nSubPixels%2==0 && isbx==nSubPixels/2) - vx[p0]=nbeta/2; - if (nSubPixels%2==0 && isby==nSubPixels/2 ) - vy[p0]=nbeta/2; - } - // cout << "(" << vx[p0] << " , " << vy[p0] << " ) \t" ; - // } - } - //cout << endl; - } - // cout << "rand" << endl; - - - while (bad) { - - for (isby=0; isby<(nSubPixels+1)/2+1; isby++) { - - - for (isbx=0; isbx<(nSubPixels+1)/2+1; isbx++) { - arrx[isbx]=vx[isby*(nSubPixels+1)+isbx]; - arry[isbx]=vy[isbx*(nSubPixels+1)+isby]; - //cout << isbx << " " << arrx[isbx] << " " << isby << " " << arry[isbx] << endl; - } - - sort(arrx,arrx+(nSubPixels+1)/2+1); - sort(arry,arry+(nSubPixels+1)/2+1); - - // cout << "*****"<< endl; - // cout << endl; - - for (int isbx=0; isbx<(nSubPixels+1)/2+1; isbx++) { - vx[isby*(nSubPixels+1)+isbx]=arrx[isbx]; - vy[isbx*(nSubPixels+1)+isby]=arry[isbx]; - - - vx[(nSubPixels-isby)*(nSubPixels+1)+(nSubPixels-isbx)]=nbeta-arrx[isbx]; - vy[(nSubPixels-isbx)*(nSubPixels+1)+(nSubPixels-isby)]=nbeta-arry[isbx]; - - vx[isby*(nSubPixels+1)+(nSubPixels-isbx)]=nbeta-arrx[isbx]; - vy[isbx*(nSubPixels+1)+(nSubPixels-isby)]=arry[isbx]; - - - vx[(nSubPixels-isby)*(nSubPixels+1)+(isbx)]=arrx[isbx]; - vy[(nSubPixels-isbx)*(nSubPixels+1)+(isby)]=nbeta-arry[isbx]; - - - } - - - - } - - /* for (isby=0; isbynSubPixels-1) isbx=nSubPixels-1; */ - - /* if (iby==0) */ - /* isby=0; */ - /* else */ - /* isby= (newhhx[ibx+(iby-1)*nbeta])/bsize-1; */ - - /* if (isby<0) isbx=0; */ - /* if (isby>nSubPixels-1) isby=nSubPixels-1; */ - /* // cout << isbx << " " << isby << endl; */ - - for (isby=0; isby PI) - dtheta -= TWOPI; - while (dtheta < -PI) - dtheta += TWOPI; - - angle += dtheta; - } - - if (abs((double)angle) < PI) - in_quad=0; - else - in_quad=1; - - if (in_quad) { - newhhx[ibx+iby*nbeta]=bsize*((double)isbx); - newhhy[ibx+iby*nbeta]=bsize*((double)isby); - break; - } - - - - - } - if (in_quad) break; - } - - } - } - - // cout << "hist" << endl; - return calcDiff(avg, newhhx, newhhy); - } - - - public: - etaInterpolationRandomBins(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationPosXY(nx,ny,ns, nb, emin,emax){}; - - etaInterpolationRandomBins(etaInterpolationRandomBins *orig): etaInterpolationPosXY(orig){}; - - virtual etaInterpolationRandomBins* Clone() { - - return new etaInterpolationRandomBins(this); - - }; - - - - virtual void prepareInterpolation(int &ok) - { - ok=1; - cout << "Adaptive bins" << endl; - - ///*Eta Distribution Rebinning*/// - double bsize=1./nSubPixels; //precision - // cout<<"nPixelsX = "<1 || etah[ii]<0 ) cout << "***"<< ii << etah[ii] << endl; */ -/* } */ -/* sprintf(tit,"/scratch/randeta_hhx_%d.tiff",iint); */ -/* WriteToTiff(etah, tit, etabins, etabins); */ - -/* for (int ii=0; ii1 || etah[ii]<0 ) cout << "***"<< ii << etah[ii] << endl; */ -/* } */ -/* sprintf(tit,"/scratch/randeta_hhy_%d.tiff",iint); */ -/* WriteToTiff(etah, tit, etabins, etabins); */ -/* #endif */ - - if (new_diff -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "EtaVEL.h" -#include "EtaVEL.cpp" -/* -Zum erstellen der correction map ist createGainAndEtaFile(...) in EVELAlg.C der entry point. -Zum erstellen des HR images ist createImage(...) der entry point. -*/ -int etabins = 25; -int nEtas = 25; -Double_t dum[3][3]; -Int_t x,y,f,q; - -int counter[5]; -int remoteCounter[5]; - -//TH2D *sum = new TH2D("sum","sum",3,-0.1,2.1,3,-0.1,2.1); -//TH2F *subPos = new TH2F("subPos","subPos", 100, -1.,1. ,100, -1.,1.); -TH2D *subPosAEta = new TH2D("subPosAEta","subPosAEta", 50, -.5,1.5 ,50, -.5,1.5); -TH2D *subPosBEta = new TH2D("subPosBEta","subPosBEta", 50, -.5,1.5 ,50, -.5,1.5); - - - -TH1D *cE = new TH1D("clusterEnergy","clusterEnergy",400, 0.,4000.); -//TH1D *cES = new TH1D("clusterEnergyS","clusterEnergyS",400, 0.,4000.); - - -TH2D *cES3vs2 = new TH2D("clusterEnergy3vs2","clusterEnergy3vs2",800, 0.,8000.,600,0.,6000.); -TH2D *cES3vs2S = new TH2D("clusterEnergy3vs2S","clusterEnergy3vs2S",800, 0.,8000.,600,0.,6000.); - -double th = 0.99; -double sigmas = 1.0; - -TH2D *imgRLR = new TH2D("imgRLR","imgRLR",160,0.0,160.0 ,160 ,0.0,160.0); -TH2D *imgLR = new TH2D("imgLR","imgLR",160*2,0.0,160.0 ,160*2 ,0.0,160.0); - -TH2D *clusHist= new TH2D("clusHist","clusHist",3,-0.5,2.5,3,-0.5,2.5); -TH2D *clusHistC= new TH2D("clusHistC","clusHistC",3,-0.5,2.5,3,-0.5,2.5); - -int **imgArray; - -int findShape(Double_t cluster[3][3], double sDum[2][2]){ - int corner = -1; - - double sum = cluster[0][0] + cluster[1][0] + cluster[2][0] + cluster[0][1] + cluster[1][1] + cluster[2][1] + cluster[0][2] + cluster[1][2] + cluster[2][2]; - - double sumTL = cluster[0][0] + cluster[1][0] + cluster[0][1] + cluster[1][1]; //2 ->BL - double sumTR = cluster[1][0] + cluster[2][0] + cluster[2][1] + cluster[1][1]; //0 ->TL - double sumBL = cluster[0][1] + cluster[0][2] + cluster[1][2] + cluster[1][1]; //3 ->BR - double sumBR = cluster[1][2] + cluster[2][1] + cluster[2][2] + cluster[1][1]; //1 ->TR - double sumMax = 0; - - - //double **sDum = subCluster; - Double_t ssDum[2][2]; - - // if(sumTL >= sumMax){ - sDum[0][0] = cluster[0][0]; sDum[1][0] = cluster[1][0]; - sDum[0][1] = cluster[0][1]; sDum[1][1] = cluster[1][1]; - - ssDum[0][0] = cluster[0][0]; ssDum[1][0] = cluster[0][1]; - ssDum[0][1] = cluster[1][0]; ssDum[1][1] = cluster[1][1]; - - corner = 2; - sumMax=sumTL; - // } - - if(sumTR >= sumMax){ - sDum[0][0] = cluster[1][0]; sDum[1][0] = cluster[2][0]; - sDum[0][1] = cluster[1][1]; sDum[1][1] = cluster[2][1]; - - ssDum[0][0] = cluster[2][0]; ssDum[1][0] = cluster[2][1]; - ssDum[0][1] = cluster[1][0]; ssDum[1][1] = cluster[1][1]; - - corner = 0; - sumMax=sumTR; - } - - if(sumBL >= sumMax){ - sDum[0][0] = cluster[0][1]; sDum[1][0] = cluster[1][1]; - sDum[0][1] = cluster[0][2]; sDum[1][1] = cluster[1][2]; - - ssDum[0][0] = cluster[0][2]; ssDum[1][0] = cluster[0][1]; - ssDum[0][1] = cluster[1][2]; ssDum[1][1] = cluster[1][1]; - - corner = 3; - sumMax=sumBL; - } - - if(sumBR >= sumMax){ - sDum[0][0] = cluster[1][1]; sDum[1][0] = cluster[2][1]; - sDum[0][1] = cluster[1][2]; sDum[1][1] = cluster[2][2]; - - ssDum[0][0] = cluster[2][2]; ssDum[1][0] = cluster[2][1]; - ssDum[0][1] = cluster[1][2]; ssDum[1][1] = cluster[1][1]; - - corner = 1; - sumMax=sumBR; - } - - switch(corner){ - case 0: - cES3vs2->Fill(sum,sumTR); break; - case 1: - cES3vs2->Fill(sum,sumBR); break; - case 2: - cES3vs2->Fill(sum,sumTL); break; - case 3: - cES3vs2->Fill(sum,sumBL); break; - } - - counter[corner]++; - remoteCounter[q]++; - - // cout << "local corner is: " << corner << " remote corner is: " << q << endl; - - return corner; -} - - - - -int placePhoton( TH2D *img, double subCluster[2][2], int cX, int cY, int corner, double *sX, double *sY, double *scX, double *scY){ - double tot = subCluster[0][0] + subCluster[0][1] + subCluster[1][0] + subCluster[1][1]; - double t = subCluster[1][0] + subCluster[1][1]; - double r = subCluster[0][1] + subCluster[1][1]; - - double xHitC = r/tot; - double yHitC = t/tot; - - imgRLR->Fill(cX,cY); - - cE->Fill(tot); - - double dX, dY; - - //before looking at annas code - /* if(corner == 0){ dX=-1.; dY=-1.; } - if(corner == 1){ dX=-1.; dY=+1.; } - if(corner == 2){ dX=+1.; dY=-1.; } - if(corner == 3){ dX=+1.; dY=+1.; }*/ - - if(corner == 0){ dX=-1.; dY=+1.; } //top left - if(corner == 1){ dX=+1.; dY=+1.; } //top right - if(corner == 2){ dX=-1.; dY=-1.; } //bottom left - if(corner == 3){ dX=+1.; dY=-1.; } //bottom right - - imgLR->Fill(cX+0.25*dX,cY+0.25*dY); - - double posX = ((double)cX) + 0.5*dX + xHitC; - double posY = ((double)cY) + 0.5*dY + yHitC; - - subPosBEta->Fill(xHitC ,yHitC); - if(img){ - img->Fill(posX,posY); - } - - if(xHitC < 0.02&& yHitC < 0.02){ - - cES3vs2S->Fill(dum[0][0]+dum[0][1]+dum[0][2]+dum[1][0]+dum[1][1]+dum[1][2]+dum[2][0]+dum[2][1]+dum[2][2],subCluster[0][0]+subCluster[0][1]+subCluster[1][0]+subCluster[1][1]); - } - - - if(sX && sY && scX && scY){ - *sX = xHitC; //0.5 + 0.5*dX + xHitC; - *sY = yHitC; //0.5 + 0.5*dY + yHitC; - *scX = ((double)cX) + 0.5*dX; - *scY = ((double)cY) + 0.5*dY; - } - return 1; -} - - - -void placePhotonCorr(TH2D *img, EtaVEL *e,double sX, double sY, double scX, double scY){ - int bin = e->findBin(sX,sY); - if(bin <= 0) return; - double subX = ((double)(e->getXBin(bin))+.5)/((double)e->getNPixels()); - double subY = ((double)(e->getYBin(bin))+.5)/((double)e->getNPixels()); - - if(img!=NULL){ - img->Fill(scX+ subX , scY+ subY); - } - subPosAEta->Fill(subX,subY); - - int iscx = scX; - int iscy = scY; - if(iscx >=nx || iscx<0 || iscy >=ny || iscy<0) return; - //cout << iscx*e->getNPixels()+e->getXBin(bin) << " " << iscy*e->getNPixels()+e->getXBin(bin) << endl; - if(img==NULL) return; - imgArray[iscx*e->getNPixels()+e->getXBin(bin)][iscy*e->getNPixels()+e->getYBin(bin)]++; -} - -void gainCorrection(Double_t corrected[3][3], TH2D *gainMap){ - - for(int xx = 0; xx < 3; xx++) - for(int yy = 0; yy < 3; yy++){ - if(gainMap && gainMap->GetBinContent(x+xx+2,y+yy+2) != 0){ - corrected[xx][yy] = dum[xx][yy] / gainMap->GetBinContent(x+xx+2,y+yy+2); - clusHistC->Fill(xx,yy,corrected[xx][yy]); - } - else - corrected[xx][yy] = dum[xx][yy]; - - clusHist->Fill(xx,yy,dum[xx][yy]); - } -} - - -EtaVEL *plotEtaDensity(TChain* tree2, TEntryList *el, EtaVEL *oldEta = NULL, TH2D **img = NULL, TH2D *gainMap=NULL, int nPixels=25) { - - - - EtaVEL *newEta = new EtaVEL(25,-0.02,1.02); - - Long64_t listEntries=el->GetN(); - Long64_t treeEntry; - Long64_t chainEntry; - - Int_t treenum=0; - tree2->SetEntryList(el); - - double gainCorrC[3][3]; - double subCluster[2][2]; - double sX, sY, scX, scY; - - cout << "Events: " << listEntries << endl; - if(oldEta == NULL){ cout << "Old Eta is NULL " << endl; } - for(int i = 0; i<4; i++){ counter[i] = 0; remoteCounter[i] = 0; } - - for (Long64_t il =0; ilGetEntryAndTree(il,treenum); - - chainEntry = treeEntry+tree2->GetTreeOffset()[treenum]; - if (tree2->GetEntry(chainEntry)) { - - gainCorrection(gainCorrC,gainMap); - //cout << gainCorrC[1][1] << endl; - - //finds corner - int corner = findShape(gainCorrC,subCluster); - - int validEvent; - - - if(img){ - validEvent = placePhoton(img[0],subCluster,x,y, corner, &sX, &sY, &scX, &scY); - }else{ - //calc etaX, etaY - validEvent = placePhoton(NULL,subCluster,x,y, corner, &sX, &sY, &scX, &scY); - } - - //fill etavel - newEta->fill(sX,sY); - - - - - if(oldEta && img && img[1]){ - placePhotonCorr(img[1],oldEta, sX,sY, scX, scY); - }else{ - placePhotonCorr(NULL,newEta,sX,sY,scX,scY); - } - - - } - //cout << il << endl; - int ssize = 500000; - if(il % ssize == 0 && il != 0 && oldEta==NULL){ - - cout << " -------------- "<< endl; - newEta->updatePixelPos(); - - - //newEta->resolveSelfIntersect(); - char tit[1000]; - /* TFile *ff = new TFile("/scratch/Spider.root","UPDATE"); - sprintf(tit,"subPosAEta%i",newEta->getIt()); subPosAEta->SetName(tit); - subPosAEta->Write(); subPosAEta->Reset(); - sprintf(tit,"subPosBEta%i",newEta->getIt()); subPosBEta->SetName(tit); - subPosBEta->Write(); subPosBEta->Reset(); - sprintf(tit,"Eta%i",newEta->getIt()); newEta->Write(tit); - ff->Close(); */ - //il = 0; - } - - if(il % ssize == ssize-1){ - double prog = (double)il/(double)listEntries*100.; - cout << prog << "%" << endl; - //if(prog > 19.) return newEta; - if(newEta->converged == 1){ cout << "converged ... " << endl; return newEta; } - } - - } - - cout << "local corners: " ; - for(int i = 0; i<4; i++) cout << i << ": " << counter[i] << " || " ; - cout << endl; - - //cout << "remote corners: " ; - //for(int i = 0; i<4; i++) cout << i << ": " << remoteCounter[i] << " || " ; - //cout << endl; - - return newEta; -} - - - - -TChain *openTree(char *tname, char *fname,double lEc, double hEc, double rms=5., char *chainName=">>thischan"){ - TChain *tree2; - // TH1D **etaDI; - char cut[1000]; - - tree2=new TChain(tname); - tree2->Add(fname); - tree2->Print(); - - //sprintf(cut,"(x<=40) && (data[%d][%d]>%f*rms) && Sum$(data)<%f && Sum$(data)>%f",1,1,rms, hEc, lEc); - // sprintf(cut,"(x<=40) && (data[%d][%d]>%f*rms)",1,1,rms);// && Sum$(data)<%f && Sum$(data)>%f",1,1,rms, hEc, lEc); - sprintf(cut,"(x<=40) && Sum$(data)<%f && Sum$(data)>%f", hEc, lEc); - // sprintf(cut,""); - cout << cut << endl; - - tree2->Draw(chainName, cut, "entrylist"); - - - tree2->SetBranchAddress("iFrame",&f); - tree2->SetBranchAddress("x",&x); - tree2->SetBranchAddress("y",&y); - tree2->SetBranchAddress("data",dum); - //tree2->SetBranchAddress("q",&q); - - cout << "openTree : end" << endl; - return tree2; -} - -EtaVEL *etaDensity(char *tname, char *fname, double lEc = 1000, double hEc=3000, TH2D *gainMap=NULL, int nPixels=25) { - /** open tree and make selection */ - TChain *tree2 = openTree(tname,fname,lEc,hEc); - TEntryList *elist = (TEntryList*)gDirectory->Get("thischan"); - if(elist == NULL) { cout << "could not open tree " << endl; return NULL; } - - EtaVEL *etaDen = plotEtaDensity(tree2,elist,NULL,NULL,gainMap,nPixels); - - - //etaDen->Draw("colz"); - cout << "done" << endl; - - return etaDen; -} - -void interpolate(char *tname, char *fname, EtaVEL *etaDI, double lEc = 1000, double hEc=3000, TH2D *gainMap=NULL) { - - TChain *tree2 = openTree(tname,fname,lEc,hEc,5.,">>intChain"); - TEntryList *elist = (TEntryList*)gDirectory->Get("intChain"); - if(elist == NULL) { cout << "could not open tree " << endl; return; } - - double nPixels = (double)etaDI->getNPixels(); - - TH2D **img = new TH2D*[3]; - img[0] = new TH2D("img","img",nPixels*160,0.0,160.0 ,nPixels*160 ,0.0,160.0); - img[1] = new TH2D("imgE","imgE",nPixels*160,0.0,160.0 ,nPixels*160 ,0.0,160.0); - - int inPixels = etaDI->getNPixels(); - - imgArray = new int*[inPixels*160]; - for(int i = 0; i < inPixels*160; i++){ - imgArray[i] = new int[inPixels*160]; - for(int j = 0; j < inPixels*160; j++){ - imgArray[i][j] = 0; - } - } - - cout << "starting" << endl; - plotEtaDensity(tree2,elist, etaDI,img,gainMap); - - //img->Draw("colz"); -} - - -TH2D *createGainMap(char *tname, char *fname, double lEc = 0,double hEc=10000){ - char name[100]; - TH1D *avgSpec3 = new TH1D("avgSpec3", "avgSpec3",hEc/20,0,hEc); - TH1D ***specs3 = new TH1D**[160]; - TH1D ***specs1 = new TH1D**[160]; - for(int xx = 0; xx < 160; xx++){ - specs3[xx] = new TH1D*[160]; - specs1[xx] = new TH1D*[160]; - for(int yy = 0; yy < 160; yy++){ - sprintf(name,"S3x%iy%i",xx,yy); - specs3[xx][yy] = new TH1D(name,name,hEc/20,0,hEc); - sprintf(name,"S1x%iy%i",xx,yy); - specs1[xx][yy] = new TH1D(name,name,hEc/20,0,hEc); - } - } - - - TChain *tree2 = openTree(tname,fname,0,hEc,5.,">>gainChan"); - TEntryList *elist = (TEntryList*)gDirectory->Get("gainChan"); - if(elist == NULL) { cout << "could not open tree " << endl; return NULL; } - - Long64_t listEntries=elist->GetN(); - Long64_t treeEntry; - Long64_t chainEntry; - - Int_t treenum=0; - tree2->SetEntryList(elist); - - cout << "Events: " << listEntries << endl; - for(int i = 0; i<4; i++) counter[i] = 0; - for (Long64_t il =0; ilGetEntryAndTree(il,treenum); - chainEntry = treeEntry+tree2->GetTreeOffset()[treenum]; - - if (tree2->GetEntry(chainEntry)) { - double sum = 0; - for(int xx = 0; xx < 3; xx++) - for(int yy = 0; yy < 3; yy++) - sum += dum[xx][yy]; - specs3[x][y]->Fill(sum); - specs1[x][y]->Fill(dum[1][1]); - avgSpec3->Fill(sum); - } - } - - TH2D *gainMap3 = new TH2D("gainMap3","gainMap3",160,-0.5,160.-0.5,160,-.5,160.-.5); - TH2D *gainMap1 = new TH2D("gainMap1","gainMap1",160,-0.5,160.-0.5,160,-.5,160.-.5); - for(int xx = 0; xx < 160; xx++){ - for(int yy = 0; yy < 160; yy++){ - TF1 *gf3 = new TF1("gf3","gaus", lEc, hEc); - specs3[xx][yy]->Fit(gf3,"Q"); - double e3 = gf3->GetParameter(1); - gainMap3->Fill(xx,yy,e3); - - TF1 *gf1 = new TF1("gf1","gaus", lEc, hEc); - specs1[xx][yy]->Fit(gf1,"Q"); - double e1 = gf1->GetParameter(1); - gainMap1->Fill(xx,yy,e1); - - } - } - - return gainMap3; -} - -void writeMatlab2DHisto(int xx, int yy,char *outFileName){ - ofstream outFile; - outFile.open (outFileName); - - cout << "create matlab file with " << xx << " xbins and " << yy << " ybins" << endl; - - for(int y = 0; y < yy; y++){ - for(int x = 0; x < xx; x++){ - outFile << imgArray[x][y] << "\t"; - } - outFile << endl; - } - - outFile.close(); -} - -//COMPLETE STUFF - -void createImage(char *tdir, char *tname, char *ftname, char *ifname = NULL, int useGM=0, double lEth=-1., double hEth=-1.){ - imgRLR->Reset(); - imgLR->Reset(); - - char fname[1000]; - char inFName[1000]; - char outFName[1000]; - char moutFName[1000]; - if(ifname == NULL){ - sprintf(fname,"%s/%s_*.root",tdir,tname); - }else{ - sprintf(fname,"%s",ifname); - } - - if(useGM) sprintf(inFName,"%s/%s-PlotsWGMVEL.root",tdir,ftname); - else sprintf(inFName,"%s/%s-PlotsVEL.root",tdir,ftname); - - sprintf(outFName,"%s/%s-ImgVEL.root",tdir,tname); - sprintf(moutFName,"%s/%s-ImgVEL.mf",tdir,tname); - - TFile *inFile = new TFile(inFName,"READ"); - - cout << "Image Tree File Name: " << fname << endl; - cout << "Eta File Name: " << inFName << endl; - cout << "Out File Name: " << outFName << endl; - cout << "Matlab Out File Name: " << moutFName << endl; - - TH2D *gm = NULL; - if(useGM){ - cout << "Load gain map" << endl; - gm = (TH2D *)gDirectory->Get("gainMap"); - if(gm == NULL){ cout << "can not find gainMap in file" << endl; return; } - } - - cout << "Load eta" << endl; - EtaVEL *ee = (EtaVEL *)gDirectory->Get("etaDist"); - - cout << "Select Energy BW" << endl; - TH1D *spec = (TH1D *)gDirectory->Get("avgSpec3"); - if(spec == NULL){ cout << "can not find avgSpec3" << endl; return; } - - TF1 *gf3 = new TF1("gf3","gaus", 0, 10000); - spec->Fit(gf3,"Q"); - double avgE = gf3->GetParameter(1); - double sigE = gf3->GetParameter(2); - cout << "avgE: " << avgE << " sigE: " << sigE << endl; - cout << endl; - - if(lEth == -1.) lEth = avgE-5.*sigE; - if(hEth == -1.) hEth = avgE+5.*sigE; - cout << lEth << " < E < " << hEth << " (eV)" << endl; - - cout << "start with interpolation" << endl; - interpolate( tname, fname, ee,lEth,hEth ,gm); - - - TH2D *img = (TH2D *)gDirectory->Get("img"); - if(img == NULL){ cout << "could not find 2d-histogram: img " << endl; return; } - - - TH2D *imgE = (TH2D *)gDirectory->Get("imgE"); - if(imgE == NULL){ cout << "could not find 2d-histogram: imgE " << endl; return; } - - - //TH2D *imgEOM = (TH2D *)gDirectory->Get("imgEOM"); - //if(imgEOM == NULL){ cout << "could not find 2d-histogram: imgEOM " << endl; return; } - - TFile *outFile = new TFile(outFName,"UPDATE"); - imgLR->Write(); - imgRLR->Write(); - imgE->Write(); - //imgEOM->Write(); - img->Write(); - outFile->Close(); - inFile->Close(); - cout << "writing matlab file: " << moutFName << endl; - writeMatlab2DHisto(160*ee->getNPixels(),160*ee->getNPixels(),moutFName); - cout << "Done : " << outFName << endl; - -} - -/** - \par tdir input tree directory - \par tname input tree name - \par ifname input file name if different than tdir/tname_*.root - \par useGM use gain map - \par maxExpEinEv spectrum maximum - \par nPixels sub-pixels bins - \par lEth low threshold - \par hEth high threshold - - */ - - -EtaVEL *createGainAndEtaFile(char *tdir, char *tname, char *ifname=NULL, int useGM=0, double maxExpEinEv=25000., int nPixels =25, double lEth=-1., double hEth=-1.){ - char fname[1000]; - char outFName[1000]; - - - if(ifname == NULL){ - sprintf(fname,"%s/%s_*.root",tdir,tname); - }else{ - sprintf(fname,"%s",ifname); - } - - if(useGM) sprintf(outFName,"%s/%s-PlotsWGVEL.root",tdir,tname); - else sprintf(outFName,"%s/%s-PlotsVEL.root",tdir,tname); - - - cout << "Tree File Name: " << fname << endl; - cout << "Output File Name: " << outFName << endl; - - /** creates gain map and 3x3 spectrum */ - cout << "Creating gain map: " << endl; - TH2D *gm = createGainMap(tname,fname,0,maxExpEinEv/10.); - gm->SetName("gainMap"); - - - /** gets average 3x3 spectrum and fits it with a gaus */ - TH1D *spec = (TH1D *)gDirectory->Get("avgSpec3"); - if(spec == NULL){ cout << "can not find avgSpec3" << endl; return NULL; } - TF1 *gf3 = new TF1("gf3","gaus", 0, maxExpEinEv/10.); - spec->Fit(gf3,"Q"); - double avgE = gf3->GetParameter(1); - double sigE = gf3->GetParameter(2); - cout << "avgE: " << avgE << " sigE: " << sigE << endl; - cout << endl; - - - /** sets high and low threshold if not given by the user */ - if(lEth == -1.) lEth = avgE-5.*sigE; - if(hEth == -1.) hEth = avgE+5.*sigE; - cout << lEth << " < E < " << hEth << " (eV)" << endl; - - - - - cout << "calculating eta stuff" << endl; - - EtaVEL *newEta; - if(useGM) newEta = etaDensity(tname,fname,lEth,hEth,gm,nPixels); - else newEta = etaDensity(tname,fname,lEth,hEth,NULL,nPixels); - - cout << "writing to file " << outFName << endl; - - TFile *outFile = new TFile(outFName,"UPDATE"); - - newEta->Write("etaDist"); - - gm->Write(); - spec->Write(); - subPosAEta->Write(); - cES3vs2->Write(); - - outFile->Close(); - cout << "Done : " << outFName << endl; - return newEta; -} - -void exportSpec(char *tdir, char *tname){ - char tfname[1000]; - char ofname[1000]; - char cleanName[1000]; - - for(int p = 0; p < strlen(tname);p++){ - cleanName[p+1] = '\0'; - cleanName[p] = tname[p]; - - if(tname[p] == '-') cleanName[p] = '_'; - } - - sprintf(tfname,"%s/%s-PlotsVEL.root",tdir,tname); - sprintf(ofname,"%s/%s_SpecVEL.m",tdir,cleanName); - TFile *tf = new TFile(tfname); - TH1D *spec = (TH1D *)gDirectory->Get("avgSpec3"); - - ofstream outFile; - outFile.open (ofname); - - if(outFile.fail()){ - cout << "Could not open file : " << ofname << endl; - return; - } - - cout << "create matlab file with with spec " << ofname << endl; - - - outFile << cleanName << " = [ " << endl; - for(int i = 0; i < spec->GetNbinsX(); i++){ - outFile << i << " " << spec->GetBinCenter(i) << " " << spec->GetBinContent(i) << " ; " << endl; - } - - outFile << " ] ; " << endl; - - outFile.close(); -} diff --git a/slsDetectorCalibration/interpolations/etaVEL/EtaVEL.cpp b/slsDetectorCalibration/interpolations/etaVEL/EtaVEL.cpp deleted file mode 100644 index 922c91d4f..000000000 --- a/slsDetectorCalibration/interpolations/etaVEL/EtaVEL.cpp +++ /dev/null @@ -1,679 +0,0 @@ -#include "EtaVEL.h" -#include - - -// ClassImp(EtaVEL); - -// double Median(const TH1D * histo1) { - -// int numBins = histo1->GetXaxis()->GetNbins(); -// Double_t *x = new Double_t[numBins]; -// Double_t* y = new Double_t[numBins]; -// for (int i = 0; i < numBins; i++) { -// x[i] = histo1->GetBinCenter(i); -// y[i] = histo1->GetBinContent(i); -// } -// return TMath::Median(numBins, x, y); -// } - - -double *EtaVEL::getPixelCorners(int x, int y){ - double tlX,tlY,trX,trY,blX,blY,brX,brY; - tlX = xPPos[getCorner(x,y+1)]; - tlY = yPPos[getCorner(x,y+1)]; - trX = xPPos[getCorner(x+1,y+1)]; - trY = yPPos[getCorner(x+1,y+1)]; - blX = xPPos[getCorner(x,y)]; - blY = yPPos[getCorner(x,y)]; - brX = xPPos[getCorner(x+1,y)]; - brY = yPPos[getCorner(x+1,y)]; - - //cout << "gPC: TL: " << getCorner(x,y+1) << " TR: " << getCorner(x+1,y+1) << " BL " << getCorner(x,y) << " BR " << getCorner(x+1,y) << endl; - - double *c = new double[8]; - c[0] = tlX; c[1] = trX; c[2] = brX; c[3] = blX; - c[4] = tlY; c[5] = trY; c[6] = brY; c[7] = blY; - return c; -} - - -int EtaVEL::findBin(double xx, double yy){ - - double tlX,tlY,trX,trY,blX,blY,brX,brY; - /********Added by anna ******/ - // if (xxmax) xx=max-1E-6; - // if (yymax) yy=max-1E-6; - /**************/ - - - int bin = -1; - for(int x = 0; x < nPixels; x++){ - for(int y = 0; y < nPixels; y++){ - double *c = getPixelCorners(x,y); - tlX = c[0]; trX = c[1]; brX = c[2]; blX = c[3]; - tlY = c[4]; trY = c[5]; brY = c[6]; blY = c[7]; - - ///if(y == 0){ - // cout << "x: " << x << " blY " << blY << " brY " << brY << endl; - //} - - int out = 0; - - double tb = 0; - double bb = 0; - double lb = 0; - double rb = 0; - - if((trX-tlX)>0.) - tb = (trY - tlY)/(trX-tlX); - - if((brX-blX)>0.) - bb = (brY - blY)/(brX-blX); - - if((tlY-blY)>0.) - lb = (tlX - blX)/(tlY-blY); - - if((trY-brY)>0.) - rb = (trX - brX)/(trY-brY); - - double ty = tlY + tb * (xx - tlX); - double by = blY + bb * (xx - blX); - - double lx = blX + lb * (yy - blY); - double rx = brX + rb * (yy - brY); - - - - - if(yy >= ty) out++; - if(yy < by) out++; - if(xx < lx) out++; - if(xx >= rx) out++; - - //cout << "ty " << ty << endl; - //cout << "by " << by << endl; - //cout << "lx " << lx << endl; - //cout << "rx " << rx << endl; - - //double dist = (xx - xPPos[getBin(x,y)]) * (xx - xPPos[getBin(x,y)]) + (yy - yPPos[getBin(x,y)]) * (yy - yPPos[getBin(x,y)]); - //cout << "x " << x << " y " << y << " out " << out << " ty " << ty << endl; - //cout << "tl " << tlX << "/" << tlY << " tr " << trX << "/" << trY << endl; - //cout << "bl " << blX << "/" << blY << " br " << brX << "/" << brY << endl; - - //cout << " tb " << tb << endl; - - - delete[] c; - if(out == 0){ return getBin(x,y); } - } - } - - return -1; -} - -void EtaVEL::createLogEntry(){ - if(it >= nIterations){ - cerr << "log full" << endl; - } - log[it].itN = it; - log[it].xPos = new double[nPixels*nPixels+1]; - log[it].yPos = new double[nPixels*nPixels+1]; - log[it].binCont = new double[nPixels*nPixels+1]; - for(int x = 0; x < nPixels; x++) - for(int y = 0; y < nPixels; y++){ - log[it].xPos[getBin(x,y)] = xPPos[getBin(x,y)]; - log[it].yPos[getBin(x,y)] = yPPos[getBin(x,y)]; - log[it].binCont[getBin(x,y)] = binCont[getBin(x,y)]; - } - it++; -} - -void EtaVEL::updatePixelCorner(){ - double w = 20; - int rows = (nPixels+1)*(nPixels+1) + 4 + 4 * 4;//(4*(nPixels+1))-4; - int cols = (nPixels+1)*(nPixels+1); - - double *rVx = new double[rows]; - double *rVy = new double[rows]; - - double *posMat = new double[rows*cols]; - for(int i = 0 ; i < rows*cols; i++) posMat[i] = 0; - int boundaryPoint = 0; - - cout << "linear sys stuff" << endl; - - double minELength = 100000000000000; int minX=-1, minY=-1; - - for(int y = 0; y < nPixels+1; y++){ - for(int x = 0; x < nPixels+1; x++){ - double bx = 0, by = 0; - - //boundary conditions - - if((x == 0 && y % 5 == 0) || - (x == nPixels && y % 5 == 0) || - (y == 0 && x % 5 == 0) || - (y == nPixels && x % 5 == 0)){ - - bx = xPPos[getCorner(x,y)]; - //cout << "bP " << boundaryPoint << " bx " << bx << endl; - by = yPPos[getCorner(x,y)]; - rVx[(nPixels+1)*(nPixels+1) + boundaryPoint] = bx*w; - rVy[(nPixels+1)*(nPixels+1) + boundaryPoint] = by*w; - posMat[(nPixels+1)*(nPixels+1)*cols + boundaryPoint * cols + getCorner(x,y)-1] = w; - boundaryPoint++; - } - - double tot = 4 - (x == 0) - (y == 0) - (x == nPixels) - (y == nPixels); - //cout << "totW: " << tot << endl; - //tot = 4.; - double eLength = 0; - if(x != 0) eLength += edgeL[getEdgeX(x-1,y)]; - if(y != 0) eLength += edgeL[getEdgeY(x,y-1)]; - if(x != nPixels) eLength += edgeL[getEdgeX(x,y)]; - if(y != nPixels) eLength += edgeL[getEdgeY(x,y)]; - - /*cout << "Corner X:" <Print(); - k->SetMatrixArray(posMat); - // k->Print(); - - - //solve linear system - - Bool_t ok; - TDecompSVD *s = new TDecompSVD(*k); - s->Solve(*fx); - s->Solve(*fy); - - double *fxA = fx->GetMatrixArray(); - double *fyA = fy->GetMatrixArray(); - - - for(int y = 0; y < nPixels+1; y++){ - for(int x = 0; x < nPixels+1; x++){ - //do not update boundaries - - if(!(x == 0 || - x == nPixels|| - y == 0 || - y == nPixels)){ - xPPos[getCorner(x,y)] = fxA[getCorner(x,y)-1]; - yPPos[getCorner(x,y)] = fyA[getCorner(x,y)-1]; - } - } - } -} - -void EtaVEL::updatePixelPos(){ - double xMov, yMov, d1Mov, d2Mov; - createLogEntry(); - double *chMap = getChangeMap(); - int ch =0; - - cout << "update edge lengths" << endl; - for(int x = 0; x < nPixels; x++) - for(int y = 0; y < nPixels; y++){ - - - /*cout << "Pixel X:" < 0. & totCont > 0.){ - dd=sqrt(r/avg); - /**Added by Anna */ - if (dd>2.) dd=1.5; - if (dd<0.5) dd=0.75; - chMap[getBin(x,y)] = dd; - /** */ - //if( chMap[getBin(x,y)] < 1.){ chMap[getBin(x,y)] = 1/1.2; } - //if( chMap[getBin(x,y)] > 1.){ chMap[getBin(x,y)] = 1.2; } - //if( chMap[getBin(x,y)] < 1/1.2){ chMap[getBin(x,y)] = 1/1.2; } - //if( chMap[getBin(x,y)] > 1.2){ chMap[getBin(x,y)] = 1.2; } - }else if(totCont > 0.){ - chMap[getBin(x,y)] =0.5; //1/1.2; - }else{ - chMap[getBin(x,y)] = 1.; - } - - //if(r < avg + 2*acc && r > avg - 2*acc){ totInRange++;}// chMap[getBin(x,y)] = 1.; } - - /** Commente away by Anna - if(converged == 0 && r < med+20*acc){ chMap[getBin(x,y)] = 1.; } - if(converged == 2 && r < med+20*acc && r > med-03*acc){ chMap[getBin(x,y)] = 1.; } - if(r < med+03*acc){ totInRange03s++; } - if(r < med+07*acc){ totInRange07s++; } - if(r < med+12*acc){ totInRange12s++; } - if(r < med+20*acc){ totInRange20s++; } - if(r < med+25*acc){ totInRange25s++; } - */ - - //cout << "x " << x << " y " << y << " r " << r << " ch " << chMap[getBin(x,y)] << endl; - // if(r - avg > acc){ totOffAcc += r-avg;} - //if(r - avg < -acc){ totOffAcc += avg-r;} - totOffAcc += (avg-r)*(avg-r); - chi_sq+=(avg-r)*(avg-r)/r; - //cout << " x " << x << " y " << y << " bC " << binCont[x*nPixels+y] << " r " << r << endl; - - if(r > maxC){ maxC = r; maxX = x; maxY = y; } - if(r < minC){minC = r; minX = x; minY = y; } - - } - } - // cout << "totInBins " << totInBins << " zero Bin " << binCont[0] << endl; - cout << "AvgOffAcc: " << sqrt(totOffAcc/(double)(nPixels*nPixels)) << endl; - cout << "***********Reduced Chi Square: " << chi_sq/((double)(nPixels*nPixels)) << endl; - // cout << "totInRange03 (<" << med+03*acc << "): " << totInRange03s << endl; - // cout << "totInRange07 (<" << med+07*acc << "): " << totInRange07s << endl; - // cout << "totInRange12 (<" << med+12*acc << "): " << totInRange12s << endl; - // cout << "totInRange20 (<" << med+20*acc << "): " << totInRange20s << endl; - // cout << "totInRange25 (<" << med+25*acc << "): " << totInRange25s << endl; - double maxSig = (maxC - avg)*(maxC - avg) / avg;//acc; - double minSig = (avg - minC)*(avg - minC) / avg;//acc; - cout << "Max Pixel X: " << maxX << " Y: " << maxY << " P# " << getBin(maxX,maxY) << " count: " << maxC << " sig: "<< maxSig << endl; - cout << "Min Pixel X: " << minX << " Y: " << minY << " P# " << getBin(minX,minY) << " count: " << minC << " sig: "<< minSig << endl; - - // if(maxSig <= 25){ converged = 2; cout << "reached first converstion step!!!" << endl; } - //if(minSig <= 7 && converged == 2) { converged = 1; } - if (chi_sq<3) converged=2; - if (chi_sq<1) converged=1; - cout << "Conversion step "<< converged << endl; - return chMap; -} - -TH2D *EtaVEL::getContent(int it, int changeType){ - TH2D *cont = new TH2D("cont","cont",nPixels,min,max,nPixels,min,max); - double *chMap = NULL; - if(changeType ==1) chMap = getChangeMap(); - double *szMap = getSizeMap(); - for(int x = 0; x < nPixels; x++) - for(int y = 0; y < nPixels; y++){ - if(changeType ==2 ){ - cont->SetBinContent(x+1,y+1,szMap[getBin(x,y)]); - } - if(changeType ==1 ){ - cont->SetBinContent(x+1,y+1,chMap[getBin(x,y)]); - } - if(changeType ==0 ){ - if(it == -1){ - cont->SetBinContent(x+1,y+1,binCont[getBin(x,y)]); - //cout << "x " << x << " y " << y << " cont " << binCont[getBin(x,y)] << endl; - } - else{cont->SetBinContent(x+1,y+1,log[it].binCont[getBin(x,y)]);} - } - } - return cont; -} - -TH1D *EtaVEL::getCounts(){ - TH1D *ch = new TH1D("ch","ch",500,0,totCont/(nPixels*nPixels)*4); - for(int x = 0; x < nPixels; x++) - for(int y = 0; y < nPixels; y++){ - ch->Fill(binCont[getBin(x,y)]); - } - return ch; - -} - -void EtaVEL::printGrid(){ - - double *colSum = new double[nPixels+1]; - double *rowSum = new double[nPixels+1]; - - for(int i = 0; i < nPixels+1; i++){ - colSum[i] = 0.; - rowSum[i] = 0.; - for(int j = 0; j < nPixels; j++){ - rowSum[i] += edgeL[getEdgeX(j,i)]; - colSum[i] += edgeL[getEdgeY(i,j)]; - } - } - - cout << endl; - - cout.precision(3); cout << fixed; - cout << " "; - for(int x = 0; x < nPixels+1; x++){ - cout << setw(2) << x << " (" << colSum[x] << ") "; - } - cout << endl; - for(int y = 0; y < nPixels+1; y++){ - cout << setw(2) << y << " "; - for(int x = 0; x < nPixels+1; x++){ - cout << "(" << xPPos[getCorner(x,y)] << "/" << yPPos[getCorner(x,y)] << ") " ; - if(x < nPixels) cout << " -- " << edgeL[getEdgeX(x,y)]/rowSum[y]*(max-min) << " -- "; - } - cout << " | " << rowSum[y] << endl; - - if(y < nPixels){ - cout << " "; - for(int x = 0; x < nPixels+1; x++){ - cout << edgeL[getEdgeY(x,y)]/colSum[x]*(max-min) << " "; - } - cout << endl; - } - - } - delete[] colSum; - delete[] rowSum; - -} - -TMultiGraph *EtaVEL::plotPixelBorder(int plotCenters){ - TMultiGraph *mg = new TMultiGraph(); - double cx[5], cy[5]; - for(int x = 0; x < nPixels; x++) - for(int y = 0; y < nPixels; y++){ - double *c = getPixelCorners(x,y); - cx[0]=c[0]; cx[1]=c[1]; cx[2]=c[2]; cx[3]=c[3]; cx[4]=c[0]; - cy[0]=c[4]; cy[1]=c[5]; cy[2]=c[6]; cy[3]=c[7]; cy[4]=c[4]; - - - TGraph *g = new TGraph(5,cx,cy); - mg->Add(g); - if(plotCenters){ - g = new TGraph(1,&(xPPos[getBin(x,y)]),&(yPPos[getBin(x,y)])); - mg->Add(g); - } - delete[] c; - } - return mg; -} - -TMultiGraph *EtaVEL::plotLog(int stepSize, int maxIt){ - int mIt; - TMultiGraph *mg = new TMultiGraph(); - double **xposl = new double*[nPixels*nPixels+1]; - double **yposl = new double*[nPixels*nPixels+1]; - if(maxIt==-1){ mIt = it; } else{ mIt = maxIt; }; - cout << "mIt " << mIt << " steps " << mIt/stepSize << endl; - for(int x = 0; x < nPixels; x++){ - for(int y = 0; y < nPixels; y++){ - xposl[getBin(x,y)] = new double[mIt/stepSize]; - yposl[getBin(x,y)] = new double[mIt/stepSize]; - for(int i = 0; i < mIt/stepSize; i++){ - xposl[getBin(x,y)][i] = log[i*stepSize].xPos[getBin(x,y)]; - yposl[getBin(x,y)][i] = log[i*stepSize].yPos[getBin(x,y)]; - } - TGraph *g = new TGraph(mIt/stepSize,xposl[getBin(x,y)],yposl[getBin(x,y)]); - g->SetLineColor((x*y % 9) + 1); - - if(x == 0) g->SetLineColor(2); - if(y == 0) g->SetLineColor(3); - if(x == nPixels-1) g->SetLineColor(4); - if(y == nPixels-1) g->SetLineColor(5); - mg->Add(g); - } - } - return mg; -} - -void EtaVEL::serialize(ostream &o){ - // b.WriteVersion(EtaVEL::IsA()); - char del = '|'; - o << min << del; - o << max << del; - o << ds << del; - o << nPixels << del; - o << it << del; - o << totCont << del; - for(int i = 0; i < (nPixels+1)*(nPixels+1)+1; i++){ - o << xPPos[i] << del; - o << yPPos[i] << del; - } - for(int i = 0; i < nPixels*nPixels+1; i++){ - o << binCont[i] << del; - } - - for(int i = 0; i < it; i++){ - o << log[i].itN << del; - for(int j = 0; j < (nPixels+1)*(nPixels+1)+1; j++){ - o << log[i].xPos[j] << del; - o << log[i].yPos[j] << del; - } - for(int j = 0; j < nPixels*nPixels+1; j++){ - o << log[i].binCont[j] << del; - } - } -} - -void EtaVEL::deserialize(istream &is){ - delete[] xPPos; - delete[] yPPos; - delete[] binCont; - - char del; - - is >> min >> del; - is >> max >> del; - is >> ds >> del; - is >> nPixels >> del; - is >> it >> del; - is >> totCont >> del; - - xPPos = new double[(nPixels+1)*(nPixels+1)+1]; - yPPos = new double[(nPixels+1)*(nPixels+1)+1]; - binCont = new double[nPixels*nPixels+1]; - - cout << "d"; - - for(int i = 0; i < (nPixels+1)*(nPixels+1)+1; i++){ - is >> xPPos[i] >> del; - is >> yPPos[i] >> del; - } - - cout << "d"; - - for(int i = 0; i < nPixels*nPixels+1; i++){ - is >> binCont[i] >> del; - } - - cout << "d"; - - for(int i = 0; i < it; i++){ - is >> log[i].itN >> del; - log[i].xPos = new double[(nPixels+1)*(nPixels+1)+1]; - log[i].yPos = new double[(nPixels+1)*(nPixels+1)+1]; - log[i].binCont = new double[nPixels*nPixels+1]; - - for(int j = 0; j < (nPixels+1)*(nPixels+1)+1; j++){ - is >> log[i].xPos[j] >> del; - is >> log[i].yPos[j] >> del; - } - for(int j = 0; j < nPixels*nPixels+1; j++){ - is >> log[i].binCont[j] >> del; - } - cout << "d"; - } - cout << endl; -} - -void EtaVEL::Streamer(TBuffer &b){ - if (b.IsReading()) { - Version_t v = b.ReadVersion(); - - delete[] xPPos; - delete[] yPPos; - delete[] binCont; - - b >> min; - b >> max; - b >> ds; - b >> nPixels; - b >> it; - b >> totCont; - - xPPos = new double[(nPixels+1)*(nPixels+1)+1]; - yPPos = new double[(nPixels+1)*(nPixels+1)+1]; - binCont = new double[nPixels*nPixels+1]; - - for(int i = 0; i < (nPixels+1)*(nPixels+1)+1; i++){ - b >> xPPos[i]; - b >> yPPos[i]; - } - for(int i = 0; i < nPixels*nPixels+1; i++){ - b >> binCont[i]; - } - - for(int i = 0; i < it; i++){ - b >> log[i].itN; - log[i].xPos = new double[(nPixels+1)*(nPixels+1)+1]; - log[i].yPos = new double[(nPixels+1)*(nPixels+1)+1]; - log[i].binCont = new double[nPixels*nPixels+1]; - - for(int j = 0; j < (nPixels+1)*(nPixels+1)+1; j++){ - b >> log[i].xPos[j]; - b >> log[i].yPos[j]; - } - for(int j = 0; j < nPixels*nPixels+1; j++){ - b >> log[i].binCont[j]; - } - } - - } else { - b.WriteVersion(EtaVEL::IsA()); - b << min; - b << max; - b << ds; - b << nPixels; - b << it; - b << totCont; - for(int i = 0; i < (nPixels+1)*(nPixels+1)+1; i++){ - b << xPPos[i]; - b << yPPos[i]; - } - for(int i = 0; i < nPixels*nPixels+1; i++){ - b << binCont[i]; - } - - for(int i = 0; i < it; i++){ - b << log[i].itN; - for(int j = 0; j < (nPixels+1)*(nPixels+1)+1; j++){ - b << log[i].xPos[j]; - b << log[i].yPos[j]; - } - for(int j = 0; j < nPixels*nPixels+1; j++){ - b << log[i].binCont[j]; - } - } - } -} - diff --git a/slsDetectorCalibration/interpolations/etaVEL/EtaVEL.h b/slsDetectorCalibration/interpolations/etaVEL/EtaVEL.h deleted file mode 100644 index 5c73d8a83..000000000 --- a/slsDetectorCalibration/interpolations/etaVEL/EtaVEL.h +++ /dev/null @@ -1,164 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -//#include - - -#include -#include -#include - -#include -#include - -using namespace std; - -#ifndef ETAVPS -#define ETAVPS - -typedef struct { - int itN; - double *xPos; - double *yPos; - double *binCont; -} itLog; - - - -class EtaVEL : public TObject{ - - public: - EtaVEL(int numberOfPixels = 25, double minn=0., double maxx=1., int nnx=160, int nny=160) : nPixels(numberOfPixels), min(minn), max(maxx), converged(0), nx(nnx), ny(nny), chi_sq(0){ - //acc = 0.02; - ds = 0.005; - - init(); - } - void init(){ - double pOffset = (max-min)/(double)nPixels; - xPPos = new double[(nPixels+1)*(nPixels+1)+1]; - yPPos = new double[(nPixels+1)*(nPixels+1)+1]; - binCont = new double[nPixels*nPixels+1]; - totCont = 0.; - edgeL = new double[2*nPixels*(nPixels+1)+1]; - - for(int ii = 0; ii < 2*nPixels*(nPixels+1)+1; ii++){ - edgeL[ii] = 1.0; - //cout << "ii " << ii << endl; - } - - for(int x = 0; x < nPixels+1; x++){ - for(int y = 0; y < nPixels+1; y++){ - xPPos[getCorner(x,y)] = min + (double)x * pOffset; - yPPos[getCorner(x,y)] = min + (double)y * pOffset; - - if(x < nPixels && y < nPixels) binCont[getBin(x,y)] = 0; - } - } - // edgeL[1] = 3.0; - updatePixelCorner(); - it = 0; - - log = new itLog[nIterations]; - } - - void fill(double x, double y, double amount = 1.){ - totCont+=amount; - int bin = findBin(x,y); - if(bin < 0) { - //cout << "can not find bin x: " << x << " y: " << y << endl; - totCont-=amount; - } - binCont[bin]+=amount; - - } - - int getBin(int x, int y){ - if(x < 0 || x >= nPixels || y < 0 || y >= nPixels){ - //cout << "getBin: out of bounds : x " << x << " y " << y << endl; - return 0; - } - return y*nPixels+x+1; - } - - int getXBin(int bin){ - return (bin-1)%nPixels; - } - - int getYBin(int bin){ - return (bin-1)/nPixels; - } - - int getCorner(int x, int y){ - return y*(nPixels+1)+x+1; - } - - int getEdgeX(int x,int row){ - int ret = row*nPixels+x+1; - //cout << "| edge X x " << x << " row " << row << ": "<< ret << " | "; - return ret; - } - - int getEdgeY(int col, int y){ - int ret = nPixels*(nPixels+1)+col*nPixels+y+1; - //cout << "| edge Y col " << col << " y " << y << ": "<< ret << " | "; - return ret; - } - - - int getIt(){ return it; }; - - int getNPixels(){ return nPixels; } - double *getXPPos(){ return xPPos; } - double *getYPPos(){ return yPPos; } - - void updatePixelCorner(); - double *getPixelCorners(int x, int y); - int findBin(double xx, double yy); - void createLogEntry(); - - void updatePixelPos(); - double *getSizeMap(); - double *getChangeMap(); - TH2D *getContent(int it=-1, int changeType = 0); - TMultiGraph *plotPixelBorder(int plotCenters=0); - TMultiGraph *plotLog(int stepSize=1, int maxIt=-1); - void printGrid(); - TH1D *getCounts(); - - void serialize(ostream &o); - void deserialize(istream &is); - - int converged ; - double getChiSq(){return chi_sq;}; - - private: - itLog *log; - int it; - const static int nIterations =10000; - int nx, ny; - int nPixels; - double *xPPos; - double *yPPos; - double *binCont; - double totCont; - double *edgeL; - // double acc; - double ds; - double min,max; - double chi_sq; - - ClassDefNV(EtaVEL,1); - #pragma link C++ class EtaVEL-; -}; - -#endif diff --git a/slsDetectorCalibration/interpolations/etaVEL/EtaVELTr.py b/slsDetectorCalibration/interpolations/etaVEL/EtaVELTr.py deleted file mode 100644 index ebb152737..000000000 --- a/slsDetectorCalibration/interpolations/etaVEL/EtaVELTr.py +++ /dev/null @@ -1,393 +0,0 @@ -import numpy as np -import math - -maxf = 2 -minf = 0.5 - -class EtaVELTr: - def __init__(self, numberOfPixels = 25, minn=0., maxx=1.): - self.nPixels = numberOfPixels - self.nCorners = self.nPixels + 1 - self.minEta = minn - self.maxEta = maxx - #self.corners = [] - self.edgesX = [] - self.edgesY = [] - self.edgesE = [] - self.edgesF = [] - self.edgesG = [] - self.edgesH = [] - self.counts = [] - self.pOffset = (self.maxEta-self.minEta)/self.nPixels - - self.cPosX = [] - self.cPosY = [] - self.zPosX = [] - self.zPosY = [] - - self.sqSums = [] - self.cIteration = 0 - self.bSqSum = 0 - - self.initGrid() - #self.calculatePixelCorners() - self.update() - - def initGrid(self): - dd = 1 / math.sqrt(2) - - #self.corners = [ [self.minEta + x * pOffset, self.minEta + y * pOffset] for y in range(self.nPixels)] for x in range(self.nPixels) - self.cPosX = [ [self.minEta + x * self.pOffset for x in range(self.nCorners)] for y in range(self.nCorners) ] - self.cPosY = [ [self.minEta + y * self.pOffset for x in range(self.nCorners)] for y in range(self.nCorners) ] - self.counts = [ [ [0,0,0,0] for x in range(self.nPixels) ] for y in range(self.nPixels) ] - self.edgesX = [ [ 1 for x in range(self.nCorners) ] for y in range(self.nCorners + 1) ] - self.edgesY = [ [ 1 for x in range(self.nCorners+1) ] for y in range(self.nCorners) ] - self.edgesE = [ [ dd for x in range(self.nPixels) ] for y in range(self.nPixels) ] - self.edgesF = [ [ dd for x in range(self.nPixels) ] for y in range(self.nPixels) ] - self.edgesG = [ [ dd for x in range(self.nPixels) ] for y in range(self.nPixels) ] - self.edgesH = [ [ dd for x in range(self.nPixels) ] for y in range(self.nPixels) ] - - - - def update(self): - self.normalizeEdgeLengths() - self.calculateEdgeLengths2() - self.calculatePixelCorners2() - conv = False - out = 0 - outList = [] - tot = self.nPixels*self.nPixels*4 - sqSum = 0 - avg = self.getAvgCounts() - avgPS = self.getAvgCounts() + 1*math.sqrt(self.getAvgCounts()) - avgMS = self.getAvgCounts() - 1*math.sqrt(self.getAvgCounts()) - for y in range(self.nPixels): - for x in range(self.nPixels): - for t in range(4): - sqSum += (avg -self.counts[y][x][t]) * (avg -self.counts[y][x][t]) - if self.counts[y][x][t] > avgPS or self.counts[y][x][t] < avgMS: - - out += 1 - outList.append([y,x,t,self.counts[y][x][t]]) - - outList = sorted(outList,key=lambda t: abs(self.counts[t[0]][t[1]][t[2]]/self.getAvgCounts())) - self.counts = [ [ [0,0,0,0] for x in range(self.nPixels) ] for y in range(self.nPixels) ] - print("There are {} of {} triangles out of 1 std ({} %)".format(out,tot,out/tot*100)) - print("Total Sq Err: {}".format(sqSum)) - - self.sqSums.append(sqSum) - - if len(self.sqSums) > 2 and np.diff(self.sqSums)[-1] > 0: - print("converged after {} steps: sqSums {} diff(sqSums) {}".format(self.cIteration,self.sqSums,np.diff(self.sqSums))) - conv = True - self.bSqSum = self.sqSums[-2] - - self.cIteration += 1 - return [conv,outList,sqSum] - - def normalizeEdgeLengths(self): - sumL = 0 - sumL += sum(map(sum,zip(*self.edgesX))) - sumL += sum(map(sum,zip(*self.edgesY))) - sumL += sum(map(sum,zip(*self.edgesE))) - sumL += sum(map(sum,zip(*self.edgesF))) - sumL += sum(map(sum,zip(*self.edgesG))) - sumL += sum(map(sum,zip(*self.edgesH))) - avgL = sumL/(4*self.nPixels*self.nPixels+2*self.nCorners*(self.nCorners+1)) - print("total Sum is {} avg: {}".format(sumL,avgL)) - self.edgesX = [ [ x/avgL for x in y ] for y in self.edgesX ] - self.edgesY = [ [ x/avgL for x in y ] for y in self.edgesY ] - self.edgesE = [ [ x/avgL for x in y ] for y in self.edgesE ] - self.edgesF = [ [ x/avgL for x in y ] for y in self.edgesF ] - self.edgesG = [ [ x/avgL for x in y ] for y in self.edgesG ] - self.edgesH = [ [ x/avgL for x in y ] for y in self.edgesH ] - - def _shapeF(self,f): - f = (f - 1) * 0.6 + 1 - if f > maxf: - return maxf - if f < minf: - return minf - return f - - def calculateEdgeLengths2(self): - if self.getTotalCounts() == 0: - return - avg = self.getAvgCounts() - - for y in range(self.nPixels): - for x in range(self.nPixels): - for t in range(4): - pc = self.counts[y][x][t] - if pc == 0: - f = maxf - else: - f = math.sqrt(avg/pc) - if pc > avg-math.sqrt(avg) and pc < avg+math.sqrt(avg): - f = 1. - sf = self._shapeF(f) - if t == 0: - self.edgesX[y][x] = self.edgesX[y][x] / sf - self.edgesE[y][x] = self.edgesE[y][x] / sf - self.edgesF[y][x] = self.edgesF[y][x] / sf - if t == 1: - self.edgesY[y][x+1] = self.edgesY[y][x+1] / sf - self.edgesF[y][x] = self.edgesF[y][x] / sf - self.edgesH[y][x] = self.edgesH[y][x] / sf - if t == 2: - self.edgesX[y+1][x] = self.edgesX[y+1][x] / sf - self.edgesH[y][x] = self.edgesH[y][x] / sf - self.edgesG[y][x] = self.edgesG[y][x] / sf - if t == 3: - self.edgesY[y][x] = self.edgesY[y][x] / sf - self.edgesG[y][x] = self.edgesG[y][x] / sf - self.edgesE[y][x] = self.edgesE[y][x] / sf - - - def calculatePixelCorners2(self): - w = 20 - posMat = [] - CrVx = np.zeros((self.nCorners,self.nCorners)) - CrVy = np.zeros((self.nCorners,self.nCorners)) - ZrVx = np.zeros((self.nPixels,self.nPixels)) - ZrVy = np.zeros((self.nPixels,self.nPixels)) - - #boundary conditions matrix/vectors - BCposMatX = [] - BCposMatY = [] - BCrVx = [] - BCrVy = [] - - for y in range(self.nCorners): - for x in range(self.nCorners): - BClineX = np.zeros((self.nCorners,self.nCorners)) - BClineY = np.zeros((self.nCorners,self.nCorners)) - if (x == 0 and y == 0) or \ - (x == 0 and y == self.nPixels) or \ - (x == self.nPixels and y == 0) or \ - (x == self.nPixels and y == self.nPixels): - BClineX[y][x] = w - BClineY[y][x] = w - BCrVx.append(self.getCornerPos(y,x)[0] * w) - BCrVy.append(self.getCornerPos(y,x)[1] * w) - #print("bclinex shape {} zeros shape {}".format( BClineX.reshape((self.nCorners*self.nCorners,)).shape , np.zeros((self.nPixels*self.nPixels)).shape )) - BCposMatX.append(np.hstack((BClineX.reshape((self.nCorners*self.nCorners,)),np.zeros((self.nPixels*self.nPixels,)) )) ) - BCposMatY.append(np.hstack((BClineY.reshape((self.nCorners*self.nCorners,)),np.zeros((self.nPixels*self.nPixels,)) )) ) - - elif x == 0 or x == self.nPixels: - BClineX[y][x] = w - #BClineY[y][x] = 1 - BCrVx.append(self.getCornerPos(y,x)[0] * w) - #BCrVy.append(self.getCornerPos(y,x)[1]) - BCposMatX.append(np.hstack((BClineX.reshape((self.nCorners*self.nCorners,)),np.zeros((self.nPixels*self.nPixels,)) )) ) - #BCposMatY.append(np.hstack((BClineY.reshape((self.nCorners*self.nCorners,)),np.zeros((self.nPixels*self.nPixels,)) )) ) - elif y == 0 or y == self.nPixels: - #BClineX[y][x] = 1 - BClineY[y][x] = w - #BCrVx.append(self.getCornerPos(y,x)[0]) - BCrVy.append(self.getCornerPos(y,x)[1] * w) - #BCposMatX.append(np.hstack((BClineX.reshape((self.nCorners*self.nCorners,)),np.zeros((self.nPixels*self.nPixels,)) )) ) - BCposMatY.append(np.hstack((BClineY.reshape((self.nCorners*self.nCorners,)),np.zeros((self.nPixels*self.nPixels,)) )) ) - - - eLength = 0 - - if x != 0: - eLength += self.edgesX[y][x-1] - if y != 0: - eLength += self.edgesY[y-1][x] - if x != self.nPixels: - eLength += self.edgesX[y][x] - if y != self.nPixels: - eLength += self.edgesY[y][x] - - if y != 0 and x != 0: - eLength += self.edgesH[y-1][x-1] - if y != self.nPixels and x != 0: - eLength += self.edgesF[y][x-1] - if y != 0 and x != self.nPixels: - eLength += self.edgesG[y-1][x] - if y != self.nPixels and x != self.nPixels: - eLength += self.edgesE[y][x] - - line = np.zeros((self.nCorners,self.nCorners)) - lineZ = np.zeros((self.nPixels,self.nPixels)) - - - if x != 0: - line[y][x-1] = - self.edgesX[y][x-1]/eLength - if y != 0: - line[y-1][x] = - self.edgesY[y-1][x]/eLength - if x != self.nPixels: - line[y][x+1] = - self.edgesX[y][x]/eLength - if y != self.nPixels: - line[y+1][x] = - self.edgesY[y][x]/eLength - - if y != 0 and x != 0: - lineZ[y-1][x-1] = -self.edgesH[y-1][x-1]/eLength - if y != self.nPixels and x != 0: - lineZ[y][x-1] = -self.edgesF[y][x-1]/eLength - if y != 0 and x != self.nPixels: - lineZ[y-1][x] = -self.edgesG[y-1][x]/eLength - if y != self.nPixels and x != self.nPixels: - lineZ[y][x] = -self.edgesE[y][x]/eLength - - - line[y][x] = 1 - CrVx[y][x] = 0 - CrVy[y][x] = 0 - posMat.append( \ - np.hstack(( \ - line.reshape((self.nCorners*self.nCorners,)), \ - lineZ.reshape((self.nPixels*self.nPixels,)) \ - )) \ - ) - - for y in range(self.nPixels): - for x in range(self.nPixels): - line = np.zeros((self.nCorners,self.nCorners)) - lineZ = np.zeros((self.nPixels,self.nPixels)) - - eLength = self.edgesE[y][x] + self.edgesF[y][x] +self.edgesG[y][x] +self.edgesH[y][x] - line[y][x] = -self.edgesE[y][x] / eLength - line[y][x+1] = -self.edgesF[y][x] / eLength - line[y+1][x] = -self.edgesG[y][x] / eLength - line[y+1][x+1] = -self.edgesH[y][x] / eLength - - lineZ[y][x] = 1 - ZrVx[y][x] = 0 - ZrVy[y][x] = 0 - posMat.append( \ - np.hstack(( \ - line.reshape((self.nCorners*self.nCorners,)), \ - lineZ.reshape((self.nPixels*self.nPixels,)) \ - )) \ - ) - - CrVxFlat = CrVx.reshape((self.nCorners*self.nCorners,)) - CrVyFlat = CrVy.reshape((self.nCorners*self.nCorners,)) - ZrVxFlat = ZrVx.reshape((self.nPixels*self.nPixels,)) - ZrVyFlat = ZrVy.reshape((self.nPixels*self.nPixels,)) - posMat = np.asarray(posMat) - - BCrVyFlat = np.asarray(BCrVy) - BCrVxFlat = np.asarray(BCrVx) - BCposMatX = np.asarray(BCposMatX) - BCposMatY = np.asarray(BCposMatY) - - print ("BCposMatY vy {} shape posMat {}".format(BCposMatY.shape,posMat.shape)) - - FinalrVy = np.hstack((CrVyFlat,ZrVyFlat,BCrVyFlat)) - FinalrVx = np.hstack((CrVxFlat,ZrVxFlat,BCrVxFlat)) - FinalposMatX = np.vstack((posMat,BCposMatX)) - FinalposMatY = np.vstack((posMat,BCposMatY)) - - print("posMat shape {}".format(posMat.shape)) - print("posMatX shape {}".format(FinalposMatX.shape)) - print("rVxFlat shape {}".format(FinalrVx.shape)) - - #print("posMat {}".format(FinalposMat)) - #print("rVxFlat {}".format(FinalrVx)) - - xPos = np.linalg.lstsq(FinalposMatX,FinalrVx)[0] - yPos = np.linalg.lstsq(FinalposMatY,FinalrVy)[0] - - print("xPosShape {} cutXPosShape {}".format(xPos.shape,xPos[:self.nCorners][:self.nCorners].shape)) - - self.cPosX = xPos[:self.nCorners*self.nCorners].reshape((self.nCorners,self.nCorners)) - self.cPosY = yPos[:self.nCorners*self.nCorners].reshape((self.nCorners,self.nCorners)) - - self.zPosX = xPos[self.nCorners*self.nCorners:].reshape((self.nPixels,self.nPixels)) - self.zPosY = yPos[self.nCorners*self.nCorners:].reshape((self.nPixels,self.nPixels)) - - - - def fill(self,yy,xx,count = 1): - [y,x,t] = self.getPixel(yy,xx) - self.counts[y][x][t] += count - - def getCountDist(self): - c = [] - for y in range(self.nPixels): - for x in range(self.nPixels): - c.append(self.counts[y][x]) - return c - - def getPixel(self,yy,xx, debug = False): - for y in range(self.nPixels): - for x in range(self.nPixels): - for t in range(4): - [v1x,v1y,v2x,v2y,v3x,v3y] = self.getTriangleCorner(y,x,t) - if self.pointInTriangle([xx,yy],[v1x,v1y],[v2x,v2y],[v3x,v3y]): - return [y,x,t] - - if not debug: - raise Exception("not inside a pixel") - else: - print("no pixel found") - return [0,0] - - #http://stackoverflow.com/questions/2049582/how-to-determine-a-point-in-a-2d-triangle - def trSign (self, p1, p2, p3): - return (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1]); - - def pointInTriangle (self,pt, v1, v2, v3): - b1 = self.trSign(pt, v1, v2) < 0.0 - b2 = self.trSign(pt, v2, v3) < 0.0 - b3 = self.trSign(pt, v3, v1) < 0.0 - return ((b1 == b2) and (b2 == b3)); - - def getAvgCounts(self): - return self.getTotalCounts() / self.nPixels/self.nPixels/4. - - def getTotalCounts(self): - tot = 0 - for y in range(self.nPixels): - for x in range(self.nPixels): - for t in range(4): - tot += self.counts[y][x][t] - return tot - - #tl tr bl br - def getPixelCorners(self,iy,ix): - return self.getCornerPos(iy,ix) + self.getCornerPos(iy,ix+1) + self.getCornerPos(iy+1,ix) + self.getCornerPos(iy+1,ix+1) - - def getTriangleCorner(self,iy,ix,tr): - if tr == 0: - return self.getCornerPos(iy,ix) + self.getCornerPos(iy,ix+1) + [self.zPosX[iy][ix],self.zPosY[iy][ix]] - if tr == 1: - return self.getCornerPos(iy,ix+1) + self.getCornerPos(iy+1,ix+1) + [self.zPosX[iy][ix],self.zPosY[iy][ix]] - if tr == 2: - return self.getCornerPos(iy+1,ix+1) + self.getCornerPos(iy+1,ix) + [self.zPosX[iy][ix],self.zPosY[iy][ix]] - if tr == 3: - return self.getCornerPos(iy+1,ix) + self.getCornerPos(iy,ix) + [self.zPosX[iy][ix],self.zPosY[iy][ix]] - - def getCornerPos(self,iy,ix): - return [self.cPosX[iy][ix],self.cPosY[iy][ix]] - - def getXEdgePos(self,iy,ix): - p1 = self.getCornerPos(iy,ix) - p2 = self.getCornerPos(iy,ix+1) - return [p1[0],p1[1],p2[0],p2[1]] - - def getYEdgePos(self,iy,ix): - p1 = self.getCornerPos(iy,ix) - p2 = self.getCornerPos(iy+1,ix) - return [p1[0],p1[1],p2[0],p2[1]] - - def getEEdgePos(self,iy,ix): - p1 = self.getCornerPos(iy,ix) - return [p1[0],p1[1],self.zPosX[iy][ix],self.zPosY[iy][ix]] - - def getFEdgePos(self,iy,ix): - p1 = self.getCornerPos(iy,ix+1) - return [p1[0],p1[1],self.zPosX[iy][ix],self.zPosY[iy][ix]] - - def getGEdgePos(self,iy,ix): - p1 = self.getCornerPos(iy+1,ix) - return [p1[0],p1[1],self.zPosX[iy][ix],self.zPosY[iy][ix]] - - def getHEdgePos(self,iy,ix): - p1 = self.getCornerPos(iy+1,ix+1) - return [p1[0],p1[1],self.zPosX[iy][ix],self.zPosY[iy][ix]] - diff --git a/slsDetectorCalibration/interpolations/etaVEL/etaVELInterpolation.cpp b/slsDetectorCalibration/interpolations/etaVEL/etaVELInterpolation.cpp deleted file mode 100644 index 1cdd3c718..000000000 --- a/slsDetectorCalibration/interpolations/etaVEL/etaVELInterpolation.cpp +++ /dev/null @@ -1,134 +0,0 @@ -#include "interpolation_EtaVEL.h" -#include "TH2F.h" -#include "TCanvas.h" -#include "TROOT.h" -//#include "EtaVEL.h" -#include "EtaVEL.cpp" -/* -Zum erstellen der correction map ist createGainAndEtaFile(...) in EVELAlg.C der entry point. -Zum erstellen des HR images ist createImage(...) der entry point. -*/ -interpolation_EtaVEL::interpolation_EtaVEL(int nx, int ny, int ns, double etamin, double etamax, int p) : slsInterpolation(nx, ny, ns), newEta(NULL), heta(NULL), plot(p) { - newEta = new EtaVEL(nSubPixels,etamin,etamax,nPixelsX, nPixelsY); - heta= new TH2F("heta","heta",50*nSubPixels, etamin,etamax,50*nSubPixels, etamin,etamax); - heta->SetStats(kFALSE); -} - -interpolation_EtaVEL::~interpolation_EtaVEL() { - delete newEta; - delete heta; -} - - -void interpolation_EtaVEL::prepareInterpolation(int &ok, int maxit) { - int nit=0; - while ((newEta->converged != 1) && nit++Modified(); - gPad->Update(); - } - if (newEta->converged==1) ok=1; else ok=0; -} - -int interpolation_EtaVEL::addToFlatField(Double_t *cluster, Double_t &etax, Double_t &etay) { - Double_t sum, totquad, sDum[2][2]; - int corner =calcEta(cluster, etax, etay, sum, totquad, sDum); - //check if it's OK...should redo it every time? - //or should we fill a finer histogram and afterwards re-fill the newEta? - addToFlatField(etax, etay); - return corner; -} - -int interpolation_EtaVEL::addToFlatField(Double_t etax, Double_t etay) { - // newEta->fill(etaX,etaY); - heta->Fill(etax,etay); - return 0; -} - -void interpolation_EtaVEL::iterate() { - cout << " -------------- newEta refilled"<< endl; - for (int ibx=0; ibxGetNbinsX(); ibx++) { - for (int iby=0; ibyGetNbinsY(); iby++) { - newEta->fill(heta->GetXaxis()->GetBinCenter(ibx+1),heta->GetYaxis()->GetBinCenter(iby+1),heta->GetBinContent(ibx+1,iby+1)); - } - } - newEta->updatePixelPos(); - cout << " -------------- pixelPosition updated"<< endl; -} - -void interpolation_EtaVEL::DrawH() { - heta->Draw("col"); - (newEta->plotPixelBorder())->Draw(); -} - - -void interpolation_EtaVEL::getInterpolatedPosition(Int_t x, Int_t y, Double_t *cluster, Double_t &int_x, Double_t &int_y) { - - Double_t etax, etay, sum, totquad, sDum[2][2]; - - int corner =calcEta(cluster, etax, etay, sum, totquad, sDum); - - int bin = newEta->findBin(etax,etay); - if (bin<=0) { - int_x=-1; - int_y=-1; - return; - } - double subX = ((double)(newEta->getXBin(bin))+.5)/((double)newEta->getNPixels()); - double subY = ((double)(newEta->getYBin(bin))+.5)/((double)newEta->getNPixels()); - - double dX, dY; - switch (corner) { - case TOP_LEFT: - dX=-1.; - dY=+1.; - break; - case TOP_RIGHT: - dX=+1.; - dY=+1.; - break; - case BOTTOM_LEFT: - dX=-1.; - dY=-1.; - break; - case BOTTOM_RIGHT: - dX=+1.; - dY=-1.; - break; - default: - dX=0; - dY=0; - } - - int_x=((double)x)+ subX+0.5*dX; - int_y=((double)y)+ subY+0.5*dY; - - // cout << corner << " " << subX<< " " << subY << " " << dX << " " << dY << " " << int_x << " " << int_y << endl; - -}; - - -// void interpolation_EtaVEL::Streamer(TBuffer &b){newEta->Streamer(b);}; -void interpolation_EtaVEL::getInterpolatedBin(Double_t *cluster, Int_t &int_x, Int_t &int_y) { - - Double_t etax, etay, sum, totquad, sDum[2][2]; - - int corner =calcEta(cluster, etax, etay, sum, totquad, sDum); - - int bin = newEta->findBin(etax,etay); - if (bin<0) { - int_x=-1; - int_y=-1; - return; - } - int_x=newEta->getXBin(bin); - int_y=newEta->getYBin(bin); - - - -}; - diff --git a/slsDetectorCalibration/interpolations/etaVEL/etaVELInterpolation.h b/slsDetectorCalibration/interpolations/etaVEL/etaVELInterpolation.h deleted file mode 100644 index 8fbacf96d..000000000 --- a/slsDetectorCalibration/interpolations/etaVEL/etaVELInterpolation.h +++ /dev/null @@ -1,55 +0,0 @@ -#ifndef INTERPOLATION_ETAVEL_H -#define INTERPOLATION_ETAVEL_H - -#include -#include "EtaVEL.h" -//#include "TH2F.h" -//#include "EtaVEL.cpp" -//class EtaVEL; - -class etaVELInterpolation: public etaInterpolationBase { - - public: - interpolation_EtaVEL(int nx=40, int ny=160, int ns=25, double etamin=-0.02, double etamax=1.02, int p=0); - ~interpolation_EtaVEL(); - - - //create eta distribution, eta rebinnining etc. - //returns flat field image - void prepareInterpolation(int &ok){prepareInterpolation(ok,10000);}; - void prepareInterpolation(int &ok, int maxit); - - //create interpolated image - //returns interpolated image - - //return position inside the pixel for the given photon - void getInterpolatedPosition(Int_t x, Int_t y, Double_t *data, Double_t &int_x, Double_t &int_y); - void getInterpolatedBin(Double_t *cluster, Int_t &int_x, Int_t &int_y); - - - - int addToFlatField(Double_t *cluster, Double_t &etax, Double_t &etay); - int addToFlatField(Double_t etax, Double_t etay); - int setPlot(int p=-1) {if (p>=0) plot=p; return plot;}; - // int WriteH(){newEta->Write("newEta"); heta->Write("heta");}; - EtaVEL *setEta(EtaVEL *ev){if (ev) {delete newEta; newEta=ev;} return newEta;}; - - - - // TH2F *setEta(TH2F *ev){if (ev) {delete heta; heta=ev;} return heta;}; - void iterate(); - // void DrawH(); - double getChiSq(){return newEta->getChiSq();}; - - - - protected: - EtaVEL *newEta; - // TH2F *heta; - int plot; - - // ClassDefNV(interpolation_EtaVEL,1); - // #pragma link C++ class interpolation_EtaVEL-; -}; - -#endif diff --git a/slsDetectorCalibration/interpolations/linearInterpolation.h b/slsDetectorCalibration/interpolations/linearInterpolation.h deleted file mode 100644 index 605de4c93..000000000 --- a/slsDetectorCalibration/interpolations/linearInterpolation.h +++ /dev/null @@ -1,234 +0,0 @@ -#ifndef LINEAR_INTERPOLATION_H -#define LINEAR_INTERPOLATION_H - -//#include -//#include -//#include - -#include "slsInterpolation.h" - -class linearInterpolation : public slsInterpolation{ - - public: - linearInterpolation(int nx=400, int ny=400, int ns=25) : slsInterpolation(nx,ny,ns) {}; - linearInterpolation(linearInterpolation *orig) : slsInterpolation(orig) {}; - - virtual void prepareInterpolation(int &ok){ok=1;}; - - virtual linearInterpolation* Clone() { - - return new linearInterpolation(this); - - }; - - - ////////////////////////////////////////////////////////////////////////////// - //////////// /*It return position hit for the event in input */ ////////////// - virtual void getInterpolatedPosition(int x, int y, double *data, double &int_x, double &int_y) - { - double sDum[2][2]; - double tot, totquad; - double etax,etay; - - int corner; - corner=calcQuad(data, tot, totquad, sDum); - if (nSubPixels>2) { - calcEta(totquad, sDum, etax, etay); - } - getInterpolatedPosition(x, y, etax,etay, corner, int_x, int_y); - - return; - }; - - virtual void getInterpolatedPosition(int x, int y, int *data, double &int_x, double &int_y) - { - double sDum[2][2]; - double tot, totquad; - double etax,etay; - - int corner; - corner=calcQuad(data, tot, totquad, sDum); - if (nSubPixels>2) - calcEta(totquad, sDum, etax, etay); - getInterpolatedPosition(x,y,etax,etay,corner,int_x,int_y); - - return; - }; - - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,double *cl,double &int_x, double &int_y) { - - double eta_x, eta_y; - if (nSubPixels>2) { - double cc[2][2]; - double *cluster[3]; - cluster[0]=cl; - cluster[1]=cl+3; - cluster[2]=cl+6; - int xoff, yoff; - - switch (quad) { - case BOTTOM_LEFT: - xoff=0; - yoff=0; - break; - case BOTTOM_RIGHT: - xoff=1; - yoff=0; - break; - case TOP_LEFT: - xoff=0; - yoff=1; - break; - case TOP_RIGHT: - xoff=1; - yoff=1; - break; - default: - ; - } - cc[0][0]=cluster[yoff][xoff]; - cc[1][0]=cluster[yoff+1][xoff]; - cc[0][1]=cluster[yoff][xoff+1]; - cc[1][1]=cluster[yoff+1][xoff+1]; - calcEta(totquad,cc,eta_x,eta_y); - } - // cout << x << " " << y << " " << eta_x << " " << eta_y << " " << int_x << " " << int_y << endl; - return getInterpolatedPosition(x,y,eta_x, eta_y,quad,int_x,int_y); - - - - - - - - } - - - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,int *cl,double &int_x, double &int_y) { - - double cc[2][2]; - int *cluster[3]; - int xoff, yoff; - cluster[0]=cl; - cluster[1]=cl+3; - cluster[2]=cl+6; - - switch (quad) { - case BOTTOM_LEFT: - xoff=0; - yoff=0; - break; - case BOTTOM_RIGHT: - xoff=1; - yoff=0; - break; - case TOP_LEFT: - xoff=0; - yoff=1; - break; - case TOP_RIGHT: - xoff=1; - yoff=1; - break; - default: - ; - } - double etax, etay; - if (nSubPixels>2) { - cc[0][0]=cluster[yoff][xoff]; - cc[1][0]=cluster[yoff+1][xoff]; - cc[0][1]=cluster[yoff][xoff+1]; - cc[1][1]=cluster[yoff+1][xoff+1]; - calcEta(totquad,cc,etax,etay); - } - // cout << x << " " << y << " " << etax << " " << etay << " " << int_x << " " << int_y << endl; - return getInterpolatedPosition(x,y,etax, etay,quad,int_x,int_y); - - } - - - - virtual void getInterpolatedPosition(int x, int y, double etax, double etay, int corner, double &int_x, double &int_y) - { - - double xpos_eta,ypos_eta; - double dX,dY; - switch (corner) - { - case TOP_LEFT: - dX=-1.; - dY=0; - break; - case TOP_RIGHT: - dX=0; - dY=0; - break; - case BOTTOM_LEFT: - dX=-1.; - dY=-1.; - break; - case BOTTOM_RIGHT: - dX=0; - dY=-1.; - break; - default: - cout << "bad quadrant" << endl; - dX=0.; - dY=0.; - } - - - if (nSubPixels>2) { - xpos_eta=(etax)+dX; - ypos_eta=(etay)+dY; - } else { - xpos_eta=0.5*dX+0.25; - ypos_eta=0.5*dY+0.25; - } - int_x=((double)x) + xpos_eta; - int_y=((double)y) + ypos_eta; - // cout <<"**"<< x << " " << y << " " << xpos_eta << " " << ypos_eta << " " << corner << endl; - return; - }; - - - - - - - - //////////////////////////////////////////////////////////////////////////////////////////////////////// - virtual void getPositionETA3(int x, int y, double *data, double &int_x, double &int_y) - { - double sDum[2][2]; - double tot, totquad; - double eta3x,eta3y; - - calcQuad(data, tot, totquad, sDum); - calcEta3(data,eta3x, eta3y,tot); - - double xpos_eta,ypos_eta; - - xpos_eta=eta3x; - ypos_eta=eta3y; - - int_x=((double)x) + xpos_eta; - int_y=((double)y) + ypos_eta; - - return; - }; - //////////////////////////////////////////////////////////////////////////////////////////////////////// - - virtual int addToFlatField(double *cluster, double &etax, double &etay){}; - virtual int addToFlatField(int *cluster, double &etax, double &etay){}; - virtual int addToFlatField(double etax, double etay){}; - virtual int addToFlatField(double totquad,int quad,double *cl,double &etax, double &etay) {}; - virtual int addToFlatField(double totquad,int quad,int *cl,double &etax, double &etay) {}; - - protected: - ; - - -}; - -#endif diff --git a/slsDetectorCalibration/interpolations/noInterpolation.h b/slsDetectorCalibration/interpolations/noInterpolation.h deleted file mode 100644 index be072f926..000000000 --- a/slsDetectorCalibration/interpolations/noInterpolation.h +++ /dev/null @@ -1,104 +0,0 @@ -#ifndef NO_INTERPOLATION_H -#define NO_INTERPOLATION_H - -/* #ifdef MYROOT1 */ -/* #include */ -/* #include */ -/* #include */ -/* #include */ -/* #include */ -/* #endif */ - -#include -#include "slsInterpolation.h" - - - -class noInterpolation : public slsInterpolation{ - public: - noInterpolation(int nx=400, int ny=400, int ns=25) : slsInterpolation(nx,ny,ns) {};// {eventGenerator=new TRandom();}; - noInterpolation(noInterpolation *orig) : slsInterpolation(orig){}; - virtual void prepareInterpolation(int &ok){ok=1;}; - - ////////////////////////////////////////////////////////////////////////////// - //////////// /*It return position hit for the event in input */ ////////////// - - virtual noInterpolation* Clone() { - - return new noInterpolation(this); - - }; - - - virtual void getInterpolatedPosition(int x, int y, double *data, double &int_x, double &int_y) - { - //Random coordinate in the Pixel reference - int_x = x + ((double)rand())/((double)RAND_MAX) -0.5;//eventGenerator->Uniform(-0.5,0.5); - int_y = y + ((double)rand())/((double)RAND_MAX) -0.5;//eventGenerator->Uniform(-0.5,0.5); - - return ; - }; - - virtual void getInterpolatedPosition(int x, int y, int *data, double &int_x, double &int_y) - { - return getInterpolatedPosition(x, y, (double*)NULL, int_x, int_y); - } - - - virtual void getInterpolatedPosition(int x, int y, double etax, double etay, int corner, double &int_x, double &int_y) - { - getInterpolatedPosition(x, y, (double*)NULL, int_x, int_y); - }; - - - - - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,double *cl,double &etax, double &etay){ - getInterpolatedPosition(x, y, (double*)NULL, etax, etay); - }; - - - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,int *cl,double &etax, double &etay){ - getInterpolatedPosition(x, y, (double*)NULL, etax, etay); - }; - - - - ////////////////////////////////////////////////////////////////////////////////////// - virtual void getPositionETA3(int x, int y, double *data, double &int_x, double &int_y) - { - //Random coordinate in the Pixel reference - int_x = x + ((double)rand())/((double)RAND_MAX) -0.5;//eventGenerator->Uniform(-0.5,0.5); - int_y = y + ((double)rand())/((double)RAND_MAX) -0.5;//eventGenerator->Uniform(-0.5,0.5); - - return ; - }; - - virtual void getPositionETA3(int x, int y, int *data, double &int_x, double &int_y) - { - return getPositionETA3(x, y, (double*)NULL, int_x, int_y); - }; - - - - ////////////////////////////////////////////////////////////////////////////////////// - virtual int addToFlatField(double *cluster, double &etax, double &etay){return 0;}; - - virtual int addToFlatField(int *cluster, double &etax, double &etay){return 0;}; - - virtual int addToFlatField(double etax, double etay){return 0;}; - - virtual int addToFlatField(double totquad,int quad,double *cl,double &etax, double &etay){return 0;}; - - - virtual int addToFlatField(double totquad,int quad,int *cl,double &etax, double &etay){return 0;}; - - virtual void resetFlatField(){}; - protected: - ; - // TRandom *eventGenerator; - // ClassDefNV(slsInterpolation,1); - // #pragma link C++ class slsInterpolation-; -}; - -#endif diff --git a/slsDetectorCalibration/interpolations/slsInterpolation.h b/slsDetectorCalibration/interpolations/slsInterpolation.h deleted file mode 100644 index 3440d3fe2..000000000 --- a/slsDetectorCalibration/interpolations/slsInterpolation.h +++ /dev/null @@ -1,503 +0,0 @@ -#ifndef SLS_INTERPOLATION_H -#define SLS_INTERPOLATION_H - -#include -#ifndef MY_TIFF_IO_H -#include "tiffIO.h" -#endif - -#ifndef DEF_QUAD -#define DEF_QUAD - enum quadrant { - TOP_LEFT=0, - TOP_RIGHT=1, - BOTTOM_LEFT=2, - BOTTOM_RIGHT=3, - UNDEFINED_QUADRANT=-1 - }; -#endif -#include - -#include -#include -using namespace std; - -//#ifdef MYROOT1 -//: public TObject -//#endif -class slsInterpolation -{ - - public: - slsInterpolation(int nx=400, int ny=400, int ns=25) :nPixelsX(nx), nPixelsY(ny), nSubPixels(ns), id(0) { - - hint=new int[ns*nx*ns*ny]; - -}; - - slsInterpolation(slsInterpolation *orig){ - nPixelsX=orig->nPixelsX; - nPixelsY=orig->nPixelsY; - nSubPixels=orig->nSubPixels; - - hint=new int[nSubPixels*nPixelsX*nSubPixels*nPixelsY]; - memcpy(hint, orig->hint,nSubPixels*nPixelsX*nSubPixels*nPixelsY*sizeof(int)); - - }; - - virtual int setId(int i) {id=i; return id;}; - - virtual slsInterpolation* Clone() =0; /*{ - return new slsInterpolation(this); - }*/ - - int getNSubPixels() {return nSubPixels;}; - - - int setNSubPixels(int ns) { - if (ns>0 && ns!=nSubPixels) { - delete [] hint; - nSubPixels=ns; - hint=new int[nSubPixels*nPixelsX*nSubPixels*nPixelsY]; - } - return nSubPixels; - } - - int getImageSize(int &nnx, int &nny, int &ns) { - nnx=nSubPixels*nPixelsX; - nny=nSubPixels*nPixelsY; - ns=nSubPixels; - return nSubPixels*nSubPixels*nPixelsX*nPixelsY; - }; - - - //create eta distribution, eta rebinnining etc. - //returns flat field image - virtual void prepareInterpolation(int &ok)=0; - - //create interpolated image - //returns interpolated image - virtual int *getInterpolatedImage(){ - // cout << "return interpolated image " << endl; - /* for (int i=0; i=0 && ix<(nPixelsX*nSubPixels) && iy<(nSubPixels*nPixelsY) && iy>=0 ){ - // cout << int_x << " " << int_y << " " << " " << ix << " " << iy << " " << ix+iy*nPixelsX*nSubPixels << " " << hint[ix+iy*nPixelsX*nSubPixels]; - (*(hint+ix+iy*nPixelsX*nSubPixels))+=1; - // cout << " " << hint[ix+iy*nPixelsX*nSubPixels] << endl; - }// else - // cout << "bad! "<< int_x << " " << int_y << " " << " " << ix << " " << iy << " " << ix+iy*nPixelsX*nSubPixels << endl; - - return hint; - }; - - - virtual int addToFlatField(double *cluster, double &etax, double &etay)=0; - virtual int addToFlatField(int *cluster, double &etax, double &etay)=0; - virtual int addToFlatField(double totquad,int quad,int *cl,double &etax, double &etay)=0; - virtual int addToFlatField(double totquad,int quad,double *cluster,double &etax, double &etay)=0; - virtual int addToFlatField(double etax, double etay)=0; - - virtual int *getFlatField(){return NULL;}; - virtual int *setFlatField(int *h, int nb=-1, double emin=-1, double emax=-1){return NULL;}; - virtual void *writeFlatField(const char * imgname){return NULL;}; - virtual void *readFlatField(const char * imgname, int nb=-1, double emin=1, double emax=0){return NULL;}; - virtual int *getFlatField(int &nb, double &emin, double &emax){nb=0; emin=0; emax=0; return getFlatField();}; - - virtual void resetFlatField()=0; - - //virtual void Streamer(TBuffer &b); - - static int calcQuad(int *cl, double &sum, double &totquad, double sDum[2][2]){ - double cli[3*3];//=new int[3*3]; - for (int i=0; i<9; i++) - cli[i]=cl[i]; - return calcQuad(cli, sum, totquad, sDum); - - } - - - static int calcQuad(double *cl, double &sum, double &totquad, double sDum[2][2]){ - - int corner = UNDEFINED_QUADRANT; - /* double *cluster[3]; */ - /* cluster[0]=cl; */ - /* cluster[1]=cl+3; */ - /* cluster[2]=cl+6; */ - - sum=0; - double sumBL=0; - double sumTL=0; - double sumBR=0; - double sumTR=0; - int xoff=0, yoff=0; - for (int ix=0; ix<3; ix++) { - for (int iy=0; iy<3; iy++) { - sum+=cl[ix+3*iy]; - if (ix<=1 && iy<=1) sumBL+=cl[ix+iy*3]; - if (ix<=1 && iy>=1) sumTL+=cl[ix+iy*3]; - if (ix>=1 && iy<=1) sumBR+=cl[ix+iy*3]; - if (ix>=1 && iy>=1) sumTR+=cl[ix+iy*3]; - } - } - - /* sDum[0][0] = cluster[0][0]; sDum[1][0] = cluster[1][0]; */ - /* sDum[0][1] = cluster[0][1]; sDum[1][1] = cluster[1][1]; */ - corner = BOTTOM_LEFT; - totquad=sumBL; - xoff=0; - yoff=0; - - - if(sumTL >= totquad){ - /* sDum[0][0] = cluster[1][0]; sDum[1][0] = cluster[2][0]; */ - /* sDum[0][1] = cluster[1][1]; sDum[1][1] = cluster[2][1]; */ - - corner = TOP_LEFT; - totquad=sumTL; - xoff=0; - yoff=1; - } - - if(sumBR >= totquad){ - /* sDum[0][0] = cluster[0][1]; sDum[1][0] = cluster[1][1]; */ - /* sDum[0][1] = cluster[0][2]; sDum[1][1] = cluster[1][2]; */ - - xoff=1; - yoff=0; - corner = BOTTOM_RIGHT; - totquad=sumBR; - } - - if(sumTR >= totquad){ - xoff=1; - yoff=1; - /* sDum[0][0] = cluster[1][1]; sDum[1][0] = cluster[2][1]; */ - /* sDum[0][1] = cluster[1][2]; sDum[1][1] = cluster[2][2]; */ - corner = TOP_RIGHT; - totquad=sumTR; - } - - - for (int ix=0; ix<2; ix++) { - for (int iy=0; iy<2; iy++) { - sDum[iy][ix] = cl[ix+xoff+(iy+yoff)*3]; - } - } - - return corner; - - } - - static int calcEta(double totquad, double sDum[2][2], double &etax, double &etay){ - double t,r; - - if (totquad>0) { - t = sDum[1][0] + sDum[1][1]; - r = sDum[0][1] + sDum[1][1]; - etax=r/totquad; - etay=t/totquad; - } - return 0; - - } - - static int calcEta(double *cl, double &etax, double &etay, double &sum, double &totquad, double sDum[2][2]) { - int corner = calcQuad(cl,sum,totquad,sDum); - calcEta(totquad, sDum, etax, etay); - - return corner; - } - - - static int calcEta(int *cl, double &etax, double &etay, double &sum, double &totquad, double sDum[2][2]) { - int corner = calcQuad(cl,sum,totquad,sDum); - calcEta(totquad, sDum, etax, etay); - - return corner; - } - - - static int calcEtaL(double totquad, int corner, double sDum[2][2], double &etax, double &etay){ - double t,r, toth, totv; - if (totquad>0) { - switch(corner) { - case TOP_LEFT: - t = sDum[1][1]; - r = sDum[0][1] ; - toth=sDum[0][1]+sDum[0][0]; - totv=sDum[0][1]+sDum[1][1]; - break; - case TOP_RIGHT: - t = sDum[1][0] ; - r = sDum[0][1] ; - toth=sDum[0][1]+sDum[0][0]; - totv=sDum[1][0]+sDum[0][0]; - break; - case BOTTOM_LEFT: - r = sDum[1][1] ; - t = sDum[1][1] ; - toth=sDum[1][0]+sDum[1][1]; - totv=sDum[0][1]+sDum[1][1]; - break; - case BOTTOM_RIGHT: - t = sDum[1][0] ; - r = sDum[1][1] ; - toth=sDum[1][0]+sDum[1][1]; - totv=sDum[1][0]+sDum[0][0]; - break; - default: - etax=-1000; - etay=-1000; - return 0; - } - //etax=r/totquad; - //etay=t/totquad; - etax=r/toth; - etay=t/totv; - } - return 0; - } - - - - static int calcEtaL(double *cl, double &etax, double &etay, double &sum, double &totquad, double sDum[2][2]) { - int corner = calcQuad(cl,sum,totquad,sDum); - calcEtaL(totquad, corner, sDum, etax, etay); - - return corner; - } - - static int calcEtaL(int *cl, double &etax, double &etay, double &sum, double &totquad, double sDum[2][2]) { - int corner = calcQuad(cl,sum,totquad,sDum); - calcEtaL(totquad, corner, sDum, etax, etay); - - return corner; - } - - - - static int calcEtaC3(double *cl, double &etax, double &etay, double &sum, double &totquad, double sDum[2][2]){ - - int corner = calcQuad(cl,sum,totquad,sDum); - calcEta(sum, sDum, etax, etay); - return corner; - - } - - - - static int calcEtaC3(int *cl, double &etax, double &etay, double &sum, double &totquad, double sDum[2][2]){ - - int corner = calcQuad(cl,sum,totquad,sDum); - calcEta(sum, sDum, etax, etay); - return corner; - - } - - - - static int calcEta3(double *cl, double &etax, double &etay, double &sum) { - double l=0,r=0,t=0,b=0, val; - sum=0; - // int quad; - for (int ix=0; ix<3; ix++) { - for (int iy=0; iy<3; iy++) { - val=cl[ix+3*iy]; - sum+=val; - if (iy==0) l+=val; - if (iy==2) r+=val; - if (ix==0) b+=val; - if (ix==2) t+=val; - } - } - if (sum>0) { - etax=(-l+r)/sum; - etay=(-b+t)/sum; - } - /* if (etax<-1 || etax>1 || etay<-1 || etay>1) { */ - /* cout << "**********" << etax << " " << etay << endl; */ - /* for (int ix=0; ix<3; ix++) { */ - /* for (int iy=0; iy<3; iy++) { */ - /* cout << cl[iy+3*ix] << "\t" ; */ - - /* } */ - /* cout << endl; */ - /* } */ - /* cout << sum << " " << l << " " << r << " " << t << " " << b << endl; */ - - /* } */ - - - if (etax>=0 && etay>=0) - return TOP_RIGHT; - if (etax<0 && etay>=0) - return TOP_LEFT; - if (etax<0 && etay<0) - return BOTTOM_LEFT; - return BOTTOM_RIGHT; - } - - - static int calcEta3(int *cl, double &etax, double &etay, double &sum) { - double cli[9]; - for (int ix=0; ix<9; ix++) cli[ix]=cl[ix]; - - return calcEta3(cli, etax, etay, sum); - } - - - /* static int calcMyEta(double totquad, int quad, double *cl, double &etax, double &etay) { */ - /* double l,r,t,b, sum; */ - /* int yoff; */ - /* switch (quad) { */ - /* case BOTTOM_LEFT: */ - /* case BOTTOM_RIGHT: */ - /* yoff=0; */ - /* break; */ - /* case TOP_LEFT: */ - /* case TOP_RIGHT: */ - /* yoff=1; */ - /* break; */ - /* default: */ - /* ; */ - /* } */ - /* l=cl[0+yoff*3]+cl[0+yoff*3+3]; */ - /* r=cl[2+yoff*3]+cl[2+yoff*3+3]; */ - /* b=cl[0+yoff*3]+cl[1+yoff*3]*cl[2+yoff*3]; */ - /* t=cl[0+yoff*3+3]+cl[1+yoff*3+3]*cl[0+yoff*3+3]; */ - /* sum=t+b; */ - /* if (sum>0) { */ - /* etax=(-l+r)/sum; */ - /* etay=(+t)/sum; */ - /* } */ - - /* return -1; */ - /* } */ - - /* static int calcMyEta(double totquad, int quad, int *cl, double &etax, double &etay) { */ - /* double l,r,t,b, sum; */ - /* int yoff; */ - /* switch (quad) { */ - /* case BOTTOM_LEFT: */ - /* case BOTTOM_RIGHT: */ - /* yoff=0; */ - /* break; */ - /* case TOP_LEFT: */ - /* case TOP_RIGHT: */ - /* yoff=1; */ - /* break; */ - /* default: */ - /* ; */ - /* } */ - /* l=cl[0+yoff*3]+cl[0+yoff*3+3]; */ - /* r=cl[2+yoff*3]+cl[2+yoff*3+3]; */ - /* b=cl[0+yoff*3]+cl[1+yoff*3]*cl[2+yoff*3]; */ - /* t=cl[0+yoff*3+3]+cl[1+yoff*3+3]*cl[0+yoff*3+3]; */ - /* sum=t+b; */ - /* if (sum>0) { */ - /* etax=(-l+r)/sum; */ - /* etay=(+t)/sum; */ - /* } */ - - /* return -1; */ - /* } */ - - - - /* static int calcEta3X(double *cl, double &etax, double &etay, double &sum) { */ - /* double l,r,t,b; */ - /* sum=cl[0]+cl[1]+cl[2]+cl[3]+cl[4]+cl[5]+cl[6]+cl[7]+cl[8]; */ - /* if (sum>0) { */ - /* l=cl[3]; */ - /* r=cl[5]; */ - /* b=cl[1]; */ - /* t=cl[7]; */ - /* etax=(-l+r)/sum; */ - /* etay=(-b+t)/sum; */ - /* } */ - /* return -1; */ - /* } */ - - - /* static int calcEta3X(int *cl, double &etax, double &etay, double &sum) { */ - /* double l,r,t,b; */ - /* sum=cl[0]+cl[1]+cl[2]+cl[3]+cl[4]+cl[5]+cl[6]+cl[7]+cl[8]; */ - /* if (sum>0) { */ - /* l=cl[3]; */ - /* r=cl[5]; */ - /* b=cl[1]; */ - /* t=cl[7]; */ - /* etax=(-l+r)/sum; */ - /* etay=(-b+t)/sum; */ - /* } */ - /* return -1; */ - /* } */ - - - - - - - protected: - int nPixelsX, nPixelsY; - int nSubPixels; - int id; - int *hint; -}; - -#endif diff --git a/slsDetectorCalibration/moench03CommonMode.h b/slsDetectorCalibration/moench03CommonMode.h deleted file mode 100644 index 7c950a9e4..000000000 --- a/slsDetectorCalibration/moench03CommonMode.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef MOENCH03COMMONMODE_H -#define MOENCH03COMMONMODE_H - -#include "commonModeSubtraction.h" - -class moench03CommonMode : public commonModeSubtraction { - /** @short class to calculate the common mode noise for moench02 i.e. on 4 supercolumns separately */ - public: - /** constructor - initalizes a commonModeSubtraction with 4 different regions of interest - \param nn number of samples for the moving average - */ - moench03CommonMode(int nn=1000) : commonModeSubtraction(nn,32){} ; - - - /** add value to common mode as a function of the pixel value, subdividing the region of interest in the 4 supercolumns of 40 columns each; - \param val value to add to the common mode - \param ix pixel coordinate in the x direction - \param iy pixel coordinate in the y direction - */ - virtual void addToCommonMode(double val, int ix=0, int iy=0) { - // (void) iy; - int isc=ix/25+(iy/200)*16; - if (isc>=0 && isc=0 && isc0) return cmPed[isc]/nCm[isc]-cmStat[isc].Mean(); - } - return 0; - }; - -}; - - -#endif diff --git a/slsDetectorCalibration/moenchCommonMode.h b/slsDetectorCalibration/moenchCommonMode.h deleted file mode 100644 index dba0df2b7..000000000 --- a/slsDetectorCalibration/moenchCommonMode.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef MOENCHCOMMONMODE_H -#define MOENCHCOMMONMODE_H - -#include "commonModeSubtraction.h" - -class moenchCommonMode : public commonModeSubtraction { - /** @short class to calculate the common mode noise for moench02 i.e. on 4 supercolumns separately */ - public: - /** constructor - initalizes a commonModeSubtraction with 4 different regions of interest - \param nn number of samples for the moving average - */ - moenchCommonMode(int nn=1000) : commonModeSubtraction(nn,4){} ; - - - /** add value to common mode as a function of the pixel value, subdividing the region of interest in the 4 supercolumns of 40 columns each; - \param val value to add to the common mode - \param ix pixel coordinate in the x direction - \param iy pixel coordinate in the y direction - */ - virtual void addToCommonMode(double val, int ix=0, int iy=0) { - (void) iy; - int isc=ix/40; - if (isc>=0 && isc=0 && isc0) return cmPed[isc]/nCm[isc]-cmStat[isc].Mean(); - } - return 0; - }; - -}; - - -#endif diff --git a/slsDetectorCalibration/moenchExecutables/Makefile.cluster_finder b/slsDetectorCalibration/moenchExecutables/Makefile.cluster_finder deleted file mode 100644 index b8414b77f..000000000 --- a/slsDetectorCalibration/moenchExecutables/Makefile.cluster_finder +++ /dev/null @@ -1,39 +0,0 @@ - -CBFLIBDIR= /afs/psi.ch/project/sls_det_software/CBFlib-0.9.5/ -#ZMQLIB=../slsReceiverSoftware/include -#LIBRARYCBF=$(CBFLIBDIR)/lib/*.o -INCDIR=-I. -I../ -I../interpolations -I../interpolations/etaVEL -I../dataStructures -I../../slsReceiverSoftware/include -I$(CBFLIBDIR)/include/ -#LIBHDF5= -LDFLAG= ../tiffIO.cpp -L/usr/lib64/ -lpthread -lm -lstdc++ -L. -pthread -lrt -L$(CBFLIBDIR)/lib/ -ltiff -#-L$(ZMQLIB) -lzmq -#-L../../bin -MAIN=moench03ClusterFinder.cpp -#-lhdf5 -#DESTDIR?=../bin - -all: moenchClusterFinder moenchMakeEta moenchInterpolation moenchNoInterpolation moenchPhotonCounter moenchAnalog - - - -moenchClusterFinder: $(MAIN) $(INCS) clean - g++ -o moenchClusterFinder $(MAIN) $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DSAVE_ALL -DOLDDATA #-DNEWRECEIVER - -moenchMakeEta: moench03MakeEta.cpp $(INCS) clean - g++ -o moenchMakeEta moench03MakeEta.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DSAVE_ALL - -moenchInterpolation: moench03Interpolation.cpp $(INCS) clean - g++ -o moenchInterpolation moench03Interpolation.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DSAVE_ALL - -moenchNoInterpolation: moench03NoInterpolation.cpp $(INCS) clean - g++ -o moenchNoInterpolation moench03NoInterpolation.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DSAVE_ALL - -moenchPhotonCounter: moenchPhotonCounter.cpp $(INCS) clean - g++ -o moenchPhotonCounter moenchPhotonCounter.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DSAVE_ALL -DNEWRECEIVER - -moenchAnalog: moenchPhotonCounter.cpp $(INCS) clean - g++ -o moenchAnalog moenchPhotonCounter.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DSAVE_ALL -DNEWRECEIVER -DANALOG - -clean: - rm -f moenchClusterFinder moenchMakeEta moenchInterpolation moenchNoInterpolation moenchPhotonCounter - - diff --git a/slsDetectorCalibration/moenchExecutables/Makefile.cluster_finder_ra b/slsDetectorCalibration/moenchExecutables/Makefile.cluster_finder_ra deleted file mode 100644 index 2327809f2..000000000 --- a/slsDetectorCalibration/moenchExecutables/Makefile.cluster_finder_ra +++ /dev/null @@ -1,34 +0,0 @@ -#module add CBFlib/0.9.5 -INCDIR=-I. -I../ -I../interpolations -I../interpolations/etaVEL -I../dataStructures -I../../slsReceiverSoftware/include - -LDFLAG= ../tiffIO.cpp -L/usr/lib64/ -lpthread -lm -lstdc++ -pthread -lrt -ltiff -O3 - -MAIN=moench03ClusterFinder.cpp - - -all: moenchClusterFinder moenchMakeEta moenchInterpolation moenchNoInterpolation moenchPhotonCounter moenchAnalog - - - -moenchClusterFinder: moench03ClusterFinder.cpp $(INCS) clean - g++ -o moenchClusterFinder moench03ClusterFinder.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DSAVE_ALL -DNEWRECEIVER - -moenchMakeEta: moench03Interpolation.cpp $(INCS) clean - g++ -o moenchMakeEta moench03Interpolation.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DFF - -moenchInterpolation: moench03Interpolation.cpp $(INCS) clean - g++ -o moenchInterpolation moench03Interpolation.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) - -moenchNoInterpolation: moench03NoInterpolation.cpp $(INCS) clean - g++ -o moenchNoInterpolation moench03NoInterpolation.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) - -moenchPhotonCounter: moenchPhotonCounter.cpp $(INCS) clean - g++ -o moenchPhotonCounter moenchPhotonCounter.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DNEWRECEIVER - -moenchAnalog: moenchPhotonCounter.cpp $(INCS) clean - g++ -o moenchAnalog moenchPhotonCounter.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DNEWRECEIVER -DANALOG - -clean: - rm -f moenchClusterFinder moenchMakeEta moenchInterpolation moenchNoInterpolation moenchPhotonCounter moenchAnalog - - diff --git a/slsDetectorCalibration/moenchExecutables/Makefile.moench b/slsDetectorCalibration/moenchExecutables/Makefile.moench deleted file mode 100644 index b49a76212..000000000 --- a/slsDetectorCalibration/moenchExecutables/Makefile.moench +++ /dev/null @@ -1,20 +0,0 @@ - -CBFLIBDIR=/afs/psi.ch/project/sls_det_software/CBFlib-0.9.5 -LIBRARYCBF=$(CBFLIBDIR)/lib/*.o -INCDIR=-IslsDetectorCalibration -I../slsReceiverSoftware/include -I$(CBFLIBDIR)/include/ -I. -IetaVEL -LIBHDF5=-L$(CBFLIBDIR)/lib/ -lhdf5 -LDFLAG= -L/usr/lib64/ -lpthread -#-L../../bin -MAIN=moench03OnTheFlyAnalysis.C - -#DESTDIR?=../bin - -all: moench03OnTheFlyAnalysis - - - -moench03OnTheFlyAnalysis: $(MAIN) $(INCS) clean - g++ -o moench03OnTheFlyAnalysis $(MAIN) -lm -ltiff -lstdc++ $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DSAVE_ALL - -clean: - rm -f moench03OnTheFlyAnalysis diff --git a/slsDetectorCalibration/moenchExecutables/Makefile.moench_eta b/slsDetectorCalibration/moenchExecutables/Makefile.moench_eta deleted file mode 100644 index 7f575d6cb..000000000 --- a/slsDetectorCalibration/moenchExecutables/Makefile.moench_eta +++ /dev/null @@ -1,23 +0,0 @@ - -CBFLIBDIR= /home/l_msdetect/CBFlib-0.9.5 -ZMQLIB=../slsReceiverSoftware/include -LIBRARYCBF=$(CBFLIBDIR)/lib/*.o -INCDIR=-IslsDetectorCalibration -I../slsReceiverSoftware/include -I$(CBFLIBDIR)/include/ -I. -#-IetaVEL -LIBHDF5= -LDFLAG= -L/usr/lib64/ -lpthread -lm -lstdc++ -L. -lzmq -pthread -lrt -L$(CBFLIBDIR)/lib/ -lhdf5 -ltiff -L$(ZMQLIB) -#-L../../bin -MAIN=moench03ClusterFinder.cpp - -#DESTDIR?=../bin - -all: moench03ClusterFinder - - - -moench03ClusterFinder: $(MAIN) $(INCS) clean - g++ -o moenchClusterFinder $(MAIN) $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) tiffIO.cpp -DSAVE_ALL - -clean: - rm -f moench03ClusterFinder - diff --git a/slsDetectorCalibration/moenchExecutables/Makefile.moench_zmq b/slsDetectorCalibration/moenchExecutables/Makefile.moench_zmq deleted file mode 100644 index c0b8ea708..000000000 --- a/slsDetectorCalibration/moenchExecutables/Makefile.moench_zmq +++ /dev/null @@ -1,32 +0,0 @@ - -CBFLIBDIR=/afs/psi.ch/project/sls_det_software/CBFlib-0.9.5 -ZMQLIB=../../slsReceiverSoftware/include -LIBRARYCBF=$(CBFLIBDIR)/lib/*.o -INCDIR=-I../../slsReceiverSoftware/include -I$(CBFLIBDIR)/include/ -I. -I../dataStructures ../tiffIO.cpp -I../ -I../interpolations/ -LIBHDF5= -#-I../interpolations/etaVEL -LDFLAG= -L/usr/lib64/ -lpthread -lm -lstdc++ -L. -lzmq -pthread -lrt -lhdf5 -ltiff -L$(ZMQLIB) -L$(CBFLIBDIR)/lib/ -O3 -#-L../../bin - -#DESTDIR?=../bin - -aaa: moenchZmqProcess - -all: moenchZmqClusterFinder moenchZmqInterpolating moenchZmqAnalog - -moenchZmqProcess: moenchZmqProcess.cpp $(INCS) clean - g++ -o moenchZmqProcess moenchZmqProcess.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DNEWZMQ - -moenchZmqInterpolating: $(MAIN) $(INCS) clean - g++ -o moenchZmqInterpolating moenchZmqInterpolating.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DSAVE_ALL - -moenchZmqClusterFinder: $(MAIN) $(INCS) clean - g++ -o moenchZmqClusterFinder moenchZmqClusterFinder.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DSAVE_ALL - -moenchZmqAnalog: $(MAIN) $(INCS) clean - g++ -o moenchZmqAnalog moenchZmqAnalog.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DSAVE_ALL - -clean: - rm -f moench03ZmqInterpolating moench03ZmqClusterFinder moenchZmqAnalog moenchZmqProcess - - diff --git a/slsDetectorCalibration/moenchExecutables/Makefile.moench_zmq_rh7 b/slsDetectorCalibration/moenchExecutables/Makefile.moench_zmq_rh7 deleted file mode 100644 index 89c794c17..000000000 --- a/slsDetectorCalibration/moenchExecutables/Makefile.moench_zmq_rh7 +++ /dev/null @@ -1,17 +0,0 @@ - -ZMQLIB=../../slsReceiverSoftware/include -INCDIR= -I$(ZMQLIB) -I. -I../dataStructures ../tiffIO.cpp -I../ -I../interpolations/ -LDFLAG= -L/usr/lib64/ -lpthread -lm -lstdc++ -lzmq -pthread -lrt -ltiff -L$(ZMQLIB) -O3 -g -#-L../../bin -lhdf5 -L. - -#DESTDIR?=../bin - -all: moenchZmqProcess - -moenchZmqProcess: moenchZmqProcess.cpp clean - g++ -o moenchZmqProcess moenchZmqProcess.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DNEWZMQ -DINTERP - -clean: - rm -f moenchZmqProcess - - diff --git a/slsDetectorCalibration/moenchExecutables/Makefile.phoenix b/slsDetectorCalibration/moenchExecutables/Makefile.phoenix deleted file mode 100644 index 7379db1a7..000000000 --- a/slsDetectorCalibration/moenchExecutables/Makefile.phoenix +++ /dev/null @@ -1,24 +0,0 @@ - -CBFLIBDIR= /afs/psi.ch/project/sls_det_software/CBFlib-0.9.5/ -#ZMQLIB=../slsReceiverSoftware/include -LIBRARYCBF=$(CBFLIBDIR)/lib/*.o -INCDIR=-I.. -I. -I../interpolations -I../interpolations/etaVEL -I../../slsReceiverSoftware/include -I$(CBFLIBDIR)/include/ ../tiffIO.cpp -I../dataStructures -#LIBHDF5= -LDFLAG= -L/usr/lib64/ -lpthread -lm -lstdc++ -L. -pthread -lrt -L$(CBFLIBDIR)/lib/ -ltiff -lhdf5 -#-L$(ZMQLIB) -lzmq -#-L../../bin -MAIN=moench03ClusterFinderPhoenix.cpp -# -#DESTDIR?=../bin - -all: moenchClusterFinderPhoenix -#moenchMakeEtaPhoenix moenchInterpolationPhoenix - - - -moenchClusterFinderPhoenix: $(MAIN) $(INCS) clean - g++ -o moenchClusterFinderPhoenix $(MAIN) $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) - -clean: - rm -f moenchClusterFinderPhoenix - diff --git a/slsDetectorCalibration/moenchExecutables/Makefile.reoder_image b/slsDetectorCalibration/moenchExecutables/Makefile.reoder_image deleted file mode 100644 index 2ad256370..000000000 --- a/slsDetectorCalibration/moenchExecutables/Makefile.reoder_image +++ /dev/null @@ -1,22 +0,0 @@ - -CBFLIBDIR= /afs/psi.ch/project/sls_det_software/CBFlib-0.9.5/ -#ZMQLIB=../slsReceiverSoftware/include -INCDIR=-I. -I../ -I../interpolations -I../interpolations/etaVEL -I../dataStructures -I../../slsReceiverSoftware/include -I$(CBFLIBDIR)/include/ -LDFLAG= ../tiffIO.cpp -L/usr/lib64/ -lpthread -lm -lstdc++ -L. -pthread -lrt -L$(CBFLIBDIR)/lib/ -ltiff -MAIN=moench03ReorderImage.cpp - -all: moenchReorderImage moenchClusterFinder - - - -moenchReorderImage: $(MAIN) $(INCS) clean - g++ -o moenchReorderImage $(MAIN) $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DSAVE_ALL -DNEWRECEIVER - -moenchClusterFinder: moench03ClusterFinder.cpp - g++ -o moenchClusterFinder $(MAIN) $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DSAVE_ALL -DNEWRECEIVER - - -clean: - rm -f moenchReorderImage moenchClusterFinder - - diff --git a/slsDetectorCalibration/moenchExecutables/Makefile.tiff_to_th2f b/slsDetectorCalibration/moenchExecutables/Makefile.tiff_to_th2f deleted file mode 100644 index db51710b7..000000000 --- a/slsDetectorCalibration/moenchExecutables/Makefile.tiff_to_th2f +++ /dev/null @@ -1,27 +0,0 @@ -#INCSROOT= receiverGui.h -#INCS= $(INCSROOT) moench03_receiver.h -#LINKDEF=receiverGuiLinkDef.h - -#CBFLIBDIR= /afs/psi.ch/project/sls_det_software/CBFlib-0.9.5/ -#ZMQLIB=../slsReceiverSoftware/include -#LIBRARYCBF=$(CBFLIBDIR)/lib/*.o -INCDIR=-I. -I../ -I../interpolations -I../interpolations/etaVEL -I../dataStructures -I../../slsReceiverSoftware/include -I$(ROOTSYS)/include -#-I$(CBFLIBDIR)/include/ -#LIBHDF5= -LDFLAG= -L/usr/lib64/ -lpthread -lm -lstdc++ -L. -pthread -lrt -ltiff -#-L$(CBFLIBDIR)/lib/ -lhdf5 - -MAIN=tiff_to_th2f.cpp - - -all: tiff_to_th2f - - - -tiff_to_th2f: $(MAIN) $(INCS) - - g++ -o tiff_to_th2f $(MAIN) `root-config --cflags --glibs` -lMinuit -lm -ltiff -lstdc++ $(LDFLAG) $(INCDIR) ../tiffIO.cpp -#$(LIBRARYCBF) $(LIBHDF5) -clean: - rm -f tiff_to_th2f - diff --git a/slsDetectorCalibration/moenchExecutables/moench03ClusterFinder.cpp b/slsDetectorCalibration/moenchExecutables/moench03ClusterFinder.cpp deleted file mode 100644 index d963e8726..000000000 --- a/slsDetectorCalibration/moenchExecutables/moench03ClusterFinder.cpp +++ /dev/null @@ -1,218 +0,0 @@ -//#include "ansi.h" -#include - - -//#include "moench03T1ZmqData.h" -#ifdef NEWRECEIVER -#ifndef RECT -#include "moench03T1ReceiverDataNew.h" -#endif - -#ifdef RECT -#include "moench03T1ReceiverDataNewRect.h" -#endif - -#endif - - -#ifdef CSAXS_FP -#include "moench03T1ReceiverData.h" -#endif -#ifdef OLDDATA -#include "moench03Ctb10GbT1Data.h" -#endif - -// #include "interpolatingDetector.h" -//#include "etaInterpolationPosXY.h" -// #include "linearInterpolation.h" -// #include "noInterpolation.h" -#include "multiThreadedAnalogDetector.h" -#include "singlePhotonDetector.h" -//#include "interpolatingDetector.h" - -#include -#include -#include -#include - -#include -using namespace std; - - -int main(int argc, char *argv[]) { - - - if (argc<6) { - cout << "Usage is " << argv[0] << "indir outdir fname runmin runmax " << endl; - return 1; - } - int p=10000; - int fifosize=1000; - int nthreads=24; - int nsubpix=25; - int etabins=nsubpix*10; - double etamin=-1, etamax=2; - int csize=3; - int nx=400, ny=400; - int save=1; - int nsigma=5; - int nped=1000; - int ndark=100; - int ok; - int iprog=0; - - - - - -#ifdef NEWRECEIVER -#ifdef RECT - cout << "Should be rectangular!" <readPedestals("/scratch/ped_100.tiff"); - // interp->readFlatField("/scratch/eta_100.tiff",etamin,etamax); - // cout << "filter "<< endl; - - - int size = 327680;////atoi(argv[3]); - - int* image; - //int* image =new int[327680/sizeof(int)]; - filter->newDataSet(); - - - int ff, np; - int dsize=decoder->getDataSize(); - cout << " data size is " << dsize; - - - char data[dsize]; - - ifstream filebin; - char *indir=argv[1]; - char *outdir=argv[2]; - char *fformat=argv[3]; - int runmin=atoi(argv[4]); - int runmax=atoi(argv[5]); - - char fname[10000]; - char outfname[10000]; - char imgfname[10000]; - char pedfname[10000]; - // strcpy(pedfname,argv[6]); - char fn[10000]; - - std::time_t end_time; - - FILE *of=NULL; - cout << "input directory is " << indir << endl; - cout << "output directory is " << outdir << endl; - cout << "fileformat is " << fformat << endl; - - - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - - - - - - - - - char* buff; - multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); - - - mt->setDetectorMode(ePhotonCounting); - mt->setFrameMode(eFrame); - mt->StartThreads(); - mt->popFree(buff); - - - cout << "mt " << endl; - - int ifr=0; - - - for (int irun=runmin; irunsetFilePointer(of); - // cout << "file pointer set " << endl; - } else { - cout << "Could not open "<< outfname << " for writing " << endl; - mt->setFilePointer(NULL); - return 1; - } - // //while read frame - ff=-1; - while (decoder->readNextFrame(filebin, ff, np,buff)) { - // cout << "*"<pushData(buff); - // // //pop - mt->nextThread(); - // // // cout << " " << (void*)buff; - mt->popFree(buff); - ifr++; - if (ifr%10000==0) cout << ifr << " " << ff << endl; - ff=-1; - } - cout << "--" << endl; - filebin.close(); - // //close file - // //join threads - while (mt->isBusy()) {;}//wait until all data are processed from the queues - if (of) - fclose(of); - - mt->writeImage(imgfname); - mt->clearImage(); - - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - - } else - cout << "Could not open "<< fname << " for reading " << endl; - - - } - - - return 0; -} - diff --git a/slsDetectorCalibration/moenchExecutables/moench03ClusterFinderPhoenix.cpp b/slsDetectorCalibration/moenchExecutables/moench03ClusterFinderPhoenix.cpp deleted file mode 100644 index 7ae1f4559..000000000 --- a/slsDetectorCalibration/moenchExecutables/moench03ClusterFinderPhoenix.cpp +++ /dev/null @@ -1,201 +0,0 @@ -//#include "ansi.h" -#include - -//#include "moench03T1ZmqData.h" -//#include "moench03T1ReceiverData.h" - -#include "moench03Ctb10GbT1Data.h" - -// #include "interpolatingDetector.h" -//#include "etaInterpolationPosXY.h" -// #include "linearInterpolation.h" -// #include "noInterpolation.h" -#include "multiThreadedAnalogDetector.h" -#include "singlePhotonDetector.h" -//#include "interpolatingDetector.h" - -#include -#include -#include -#include - -#include -using namespace std; - - -int main(int argc, char *argv[]) { - - - if (argc<6) { - cout << "Usage is " << argv[0] << "indir outdir fname runmin runmax " << endl; - return 0; - } - int ii=0; - int p=10000; - int fifosize=1000; - int nthreads=5; - int nsubpix=25; - int etabins=nsubpix*10; - double etamin=-1, etamax=2; - int csize=3; - int nx=400, ny=400; - int save=1; - int nsigma=5; - int nped=1000; - int ndark=100; - int ok; - int iprog=0; - moench03Ctb10GbT1Data *decoder=new moench03Ctb10GbT1Data(); - cout << "decoder" << endl; - //moench03T1ReceiverData *decoder=new moench03T1ReceiverData(); - //moench03T1ZmqData *decoder=new moench03T1ZmqData(); - singlePhotonDetector *filter=new singlePhotonDetector(decoder,csize, nsigma, 1, 0, nped, 100); - // char tit[10000]; - cout << "filter" << endl; - - - - - // filter->readPedestals("/scratch/ped_100.tiff"); - // interp->readFlatField("/scratch/eta_100.tiff",etamin,etamax); - // cout << "filter "<< endl; - - - int size = 327680;////atoi(argv[3]); - - int* image; - //int* image =new int[327680/sizeof(int)]; - filter->newDataSet(); - - cout << "dataset" << endl; - - int ff, np; - int dsize=decoder->getDataSize(); - cout << " data size is " << dsize << endl; - - - char data[dsize]; - - ifstream filebin; - char *indir=argv[1]; - cout << "input directory is " << indir << endl; - char *outdir=argv[2]; - cout << "output directory is " << outdir << endl; - char *fformat=argv[3]; - cout << "fileformat is " << fformat << endl; - int runmin=atoi(argv[4]); - cout << "runmin : " << runmin << endl; - int runmax=atoi(argv[5]); - cout << "runmax : " << runmax << endl; - - char fname[10000]; - char outfname[10000]; - char imgfname[10000]; - char pedfname[10000]; - char fn[10000]; - - std::time_t end_time; - - FILE *of=NULL; - - - cout << "time " << endl; - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - filter->setFrameMode(eFrame); - // mt->setFrameMode(ePedestal); - - - // for (int ix=0; ix<400; ix++) - // for (int iy=0; iy<400; iy++) - // cout << ix << " " << iy << " " << filter->getPedestal(ix,iy) << " " << filter->getPedestalRMS(ix,iy) << endl; - - - char* buff; - cout << "aa " << endl; - multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); - cout << "mt " << endl; - - // mt->setFrameMode(eFrame); //need to find a way to switch between flat and frames! - // mt->prepareInterpolation(ok); - mt->setFrameMode(eFrame); - mt->StartThreads(); - mt->popFree(buff); - - - - int ifr=0; - // //loop on files - // mt->setFrameMode(eFrame); - //mt->setFrameMode(eFlat); - - - - - - for (int irun=runmin; irunsetFilePointer(of); - // cout << "file pointer set " << endl; - } else { - cout << "Could not open "<< outfname << " for writing " << endl; - mt->setFilePointer(NULL); - return 1; - } - // //while read frame - ff=-1; - while (decoder->readNextFrame(filebin, ff, np,buff)) { - //cout << "*"<pushData(buff); - // // //pop - mt->nextThread(); - // // // cout << " " << (void*)buff; - mt->popFree(buff); - - ff=-1; - ii++; - if (ii%10000==0) { - - cout << ii << endl; - - while (mt->isBusy()) {;}//wait until all data are processed from the queues - mt->writeImage("/scratch/tmp.tiff"); - } - } - // cout << "--" << endl; - filebin.close(); - // //close file - // //join threads - while (mt->isBusy()) {;}//wait until all data are processed from the queues - if (of) - fclose(of); - - mt->writeImage(imgfname); - mt->clearImage(); - - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - - } else - cout << "Could not open "<< fname << " for reading " << endl; - - - } - - - return 0; -} - diff --git a/slsDetectorCalibration/moenchExecutables/moench03Interpolation.cpp b/slsDetectorCalibration/moenchExecutables/moench03Interpolation.cpp deleted file mode 100644 index eb4f5db1f..000000000 --- a/slsDetectorCalibration/moenchExecutables/moench03Interpolation.cpp +++ /dev/null @@ -1,249 +0,0 @@ - -#include "ansi.h" -#include - -//#include "moench03T1ZmqData.h" -//#define DOUBLE_SPH -//#define MANYFILES - -#ifdef DOUBLE_SPH -#include "single_photon_hit_double.h" -#endif - -#ifndef DOUBLE_SPH -#include "single_photon_hit.h" -#endif - -//#include "etaInterpolationPosXY.h" -#include "noInterpolation.h" -#include "etaInterpolationCleverAdaptiveBins.h" -//#include "etaInterpolationRandomBins.h" -using namespace std; -#define NC 400 -#define NR 400 -#define MAX_ITERATIONS (nSubPixels*100) - -#define XTALK - -int main(int argc, char *argv[]) { - -#ifndef FF - if (argc<9) { - cout << "Wrong usage! Should be: "<< argv[0] << " infile etafile outfile runmin runmax ns cmin cmax" << endl; - return 1; - } -#endif - -#ifdef FF - if (argc<7) { - cout << "Wrong usage! Should be: "<< argv[0] << " infile etafile runmin runmax cmin cmax" << endl; - return 1; - } -#endif - int iarg=4; - char infname[10000]; - char fname[10000]; - char outfname[10000]; -#ifndef FF - iarg=4; -#endif - -#ifdef FF - iarg=3; -#endif - int runmin=atoi(argv[iarg++]); - int runmax=atoi(argv[iarg++]); - cout << "Run min: " << runmin << endl; - cout << "Run max: " << runmax << endl; - - int nsubpix=4; -#ifndef FF - nsubpix=atoi(argv[iarg++]); - cout << "Subpix: " << nsubpix << endl; -#endif - float cmin=atof(argv[iarg++]); - float cmax=atof(argv[iarg++]); - cout << "Energy min: " << cmin << endl; - cout << "Energy max: " << cmax << endl; - //int etabins=500; - int etabins=1000;//nsubpix*2*100; - double etamin=-1, etamax=2; - //double etamin=-0.1, etamax=1.1; - double eta3min=-2, eta3max=2; - int quad; - double sum, totquad; - double sDum[2][2]; - double etax, etay, int_x, int_y; - double eta3x, eta3y, int3_x, int3_y, noint_x, noint_y; - int ok; - int f0=-1; - int ix, iy, isx, isy; - int nframes=0, lastframe=-1; - double d_x, d_y, res=5, xx, yy; - int nph=0, badph=0, totph=0; - FILE *f=NULL; - -#ifdef DOUBLE_SPH - single_photon_hit_double cl(3,3); -#endif - -#ifndef DOUBLE_SPH - single_photon_hit cl(3,3); -#endif - - int nSubPixels=nsubpix; -#ifndef NOINTERPOLATION - eta2InterpolationPosXY *interp=new eta2InterpolationPosXY(NC, NR, nsubpix, etabins, etamin, etamax); - //eta2InterpolationCleverAdaptiveBins *interp=new eta2InterpolationCleverAdaptiveBins(NC, NR, nsubpix, etabins, etamin, etamax); -#endif -#ifdef NOINTERPOLATION - noInterpolation *interp=new noInterpolation(NC, NR, nsubpix); -#endif - - - -#ifndef FF -#ifndef NOINTERPOLATION - cout << "read ff " << argv[2] << endl; - sprintf(fname,"%s",argv[2]); - interp->readFlatField(fname); - interp->prepareInterpolation(ok);//, MAX_ITERATIONS); -#endif - // return 0; -#endif -#ifdef FF - cout << "Will write eta file " << argv[2] << endl; -#endif - - int *img; - float *totimg=new float[NC*NR*nsubpix*nsubpix]; - for (ix=0; ixcalcQuad(cl.get_cluster(), sum, totquad, sDum); - quad=interp->calcEta(cl.get_cluster(), etax, etay, sum, totquad, sDum); - if (sum>cmin && totquad/sum>0.8 && totquad/sum<1.2 && sum200 && sum<580) { - // interp->getInterpolatedPosition(cl.x,cl.y, totquad,quad,cl.get_cluster(),int_x, int_y); -// #ifdef SOLEIL -// if (cl.x>210 && cl.x<240 && cl.y>210 && cl.y<240) { -// #endif -#ifndef FF - // interp->getInterpolatedPosition(cl.x,cl.y, cl.get_cluster(),int_x, int_y); - interp->getInterpolatedPosition(cl.x,cl.y, etax, etay, quad,int_x, int_y); - // cout <<"**************"<< endl; - // cout << cl.x << " " << cl.y << " " << sum << endl; - // cl.print(); - // cout << int_x << " " << int_y << endl; - // cout <<"**************"<< endl; - // if (etax!=0 && etay!=0 && etax!=1 && etay!=1) - interp->addToImage(int_x, int_y); - if (int_x<0 || int_y<0 || int_x>400 || int_y>400) { - cout <<"**************"<< endl; - cout << cl.x << " " << cl.y << " " << sum << endl; - cl.print(); - cout << int_x << " " << int_y << endl; - cout <<"**************"<< endl; - } -#endif -#ifdef FF - // interp->addToFlatField(cl.get_cluster(), etax, etay); -// #ifdef UCL -// if (cl.x>50) -// #endif -// if (etax!=0 && etay!=0 && etax!=1 && etay!=1) - interp->addToFlatField(etax, etay); - // if (etax==0 || etay==0) cout << cl.x << " " << cl.y << endl; - -#endif -// #ifdef SOLEIL -// } -// #endif - - if (nph%1000000==0) cout << nph << endl; - if (nph%10000000==0) { -#ifndef FF - interp->writeInterpolatedImage(outfname); -#endif -#ifdef FF - interp->writeFlatField(outfname); -#endif - - } - } - - } - - - fclose(f); -#ifdef FF - interp->writeFlatField(outfname); -#endif - -#ifndef FF - interp->writeInterpolatedImage(outfname); - - img=interp->getInterpolatedImage(); - for (ix=0; ixwriteFlatField(outfname); -#endif - - cout << "Filled " << nph << " (/"<< totph <<") " << endl; - return 0; -} - diff --git a/slsDetectorCalibration/moenchExecutables/moench03InterpolationColor.cpp b/slsDetectorCalibration/moenchExecutables/moench03InterpolationColor.cpp deleted file mode 100644 index 2adae43fe..000000000 --- a/slsDetectorCalibration/moenchExecutables/moench03InterpolationColor.cpp +++ /dev/null @@ -1,269 +0,0 @@ - -#include "ansi.h" -#include - -//#include "moench03T1ZmqData.h" -//#define DOUBLE_SPH -//#define MANYFILES - -#ifdef DOUBLE_SPH -#include "single_photon_hit_double.h" -#endif - -#ifndef DOUBLE_SPH -#include "single_photon_hit.h" -#endif - -//#include "etaInterpolationPosXY.h" -#include "noInterpolation.h" -#include "etaInterpolationCleverAdaptiveBins.h" -//#include "etaInterpolationRandomBins.h" -using namespace std; -#define NC 400 -#define NR 400 -#define MAX_ITERATIONS (nSubPixels*100) -#define MAX_EBINS 100 -#define XTALK - -int main(int argc, char *argv[]) { - -#ifndef FF - if (argc<9) { - cout << "Wrong usage! Should be: "<< argv[0] << " infile etafile outfile runmin runmax ns cmin cmax" << endl; - return 1; - } -#endif - -#ifdef FF - if (argc<7) { - cout << "Wrong usage! Should be: "<< argv[0] << " infile etafile runmin runmax cmin cmax" << endl; - return 1; - } -#endif - int iarg=4; - char infname[10000]; - char fname[10000]; - char outfname[10000]; -#ifndef FF - iarg=4; -#endif - -#ifdef FF - iarg=3; -#endif - int runmin=atoi(argv[iarg++]); - int runmax=atoi(argv[iarg++]); - cout << "Run min: " << runmin << endl; - cout << "Run max: " << runmax << endl; - - int nsubpix=4; -#ifndef FF - nsubpix=atoi(argv[iarg++]); - cout << "Subpix: " << nsubpix << endl; -#endif - float cmin=atof(argv[iarg++]); - float cmax=atof(argv[iarg++]); - cout << "Energy min: " << cmin << endl; - cout << "Energy max: " << cmax << endl; - int n_ebins=1; - if (argc>iarg) - n_ebins=atoi(argv[iarg++]); - //int etabins=500; - int etabins=1000;//nsubpix*2*100; - double etamin=-1, etamax=2; - //double etamin=-0.1, etamax=1.1; - double eta3min=-2, eta3max=2; - int quad; - double sum, totquad; - double sDum[2][2]; - double etax, etay, int_x, int_y; - double eta3x, eta3y, int3_x, int3_y, noint_x, noint_y; - int ok; - int f0=-1; - int ix, iy, isx, isy; - int nframes=0, lastframe=-1; - double d_x, d_y, res=5, xx, yy; - int nph=0, badph=0, totph=0; - FILE *f=NULL; - -#ifdef DOUBLE_SPH - single_photon_hit_double cl(3,3); -#endif - -#ifndef DOUBLE_SPH - single_photon_hit cl(3,3); -#endif - - int nSubPixels=nsubpix; - - int iebin=0; - double eb_size=(cmax-cmin)/n_ebins; -#ifndef NOINTERPOLATION - // eta2InterpolationPosXY *interp[MAX_EBINS]; - eta2InterpolationCleverAdaptiveBins *interp[MAX_EBINS]; - for (int i=0; i< n_ebins; i++) { - //interp[i]=new eta2InterpolationPosXY(NC, NR, nsubpix, etabins, etamin, etamax); - interp[i]=new eta2InterpolationCleverAdaptiveBins(NC, NR, nsubpix, etabins, etamin, etamax); - } -#endif -#ifdef NOINTERPOLATION - noInterpolation *interp=new noInterpolation(NC, NR, nsubpix); -#endif - - - -#ifndef FF -#ifndef NOINTERPOLATION - cout << "read ff " << argv[2] << endl; - for (int i=0; i< n_ebins; i++) { - sprintf(fname,argv[2],i); - interp[i]->readFlatField(fname); - interp[i]->prepareInterpolation(ok);//, MAX_ITERATIONS); - } -#endif - // return 0; -#endif -#ifdef FF - cout << "Will write eta file " << argv[2] << endl; -#endif - - int *img; - float *totimg=new float[NC*NR*nsubpix*nsubpix]; - for (ix=0; ixcalcQuad(cl.get_cluster(), sum, totquad, sDum); - quad=interp[0]->calcEta(cl.get_cluster(), etax, etay, sum, totquad, sDum); - if (sum>cmin && totquad/sum>0.8 && totquad/sum<1.2 && sum=0 && iebin200 && sum<580) { - // interp->getInterpolatedPosition(cl.x,cl.y, totquad,quad,cl.get_cluster(),int_x, int_y); -// #ifdef SOLEIL -// if (cl.x>210 && cl.x<240 && cl.y>210 && cl.y<240) { -// #endif -#ifndef FF - // interp->getInterpolatedPosition(cl.x,cl.y, cl.get_cluster(),int_x, int_y); - interp[iebin]->getInterpolatedPosition(cl.x,cl.y, etax, etay, quad,int_x, int_y); - // cout <<"**************"<< endl; - // cout << cl.x << " " << cl.y << " " << sum << endl; - // cl.print(); - // cout << int_x << " " << int_y << endl; - // cout <<"**************"<< endl; - if (etax!=0 && etay!=0 && etax!=1 && etay!=1) - interp[iebin]->addToImage(int_x, int_y); -#endif -#ifdef FF - // interp->addToFlatField(cl.get_cluster(), etax, etay); -#ifdef UCL - if (cl.x>50) -#endif - if (etax!=0 && etay!=0 && etax!=1 && etay!=1) - interp[iebin]->addToFlatField(etax, etay); - // if (etax==0 || etay==0) cout << cl.x << " " << cl.y << endl; - -#endif -// #ifdef SOLEIL -// } -// #endif - - if (nph%1000000==0) cout << nph << endl; - if (nph%10000000==0) { -#ifndef FF - for (int i=0; iwriteInterpolatedImage(outfname); - } -#endif -#ifdef FF - for (int i=0; iwriteFlatField(outfname); - } -#endif - - } - } - - } - - } - fclose(f); -#ifdef FF - for (int i=0; iwriteFlatField(outfname); - } -#endif - -#ifndef FF - for (int i=0; iwriteInterpolatedImage(outfname); - img=interp[i]->getInterpolatedImage(); - for (ix=0; ixclearInterpolatedImage(); - } - cout << "Read " << nframes << " frames (first frame: " << f0 << " last frame: " << lastframe << " delta:" << lastframe-f0 << ")"<writeFlatField(outfname); -#endif - - cout << "Filled " << nph << " (/"<< totph <<") " << endl; - return 0; -} - diff --git a/slsDetectorCalibration/moenchExecutables/moench03MakeEta.cpp b/slsDetectorCalibration/moenchExecutables/moench03MakeEta.cpp deleted file mode 100644 index c2f2f92cd..000000000 --- a/slsDetectorCalibration/moenchExecutables/moench03MakeEta.cpp +++ /dev/null @@ -1,114 +0,0 @@ - -#include "ansi.h" -#include - -#include "moench03T1ZmqData.h" -#include "single_photon_hit.h" - - #include "etaInterpolationPosXY.h" - -using namespace std; -#define NC 400 -#define NR 400 - -#define XTALK - -int main(int argc, char *argv[]) { -/** - * trial.o [socket ip] [starting port number] [outfname] - * - */ - int nsubpix=10; - int etabins=nsubpix*100; - double etamin=-1, etamax=2; - double eta3min=-2, eta3max=2; - int quad; - double sum, totquad; - double sDum[2][2]; - char fname[10000]; - double etax, etay; - int runmin, runmax; - single_photon_hit cl(3,3); -int iph=0; - - if (argc<7) { - cout << "Wrong usage! Should be: "<< argv[0] << " infile " << " outfile runmin runmax cmin cmax" << endl; - return 1; - } - - eta2InterpolationPosXY *interp2=new eta2InterpolationPosXY(NR, NC, nsubpix, etabins, etamin, etamax); - cout << "###########"<< endl; - eta3InterpolationPosXY *interp3=new eta3InterpolationPosXY(NR, NC, nsubpix, etabins, eta3min, eta3max); - // cout << eta3min << " " << eta3max << endl; - runmin=atoi(argv[3]); - runmax=atoi(argv[4]); - double cmin=atof(argv[5]); //200 - double cmax=atof(argv[6]); //3000 - -#ifdef XTALK - int old_val[3][3]; - int new_val[3][3]; - double xcorr=0.04; - - // int ix=0; -#endif - - FILE *f; - for (int i=runmin; i=0) { - new_val[iy+1][ix+1]=old_val[iy+1][ix+1]-old_val[iy+1][ix]*xcorr; - cl.set_data(new_val[iy+1][ix+1],ix,iy); - } - } - } - } -#endif - quad=interp2->calcQuad(cl.get_cluster(), sum, totquad, sDum); - - if (sum>cmin && totquad/sum>0.8 && totquad/sum<1.2 && totquadaddToFlatField(cl.get_cluster(),etax, etay); - // if (etax>0.49 && etax<0.51 && etay>0.49 && etay<0.51 ) { - // cout << cl.y << " " << cl.x << " " << quad << " "<< totquad << " " <addToFlatField(cl.get_cluster(),etax, etay); - iph++; - if (iph%1000000==0) cout << iph << endl; - if (iph%100000000==0) { - sprintf(fname,"%s_eta2.tiff",argv[2]); - interp2->writeFlatField(fname); - sprintf(fname,"%s_eta3.tiff",argv[2]); - interp3->writeFlatField(fname); - } - // if (iph>1E8) break; - } - // } - - } - fclose(f); - - } - else cout << "could not open file " << fname << endl; - } - - sprintf(fname,"%s_eta2.tiff",argv[2]); - interp2->writeFlatField(fname); - sprintf(fname,"%s_eta3.tiff",argv[2]); - interp3->writeFlatField(fname); - return 0; -} - diff --git a/slsDetectorCalibration/moenchExecutables/moench03NoInterpolation.cpp b/slsDetectorCalibration/moenchExecutables/moench03NoInterpolation.cpp deleted file mode 100644 index 9ff0ea900..000000000 --- a/slsDetectorCalibration/moenchExecutables/moench03NoInterpolation.cpp +++ /dev/null @@ -1,171 +0,0 @@ - -#include "ansi.h" -#include - -#include "moench03T1ZmqData.h" -#include "single_photon_hit.h" - -#include "noInterpolation.h" - -using namespace std; -#define NC 400 -#define NR 400 - - -int main(int argc, char *argv[]) { -/** - * trial.o [socket ip] [starting port number] [outfname] - * - */ - - if (argc<7) { - cout << "Wrong usage! Should be: "<< argv[0] << " infile " << " etafile outfile runmin runmax ns" << endl; - return 1; - } - - char infname[10000]; - char outfname[10000]; - int runmin=atoi(argv[4]); - int runmax=atoi(argv[5]); - int nsubpix=atoi(argv[6]); - - int etabins=1000;//nsubpix*2*100; - double etamin=-1, etamax=2; - int quad; - double sum, totquad; - double sDum[2][2]; - double etax, etay, int_x, int_y; - int ok; - - int ix, iy, isx, isy; - - - FILE *f=NULL; - - single_photon_hit cl(3,3); - // etaInterpolationPosXY *interp=new etaInterpolationPosXY(NC, NR, nsubpix, etabins, etamin, etamax); - noInterpolation *interp=new noInterpolation(NC, NR, nsubpix); - // interp->readFlatField(argv[2]); - // interp->prepareInterpolation(ok); - - int *img; - float *totimg=new float[NC*NR*nsubpix*nsubpix]; - for (ix=0; ixcalcQuad(cl.get_cluster(), sum, totquad, sDum); - if (sum>200 && sum<580) { - interp->getInterpolatedPosition(cl.x,cl.y, totquad,quad,cl.get_cluster(),int_x, int_y); - interp->addToImage(int_x, int_y); - } - } - fclose(f); -#ifdef FF - img=interp->getInterpolatedImage(); - for (isx=0; isxwriteInterpolatedImage(outfname); - img=interp->getInterpolatedImage(); - for (ix=0; ixclearInterpolatedImage(); - - } - } - - sprintf(outfname,argv[3],11111); - WriteToTiff(totimg, outfname,NC*nsubpix,NR*nsubpix); - - return 0; -} - diff --git a/slsDetectorCalibration/moenchExecutables/moench03ReorderImage.cpp b/slsDetectorCalibration/moenchExecutables/moench03ReorderImage.cpp deleted file mode 100644 index 69b9b20c8..000000000 --- a/slsDetectorCalibration/moenchExecutables/moench03ReorderImage.cpp +++ /dev/null @@ -1,163 +0,0 @@ -//#include "ansi.h" -#include - - - -//#include "moench03T1ZmqData.h" - -#include "moench03T1ReceiverDataNew.h" - -// #include "interpolatingDetector.h" -//#include "etaInterpolationPosXY.h" -// #include "linearInterpolation.h" -// #include "noInterpolation.h" -//#include "interpolatingDetector.h" - -#include -#include -#include -#include - -#include - -#include -using namespace std; - -#define NX 400 //number of x pixels -#define NY 400 //number of y pixels - -int main(int argc, char *argv[]) { - - - if (argc<6) { - cout << "Usage is " << argv[0] << "indir outdir fname runmin runmax " << endl; - return 1; - } - int p=10000; - int fifosize=1000; - int nthreads=8; - int nsubpix=25; - int etabins=nsubpix*10; - double etamin=-1, etamax=2; - int csize=3; - int nx=400, ny=400; - int save=1; - int nsigma=5; - int nped=1000; - int ndark=100; - int ok; - int iprog=0; - - - - - moench03T1ReceiverDataNew *decoder=new moench03T1ReceiverDataNew(); - - - uint16_t data[NY*NX]; - - - int size = 327680;////atoi(argv[3]); - - int* image; - - int ff, np; - int dsize=decoder->getDataSize(); - - - //char data[dsize]; - - ifstream filebin; - char *indir=argv[1]; - char *outdir=argv[2]; - char *fformat=argv[3]; - int runmin=atoi(argv[4]); - int runmax=atoi(argv[5]); - - char fname[10000]; - char outfname[10000]; - char imgfname[10000]; - char pedfname[10000]; - // strcpy(pedfname,argv[6]); - char fn[10000]; - - std::time_t end_time; - - FILE *of=NULL; - cout << "input directory is " << indir << endl; - cout << "output directory is " << outdir << endl; - cout << "fileformat is " << fformat << endl; - - - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - - - - - - - - char* buff; - - - - - int ifr=0; - - - for (int irun=runmin; irunreadNextFrame(filebin, ff, np,buff)) { - for (int ix=0; ix<400; ix++) - for (int iy=0; iy<400; iy++) - data[iy*NX+ix]=decoder->getChannel(buff,ix,iy); - - ifr++; - - fwrite(&ff, 8, 1,of);//write detector frame number - fwrite(&ifr, 8, 1,of);//write datset frame number - fwrite(data,2,NX*NY,of);//write reordered data - - if (ifr%10000==0) cout << ifr << " " << ff << endl; - ff=-1; - - } - cout << "--" << endl; - filebin.close(); - // //close file - // //join threads - - if (of) - fclose(of); - - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - - } else - cout << "Could not open "<< fname << " for reading " << endl; - - - } - - - return 0; -} - diff --git a/slsDetectorCalibration/moenchExecutables/moenchAnalog.cpp b/slsDetectorCalibration/moenchExecutables/moenchAnalog.cpp deleted file mode 100644 index a6f65649c..000000000 --- a/slsDetectorCalibration/moenchExecutables/moenchAnalog.cpp +++ /dev/null @@ -1,242 +0,0 @@ -//#include "ansi.h" -#include - - - -//#include "moench03T1ZmqData.h" -#ifdef NEWRECEIVER -#include "moench03T1ReceiverDataNew.h" -#endif -#ifdef CSAXS_FP -#include "moench03T1ReceiverData.h" -#endif -#ifdef OLDDATA -#include "moench03Ctb10GbT1Data.h" -#endif - -// #include "interpolatingDetector.h" -//#include "etaInterpolationPosXY.h" -// #include "linearInterpolation.h" -// #include "noInterpolation.h" -#include "multiThreadedAnalogDetector.h" -#include "singlePhotonDetector.h" -//#include "interpolatingDetector.h" - -#include -#include -#include -#include - -#include -using namespace std; - - -int main(int argc, char *argv[]) { - - - if (argc<4) { - cout << "Usage is " << argv[0] << "indir outdir fname [pedfile] [threshold]" << endl; - return 1; - } - int p=10000; - int fifosize=1000; - int nthreads=8; - int nsubpix=25; - int etabins=nsubpix*10; - double etamin=-1, etamax=2; - int csize=3; - int nx=400, ny=400; - int save=1; - int nsigma=5; - int nped=1000; - int ndark=100; - int ok; - int iprog=0; - - - -#ifdef NEWRECEIVER - moench03T1ReceiverDataNew *decoder=new moench03T1ReceiverDataNew(); - cout << "RECEIVER DATA WITH ONE HEADER!"< *filter=new analogDetector(decoder, 1, 0, nped); - // char tit[10000]; - cout << "filter " << endl; -#endif - - - - // filter->readPedestals("/scratch/ped_100.tiff"); - // interp->readFlatField("/scratch/eta_100.tiff",etamin,etamax); - // cout << "filter "<< endl; - - - int size = 327680;////atoi(argv[3]); - - int* image; - //int* image =new int[327680/sizeof(int)]; - filter->newDataSet(); - - - int ff, np; - int dsize=decoder->getDataSize(); - cout << " data size is " << dsize; - - - char data[dsize]; - - ifstream filebin; - char *indir=argv[1]; - char *outdir=argv[2]; - char *fformat=argv[3]; - char *pedfile=NULL; - if (argc>=5) { - pedfile=argv[4]; - } - double thr=0; - if (argc>=6) { - thr=atoi(argv[5]); - } - - - char fname[10000]; - char imgfname[10000]; - // strcpy(pedfname,argv[6]); - char fn[10000]; - - std::time_t end_time; - - FILE *of=NULL; - cout << "input directory is " << indir << endl; - cout << "output directory is " << outdir << endl; - cout << "input file is " << fformat << endl; - if (pedfile) - cout << "pedestal file is " << pedfile << endl; - if (thr>0) { - cout << "threshold is " << thr << endl; - filter->setThreshold(thr); - } - - filter->setROI(0,150,0,150); - - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - - - - - - - - - char* buff; - multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); - - - mt->StartThreads(); - mt->popFree(buff); - - - cout << "mt " << endl; - - int ifr=0; - - - - - - - - - - - for (int irun=0; irun<2; irun++) { - if (irun>0) { - mt->setFrameMode(eFrame); - // sprintf(fn,fformat,irun); - sprintf(fname,"%s/%s.raw",indir,fformat); - // sprintf(outfname,"%s/%s.clust",outdir,fn); - sprintf(imgfname,"%s/%s.tiff",outdir,fformat); - } else { - mt->setFrameMode(ePedestal); - // sprintf(fn,fformat,irun); - sprintf(fname,"%s/%s.raw",indir,pedfile); - // sprintf(outfname,"%s/%s.clust",outdir,fn); - // sprintf(imgfname,"%s/%s.tiff",outdir,fn); - } - cout << fname << endl; - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - // cout << fname << " " << outfname << " " << imgfname << endl; - filebin.open((const char *)(fname), ios::in | ios::binary); - // //open file - if (filebin.is_open()){ - // of=fopen(outfname,"w"); - // if (of) { - // mt->setFilePointer(of); - // // cout << "file pointer set " << endl; - // } else { - // cout << "Could not open "<< outfname << " for writing " << endl; - // mt->setFilePointer(NULL); - // return 1; - // } - // //while read frame - ff=-1; - while (decoder->readNextFrame(filebin, ff, np,buff)) { - // cout << "*"<pushData(buff); - // // //pop - mt->nextThread(); - // // // cout << " " << (void*)buff; - mt->popFree(buff); - ifr++; - if (ifr%10000==0) cout << ifr << " " << ff << endl; - ff=-1; - } - cout << "--" << endl; - filebin.close(); - // //close file - // //join threads - while (mt->isBusy()) {;}//wait until all data are processed from the queues - // if (of) - // fclose(of); - if (irun>0) { - cout << "Writing tiff to " << imgfname << endl; - mt->writeImage(imgfname); - // mt->clearImage(); - } - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - - } else - cout << "Could not open "<< fname << " for reading " << endl; - - - } - - - return 0; -} - diff --git a/slsDetectorCalibration/moenchExecutables/moenchPhotonCounter.cpp b/slsDetectorCalibration/moenchExecutables/moenchPhotonCounter.cpp deleted file mode 100644 index 342f56a28..000000000 --- a/slsDetectorCalibration/moenchExecutables/moenchPhotonCounter.cpp +++ /dev/null @@ -1,347 +0,0 @@ -//#include "ansi.h" -#include - - - -//#include "moench03T1ZmqData.h" -#ifdef NEWRECEIVER -#ifndef RECT -#include "moench03T1ReceiverDataNew.h" -#endif - -#ifdef RECT -#include "moench03T1ReceiverDataNewRect.h" -#endif - -#endif - - -#ifdef CSAXS_FP -#include "moench03T1ReceiverData.h" -#endif -#ifdef OLDDATA -#include "moench03Ctb10GbT1Data.h" -#endif - -// #include "interpolatingDetector.h" -//#include "etaInterpolationPosXY.h" -// #include "linearInterpolation.h" -// #include "noInterpolation.h" -#include "multiThreadedAnalogDetector.h" -#include "singlePhotonDetector.h" -//#include "interpolatingDetector.h" - -#include -#include -#include -#include - -#include -using namespace std; - - -int main(int argc, char *argv[]) { - - - if (argc<4) { - cout << "Usage is " << argv[0] << "indir outdir fname [runmin] [runmax] [pedfile] [threshold] [nframes] [xmin xmax ymin ymax]" << endl; - cout << "threshold <0 means analog; threshold=0 means cluster finder; threshold>0 means photon counting" << endl; - cout << "nframes <0 means sum everything; nframes=0 means one file per run; nframes>0 means one file every nframes" << endl; - return 1; - } - - int p=10000; - int fifosize=1000; - int nthreads=8; - int nsubpix=25; - int etabins=nsubpix*10; - double etamin=-1, etamax=2; - int csize=3; - int save=1; - int nsigma=5; - int nped=1000; - int ndark=100; - int ok; - int iprog=0; - - int cf=0; - -#ifdef NEWRECEIVER -#ifdef RECT - cout << "Should be rectangular!" <getDetectorSize(nx,ny); - - singlePhotonDetector *filter=new singlePhotonDetector(decoder,csize, nsigma, 1, 0, nped, 200); - - int size = 327680;////atoi(argv[3]); - - int* image; - //int* image =new int[327680/sizeof(int)]; - filter->newDataSet(); - - - int ff, np; - int dsize=decoder->getDataSize(); - //cout << " data size is " << dsize; - - - char data[dsize]; - - ifstream filebin; - char *indir=argv[1]; - char *outdir=argv[2]; - char *fformat=argv[3]; - int runmin=0; - - // cout << "argc is " << argc << endl; - if (argc>=5) { - runmin=atoi(argv[4]); - } - - int runmax=runmin; - - if (argc>=6) { - runmax=atoi(argv[5]); - } - - char *pedfile=NULL; - if (argc>=7) { - pedfile=argv[6]; - } - double thr=0; - double thr1=1; - - if (argc>=8) { - thr=atoi(argv[7]); - } - - - int nframes=0; - - if (argc>=9) { - nframes=atoi(argv[8]); - } - int xmin=0, xmax=nx, ymin=0, ymax=ny; - if (argc>=13) { - xmin=atoi(argv[9]); - xmax=atoi(argv[10]); - ymin=atoi(argv[11]); - ymax=atoi(argv[12]); - } - - - - - - char ffname[10000]; - char fname[10000]; - char imgfname[10000]; - char cfname[10000]; - char fn[10000]; - - std::time_t end_time; - - FILE *of=NULL; - cout << "input directory is " << indir << endl; - cout << "output directory is " << outdir << endl; - cout << "input file is " << fformat << endl; - cout << "runmin is " << runmin << endl; - cout << "runmax is " << runmax << endl; - if (pedfile) - cout << "pedestal file is " << pedfile << endl; - //#ifndef ANALOG - if (thr>0) { - cout << "threshold is " << thr << endl; - filter->setThreshold(thr); - } else - cf=1; - //#endif - - - filter->setROI(xmin,xmax,ymin,ymax); -#ifdef SOLEIL - filter->setROI(150,210,170,230); - nframes=-1; -#endif - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - - char* buff; - multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); -#ifndef ANALOG - mt->setDetectorMode(ePhotonCounting); - cout << "Counting!" << endl; - if (thr>0) { - cf=0; - } -#endif -//{ -#ifdef ANALOG - mt->setDetectorMode(eAnalog); - cout << "Analog!" << endl; - cf=0; -// #ifdef ANALOG -// thr1=thr; -#endif - // } - - mt->StartThreads(); - mt->popFree(buff); - - - // cout << "mt " << endl; - - int ifr=0; - - - - - if (pedfile) { - cout << "PEDESTAL " ; - sprintf(fname,"%s.raw",pedfile); - cout << fname << endl ; - sprintf(imgfname,"%s/pedestals.tiff",outdir,fformat); - std::time(&end_time); - cout << "aaa" << std::ctime(&end_time) << endl; - - - mt->setFrameMode(ePedestal); - // sprintf(fn,fformat,irun); - filebin.open((const char *)(fname), ios::in | ios::binary); - // //open file - if (filebin.is_open()){ - ff=-1; - while (decoder->readNextFrame(filebin, ff, np,buff)) { - mt->pushData(buff); - mt->nextThread(); - mt->popFree(buff); - ifr++; - if (ifr%10000==0) - cout << ifr << " " << ff << " " << np << endl; - ff=-1; - } - filebin.close(); - while (mt->isBusy()) {;} - mt->writePedestal(imgfname); - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - - } else - cout << "Could not open "<< fname << " for reading " << endl; - } - - - ifr=0; - int ifile=0; - - for (int irun=runmin; irun<=runmax; irun++) { - cout << "DATA " ; - mt->setFrameMode(eFrame); - // sprintf(fn,fformat,irun); - sprintf(ffname,"%s/%s.raw",indir,fformat); - sprintf(fname,ffname,irun); - sprintf(ffname,"%s/%s.tiff",outdir,fformat); - sprintf(imgfname,ffname,irun); - sprintf(ffname,"%s/%s.clust",outdir,fformat); - sprintf(cfname,ffname,irun); - cout << fname << " " ; - cout << imgfname << endl; - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - // cout << fname << " " << outfname << " " << imgfname << endl; - filebin.open((const char *)(fname), ios::in | ios::binary); - // //open file - ifile=0; - if (filebin.is_open()){ - if (thr<=0) { - if (cf) { - if (of==NULL) { - of=fopen(cfname,"w"); - if (of) { - mt->setFilePointer(of); - cout << "file pointer set " << endl; - } else { - cout << "Could not open "<< cfname << " for writing " << endl; - mt->setFilePointer(NULL); - return 1; - } - } - } - } - // //while read frame - ff=-1; - ifr=0; - while (decoder->readNextFrame(filebin, ff, np,buff)) { - // cout << "*"<pushData(buff); - // // //pop - mt->nextThread(); - // // // cout << " " << (void*)buff; - mt->popFree(buff); - ifr++; - if (ifr%1000==0) cout << ifr << " " << ff << endl; - if (nframes>0) { - if (ifr%nframes==0) { - //The name has an additional "_fXXXXX" at the end, where "XXXXX" is the initial frame number of the image (0,1000,2000...) - - sprintf(ffname,"%s/%s_f%05d.tiff",outdir,fformat,ifile); - sprintf(imgfname,ffname,irun); - //cout << "Writing tiff to " << imgfname << " " << thr1 << endl; - mt->writeImage(imgfname, thr1); - mt->clearImage(); - ifile++; - } - } - - ff=-1; - } - cout << "--" << endl; - filebin.close(); - // //close file - // //join threads - while (mt->isBusy()) {;} - if (nframes>=0) { - if (nframes>0) { - sprintf(ffname,"%s/%s_f%05d.tiff",outdir,fformat,ifile); - sprintf(imgfname,ffname,irun); - } - sprintf(ffname,"%s/%s.tiff",outdir,fformat); - sprintf(imgfname,ffname,irun); - cout << "Writing tiff to " << imgfname << " " << thr1 <writeImage(imgfname, thr1); - mt->clearImage(); - if (of) { - fclose(of); - of=NULL; - mt->setFilePointer(NULL); - } - } - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - } else - cout << "Could not open "<< fname << " for reading " << endl; - } - - - return 0; -} - diff --git a/slsDetectorCalibration/moenchExecutables/moenchZmqAnalog.cpp b/slsDetectorCalibration/moenchExecutables/moenchZmqAnalog.cpp deleted file mode 100644 index 4cbee47d0..000000000 --- a/slsDetectorCalibration/moenchExecutables/moenchZmqAnalog.cpp +++ /dev/null @@ -1,394 +0,0 @@ -//#define ROOTSPECTRUM - -#include "multiThreadedAnalogDetector.h" - -#include "sls_receiver_defs.h" -#include "ZmqSocket.h" -#include "moench03T1ZmqDataNew.h" - -#ifdef ROOTSPECTRUM -#include -#include -#include -#include -#include -#include -#include -#include -#endif - -#include -#include -#include -#include -#include -#include "tiffIO.h" - -#include - -//#include "analogDetector.h" -#include "singlePhotonDetector.h" -#include "ansi.h" -#include -using namespace std; - - -#define SLS_DETECTOR_JSON_HEADER_VERSION 0x2 - - -int main(int argc, char *argv[]) { -/** - * trial.o [socket ip] [starting port number] [send_socket ip] [send port number] - * - */ - int fifosize=1000; - int nthreads=20; - char* buff; - char tit[10000]; - // help - if (argc < 3 ) { - cprintf(RED, "Help: ./trial [receive socket ip] [receive starting port number] [send_socket ip] [send starting port number]\n"); - return EXIT_FAILURE; - } - - // receive parameters - bool send = false; - char* socketip=argv[1]; - uint32_t portnum = atoi(argv[2]); - int size = 32*2*5000;//atoi(argv[3]); - - // send parameters if any - char* socketip2 = 0; - uint32_t portnum2 = 0; - if (argc > 3) { - send = true; - socketip2 = argv[3]; - portnum2 = atoi(argv[4]); - } - cout << "\nrx socket ip : " << socketip << - "\nrx port num : " << portnum ; - if (send) { - cout << "\nsd socket ip : " << socketip2 << - "\nsd port num : " << portnum2; - } - cout << endl; - - //slsDetectorData *det=new moench03T1ZmqDataNew(); - moench03T1ZmqDataNew *det=new moench03T1ZmqDataNew(); - analogDetector *filter=new analogDetector(det,1,NULL,1000); - //singlePhotonDetector *filter=new singlePhotonDetector(det,3, 5, 1, 0, 1000, 10); - //filter->setROI(250, 400, 30, 150); - float threshold=1; - if (argc > 5) { - threshold=atof(argv[5]); - filter->setThreshold(threshold); - cout << "Threshold set to " << threshold << endl; - } - - int nnx, nny, nns; - int imsize=filter->getImageSize(nnx,nny,nns); - - multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); - - - - // mt->prepareInterpolation(ok); - mt->StartThreads(); - mt->popFree(buff); - - - - cout << "det " << endl; - int16_t dout[400*400]; - double ddark[400*400]; - cout << "dout " << endl; - - // receive socket - ZmqSocket* zmqsocket = new ZmqSocket(socketip,portnum); -#ifdef ROOTSPECTRUM - TH2F *h2=NULL; - TH2F *hmap=NULL; - TFile *froot=NULL; - - h2=new TH2F("hs","hs",500,-500,500,400*400,-0.5,400*400-0.5); - hmap=new TH2F("hmap","hmap",400,-0.5,400-0.5,400,-0.5,400-0.5); -#endif - cout << "zmq1 " << endl; - - if (zmqsocket->IsError()) { - cprintf(RED, "Error: Could not create Zmq socket on port %d with ip %s\n", portnum, socketip); - delete zmqsocket; - return EXIT_FAILURE; - } - zmqsocket->Connect(); - printf("Zmq Client at %s\n", zmqsocket->GetZmqServerAddress()); - - // send socket - ZmqSocket* zmqsocket2 = 0; - cout << "zmq2 " << endl; - if (send) { - zmqsocket2 = new ZmqSocket(portnum2, socketip2); - if (zmqsocket2->IsError()) { - bprintf(RED, "Error: Could not create Zmq socket server on port %d and ip %s\n", portnum2, socketip2); - delete zmqsocket2; - delete zmqsocket; - return EXIT_FAILURE; - } - zmqsocket2->Connect(); - printf("Zmq Server started at %s\n", zmqsocket2->GetZmqServerAddress()); - // zmqsocket2->Disconnect(); - } - - - // header variables - uint64_t acqIndex = -1; - uint64_t frameIndex = -1; - uint32_t subframeIndex = -1; - uint64_t fileindex = -1; - string filename = ""; - //char* image = new char[size]; - //int* image = new int[(size/sizeof(int))](); - - int *nph;//[400*400]; - int iframe=0; - char rootfname[10000]; - - char fname[10000]; - char ff[10000]; - int fi; - int length; - char newped=-1, ped=-1, dat=-1, isdark=-1; - - double *peds; - int *im; - int fnumber; - float *gm=new float[400*400]; - // infinite loop - while(1) { - - - // cout << "+++++++++++++++++++++++++++++++LOOP" << endl; - // get header, (if dummy, fail is on parse error or end of acquisition) - if (!zmqsocket->ReceiveHeader(0, acqIndex, frameIndex, subframeIndex, filename, fileindex)){ - // if (!zmqsocket->ReceiveHeader(0, acqIndex, frameIndex, subframeIndex, filename, fileindex)) { - cprintf(RED, "Got Dummy\n"); - while (mt->isBusy()) {;}//wait until all data are processed from the queues - if (dat==1) { - - sprintf(tit,"%s_%lld.tiff",filename.c_str(),fi); - cout << tit << endl; - im=mt->getImage(nnx,nny,nns); - if (isdark) cout << "getting dark "<< endl; - else cout << "subtracting dark"<< endl; - if (gm) { - for (int ii=0; ii<400*400; ii++) { - // if (image[ix]>0) cout << ix << " " << image[ix]<< endl; - if (isdark) { - ddark[ii]=(double)im[ii]/((double)iframe); - if (ddark[ii]>0) cout << "*" ; - gm[ii]=im[ii]; - if (send) dout[ii]=im[ii]; - } else { - gm[ii]=im[ii];//-ddark[ii]*iframe; - if (gm[ii]<0) gm[ii]=0; - if (send) dout[ii]=gm[ii]; - } - //cout << endl; - - } - cout << endl; - //cout << "image " << nnx << " " << nny << endl; - WriteToTiff(gm,tit ,nnx, nny); - // delete [] gm; - } else cout << "Could not allocate float image " << endl; - - - - } else { - - sprintf(tit,"%s_%lld.tiff",filename.c_str(),fi); - cout << tit << endl; - mt->writePedestal(tit); - - } - - // mt->writeImage(tit); - // cout << "wrote" << endl; - - - - - - - - - if (send) { - if (dat==1) { - //im=mt->getImage(nnx,nny,nns); - - //if (im) - // cout << "got image" << endl; - //else - // cout << "could not get image" << endl; - - - //for (int ii=0; ii<400*400; ii++) { - //if (im[ii]>0) - //cout << im[ii] << endl; - // if (im[ii]>=0) - - // if (isdark) { - //ddark[ii]=im[ii]; - // dout[ii]=im[ii]; - // } else { - // dout[ii]=im[ii]-ddark[ii]; - // if (dout[ii]<0) dout[ii]=0; - // } - // else - // dout[ii]=0; - //else - //dout[ii]=0; - // cout << im[ii] << " " << dout[ii] << endl; - // } - //for (int iiy=49; iiy<52; iiy++) - // for (int iix=80; iix<83; iix++) - // dout[iiy*400+iix]=0; - ; - } else { - peds=mt->getPedestal(); - // sprintf(tit,"%s_%lld.tiff",filename.c_str(),fi); - //cout << tit << endl; - //mt->writePedestal(tit); - if (peds) - cout << "got peds" << endl; - else - cout << "could not get peds" << endl; - for (int ii=0; ii<400*400; ii++) { - dout[ii]=peds[ii]; - // if (ii%400==10 && ii/400==10) - // cout << ii/400 << " " << ii%400 << " " << peds[ii] << " " << dout[ii] << endl; - // if (ii%400==100 && ii/400==100) - // cout << ii/400 << " " << ii%400 << " " << peds[ii] << " " << dout[ii] << endl; - } - - } - - - // zmqsocket2 = new ZmqSocket(portnum2, socketip2); - // if (zmqsocket2->IsError()) { - // bprintf(RED, "Error: Could not create Zmq socket server on port %d and ip %s\n", portnum2, socketip2); - // delete zmqsocket2; - // delete zmqsocket; - // return EXIT_FAILURE; - // } - // zmqsocket2->Connect(); - // printf("Zmq Server started at %s\n", zmqsocket2->GetZmqServerAddress()); - //zmqsocket2->Connect(); - - - zmqsocket2->SendHeaderData(0, false, SLS_DETECTOR_JSON_HEADER_VERSION,0,0,0,0,0, 0,0,ff, 0, 0,0,0,0,0,0,0,0,0,0,0,1); - - - zmqsocket2->SendData((char*)dout,length); - cprintf(GREEN, "Sent Data %d \n",length); - - zmqsocket2->SendHeaderData(0, true, SLS_DETECTOR_JSON_HEADER_VERSION); - cprintf(RED, "Sent Dummy\n"); - // zmqsocket2->Disconnect(); - - // delete zmqsocket2; - } - cout << "Acquired "<< iframe << " frames " << endl; - iframe=0; - newped=-1; - ped=-1; - dat=-1; - mt->clearImage(); - isdark=0; - continue; //continue to not get out - } - // cprintf(GREEN, "Got Header \n"); - - strcpy(ff,filename.c_str()); - fi=fileindex; - //isdark=0; - if (newped<0) { - if (filename.find("newped")!=std::string::npos) { - cout << "NEWPED" << endl; - if (newped<=0) { - newped=1; - ped=1; - while (mt->isBusy()) {;} - mt->newDataSet(); //resets pedestal - mt->setFrameMode(ePedestal); - cout << "New data set"<< endl; - } - } else { - newped=0; - } - } - if (ped<0) { - if (filename.find("ped")!=std::string::npos) { - ped=1; - dat=0; - while (mt->isBusy()) {;} - mt->setFrameMode(ePedestal); - cout << "pedestal!"<< endl; - } else { - ped=0; - dat=1; - while (mt->isBusy()) {;} - mt->setFrameMode(eFrame); - cout << "data!"<< endl; - if (filename.find("dark")!=std::string::npos) { - isdark=1; - cout << "this is a dark image" << endl; - } - - } - } - - // get data - length = zmqsocket->ReceiveData(0, buff, size); - // cprintf(GREEN, "Got Data\n"); - - //processing with image - //... - // if (iframe<10) { - // filter->addToPedestal(image); - //} else { - //SLOW!!! - //*** - //filter->getNPhotons(image); - //nph=filter->getImage(); - //filter->addToPedestal(image); - //***** - - // cprintf(BLUE, "Data processed\n"); - - - mt->pushData(buff); - mt->nextThread(); - // cout << " " << (void*)buff; - mt->popFree(buff); - - - - //stream data from socket 2 - - iframe++; - } - - // }// exiting infinite loop - - - - delete zmqsocket; - if (send) - delete zmqsocket2; - - - cout<<"Goodbye"<< endl; - return 0; -} - diff --git a/slsDetectorCalibration/moenchExecutables/moenchZmqClusterFinder.cpp b/slsDetectorCalibration/moenchExecutables/moenchZmqClusterFinder.cpp deleted file mode 100644 index 276372245..000000000 --- a/slsDetectorCalibration/moenchExecutables/moenchZmqClusterFinder.cpp +++ /dev/null @@ -1,402 +0,0 @@ -#include "sls_receiver_defs.h" -#include "ZmqSocket.h" -#include "moench03T1ZmqDataNew.h" -#include -#include -#include -#include -#include -#include "tiffIO.h" - - -//#define NEWZMQ -#ifdef NEWZMQ -#include //json header in zmq stream -#endif - -#include - -//#include "analogDetector.h" -#include "singlePhotonDetector.h" -#include "multiThreadedAnalogDetector.h" -#include "ansi.h" -#include -using namespace std; - - -#define SLS_DETECTOR_JSON_HEADER_VERSION 0x2 - - -int main(int argc, char *argv[]) { -/** - * trial.o [socket ip] [starting port number] [send_socket ip] [send port number] - * - */ - FILE *of=NULL; - int fifosize=1000; - int nthreads=20; - // help - if (argc < 3 ) { - cprintf(RED, "Help: ./trial [receive socket ip] [receive starting port number] [send_socket ip] [send starting port number]\n"); - return EXIT_FAILURE; - } - - // receive parameters - bool send = false; - char* socketip=argv[1]; - uint32_t portnum = atoi(argv[2]); - int maxSize = 32*2*8192;//5000;//atoi(argv[3]); - int size= 32*2*5000; - int multisize=size; - // send parameters if any - char* socketip2 = 0; - uint32_t portnum2 = 0; - if (argc > 3) { - send = true; - socketip2 = argv[3]; - portnum2 = atoi(argv[4]); - } - cout << "\nrx socket ip : " << socketip << - "\nrx port num : " << portnum ; - if (send) { - cout << "\nsd socket ip : " << socketip2 << - "\nsd port num : " << portnum2; - } - cout << endl; - - //slsDetectorData *det=new moench03T1ZmqDataNew(); - moench03T1ZmqDataNew *det=new moench03T1ZmqDataNew(); - //analogDetector *filter=new analogDetector(det,1,NULL,1000); - singlePhotonDetector *filter=new singlePhotonDetector(det,3, 5, 1, 0, 1000, 10); - - - char* buff; - multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); - mt->setFrameMode(eFrame); - mt->StartThreads(); - mt->popFree(buff); - - - ZmqSocket* zmqsocket=NULL; - -#ifdef NEWZMQ - // receive socket - try{ -#endif - - zmqsocket = new ZmqSocket(socketip,portnum); - - -#ifdef NEWZMQ - } catch (...) { - cprintf(RED, "Error: Could not create Zmq socket on port %d with ip %s\n", portnum, socketip); - delete zmqsocket; - return EXIT_FAILURE; - } -#endif - -#ifndef NEWZMQ - if (zmqsocket->IsError()) { - cprintf(RED, "Error: Could not create Zmq socket on port %d with ip %s\n", portnum, socketip); - delete zmqsocket; - return EXIT_FAILURE; - } -#endif - if (zmqsocket->Connect()) { - cprintf(RED, "Error: Could not connect to socket %s\n", - zmqsocket->GetZmqServerAddress()); - delete zmqsocket; - return EXIT_FAILURE; - } else - printf("Zmq Client at %s\n", zmqsocket->GetZmqServerAddress()); - - // send socket - ZmqSocket* zmqsocket2 = 0; - cout << "zmq2 " << endl; - if (send) { -#ifdef NEWZMQ - // receive socket - try{ -#endif - zmqsocket2 = new ZmqSocket(portnum2, socketip2); - - - -#ifdef NEWZMQ - } catch (...) { - cprintf(RED, "Error: Could not create Zmq socket server on port %d and ip %s\n", portnum2, socketip2); - delete zmqsocket2; - delete zmqsocket; - return EXIT_FAILURE; - } -#endif - -#ifndef NEWZMQ - if (zmqsocket2->IsError()) { - cprintf(RED, "Error: Could not create Zmq socket server on port %d and ip %s\n", portnum2, socketip2); - delete zmqsocket2; - delete zmqsocket; - return EXIT_FAILURE; - } -#endif - if (zmqsocket2->Connect()) { - cprintf(RED, "Error: Could not connect to socket %s\n", - zmqsocket2->GetZmqServerAddress()); - delete zmqsocket2; - return EXIT_FAILURE; - } else - printf("Zmq Client at %s\n", zmqsocket2->GetZmqServerAddress()); - - } - - - // header variables - uint64_t acqIndex = -1; - uint64_t frameIndex = -1; - uint32_t subFrameIndex = -1; - uint64_t fileindex = -1; - string filename = ""; - // char* image = new char[size]; - //int* image = new int[(size/sizeof(int))](); - uint32_t flippedDataX = -1; - int *nph; - int iframe=0; - char ofname[10000]; - - char fname[10000]; - int length; - int *detimage; - int nnx, nny,nns; - uint32_t imageSize = 0, nPixelsX = 0, nPixelsY = 0, dynamicRange = 0; - filter->getImageSize(nnx, nny,nns); - int16_t *dout=new int16_t [nnx*nny]; - // infinite loop - uint32_t packetNumber = 0; - uint64_t bunchId = 0; - uint64_t timestamp = 0; - int16_t modId = 0; - uint16_t xCoord = 0; - uint16_t yCoord = 0; - uint16_t zCoord = 0; - uint32_t debug = 0; - uint32_t dr = 16; - uint16_t roundRNumber = 0; - uint8_t detType = 0; - uint8_t version = 0; - int* flippedData = 0; - char* additionalJsonHeader = 0; - - uint32_t threshold=0; - - uint32_t xmin=0, xmax=400, ymin=0, ymax=400; - - string frameMode_s, detectorMode_s; - - int emin, emax; - - - int newFrame=1; - - while(1) { - - - // cout << "+++++++++++++++++++++++++++++++LOOP" << endl; - // get header, (if dummy, fail is on parse error or end of acquisition) -#ifndef NEWZMQ - if (!zmqsocket->ReceiveHeader(0, acqIndex, frameIndex, subframeIndex, filename, fileindex)){ -#endif - -#ifdef NEWZMQ - rapidjson::Document doc; - if (!zmqsocket->ReceiveHeader(0, doc, SLS_DETECTOR_JSON_HEADER_VERSION)) { - zmqsocket->CloseHeaderMessage(); - -#endif - // if (!zmqsocket->ReceiveHeader(0, acqIndex, frameIndex, subframeIndex, filename, fileindex)) { - cprintf(RED, "Got Dummy\n"); - - - - - while (mt->isBusy()) {;}//wait until all data are processed from the queues - - - detimage=mt->getImage(nnx,nny,nns); - for (int ix=0; ixSendHeaderData (0, false, SLS_DETECTOR_JSON_HEADER_VERSION, dynamicRange, fileindex, - // nnx, nny, nns*dynamicRange/8,acqIndex, frameIndex, fname, acqIndex, subFrameIndex, packetNumber,bunchId, timestamp, modId, xCoord, yCoord, zCoord,debug, roundRNumber, detType, version, flippedData, additionalJsonHeader); - - zmqsocket2->SendHeaderData (0, false, SLS_DETECTOR_JSON_HEADER_VERSION, dr, fileindex, - nnx, nny, nns*dr/8,acqIndex, frameIndex, fname, acqIndex, subFrameIndex, packetNumber,bunchId, timestamp, modId, xCoord, yCoord, zCoord,debug, roundRNumber, detType, version, flippedData, additionalJsonHeader); - -#endif - -#ifndef NEWZMQ - zmqsocket2->SendHeaderData(0, false, SLS_DETECTOR_JSON_HEADER_VERSION,0,0,0,0,0, 0,0,fname, 0, 0,0,0,0,0,0,0,0,0,0,0,1); -#endif - - zmqsocket2->SendData((char*)dout,length); - cprintf(GREEN, "Sent Data\n"); - } - - - // stream dummy to socket2 to signal end of acquisition - if (send) { - zmqsocket2->SendHeaderData(0, true, SLS_DETECTOR_JSON_HEADER_VERSION); - cprintf(RED, "Sent Dummy\n"); - } - mt->clearImage(); - if (of) { - fclose(of); - of=NULL; - } - - newFrame=1; - continue; //continue to not get out - } - -#ifdef NEWZMQ - if (newFrame) { - // acqIndex, frameIndex, subframeIndex, filename, fileindex - size = doc["size"].GetUint(); - multisize = size;// * zmqsocket->size(); - dynamicRange = doc["bitmode"].GetUint(); - nPixelsX = doc["shape"][0].GetUint(); - nPixelsY = doc["shape"][1].GetUint(); - filename = doc["fname"].GetString(); - acqIndex = doc["acqIndex"].GetUint64(); - frameIndex = doc["fIndex"].GetUint64(); - fileindex = doc["fileIndex"].GetUint64(); - subFrameIndex = doc["expLength"].GetUint(); - xCoord = doc["xCoord"].GetUint(); - yCoord = doc["yCoord"].GetUint(); - zCoord = doc["zCoord"].GetUint(); - flippedDataX=doc["flippedDataX"].GetUint(); - packetNumber=doc["packetNumber"].GetUint(); - bunchId=doc["bunchId"].GetUint(); - timestamp=doc["timestamp"].GetUint(); - modId=doc["modId"].GetUint(); - debug=doc["debug"].GetUint(); - roundRNumber=doc["roundRNumber"].GetUint(); - detType=doc["detType"].GetUint(); - version=doc["version"].GetUint(); - - - - cprintf(BLUE, "Header Info:\n" - "size: %u\n" - "multisize: %u\n" - "dynamicRange: %u\n" - "nPixelsX: %u\n" - "nPixelsY: %u\n" - "currentFileName: %s\n" - "currentAcquisitionIndex: %lu\n" - "currentFrameIndex: %lu\n" - "currentFileIndex: %lu\n" - "currentSubFrameIndex: %u\n" - "xCoordX: %u\n" - "yCoordY: %u\n" - "zCoordZ: %u\n" - "flippedDataX: %u\n" - "packetNumber: %u\n" - "bunchId: %u\n" - "timestamp: %u\n" - "modId: %u\n" - "debug: %u\n" - "roundRNumber: %u\n" - "detType: %u\n" - "version: %u\n", - size, multisize, dynamicRange, nPixelsX, nPixelsY, - filename.c_str(), acqIndex, - frameIndex, fileindex, subFrameIndex, - xCoord, yCoord,zCoord, - flippedDataX, packetNumber, bunchId, timestamp, modId, debug, roundRNumber, detType, version); - - - if (doc.HasMember("threshold")) { - version=doc["threshold"].GetUint(); - - } - - if (doc.HasMember("roi")) { - xmin=doc["roi"][0].GetUint(); - xmax=doc["roi"][1].GetUint(); - ymin=doc["roi"][2].GetUint(); - ymax=doc["roi"][3].GetUint(); - - } - - if (doc.HasMember("frameMode")) { - frameMode_s=doc["frameMode"].GetString(); - - } - - if (doc.HasMember("detectorMode")) { - detectorMode_s=doc["detectorMode"].GetString(); - - } - - if (doc.HasMember("energyRange")) { - emin=doc["energyRange"][0].GetUint(); - emax=doc["energyRange"][0].GetUint(); - - } - - - if (doc.HasMember("dynamicRange")) { - dr=doc["dynamicRange"].GetUint(); - } - - if (doc.HasMember("nSubPixels")) { - nsubPixels=doc["nSubPixels"].GetUint(); - } - - - - newFrame=0; - zmqsocket->CloseHeaderMessage(); - } -#endif - - if (of==NULL) { - sprintf(ofname,"%s_%d.clust",filename.c_str(),fileindex); - of=fopen(ofname,"w"); - if (of) { - mt->setFilePointer(of); - }else { - cout << "Could not open "<< ofname << " for writing " << endl; - mt->setFilePointer(NULL); - } - } - - // get data - length = zmqsocket->ReceiveData(0, buff, size); - mt->pushData(buff); - mt->nextThread(); - mt->popFree(buff); - - - - - iframe++; - } // exiting infinite loop - - - - delete zmqsocket; - if (send) - delete zmqsocket2; - - - cout<<"Goodbye"<< endl; - return 0; -} - diff --git a/slsDetectorCalibration/moenchExecutables/moenchZmqInterpolating.cpp b/slsDetectorCalibration/moenchExecutables/moenchZmqInterpolating.cpp deleted file mode 100644 index 2bd7e48f2..000000000 --- a/slsDetectorCalibration/moenchExecutables/moenchZmqInterpolating.cpp +++ /dev/null @@ -1,292 +0,0 @@ -#include "sls_receiver_defs.h" -#include "ZmqSocket.h" -#include "moench03T1ZmqDataNew.h" -#include -#include -#include -#include -#include -#include "tiffIO.h" - -#include - -//#include "analogDetector.h" -#include "interpolatingDetector.h" -#include "linearInterpolation.h" -#include "multiThreadedAnalogDetector.h" -#include "ansi.h" -#include -using namespace std; - - -#define SLS_DETECTOR_JSON_HEADER_VERSION 0x2 - - - - -int main(int argc, char *argv[]) { -/** - * trial.o [socket ip] [starting port number] [send_socket ip] [send port number] - * - */ - - int nthreads=20; - int nsigma=5; - int xmin=0; - int xmax=400; - int ymin=0; - int ymax=400; - int nsubpixels=2; - - - FILE *of=NULL; - int fifosize=1000; - int int_ready=0; - int ok; - // help - if (argc < 3 ) { - cprintf(RED, "Help: %s [receive socket ip] [receive starting port number] [send_socket ip] [send starting port number] [nsubpixels] [nthreads] [nsigma] [xmin xmax ymin ymax]\n", argv[0]); - return EXIT_FAILURE; - } - - char* socketip2 = 0; - uint32_t portnum2 = 0; - // receive parameters - int size = 32*2*5000;//atoi(argv[3]); - bool send = false; - - - - char* socketip=argv[1]; - uint32_t portnum = atoi(argv[2]); - if (argc > 3) { - send = true; - socketip2 = argv[3]; - portnum2 = atoi(argv[4]); - } - if (argc > 5) { - nsubpixels=atoi(argv[5]); - } - if (argc>6) { - nthreads=atoi(argv[6]); - } - if (argc>7) { - nsigma=atoi(argv[7]); - } - if (argc>11) { - xmin=atoi(argv[8]); - xmax=atoi(argv[8]); - ymin=atoi(argv[10]); - ymax=atoi(argv[11]); - } - - cout << "\nrx socket ip : " << socketip << - "\nrx port num : " << portnum ; - if (send) { - cout << "\nsd socket ip : " << socketip2 << - "\nsd port num : " << portnum2; - } - cout << endl; - - //slsDetectorData *det=new moench03T1ZmqDataNew(); - int npx, npy; - moench03T1ZmqDataNew *det=new moench03T1ZmqDataNew(); - det->getDetectorSize(npx, npy); - linearInterpolation *interp=new linearInterpolation(npx,npy,nsubpixels); - interpolatingDetector *filter=new interpolatingDetector(det,interp, nsigma, 1, 0, 1000, 100,npx,npy); - cout << "Setting noise cut to " << nsigma << " sigma"<< endl; - filter->setROI(xmin,xmax,ymin,ymax); - cout << "Setting ROI to "<< xmin << " " << xmax << " " << ymin << " " << ymax << endl; - - char* buff; - multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); - int frameMode=eFrame; - mt->setFrameMode(frameMode); - mt->StartThreads(); - mt->popFree(buff); - - - - - - // receive socket - ZmqSocket* zmqsocket = new ZmqSocket(socketip,portnum); - if (zmqsocket->IsError()) { - cprintf(RED, "Error: Could not create Zmq socket on port %d with ip %s\n", portnum, socketip); - delete zmqsocket; - return EXIT_FAILURE; - } - zmqsocket->Connect(); - printf("Zmq Client at %s\n", zmqsocket->GetZmqServerAddress()); - - // send socket - ZmqSocket* zmqsocket2 = 0; - if (send) { - zmqsocket2 = new ZmqSocket(portnum2, socketip2); - if (zmqsocket2->IsError()) { - bprintf(RED, "Error: Could not create Zmq socket server on port %d and ip %s\n", portnum2, socketip2); - delete zmqsocket2; - delete zmqsocket; - return EXIT_FAILURE; - } - zmqsocket2->Connect(); - printf("Zmq Server started at %s\n", zmqsocket2->GetZmqServerAddress()); - } - - - // header variables - uint64_t acqIndex = -1; - uint64_t frameIndex = -1; - uint32_t subframeIndex = -1; - uint64_t fileindex = -1; - string filename = ""; - char ffname[10000]; - int ffindex; - - char* image = new char[size]; - //int* image = new int[(size/sizeof(int))](); - - int *nph; - int iframe=0; - char ofname[10000]; - - char fname[10000]; - int length; - int *detimage; - int nnx, nny,nns; - int nix, niy,nis; - filter->getImageSize(nnx, nny,nns); - int16_t *dout=new int16_t [nnx*nny]; - // infinite loop - int ix, iy, isx, isy; - while(1) { - - - // cout << "+++++++++++++++++++++++++++++++LOOP" << endl; - // get header, (if dummy, fail is on parse error or end of acquisition) - if (!zmqsocket->ReceiveHeader(0, acqIndex, frameIndex, subframeIndex, filename, fileindex)){ - // if (!zmqsocket->ReceiveHeader(0, acqIndex, frameIndex, subframeIndex, filename, fileindex)) { - // cprintf(RED, "Got Dummy\n"); - while (mt->isBusy()) {;}//wait until all data are processed from the queues - if (frameMode==ePedestal) { - detped=mt->getPedestal(); - if (detped) { - - for (ix=0; ix<400; ix++) { - for (iy=0; iy<400; iy++) { - dout[iy*400+ix]+=detped[iy*400+ix]; - } - } - } - - } else { - detimage=mt->getImage(nix,niy,nis); - if (detimage) { - for (ix=0; ixSendHeaderData(0, false, SLS_DETECTOR_JSON_HEADER_VERSION,16,fileindex,400,400,400*400, acqIndex,frameIndex,fname, acqIndex, 0,0,0,0,0,0,0,0,0,0,0,1); - zmqsocket2->SendHeaderData(0, false, SLS_DETECTOR_JSON_HEADER_VERSION,0,0,0,0,0, 0,0,fname, 0, 0,0,0,0,0,0,0,0,0,0,0,1); - - zmqsocket2->SendData((char*)dout,length); - cprintf(GREEN, "Sent Data\n"); - } - - sprintf(ofname,"%s_%d.tiff",ffname,ffindex); - if (frameMode==eFlat) - mt->writeFlatField(ofname); - else if (frameMode==ePedestal) - mt->writePedestal(ofname); - else - mt->writeImage(ofname); - - - // stream dummy to socket2 to signal end of acquisition - if (send) { - zmqsocket2->SendHeaderData(0, true, SLS_DETECTOR_JSON_HEADER_VERSION); - // cprintf(RED, "Sent Dummy\n"); - cprintf(RED, "Received %d frames\n", iframe); - } - mt->clearImage(); - if (of) { - fclose(of); - of=NULL; - } - iframe=0; - continue; //continue to not get out - } - - - if (of==NULL) { - while (mt->isBusy()) {;} - sprintf(ofname,"%s_%d.clust",filename.c_str(),fileindex); - of=fopen(ofname,"w"); - if (of) { - mt->setFilePointer(of); - }else { - cout << "Could not open "<< ofname << " for writing " << endl; - mt->setFilePointer(NULL); - } - ffindex=fileindex; - strcpy(ffname,filename.c_str()); - if (filename.find("flat")!=std::string::npos) { - cout << "add to ff" << endl; - frameMode=eFlat;//ePedestal; - int_ready=0; - - } else if (filename.find("newped")!=std::string::npos) { - frameMode=ePedestal; - cout << "new pedestal" << endl; - - mt->newDataSet(); - } else if (filename.find("ped")!=std::string::npos){ - frameMode=ePedestal; - cout << "pedestal" << endl; - } else { - frameMode=eFrame; - cout << "data" << endl; - if (int_ready==0) { - mt->prepareInterpolation(ok); - cout << "prepare interpolation " << endl; - int_ready=1; - } - } - - mt->setFrameMode(frameMode); - } - - // get data - length = zmqsocket->ReceiveData(0, buff, size); - mt->pushData(buff); - mt->nextThread(); - mt->popFree(buff); - - iframe++; - } // exiting infinite loop - - - - delete zmqsocket; - if (send) - delete zmqsocket2; - - - // cout<<"Goodbye"<< endl; - return 0; -} - diff --git a/slsDetectorCalibration/moenchExecutables/moenchZmqProcess.cpp b/slsDetectorCalibration/moenchExecutables/moenchZmqProcess.cpp deleted file mode 100644 index 19cd832b1..000000000 --- a/slsDetectorCalibration/moenchExecutables/moenchZmqProcess.cpp +++ /dev/null @@ -1,710 +0,0 @@ -#define WRITE_QUAD - -#include "sls_receiver_defs.h" -#include "ZmqSocket.h" -#include "moench03T1ZmqDataNew.h" -#include -#include -#include -#include -#include -#include "tiffIO.h" - -//#define NEWZMQ -#ifdef NEWZMQ -#include //json header in zmq stream -#endif - -#include - -//#include "analogDetector.h" -//#include "multiThreadedAnalogDetector.h" -//#include "singlePhotonDetector.h" -//#include "interpolatingDetector.h" -//#include "multiThreadedCountingDetector.h" -#include "multiThreadedInterpolatingDetector.h" -#include "etaInterpolationPosXY.h" -#include "ansi.h" -#include - -//#include -#include // time_t -#include - -using namespace std; -//using namespace std::chrono; - -//#define SLS_DETECTOR_JSON_HEADER_VERSION 0x2 - - // myDet->setNetworkParameter(ADDITIONAL_JSON_HEADER, " \"what\":\"nothing\" "); - -int main(int argc, char *argv[]) { -/** - * trial.o [socket ip] [starting port number] [send_socket ip] [send port number] - * - */ - FILE *of=NULL; - int fifosize=5000; - int etabins=1000;//nsubpix*2*100; - double etamin=-1, etamax=2; - // help - if (argc < 3 ) { - cprintf(RED, "Help: ./trial [receive socket ip] [receive starting port number] [send_socket ip] [send starting port number] [nthreads] [nsubpix] [etafile]\n"); - return EXIT_FAILURE; - } - - // receive parameters - bool send = false; - char* socketip=argv[1]; - uint32_t portnum = atoi(argv[2]); - // send parameters if any - char* socketip2 = 0; - uint32_t portnum2 = 0; - - - int ok; - - // high_resolution_clock::time_point t1; - // high_resolution_clock::time_point t2 ; - time_t begin,end,finished; - - - if (argc > 4) { - socketip2 = argv[3]; - portnum2 = atoi(argv[4]); - if (portnum2>0) - send = true; - } - cout << "\nrx socket ip : " << socketip << - "\nrx port num : " << portnum ; - if (send) { - cout << "\ntx socket ip : " << socketip2 << - "\ntx port num : " << portnum2; - } - int nthreads=5; - if (argc>5) - nthreads=atoi(argv[5]); - - cout << "Number of threads is: " << nthreads << endl; - int nSubPixels=2; - if (argc>6) - nSubPixels=atoi(argv[6]); - cout << "Number of subpixels is: " << nSubPixels << endl; - - char *etafname=NULL; - if (argc>7) { - etafname=argv[7]; - cout << "Eta file name is: " << etafname << endl; - } - - - //slsDetectorData *det=new moench03T1ZmqDataNew(); - moench03T1ZmqDataNew *det=new moench03T1ZmqDataNew(); - cout << endl << " det" <getDetectorSize(npx, npy); - - - - - int maxSize = npx*npy*2;//32*2*8192;//5000;//atoi(argv[3]); - int size= maxSize;//32*2*5000; - int multisize=size; - int dataSize=size; - - char dummybuff[size]; - - - - //analogDetector *filter=new analogDetector(det,1,NULL,1000); -#ifndef INTERP - singlePhotonDetector *filter=new singlePhotonDetector(det,3, 5, 1, 0, 1000, 10); - - multiThreadedCountingDetector *mt=new multiThreadedCountingDetector(filter,nthreads,fifosize); - - // multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); -#endif -#ifdef INTERP - eta2InterpolationPosXY *interp=new eta2InterpolationPosXY(npx, npy, nSubPixels, etabins, etamin, etamax); - - if (etafname) interp->readFlatField(etafname); - - interpolatingDetector *filter=new interpolatingDetector(det,interp, 5, 1, 0, 1000, 10); - multiThreadedInterpolatingDetector *mt=new multiThreadedInterpolatingDetector(filter,nthreads,fifosize); -#endif - - - - char* buff; - mt->setFrameMode(eFrame); - mt->StartThreads(); - mt->popFree(buff); - - ZmqSocket* zmqsocket=NULL; - -#ifdef NEWZMQ - // receive socket - try{ -#endif - - zmqsocket = new ZmqSocket(socketip,portnum); - - -#ifdef NEWZMQ - } catch (...) { - cprintf(RED, "Error: Could not create Zmq socket on port %d with ip %s\n", portnum, socketip); - delete zmqsocket; - return EXIT_FAILURE; - } -#endif - -#ifndef NEWZMQ - if (zmqsocket->IsError()) { - cprintf(RED, "Error: Could not create Zmq socket on port %d with ip %s\n", portnum, socketip); - delete zmqsocket; - return EXIT_FAILURE; - } -#endif - if (zmqsocket->Connect()) { - cprintf(RED, "Error: Could not connect to socket %s\n", - zmqsocket->GetZmqServerAddress()); - delete zmqsocket; - return EXIT_FAILURE; - } else - printf("Zmq Client at %s\n", zmqsocket->GetZmqServerAddress()); - - // send socket - ZmqSocket* zmqsocket2 = 0; - // cout << "zmq2 " << endl; - if (send) { -#ifdef NEWZMQ - // receive socket - try{ -#endif - zmqsocket2 = new ZmqSocket(portnum2, socketip2); - - - -#ifdef NEWZMQ - } catch (...) { - cprintf(RED, "Error: Could not create Zmq socket server on port %d and ip %s\n", portnum2, socketip2); - // delete zmqsocket2; - // zmqsocket2=NULL; - // delete zmqsocket; - // return EXIT_FAILURE; - send = false; - } -#endif - -#ifndef NEWZMQ - if (zmqsocket2->IsError()) { - cprintf(RED, "AAA Error: Could not create Zmq socket server on port %d and ip %s\n", portnum2, socketip2); - // delete zmqsocket2; - //delete zmqsocket; - // return EXIT_FAILURE; - send = false; - } -#endif - if (zmqsocket2->Connect()) { - cprintf(RED, "BBB Error: Could not connect to socket %s\n", - zmqsocket2->GetZmqServerAddress()); - // delete zmqsocket2; - send = false; - // return EXIT_FAILURE; - } else - printf("Zmq Client at %s\n", zmqsocket2->GetZmqServerAddress()); - - } - - - // header variables - uint64_t acqIndex = -1; - uint64_t frameIndex = -1; - uint32_t subFrameIndex = -1; - uint64_t fileindex = -1; - string filename = ""; - // char* image = new char[size]; - //int* image = new int[(size/sizeof(int))](); - uint32_t flippedDataX = -1; - int *nph; - int iframe=0; - char ofname[10000]; - - char fname[10000]; - int length; - int *detimage; - int nnx, nny,nns; - uint32_t imageSize = 0, nPixelsX = 0, nPixelsY = 0, dynamicRange = 0; - // infinite loop - uint32_t packetNumber = 0; - uint64_t bunchId = 0; - uint64_t timestamp = 0; - int16_t modId = 0; - uint16_t xCoord = 0; - uint16_t yCoord = 0; - uint16_t zCoord = 0; - uint32_t debug = 0; - //uint32_t dr = 16; - //int16_t *dout;//=new int16_t [nnx*nny]; - uint32_t dr = 32; - int32_t *dout=NULL;//=new int32_t [nnx*nny]; - uint32_t nSigma=5; - uint16_t roundRNumber = 0; - uint8_t detType = 0; - uint8_t version = 0; - int* flippedData = 0; - char* additionalJsonHeader = 0; - - int32_t threshold=0; - - int32_t xmin=0, xmax=400, ymin=0, ymax=400; - - string frameMode_s, detectorMode_s, intMode_s; - - int emin, emax; - int resetFlat=0; - int resetPed=0; - int nsubPixels=1; - int isPedestal; - int isFlat=0; - int newFrame=1; - detectorMode dMode; - frameMode fMode; - double *ped; - - filter->getImageSize(nnx, nny,nns); - - - - - - - while(1) { - - - // cout << "+++++++++++++++++++++++++++++++LOOP" << endl; - // get header, (if dummy, fail is on parse error or end of acquisition) -#ifndef NEWZMQ - if (!zmqsocket->ReceiveHeader(0, acqIndex, frameIndex, subframeIndex, filename, fileindex)){ -#endif - -#ifdef NEWZMQ - rapidjson::Document doc; - if (!zmqsocket->ReceiveHeader(0, doc, SLS_DETECTOR_JSON_HEADER_VERSION)) { - /* zmqsocket->CloseHeaderMessage();*/ - -#endif - // if (!zmqsocket->ReceiveHeader(0, acqIndex, frameIndex, subframeIndex, filename, fileindex)) { - // cprintf(RED, "Got Dummy\n"); - // t1=high_resolution_clock::now(); - time(&end); - - - while (mt->isBusy()) {;}//wait until all data are processed from the queues - - if (of) { - fclose(of); - of=NULL; - } - if (newFrame>0) { - cprintf(RED,"DIDn't receive any data!\n"); - if (send) { - zmqsocket2->SendHeaderData(0, true, SLS_DETECTOR_JSON_HEADER_VERSION); - cprintf(RED, "Sent Dummy\n"); - } - } else { - if (fMode==ePedestal) { - sprintf(ofname,"%s_%d_ped.tiff",fname,fileindex); - mt->writePedestal(ofname); - cout << "Writing pedestal to " << ofname << endl; - } -#ifdef INTERP - else if (fMode==eFlat) { - mt->prepareInterpolation(ok); - sprintf(ofname,"%s_%d_eta.tiff",fname,fileindex); - mt->writeFlatField(ofname); - cout << "Writing eta to " << ofname << endl; - } -#endif - else { - sprintf(ofname,"%s_%d.tiff",fname,fileindex); - mt->writeImage(ofname); - cout << "Writing image to " << ofname << endl; - } - // cout << nns*nnx*nny*nns*dr/8 << " " << length << endl; - - if (send) { - - if (fMode==ePedestal) { - cprintf(MAGENTA,"Get pedestal!\n"); - nns=1; - nnx=npx; - nny=npy; - //dout= new int16_t[nnx*nny*nns*nns]; - dout= new int32_t[nnx*nny*nns*nns]; - // cout << "get pedestal " << endl; - ped=mt->getPedestal(); - // cout << "got pedestal " << endl; - for (int ix=0; ixgetFlatField(nb, emi, ema); - nnx=nb; - nny=nb; - dout= new int32_t[nb*nb]; - for (int ix=0; ixgetImage(nnx,nny,nns); - cprintf(MAGENTA,"Get image!\n"); - cout << nnx << " " << nny << " " << nns << endl; - // nns=1; - // nnx=npx; - // nny=npy; - // nnx=nnx*nns; - //nny=nny*nns; - dout= new int32_t[nnx*nny]; - for (int ix=0; ixSendHeaderData (0, false, SLS_DETECTOR_JSON_HEADER_VERSION, dr, fileindex, nnx, nny, nnx*nny*dr/8,acqIndex, frameIndex, fname, acqIndex, subFrameIndex, packetNumber,bunchId, timestamp, modId, xCoord, yCoord, zCoord,debug, roundRNumber, detType, version, flippedData, additionalJsonHeader); - -#endif - -#ifndef NEWZMQ - zmqsocket2->SendHeaderData(0, false, SLS_DETECTOR_JSON_HEADER_VERSION,0,0,0,0,0, 0,0,fname, 0, 0,0,0,0,0,0,0,0,0,0,0,1); -#endif - - zmqsocket2->SendData((char*)dout,nnx*nny*dr/8); - cprintf(GREEN, "Sent Data\n"); - - zmqsocket2->SendHeaderData(0, true, SLS_DETECTOR_JSON_HEADER_VERSION); - cprintf(RED, "Sent Dummy\n"); - if (dout) - delete [] dout; - dout=NULL; - - } - } - - mt->clearImage(); - - newFrame=1; - //t2 = high_resolution_clock::now(); - - time(&finished); - // auto meas_duration = duration_cast( t2 - t0 ).count(); - // auto real_duration = duration_cast( t2 - t1 ).count(); - - cout << "Measurement lasted " << difftime(end,begin) << endl; - cout << "Processing lasted " << difftime(finished,begin) << endl; - continue; //continue to not get out - - - } - -#ifdef NEWZMQ - if (newFrame) { - time(&begin); - // t0 = high_resolution_clock::now(); - //cout <<"new frame" << endl; - - // acqIndex, frameIndex, subframeIndex, filename, fileindex - size = doc["size"].GetUint(); - // multisize = size;// * zmqsocket->size(); - dynamicRange = doc["bitmode"].GetUint(); - // nPixelsX = doc["shape"][0].GetUint(); - // nPixelsY = doc["shape"][1].GetUint(); - filename = doc["fname"].GetString(); - //acqIndex = doc["acqIndex"].GetUint64(); - //frameIndex = doc["fIndex"].GetUint64(); - fileindex = doc["fileIndex"].GetUint64(); - //subFrameIndex = doc["expLength"].GetUint(); - //packetNumber=doc["packetNumber"].GetUint(); - //bunchId=doc["bunchId"].GetUint(); - //timestamp=doc["timestamp"].GetUint(); - //modId=doc["modId"].GetUint(); - //debug=doc["debug"].GetUint(); - //roundRNumber=doc["roundRNumber"].GetUint(); - //detType=doc["detType"].GetUint(); - //version=doc["version"].GetUint(); - - dataSize=size; - - strcpy(fname,filename.c_str()); - - // cprintf(BLUE, "Header Info:\n" - // "size: %u\n" - // "multisize: %u\n" - // "dynamicRange: %u\n" - // "nPixelsX: %u\n" - // "nPixelsY: %u\n" - // "currentFileName: %s\n" - // "currentAcquisitionIndex: %lu\n" - // "currentFrameIndex: %lu\n" - // "currentFileIndex: %lu\n" - // "currentSubFrameIndex: %u\n" - // "xCoordX: %u\n" - // "yCoordY: %u\n" - // "zCoordZ: %u\n" - // "flippedDataX: %u\n" - // "packetNumber: %u\n" - // "bunchId: %u\n" - // "timestamp: %u\n" - // "modId: %u\n" - // "debug: %u\n" - // "roundRNumber: %u\n" - // "detType: %u\n" - // "version: %u\n", - // size, multisize, dynamicRange, nPixelsX, nPixelsY, - // filename.c_str(), acqIndex, - // frameIndex, fileindex, subFrameIndex, - // xCoord, yCoord,zCoord, - // flippedDataX, packetNumber, bunchId, timestamp, modId, debug, roundRNumber, detType, version); - - /* Analog detector commands */ - isPedestal=0; - isFlat=0; - fMode=eFrame; - frameMode_s="frame"; - cprintf(MAGENTA, "Frame mode: "); - if (doc.HasMember("frameMode")) { - if (doc["frameMode"].IsString()) { - frameMode_s=doc["frameMode"].GetString(); - if (frameMode_s == "pedestal"){ - fMode=ePedestal; - isPedestal=1; - } else if (frameMode_s == "newPedestal"){ - mt->newDataSet(); //resets pedestal - // cprintf(MAGENTA, "Resetting pedestal\n"); - fMode=ePedestal; - isPedestal=1; - } -#ifdef INTERP - else if (frameMode_s == "flatfield") { - fMode=eFlat; - isFlat=1; - } else if (frameMode_s == "newFlatfield") { - mt->resetFlatField(); - isFlat=1; - cprintf(MAGENTA, "Resetting flatfield\n"); - fMode=eFlat; - } -#endif - else { - fMode=eFrame; - isPedestal=0; - isFlat=0; - fMode=eFrame; - frameMode_s="frame"; - } - } - } - cprintf(MAGENTA, "%s\n" , frameMode_s.c_str()); - mt->setFrameMode(fMode); - - // threshold=0; - cprintf(MAGENTA, "Threshold: "); - if (doc.HasMember("threshold")) { - if (doc["threshold"].IsInt()) { - threshold=doc["threshold"].GetInt(); - mt->setThreshold(threshold); - } - } - cprintf(MAGENTA, "%d\n", threshold); - - xmin=0; - xmax=npx; - ymin=0; - ymax=npy; - cprintf(MAGENTA, "ROI: "); - if (doc.HasMember("roi")) { - if (doc["roi"].IsArray()) { - if (doc["roi"].Size() > 0 ) - if (doc["roi"][0].IsInt()) - xmin=doc["roi"][0].GetInt(); - - if (doc["roi"].Size() > 1 ) - if (doc["roi"][1].IsInt()) - xmax=doc["roi"][1].GetInt(); - - if (doc["roi"].Size() > 2 ) - if (doc["roi"][2].IsInt()) - ymin=doc["roi"][2].GetInt(); - - if (doc["roi"].Size() > 3 ) - if (doc["roi"][3].IsInt()) - ymax=doc["roi"][3].GetInt(); - } - } - - cprintf(MAGENTA, "%d %d %d %d\n", xmin, xmax, ymin, ymax); - mt->setROI(xmin, xmax, ymin, ymax); - - if (doc.HasMember("dynamicRange")) { - dr=doc["dynamicRange"].GetUint(); - dr=32; - } - - dMode=eAnalog; - detectorMode_s="analog"; - cprintf(MAGENTA, "Detector mode: "); - if (doc.HasMember("detectorMode")) { - if (doc["detectorMode"].IsString()) { - detectorMode_s=doc["detectorMode"].GetString(); -#ifdef INTERP - if (detectorMode_s == "interpolating"){ - dMode=eInterpolating; - mt->setInterpolation(interp); - } else -#endif - if (detectorMode_s == "counting"){ - dMode=ePhotonCounting; -#ifdef INTERP - mt->setInterpolation(NULL); -#endif - } else { - dMode=eAnalog; -#ifdef INTERP - mt->setInterpolation(NULL); -#endif - } - } - - } - - mt->setDetectorMode(dMode); - cprintf(MAGENTA, "%s\n" , detectorMode_s.c_str()); - - // cout << "done " << endl; - - // /* Single Photon Detector commands */ - // nSigma=5; - // if (doc.HasMember("nSigma")) { - // if (doc["nSigma"].IsInt()) - // nSigma=doc["nSigma"].GetInt(); - // mt->setNSigma(nSigma); - // } - - // emin=-1; - // emax=-1; - // if (doc.HasMember("energyRange")) { - // if (doc["energyRange"].IsArray()) { - // if (doc["energyRange"].Size() > 0 ) - // if (doc["energyRange"][0].IsInt()) - // emin=doc["energyRange"][0].GetInt(); - - // if (doc["energyRange"].Size() > 1 ) - // if (doc["energyRange"][1].IsInt()) - // emax=doc["energyRange"][1].GetUint(); - // } - // } - // if (doc.HasMember("eMin")) { - // if (doc["eMin"][1].IsInt()) - // emin=doc["eMin"].GetInt(); - // } - // if (doc.HasMember("eMax")) { - // if (doc["eMax"][1].IsInt()) - // emin=doc["eMax"].GetInt(); - // } - // mt->setEnergyRange(emin,emax); - - // /* interpolating detector commands */ - - // if (doc.HasMember("nSubPixels")) { - // if (doc["nSubPixels"].IsUint()) - // nSubPixels=doc["nSubPixels"].GetUint(); - // mt->setNSubPixels(nSubPixels); - // } - - - newFrame=0; - /* zmqsocket->CloseHeaderMessage();*/ - } -#endif - - // cout << "file" << endl; - // cout << "data " << endl; - if (of==NULL) { - sprintf(ofname,"%s_%d.clust",filename.c_str(),fileindex); - of=fopen(ofname,"w"); - if (of) { - mt->setFilePointer(of); - }else { - cout << "Could not open "<< ofname << " for writing " << endl; - mt->setFilePointer(NULL); - } - } - - - // cout << "data" << endl; - // get data - // acqIndex = doc["acqIndex"].GetUint64(); - frameIndex = doc["fIndex"].GetUint64(); - // subFrameIndex = doc["expLength"].GetUint(); - - // bunchId=doc["bunchId"].GetUint(); - // timestamp=doc["timestamp"].GetUint(); - packetNumber=doc["packetNumber"].GetUint(); - // cout << acqIndex << " " << frameIndex << " " << subFrameIndex << " "<< bunchId << " " << timestamp << " " << packetNumber << endl; - if (packetNumber>=40) { - //*((int*)buff)=frameIndex; - memcpy(buff,&frameIndex,sizeof(int)); - length = zmqsocket->ReceiveData(0, buff+sizeof(int), size); - mt->pushData(buff); - mt->nextThread(); - mt->popFree(buff); - } else { - cprintf(RED, "Incomplete frame: received only %d packet\n", packetNumber); - length = zmqsocket->ReceiveData(0, dummybuff, size); - - } - - - - iframe++; - - } // exiting infinite loop - - - - delete zmqsocket; - if (send) - delete zmqsocket2; - - - cout<<"Goodbye"<< endl; - return 0; -} - diff --git a/slsDetectorCalibration/moenchExecutables/tiff_to_th2f.cpp b/slsDetectorCalibration/moenchExecutables/tiff_to_th2f.cpp deleted file mode 100644 index 3e248feaa..000000000 --- a/slsDetectorCalibration/moenchExecutables/tiff_to_th2f.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "tiffIO.h" - -#include - -using namespace std; - - -int main(int argc, char *argv[]) { -/** - * trial.o [socket ip] [starting port number] [outfname] - * - */ - - if (argc<3) { - cout << "Wrong usage! Should be: "<< argv[0] << " infile " << " outfile " << endl; - return 1; - } - - uint32 nx, ny; - - float *data=ReadFromTiff(argv[1],nx, ny); - - TH2F *h2=NULL; - if (data) { - TFile *fout=new TFile(argv[2],"RECREATE"); - if (fout) { - h2=new TH2F("h2",argv[1],nx,0,nx,ny,0, ny); - for (int ix=0; ixSetBinContent(ix+1, iy+1, data[ix+iy*nx]); - } - } - h2->Write(); - fout->Close(); - } - delete [] data; - } - - - - return 0; -} - diff --git a/slsDetectorCalibration/multiThreadedAnalogDetector.h b/slsDetectorCalibration/multiThreadedAnalogDetector.h deleted file mode 100644 index 1f400819d..000000000 --- a/slsDetectorCalibration/multiThreadedAnalogDetector.h +++ /dev/null @@ -1,562 +0,0 @@ -#ifndef MULTITHREADED_ANALOG_DETECTOR_H -#define MULTITHREADED_ANALOG_DETECTOR_H - -#define MAXTHREADS 1000 - -#include -#include -#include -#include -#include -#include -//#include -//#include -//#include -#include -#include -#include - -#include "analogDetector.h" -#include "circularFifo.h" -#include -#include -#include -//#include - - -using namespace std; - - - -class threadedAnalogDetector -{ -public: - threadedAnalogDetector(analogDetector *d, int fs=10000) { - char *mem, *mm; - det=d; - fifoFree=new CircularFifo(fs); - fifoData=new CircularFifo(fs); - - /* mem=(char*)calloc(fs, det->getDataSize()); */ - /* if (mem) */ - /* memset(mem,0, fs*det->getDataSize()); */ - int i; - for (i=0; igetDataSize(); - // cout << i << endl; - mm=(char*)calloc(1, det->getDataSize()); - if (mm) { - //memset(mm,0, det->getDataSize()); - fifoFree->push(mm); - } else - break; - } - if (i=0) { - det->setFrameMode((frameMode)fm); - fMode=fm; - } - return fMode; - }; - virtual double setThreshold(double th) {return det->setThreshold(th);}; - - - - virtual void setROI(int xmin, int xmax, int ymin, int ymax) {det->setROI(xmin,xmax,ymin,ymax);}; - virtual int setDetectorMode(int dm) { - if (dm>=0) { - det->setDetectorMode((detectorMode)dm); - dMode=dm; - } - return dMode; - }; - - virtual void newDataSet(){det->newDataSet();}; - //fMode=fm; return fMode;} - - /* void prepareInterpolation(int &ok) { */ - /* cout << "-" << endl; */ - /* det->prepareInterpolation(ok); */ - /* }; */ - - virtual int *getImage() { - return det->getImage(); - } - virtual int getImageSize(int &nnx, int &nny, int &ns) {return det->getImageSize(nnx, nny, ns);}; - virtual int getDetectorSize(int &nnx, int &nny) {return det->getDetectorSize(nnx, nny);}; - - ~threadedAnalogDetector() {StopThread(); free(mem); delete fifoFree; delete fifoData;} - - /** Returns true if the thread was successfully started, false if there was an error starting the thread */ - virtual bool StartThread() - { stop=0; - return (pthread_create(&_thread, NULL, processData, this) == 0); - } - - virtual void StopThread() - { stop=1; - (void) pthread_join(_thread, NULL); - } - - - virtual bool pushData(char* &ptr) { - fifoData->push(ptr); - } - - virtual bool popFree(char* &ptr) { - fifoFree->pop(ptr); - } - - virtual int isBusy() {return busy;} - - //protected: - /** Implement this method in your subclass with the code you want your thread to run. */ - //virtual void InternalThreadEntry() = 0; - virtual void *writeImage(const char * imgname) {return det->writeImage(imgname);}; - - virtual void clearImage(){det->clearImage();}; - - - virtual void setPedestal(double *ped, double *rms=NULL, int m=-1){det->setPedestal(ped,rms,m);}; - - - virtual void setPedestalRMS(double *rms){ det->setPedestalRMS(rms);}; - - virtual double *getPedestal(double *ped=NULL){return det->getPedestal(ped);}; - - - virtual double *getPedestalRMS(double *rms=NULL){ return det->getPedestalRMS(rms);}; - - - - -/** sets file pointer where to write the clusters to - \param f file pointer - \returns current file pointer -*/ - FILE *setFilePointer(FILE *f){return det->setFilePointer(f); }; - -/** gets file pointer where to write the clusters to - \returns current file pointer -*/ -FILE *getFilePointer(){return det->getFilePointer();}; - - - - virtual double setNSigma(double n) {return det->setNSigma(n);}; - virtual void setEnergyRange(double emi, double ema) {det->setEnergyRange(emi,ema);}; - - - virtual void prepareInterpolation(int &ok){ - slsInterpolation *interp=det->getInterpolation(); - if (interp) - interp->prepareInterpolation(ok); - } - - virtual int *getFlatField(){ - slsInterpolation *interp=(det)->getInterpolation(); - if (interp) - return interp->getFlatField(); - else - return NULL; - } - - virtual int *setFlatField(int *ff, int nb, double emin, double emax){ - slsInterpolation *interp=(det)->getInterpolation(); - if (interp) - return interp->setFlatField(ff, nb, emin, emax); - else - return NULL; - } - - void *writeFlatField(const char * imgname) { - slsInterpolation *interp=(det)->getInterpolation(); - cout << "interp " << interp << endl; - if (interp) { - cout << imgname << endl; - interp->writeFlatField(imgname); - } - } - void *readFlatField(const char * imgname, int nb=-1, double emin=1, double emax=0){ - slsInterpolation *interp=(det)->getInterpolation(); - if (interp) - interp->readFlatField(imgname, nb, emin, emax); - } - - virtual int *getFlatField(int &nb, double emi, double ema){ - slsInterpolation *interp=(det)->getInterpolation(); - int *ff=NULL; - if (interp) { - ff=interp->getFlatField(nb,emi,ema); - } - return ff; - } - - virtual slsInterpolation *getInterpolation() { - return (det)->getInterpolation(); - } - - virtual void resetFlatField() { - slsInterpolation *interp=(det)->getInterpolation(); - if (interp) interp->resetFlatField();//((interpolatingDetector*)det)->resetFlatField(); - } - - - virtual int setNSubPixels(int ns) { - slsInterpolation *interp=(det)->getInterpolation(); - if (interp) return interp->setNSubPixels(ns); - else return 1;}; - - - virtual slsInterpolation *setInterpolation(slsInterpolation *f){ - return (det)->setInterpolation(f); - }; -protected: - analogDetector *det; - int fMode; - int dMode; - int *dataSize; - pthread_t _thread; - char *mem; - CircularFifo *fifoFree; - CircularFifo *fifoData; - int stop; - int busy; - char *data; - int *ff; - - static void * processData(void * ptr) { - threadedAnalogDetector *This=((threadedAnalogDetector *)ptr); - return This->processData(); - } - - void * processData() { - busy=1; - while (!stop) { - if (fifoData->isEmpty()) { - busy=0; - usleep(100); - } else { - busy=1; - fifoData->pop(data); //blocking! - det->processData(data); - fifoFree->push(data); - } - } - return NULL; - } - - - -}; - - - -class multiThreadedAnalogDetector -{ -public: - multiThreadedAnalogDetector(analogDetector *d, int n, int fs=1000) : stop(0), nThreads(n), ithread(0) { - dd[0]=d; - if (nThreads==1) - dd[0]->setId(100); - else - dd[0]->setId(0); - for (int i=1; iClone(); - dd[i]->setId(i); - } - - for (int i=0; isetFrameMode(fm);} return ret;}; - virtual double setThreshold(int fm) { double ret; for (int i=0; isetThreshold(fm); return ret;}; - virtual int setDetectorMode(int dm) { int ret; for (int i=0; isetDetectorMode(dm); return ret;}; - virtual void setROI(int xmin, int xmax, int ymin, int ymax) { for (int i=0; isetROI(xmin, xmax,ymin,ymax);}; - - - virtual void newDataSet(){for (int i=0; inewDataSet();}; - - virtual int *getImage(int &nnx, int &nny, int &ns) { - int *img; - // int nnx, nny, ns; - // int nnx, nny, ns; - int nn=dets[0]->getImageSize(nnx, nny,ns); - if (image) { - delete image; - image=NULL; - } - image=new int[nn]; - //int nn=dets[0]->getImageSize(nnx, nny, ns); - //for (i=0; igetImage(); - for (int i=0; iclearImage(); - } - - } - - virtual void *writeImage(const char * imgname, double t=1) { -/* #ifdef SAVE_ALL */ -/* for (int ii=0; iiwriteImage(tit); */ -/* } */ -/* #endif */ - int nnx, nny, ns; - getImage(nnx, nny, ns); - //int nnx, nny, ns; - int nn=dets[0]->getImageSize(nnx, nny, ns); - float *gm=new float[nn]; - if (gm) { - for (int ix=0; ix0 && ix/nnx<350) cout << ix/nnx << " " << ix%nnx << " " << image[ix]<< " " << gm[ix] << endl; - } - //cout << "image " << nnx << " " << nny << endl; - WriteToTiff(gm,imgname ,nnx, nny); - delete [] gm; - } else cout << "Could not allocate float image " << endl; - return NULL; - } - - - virtual void StartThreads() { - for (int i=0; iStartThread(); - } - - } - - - - virtual void StopThreads() { - for (int i=0; iStopThread(); - - } - - - virtual int isBusy() { - int ret=0, ret1; - for (int i=0; iisBusy(); - ret|=ret1; - // if (ret1) cout << "thread " << i <<" still busy " << endl; - } - return ret; - } - - - virtual bool pushData(char* &ptr) { - dets[ithread]->pushData(ptr); - } - - virtual bool popFree(char* &ptr) { - // cout << ithread << endl; - dets[ithread]->popFree(ptr); - } - - virtual int nextThread() { - ithread++; - if (ithread==nThreads) ithread=0; - return ithread; - } - - - virtual double *getPedestal(){ - int nx, ny; - dets[0]->getDetectorSize(nx,ny); - if (ped) delete [] ped; - ped=new double[nx*ny]; - double *p0=new double[nx*ny]; - - for (int i=0; igetInterpolation(nb,emi,ema); - // cout << i << endl; - p0=dets[i]->getPedestal(p0); - if (p0) { - if (i==0) { - - for (int ib=0; ibgetDetectorSize(nx,ny); - if (h==NULL) h=ped; - for (int i=0; isetPedestal(h); - } - - return NULL; - }; - - - - - virtual void *writePedestal(const char * imgname){ - - int nx, ny; - dets[0]->getDetectorSize(nx,ny); - - getPedestal(); - float *gm=new float[nx*ny]; - if (gm) { - for (int ix=0; ixgetDetectorSize(nx,ny); - uint32 nnx; - uint32 nny; - float *gm=ReadFromTiff(imgname, nnx, nny); - if (ped) delete [] ped; - if (nnx>nx) nx=nnx; - if (nny>ny) ny=nny; - ped=new double[nx*ny]; - - for (int ix=0; ixsetFilePointer(f); - //dets[i]->setMutex(&fmutex); - } - return dets[0]->getFilePointer(); - }; - - /** gets file pointer where to write the clusters to - \returns current file pointer - */ - virtual FILE *getFilePointer(){return dets[0]->getFilePointer();}; - - - - protected: - bool stop; - const int nThreads; - threadedAnalogDetector *dets[MAXTHREADS]; - analogDetector *dd[MAXTHREADS]; - int ithread; - int *image; - int *ff; - double *ped; - pthread_mutex_t fmutex; -}; - -#endif - - - - - - - - - - - - - - - - - - diff --git a/slsDetectorCalibration/multiThreadedCountingDetector.h b/slsDetectorCalibration/multiThreadedCountingDetector.h deleted file mode 100644 index bb5048b53..000000000 --- a/slsDetectorCalibration/multiThreadedCountingDetector.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef MULTITHREADED_COUNTING_DETECTOR_H -#define MULTITHREADED_COUNTING_DETECTOR_H - - -#include "singlePhotonDetector.h" -#include "multiThreadedAnalogDetector.h" -//#include - - -using namespace std; - - -/* class threadedCountingDetector : public threadedAnalogDetector */ -/* { */ -/* public: */ -/* threadedCountingDetector(singlePhotonDetector *d, int fs=10000) : threadedAnalogDetector(d,fs) {}; */ - - -/* }; */ - - - -class multiThreadedCountingDetector : public multiThreadedAnalogDetector -{ -public: - multiThreadedCountingDetector(singlePhotonDetector *d, int n, int fs=1000) : multiThreadedAnalogDetector(d,n,fs) { }; - - virtual double setNSigma(double n) {double ret; for (int i=0; isetNSigma(n); return ret;}; - virtual void setEnergyRange(double emi, double ema) {for (int i=0; isetEnergyRange(emi,ema);}; - -}; - -#endif - - - - - - - - - - - - - - - - - - diff --git a/slsDetectorCalibration/multiThreadedInterpolatingDetector.h b/slsDetectorCalibration/multiThreadedInterpolatingDetector.h deleted file mode 100644 index bda801afa..000000000 --- a/slsDetectorCalibration/multiThreadedInterpolatingDetector.h +++ /dev/null @@ -1,112 +0,0 @@ -#ifndef MULTITHREADED_INTERPOLATING_DETECTOR_H -#define MULTITHREADED_INTERPOLATING_DETECTOR_H - - -#include "interpolatingDetector.h" -#include "multiThreadedCountingDetector.h" -//#include - - -using namespace std; - - - -class multiThreadedInterpolatingDetector : public multiThreadedCountingDetector -{ -public: - multiThreadedInterpolatingDetector(interpolatingDetector *d, int n, int fs=1000) : multiThreadedCountingDetector(d,n,fs) { }; - - virtual void prepareInterpolation(int &ok){ - /* getFlatField(); //sum up all etas */ - /* setFlatField(); //set etas to all detectors */ - /* for (int i=0; iprepareInterpolation(ok); - // } - } - - virtual int *getFlatField(){ - return (dets[0])->getFlatField(); - } - - virtual int *getFlatField(int &nb, double emi, double ema){ - return (dets[0])->getFlatField(nb,emi,ema); - } - - virtual int *setFlatField(int *h=NULL, int nb=-1, double emin=1, double emax=0){ - return (dets[0])->setFlatField(h,nb,emin,emax); - }; - - void *writeFlatField(const char * imgname){ - dets[0]->writeFlatField(imgname); - }; - - - void *readFlatField(const char * imgname, int nb=-1, double emin=1, double emax=0){ - (dets[0])->readFlatField(imgname, nb, emin, emax); - }; - - - virtual int setNSubPixels(int ns) { return (dets[0])->setNSubPixels(ns);}; - - virtual void resetFlatField() {(dets[0])->resetFlatField();}; - - -/** sets file pointer where to write the clusters to - \param f file pointer - \returns current file pointer -*/ - virtual slsInterpolation *setInterpolation(slsInterpolation *f){ - int ok; - for (int i=0; isetInterpolation(f); - return (dets[0])->getInterpolation(); - }; - - virtual slsInterpolation *getInterpolation(){ - - return (dets[0])->getInterpolation(); - }; - - - - virtual int *getImage(int &nnx, int &nny, int &ns) { - if (getInterpolation()==NULL) return multiThreadedAnalogDetector::getImage(nnx,nny,ns); - //if one interpolates, the whole image is stored in detector 0; - int *img; - // int nnx, nny, ns; - // int nnx, nny, ns; - int nn=dets[0]->getImageSize(nnx, nny,ns); - if (image) { - delete image; - image=NULL; - } - image=new int[nn]; - img=dets[0]->getImage(); - for (int i=0; i -#endif - - -#ifndef EVTYPE_DEF -#define EVTYPE_DEF -/** enum to define the even types */ -enum eventType { - PEDESTAL=0, /** pedestal */ - NEIGHBOUR=1, /** neighbour i.e. below threshold, but in the cluster of a photon */ - PHOTON=2, /** photon i.e. above threshold */ - PHOTON_MAX=3, /** maximum of a cluster satisfying the photon conditions */ - NEGATIVE_PEDESTAL=4, /** negative value, will not be accounted for as pedestal in order to avoid drift of the pedestal towards negative values */ - UNDEFINED_EVENT=-1 /** undefined */ -}; -#endif - -//template class singlePhotonDetector : -//public analogDetector { -class singlePhotonDetector : -public analogDetector { - - /** @short class to perform pedestal subtraction etc. and find single photon clusters for an analog detector */ - - public: - - - /** - - Constructor (no error checking if datasize and offsets are compatible!) - \param d detector data structure to be used - \param csize cluster size (should be an odd number). Defaults to 3 - \param nsigma number of rms to discriminate from the noise. Defaults to 5 - \param sign 1 if photons are positive, -1 if negative - \param cm common mode subtraction algorithm, if any. Defaults to NULL i.e. none - \param nped number of samples for pedestal averaging - \param nd number of dark frames to average as pedestals without photon discrimination at the beginning of the measurement - - - */ - - - singlePhotonDetector(slsDetectorData *d, - int csize=3, - double nsigma=5, - int sign=1, - commonModeSubtraction *cm=NULL, - int nped=1000, - int nd=100, int nnx=-1, int nny=-1, double *gm=NULL) : analogDetector(d, sign, cm, nped, nnx, nny, gm), nDark(nd), eventMask(NULL),nSigma (nsigma), clusterSize(csize), clusterSizeY(csize), clusters(NULL), quad(UNDEFINED_QUADRANT), tot(0), quadTot(0), eMin(-1), eMax(-1) { - - - - - fm=new pthread_mutex_t ; - - eventMask=new eventType*[ny]; - for (int i=0; i(orig) { - - nDark=orig->nDark; - myFile=orig->myFile; - - eventMask=new eventType*[ny]; - for (int i=0; ieMin; - eMax=orig->eMax; - - - nSigma=orig->nSigma; - clusterSize=orig->clusterSize; - clusterSizeY=orig->clusterSizeY; - // cluster=new single_photon_hit(clusterSize,clusterSizeY); - clusters=new single_photon_hit[nx*ny]; - - // cluster=clusters; - - setClusterSize(clusterSize); - fm=orig->fm; - - quad=UNDEFINED_QUADRANT; - tot=0; - quadTot=0; - gmap=orig->gmap; - nphTot=0; - nphFrame=0; - - } - - - - /** - duplicates the detector structure - \returns new single photon detector with same parameters - - */ - virtual singlePhotonDetector *Clone() { - return new singlePhotonDetector(this); - } - /** sets/gets number of rms threshold to detect photons - \param n number of sigma to be set (0 or negative gets) - \returns actual number of sigma parameter - */ - double setNSigma(double n=-1){if (n>=0) nSigma=n; return nSigma;} - - /** sets/gets cluster size - \param n cluster size to be set, (0 or negative gets). If even is incremented by 1. - \returns actual cluster size - */ - int setClusterSize(int n=-1){ - if (n>0 && n!=clusterSize) { - if (n%2==0) - n+=1; - clusterSize=n; - // if (clusters) - // delete [] clusters; - if (ny>clusterSize) - clusterSizeY=clusterSize; - else - clusterSizeY=1; - for (int ip=0; ipset_cluster_size(clusterSize,clusterSizeY); - //cluster=new single_photon_hit(clusterSize,clusterSizeY); - } - return clusterSize; - } - - - - /** - converts the image into number of photons - \param data pointer to data - \param nph pointer where to add the calculated photons. If NULL, the internal image will be used - \returns array with data converted into number of photons. - */ - - virtual int *getNPhotons(char *data, int *nph=NULL) { - - nphFrame=0; - double val; - if (nph==NULL) - nph=image; - //nph=new int[nx*ny]; - - double rest[ny][nx]; - int cy=(clusterSizeY+1)/2; //quad size - int cs=(clusterSize+1)/2; //quad size - - int ccs=clusterSize; //cluster size - int ccy=clusterSizeY; //cluster size - - double g=1.; - - - double tthr=thr, tthr1, tthr2; - int nn=0; - double max=0, tl=0, tr=0, bl=0,br=0, v; - double rms=0; - - int cm=0; - if (cmSub) cm=1; - - if (thr>0) { - cy=1; - cs=1; - ccs=1; - ccy=1; - } - if (iframe0) { - newFrame(); - if (cmSub) { - cout << "add to common mode?"<< endl; - addToCommonMode(data); - } - for (int iy=ymin; iyisGood(ix,iy)) { - val=subtractPedestal(data,ix,iy, cm); - - nn=analogDetector::getNPhotons(data,ix,iy);//val/thr;// - if (nn>0) { - nph[ix+nx*iy]+=nn; - rest[iy][ix]=(val-nn*thr);//?+0.5*thr - nphFrame+=nn; - nphTot+=nn; - } else - rest[iy][ix]=val; - - } - } - } - - for (int iy=ymin; iyisGood(ix,iy)) { - eventMask[iy][ix]=PEDESTAL; - max=0; - tl=0; - tr=0; - bl=0; - br=0; - tot=0; - quadTot=0; - - if (rest[iy][ix]>0.25*thr) { - eventMask[iy][ix]=NEIGHBOUR; - for (int ir=-(clusterSizeY/2); ir<(clusterSizeY/2)+1; ir++) { - for (int ic=-(clusterSize/2); ic<(clusterSize/2)+1; ic++) { - if ((iy+ir)>=0 && (iy+ir)=0 && (ix+ic)set_data(rest[iy+ir][ix+ic], ic, ir); - - - v=rest[iy+ir][ix+ic];//clusters->get_data(ic,ir); - tot+=v; - - if (ir<=0 && ic<=0) - bl+=v; - if (ir<=0 && ic>=0) - br+=v; - if (ir>=0 && ic<=0) - tl+=v; - if (ir>=0 && ic>=0) - tr+=v; - - if (v>max) { - max=v; - } - // if (ir==0 && ic==0) { - //} - } - } - - if (rest[iy][ix]>=max) { - if (bl>=br && bl>=tl && bl>=tr) { - quad=BOTTOM_LEFT; - quadTot=bl; - } else if (br>=bl && br>=tl && br>=tr) { - quad=BOTTOM_RIGHT; - quadTot=br; - } else if (tl>=br && tl>=bl && tl>=tr) { - quad=TOP_LEFT; - quadTot=tl; - } else if (tr>=bl && tr>=tl && tr>=br) { - quad=TOP_RIGHT; - quadTot=tr; - } - - if (nSigma==0) { - tthr=thr; - tthr1=thr; - tthr2=thr; - } else { - - rms=getPedestalRMS(ix,iy); - tthr=nSigma*rms; - - tthr1=nSigma*sqrt(clusterSize*clusterSizeY)*rms; - tthr2=nSigma*sqrt((clusterSize+1)/2.*((clusterSizeY+1)/2.))*rms; - - - if (thr>2*tthr) tthr=thr-tthr; - if (thr>2*tthr1) tthr1=tthr-tthr1; - if (thr>2*tthr2) tthr2=tthr-tthr2; - - } - - if (tot>tthr1 || quadTot>tthr2 || max>tthr) { - eventMask[iy][ix]=PHOTON; - nph[ix+nx*iy]++; - rest[iy][ix]-=thr; - nphFrame++; - nphTot++; - - } - } - } - } - } - } - } - } else return getClusters(data, nph); - } - return NULL; - }; - - - - - - -/** - Loops in the region of interest to find the clusters - \param data pointer to the data structure - \returns number of clusters found - - */ - -int *getClusters(char *data, int *ph=NULL) { - - - int nph=0; - double val[ny][nx]; - int cy=(clusterSizeY+1)/2; - int cs=(clusterSize+1)/2; - int ir, ic; - - double max=0, tl=0, tr=0, bl=0,br=0, *v, vv; - int cm=0; - int good=1; - if (cmSub) cm=1; - if (ph==NULL) - ph=image; - - if (iframeisGood(ix,iy)) { - max=0; - tl=0; - tr=0; - bl=0; - br=0; - tot=0; - quadTot=0; - quad=UNDEFINED_QUADRANT; - - - - eventMask[iy][ix]=PEDESTAL; - - - (clusters+nph)->rms=getPedestalRMS(ix,iy); - // cluster=clusters+nph; - - - for (int ir=-(clusterSizeY/2); ir<(clusterSizeY/2)+1; ir++) { - for (int ic=-(clusterSize/2); ic<(clusterSize/2)+1; ic++) { - - if ((iy+ir)>=iy && (iy+ir)=ix && (ix+ic)=0) - br+=*v; - if (ir>=0 && ic<=0) - tl+=*v; - if (ir>=0 && ic>=0) - tr+=*v; - if (*v>max) { - max=*v; - } - - - if (ir==0 && ic==0) { - if (*v<-nSigma*(clusters+nph)->rms) - eventMask[iy][ix]=NEGATIVE_PEDESTAL; - else if (*v>nSigma*(clusters+nph)->rms) - eventMask[iy][ix]=PHOTON; - } - - } - } - if (eventMask[iy][ix]==PHOTON && val[iy][ix]=br && bl>=tl && bl>=tr) { - (clusters+nph)->quad=BOTTOM_LEFT; - (clusters+nph)->quadTot=bl; - } else if (br>=bl && br>=tl && br>=tr) { - (clusters+nph)->quad=BOTTOM_RIGHT; - (clusters+nph)->quadTot=br; - } else if (tl>=br && tl>=bl && tl>=tr) { - (clusters+nph)->quad=TOP_LEFT; - (clusters+nph)->quadTot=tl; - } else if (tr>=bl && tr>=tl && tr>=br) { - (clusters+nph)->quad=TOP_RIGHT; - (clusters+nph)->quadTot=tr; - } - - if (max>nSigma*(clusters+nph)->rms || tot>sqrt(clusterSizeY*clusterSize)*nSigma*(clusters+nph)->rms || ((clusters+nph)->quadTot)>sqrt(cy*cs)*nSigma*(clusters+nph)->rms) { - if (val[iy][ix]>=max) { - eventMask[iy][ix]=PHOTON_MAX; - (clusters+nph)->tot=tot; - (clusters+nph)->x=ix; - (clusters+nph)->y=iy; - // (clusters+nph)->iframe=det->getFrameNumber(data); - // cout << det->getFrameNumber(data) << " " << (clusters+nph)->iframe << endl; - (clusters+nph)->ped=getPedestal(ix,iy,0); - for (int ir=-(clusterSizeY/2); ir<(clusterSizeY/2)+1; ir++) { - for (int ic=-(clusterSize/2); ic<(clusterSize/2)+1; ic++) { - (clusters+nph)->set_data(val[iy+ir][ix+ic],ic,ir); - } - } - good=1; - if (eMin>0 && tot0 && tot>eMax) good=0; - if (good) { - nph++; - image[iy*nx+ix]++; - } - - - } else { - eventMask[iy][ix]=PHOTON; - } - } else if (eventMask[iy][ix]==PEDESTAL) { - addToPedestal(data,ix,iy,cm); - } - } - } - } - nphFrame=nph; - nphTot+=nph; - //cout << nphFrame << endl; - // cout <<"**********************************"<< det->getFrameNumber(data) << " " << nphFrame << endl; - writeClusters(det->getFrameNumber(data)); - return image; - -}; - - - /**< - returns the total signal in a cluster - \param size cluser size should be 1,2 or 3 - \returns cluster center if size=1, sum of the maximum quadrant if size=2, total of the cluster if size=3 or anything else - */ - - double getClusterTotal(int size) { - switch (size) { - case 1: - return getClusterElement(0,0); - case 2: - return quadTot; - default: - return tot; - }; - }; - - /**< - retrurns the quadrant with maximum signal - \returns quadrant where the cluster is located */ - - quadrant getQuadrant() {return quad;}; - - - /** returns value for cluster element in relative coordinates - \param ic x coordinate (center is (0,0)) - \param ir y coordinate (center is (0,0)) - \returns cluster element - */ - double getClusterElement(int ic, int ir=0){return clusters->get_data(ic,ir);}; - - /** returns event mask for the given pixel - \param ic x coordinate (center is (0,0)) - \param ir y coordinate (center is (0,0)) - \returns event mask enum for the given pixel - */ - eventType getEventMask(int ic, int ir=0){return eventMask[ir][ic];}; - - -#ifdef MYROOT1 - /** generates a tree and maps the branches - \param tname name for the tree - \param iFrame pointer to the frame number - \returns returns pointer to the TTree - */ - TTree *initEventTree(char *tname, int *iFrame=NULL) { - TTree* tall=new TTree(tname,tname); - - if (iFrame) - tall->Branch("iFrame",iFrame,"iframe/I"); - else - tall->Branch("iFrame",&(clusters->iframe),"iframe/I"); - - tall->Branch("x",&(clusters->x),"x/I"); - tall->Branch("y",&(clusters->y),"y/I"); - char tit[100]; - sprintf(tit,"data[%d]/D",clusterSize*clusterSizeY); - tall->Branch("data",clusters->data,tit); - tall->Branch("pedestal",&(clusters->ped),"pedestal/D"); - tall->Branch("rms",&(clusters->rms),"rms/D"); - tall->Branch("tot",&(clusters->tot),"tot/D"); - tall->Branch("quadTot",&(clusters->quadTot),"quadTot/D"); - tall->Branch("quad",&(clusters->quad),"quad/I"); - return tall; - }; -#else -/** write cluster to filer - \param f file pointer -*/ - void writeCluster(FILE* f){clusters->write(f);}; - -/** - write clusters to file - \param f file pointer - \param clusters array of clusters structures - \param nph number of clusters to be written to file - -*/ - - static void writeClusters(FILE *f, single_photon_hit *cl, int nph, int fn=0){ - -/* #ifndef OLDFORMAT */ -/* if (fwrite((void*)&fn, 1, sizeof(int), f)) */ -/* if (fwrite((void*)&nph, 1, sizeof(int), f)) */ -/* #endif */ - for (int i=0; iwrite(f); -}; - void writeClusters(FILE *f, int fn=0){ - writeClusters(f,clusters,nphFrame, fn); - //for (int i=0; iwrite(f); -}; - void writeClusters(int fn){ - if (myFile) { - //cout << "++" << endl; - pthread_mutex_lock(fm); - // cout <<"**********************************"<< fn << " " << nphFrame << endl; - writeClusters(myFile,clusters,nphFrame, fn); - // for (int i=0; iwrite(myFile); - pthread_mutex_unlock(fm); - //cout << "--" << endl; - } - }; -#endif - - virtual void processData(char *data, int *val=NULL) { - // cout << "sp" << endl; - switch(fMode) { - case ePedestal: - //cout <<"spc add to ped " << endl; - addToPedestal(data); - break; - default: - switch (dMode) { - case eAnalog: - analogDetector::processData(data,val); - break; - default: - // cout <<"spc " << endl; - getNPhotons(data,val); - } - } - iframe++; - // cout << "done" << endl; - }; - int getPhFrame(){return nphFrame;}; - int getPhTot(){return nphTot;}; - - void setEnergyRange(double emi, double ema){eMin=emi; eMax=ema;}; - void getEnergyRange(double &emi, double &ema){emi=eMin; ema=eMax;}; - - void setMutex(pthread_mutex_t *m){fm=m;}; - - protected: - - int nDark; /**< number of frames to be used at the beginning of the dataset to calculate pedestal without applying photon discrimination */ - eventType **eventMask; /**< matrix of event type or each pixel */ - double nSigma; /**< number of sigma parameter for photon discrimination */ - double eMin, eMax; - int clusterSize; /**< cluster size in the x direction */ - int clusterSizeY; /**< cluster size in the y direction i.e. 1 for strips, clusterSize for pixels */ - // single_photon_hit *cluster; /**< single photon hit data structure */ - single_photon_hit *clusters; /**< single photon hit data structure */ - quadrant quad; /**< quadrant where the photon is located */ - double tot; /**< sum of the 3x3 cluster */ - double quadTot; /**< sum of the maximum 2x2cluster */ - int nphTot; - int nphFrame; - - pthread_mutex_t *fm; - - }; - - - - - -#endif diff --git a/slsDetectorCalibration/single_photon_hit.h b/slsDetectorCalibration/single_photon_hit.h deleted file mode 100644 index 7bb53120f..000000000 --- a/slsDetectorCalibration/single_photon_hit.h +++ /dev/null @@ -1,263 +0,0 @@ -#ifndef SINGLE_PHOTON_HIT_H -#define SINGLE_PHOTON_HIT_H -#include -#include - -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; - -#ifndef DEF_QUAD -#define DEF_QUAD - enum quadrant { - TOP_LEFT=0, - TOP_RIGHT=1, - BOTTOM_LEFT=2, - BOTTOM_RIGHT=3, - UNDEFINED_QUADRANT=-1 - }; -#endif - - -class single_photon_hit { - - /** @short Structure for a single photon hit */ - - public: - /** constructor, instantiates the data array -- all class elements are public! - \param nx cluster size in x direction - \param ny cluster size in y direction (defaults to 1 for 1D detectors) - */ - single_photon_hit(int nx=3, int ny=3): dx(nx), dy(ny) {data=new int[dx*dy];}; - - ~single_photon_hit(){delete [] data;}; /**< destructor, deletes the data array */ - - /** binary write to file of all elements of the structure, except size of the cluster - \param myFile file descriptor - */ - size_t write(FILE *myFile) { - //fwrite((void*)this, 1, 3*sizeof(int)+4*sizeof(double)+sizeof(quad), myFile); - - // if (fwrite((void*)this, 1, sizeof(int)+2*sizeof(int16_t), myFile)) - //#ifdef OLDFORMAT - if (fwrite((void*)&iframe, 1, sizeof(int), myFile)) {}; - //#endif -#ifndef WRITE_QUAD - //printf("no quad "); - if (fwrite((void*)&x, 2, sizeof(int16_t), myFile)) - return fwrite((void*)data, 1, dx*dy*sizeof(int), myFile); -#endif -#ifdef WRITE_QUAD - // printf("quad "); - int qq[4]; - switch(quad) { - case TOP_LEFT: - qq[0]=data[3]; - qq[1]=data[4]; - qq[2]=data[6]; - qq[3]=data[7]; - x=x-1; - y=y; - break; - - case TOP_RIGHT: - qq[0]=data[4]; - qq[1]=data[5]; - qq[2]=data[7]; - qq[3]=data[8]; - x=x; - y=y; - break; - - - case BOTTOM_LEFT: - qq[0]=data[0]; - qq[1]=data[1]; - qq[2]=data[3]; - qq[3]=data[4]; - x=x-1; - y=y-1; - break; - case BOTTOM_RIGHT: - qq[0]=data[1]; - qq[1]=data[2]; - qq[2]=data[4]; - qq[3]=data[5]; - x=x; - y=y-1; - break; - - - default: - ; - } - if (fwrite((void*)&x, 2, sizeof(int16_t), myFile)) - return fwrite((void*)qq, 1, 4*sizeof(int), myFile); -#endif - return 0; - }; - - /** - binary read from file of all elements of the structure, except size of the cluster. The structure is then filled with those args - \param myFile file descriptor - */ - size_t read(FILE *myFile) { - //fread((void*)this, 1, 3*sizeof(int)+4*sizeof(double)+sizeof(quad), myFile); - - //#ifdef OLDFORMAT - if (fread((void*)&iframe, 1, sizeof(int), myFile)) {} - //#endif -#ifndef WRITE_QUAD - // printf( "no quad \n"); - if (fread((void*)&x, 2, sizeof(int16_t), myFile)) - return fread((void*)data, 1, dx*dy*sizeof(int), myFile); -#endif -#ifdef WRITE_QUAD - int qq[4]; - // printf( "quad \n"); - if (fread((void*)&x, 2, sizeof(int16_t), myFile)) - if (fread((void*)qq, 1, 4*sizeof(int), myFile)) { - - quad=TOP_RIGHT; - int mm=qq[0]; - for (int i=1; i<4; i++) { - if (qq[i]0) dx=nx; if (ny>0) dy=ny; delete [] data; data=new int[dx*dy];}; - void get_cluster_size(int &nx, int &ny) {nx=dx; ny=dy;}; - void get_pixel(int &x1, int &y1) {x1=x; y1=y;}; - - /** - gets the value to the element of the cluster matrix, with relative coordinates where the center of the cluster is (0,0) - \param ix coordinate x within the cluster (center is (0,0)) - \param iy coordinate y within the cluster (center is (0,0)) - \returns value of the cluster element - */ - double get_data(int ix, int iy=0){return data[(iy+dy/2)*dx+ix+dx/2];}; - int *get_cluster() {return data;}; - - int iframe; /**< frame number */ - int16_t x; /**< x-coordinate of the center of hit */ - int16_t y; /**< x-coordinate of the center of hit */ - double rms; /**< noise of central pixel l -- at some point it can be removed*/ - double ped; /**< pedestal of the central pixel -- at some point it can be removed*/ - double tot; /**< sum of the 3x3 cluster */ - quadrant quad; /**< quadrant where the photon is located */ - double quadTot; /**< sum of the maximum 2x2cluster */ - int dx; /**< size of data cluster in x */ - int dy; /**< size of data cluster in y */ - int *data; /**< pointer to data */ -}; - - - -#endif diff --git a/slsDetectorCalibration/single_photon_hit_double.h b/slsDetectorCalibration/single_photon_hit_double.h deleted file mode 100644 index 7019b4149..000000000 --- a/slsDetectorCalibration/single_photon_hit_double.h +++ /dev/null @@ -1,98 +0,0 @@ -#ifndef SINGLE_PHOTON_HIT_H -#define SINGLE_PHOTON_HIT_H -#include -#include - -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; - -#ifndef DEF_QUAD -#define DEF_QUAD - enum quadrant { - TOP_LEFT=0, - TOP_RIGHT=1, - BOTTOM_LEFT=2, - BOTTOM_RIGHT=3, - UNDEFINED_QUADRANT=-1 - }; -#endif - - -class single_photon_hit_double { - - /** @short Structure for a single photon hit */ - - public: - /** constructor, instantiates the data array -- all class elements are public! - \param nx cluster size in x direction - \param ny cluster size in y direction (defaults to 1 for 1D detectors) - */ - single_photon_hit_double(int nx=3, int ny=3): dx(nx), dy(ny) { - data=new double[dx*dy]; - }; - - ~single_photon_hit_double(){delete [] data;}; /**< destructor, deletes the data array */ - - /** binary write to file of all elements of the structure, except size of the cluster - \param myFile file descriptor - */ - size_t write(FILE *myFile) { - //fwrite((void*)this, 1, 3*sizeof(int)+4*sizeof(double)+sizeof(quad), myFile); - if (fwrite((void*)this, 1, sizeof(int)+2*sizeof(int), myFile)) - return fwrite((void*)data, 1, dx*dy*sizeof(double), myFile); - return 0; - }; - - /** - binary read from file of all elements of the structure, except size of the cluster. The structure is then filled with those args - \param myFile file descriptor - */ - size_t read(FILE *myFile) { - //fread((void*)this, 1, 3*sizeof(int)+4*sizeof(double)+sizeof(quad), myFile); - - if (fread((void*)this, 1, sizeof(int)+2*sizeof(int), myFile)) - return fread((void*)data, 1, dx*dy*sizeof(double), myFile); - return 0; - }; - - /** - assign the value to the element of the cluster matrix, with relative coordinates where the center of the cluster is (0,0) - \param v value to be set - \param ix coordinate x within the cluster (center is (0,0)) - \param iy coordinate y within the cluster (center is (0,0)) - */ - void set_data(double v, int ix, int iy=0){data[(iy+dy/2)*dx+ix+dx/2]=v;}; - - void set_cluster_size(int nx, int ny) { - - if (nx>0) dx=nx; if (ny>0) dy=ny; delete [] data; data=new double[dx*dy]; - }; - void get_cluster_size(int &nx, int &ny) {nx=dx; ny=dy;}; - void get_pixel(int &x1, int &y1) {x1=x; y1=y;}; - - /** - gets the value to the element of the cluster matrix, with relative coordinates where the center of the cluster is (0,0) - \param ix coordinate x within the cluster (center is (0,0)) - \param iy coordinate y within the cluster (center is (0,0)) - \returns value of the cluster element - */ - double get_data(int ix, int iy=0){return data[(iy+dy/2)*dx+ix+dx/2];}; - double *get_cluster() {return data;}; - - int iframe; /**< frame number */ - int x; /**< x-coordinate of the center of hit */ - int y; /**< x-coordinate of the center of hit */ - double rms; /**< noise of central pixel l -- at some point it can be removed*/ - double ped; /**< pedestal of the central pixel -- at some point it can be removed*/ - double tot; /**< sum of the 3x3 cluster */ - quadrant quad; /**< quadrant where the photon is located */ - double quadTot; /**< sum of the maximum 2x2cluster */ - int dx; /**< size of data cluster in x */ - int dy; /**< size of data cluster in y */ - double *data; /**< pointer to data */ -}; - - - -#endif diff --git a/slsDetectorCalibration/single_photon_hit_old.h b/slsDetectorCalibration/single_photon_hit_old.h deleted file mode 100644 index 587a09c1f..000000000 --- a/slsDetectorCalibration/single_photon_hit_old.h +++ /dev/null @@ -1,93 +0,0 @@ -#ifndef SINGLE_PHOTON_HIT_H -#define SINGLE_PHOTON_HIT_H -#include -#include - -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; - -#ifndef DEF_QUAD -#define DEF_QUAD - enum quadrant { - TOP_LEFT=0, - TOP_RIGHT=1, - BOTTOM_LEFT=2, - BOTTOM_RIGHT=3, - UNDEFINED_QUADRANT=-1 - }; -#endif - - -class single_photon_hit { - - /** @short Structure for a single photon hit */ - - public: - /** constructor, instantiates the data array -- all class elements are public! - \param nx cluster size in x direction - \param ny cluster size in y direction (defaults to 1 for 1D detectors) - */ - single_photon_hit(int nx=3, int ny=3): dx(nx), dy(ny) {data=new int[dx*dy];}; - - ~single_photon_hit(){delete [] data;}; /**< destructor, deletes the data array */ - - /** binary write to file of all elements of the structure, except size of the cluster - \param myFile file descriptor - */ - size_t write(FILE *myFile) { - //fwrite((void*)this, 1, 3*sizeof(int)+4*sizeof(double)+sizeof(quad), myFile); - if (fwrite((void*)this, 1, sizeof(int)+2*sizeof(int16_t), myFile)) - return fwrite((void*)data, 1, dx*dy*sizeof(int), myFile); - return 0; - }; - - /** - binary read from file of all elements of the structure, except size of the cluster. The structure is then filled with those args - \param myFile file descriptor - */ - size_t read(FILE *myFile) { - //fread((void*)this, 1, 3*sizeof(int)+4*sizeof(double)+sizeof(quad), myFile); - - if (fread((void*)this, 1, sizeof(int)+2*sizeof(int16_t), myFile)) - return fread((void*)data, 1, dx*dy*sizeof(int), myFile); - return 0; - }; - - /** - assign the value to the element of the cluster matrix, with relative coordinates where the center of the cluster is (0,0) - \param v value to be set - \param ix coordinate x within the cluster (center is (0,0)) - \param iy coordinate y within the cluster (center is (0,0)) - */ - void set_data(double v, int ix, int iy=0){data[(iy+dy/2)*dx+ix+dx/2]=v;}; - - void set_cluster_size(int nx, int ny) {if (nx>0) dx=nx; if (ny>0) dy=ny; delete [] data; data=new int[dx*dy];}; - void get_cluster_size(int &nx, int &ny) {nx=dx; ny=dy;}; - void get_pixel(int &x1, int &y1) {x1=x; y1=y;}; - - /** - gets the value to the element of the cluster matrix, with relative coordinates where the center of the cluster is (0,0) - \param ix coordinate x within the cluster (center is (0,0)) - \param iy coordinate y within the cluster (center is (0,0)) - \returns value of the cluster element - */ - double get_data(int ix, int iy=0){return data[(iy+dy/2)*dx+ix+dx/2];}; - int *get_cluster() {return data;}; - - int iframe; /**< frame number */ - int16_t x; /**< x-coordinate of the center of hit */ - int16_t y; /**< x-coordinate of the center of hit */ - double rms; /**< noise of central pixel l -- at some point it can be removed*/ - double ped; /**< pedestal of the central pixel -- at some point it can be removed*/ - double tot; /**< sum of the 3x3 cluster */ - quadrant quad; /**< quadrant where the photon is located */ - double quadTot; /**< sum of the maximum 2x2cluster */ - int dx; /**< size of data cluster in x */ - int dy; /**< size of data cluster in y */ - int *data; /**< pointer to data */ -}; - - - -#endif diff --git a/slsDetectorCalibration/slsDetectorCalibration.doxy b/slsDetectorCalibration/slsDetectorCalibration.doxy deleted file mode 100644 index 4ea3784d3..000000000 --- a/slsDetectorCalibration/slsDetectorCalibration.doxy +++ /dev/null @@ -1,103 +0,0 @@ -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. -# Private class members and static file members will be hidden unless -# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES - -EXTRACT_ALL = YES - -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class -# will be included in the documentation. - -EXTRACT_PRIVATE = NO - - - -# If the EXTRACT_STATIC tag is set to YES all static members of a file -# will be included in the documentation. - -EXTRACT_STATIC = YES - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) -# defined locally in source files will be included in the documentation. -# If set to NO only classes defined in header files are included. - -EXTRACT_LOCAL_CLASSES = YES - -# This flag is only useful for Objective-C code. When set to YES local -# methods, which are defined in the implementation section but not in -# the interface are included in the documentation. -# If set to NO (the default) only methods in the interface are included. - -EXTRACT_LOCAL_METHODS = YES - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base -# name of the file that contains the anonymous namespace. By default -# anonymous namespace are hidden. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all -# undocumented members of documented classes, files or namespaces. -# If set to NO (the default) these members will be included in the -# various overviews, but no documentation section is generated. -# This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. -# If set to NO (the default) these classes will be included in the various -# overviews. This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all -# friend (class|struct|union) declarations. -# If set to NO (the default) these declarations will be included in the -# documentation. - -HIDE_FRIEND_COMPOUNDS = NO - -INTERNAL_DOCS = NO - -SHOW_INCLUDE_FILES = NO - -SHOW_FILES = NO - -SHOW_NAMESPACES = NO - -COMPACT_LATEX = YES - -PAPER_TYPE = a4 - -PDF_HYPERLINKS = YES - -USE_PDFLATEX = YES - -LATEX_HIDE_INDICES = YES - -PREDEFINED = __cplusplus - -INPUT = analogDetector.h \ - pedestalSubtraction.h \ - MovingStat.h \ - singlePhotonDetector.h \ - interpolatingDetector.h tiffIO.h \ - single_photon_hit.h \ - dataStructures/slsDetectorData.h \ - commonModeSubtraction.h \ - RunningStat.h \ - interpolations/etaInterpolationBase.h \ - interpolations/slsInterpolation.h \ - interpolations/etaInterpolationPosXY.h \ - interpolations/linearInterpolation.h \ - interpolations/noInterpolation.h \ - interpolations/etaInterpolationGlobal.h \ - multiThreadedAnalogDetector.h - - -OUTPUT_DIRECTORY = slsDetectorCalibrationDocs - -#moench03Ctb10GbT1Data.h moench03TCtbData.h moench03T1CtbData.h moench03CtbData.h moench03Ctb10GbData.h moench03TCtb10GbData.h Mythen3_01_jctbData.h adcSar2_jctbData.h eigerHalfModuleData.h energyCalibration.h slsReceiverData.h gotthardModuleData.h gotthardShortModuleData.h jungfrau02Data.h jungfrau10ModuleData.h moench02Ctb10GbData.h moench02CtbData.h moench02ModuleData.h moench03CommonMode.h moenchCommonMode.h chiptestBoardData.h interpolation/etaVEL/interpolation_EtaVEL.h interpolation/etaVEL/EtaVEL.h etaVEL/iterativeEtaInterpolation.h dataStructures/moench03T1ZmqData.h \ No newline at end of file diff --git a/slsDetectorCalibration/slsDetectorData.h b/slsDetectorCalibration/slsDetectorData.h deleted file mode 100644 index 912573f3b..000000000 --- a/slsDetectorCalibration/slsDetectorData.h +++ /dev/null @@ -1,338 +0,0 @@ -#ifndef SLSDETECTORDATA_H -#define SLSDETECTORDATA_H - -#include -#include -#include - -using namespace std; - - -template -class slsDetectorData { - - protected: - const int nx; /**< Number of pixels in the x direction */ - const int ny; /**< Number of pixels in the y direction */ - int dataSize; /**=0 && ix=0 && iy=0 && ix=0 && iydataSize) dsize=dataSize; - for (int ip=0; ip<(dsize/sizeof(dataType)); ip++) { - getPixel(ip,ix,iy); - if (ix>=0 && ix=0 && iydataSize) dsize=dataSize; - for (int ip=0; ip<(dsize/sizeof(dataType)); ip++) { - getPixel(ip,ix,iy); - if (ix>=0 && ix=0 && iy=0 && ix=0 && iy=0 && dataMap[iy][ix] -#include // exit() -template -class slsReceiverData : public slsDetectorData { - - -public: - - /** - slsReceiver data structure. Works for data acquired using the slsDetectorReceiver subdivided in different packets with headers and footers. - Inherits and implements slsDetectorData. - - Constructor (no error checking if datasize and offsets are compatible!) - \param npx number of pixels in the x direction - \param npy number of pixels in the y direction (1 for strips) - \param np number of packets - \param psize packets size - \param dMap array of size nx*ny storing the pointers to the data in the dataset (as offset) - \param dMask Array of size nx*ny storing the polarity of the data in the dataset (should be 0 if no inversion is required, 0xffffffff is inversion is required) - \param dROI Array of size nx*ny. The elements are 1s if the channel is good or in the ROI, 0 is bad or out of the ROI. NULL (default) means all 1s. - - */ - slsReceiverData(int npx, int npy, int np, int psize, int **dMap=NULL, dataType **dMask=NULL, int **dROI=NULL): slsDetectorData(npx, npy, np*psize, dMap, dMask, dROI), nPackets(np), packetSize(psize) {}; - - - /** - - Returns the frame number for the given dataset. Virtual func: works for slsDetectorReceiver data (also for each packet), but can be overloaded. - \param buff pointer to the dataset - \returns frame number - - */ - - virtual int getFrameNumber(char *buff){return ((*(int*)buff)&(0xffffff00))>>8;}; - - /** - - Returns the packet number for the given dataset. Virtual func: works for slsDetectorReceiver packets, but can be overloaded. - \param buff pointer to the dataset - \returns packet number number - - */ - - virtual int getPacketNumber(char *buff){return (*(int*)buff)&0xff;}; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! - \param data pointer to the memory to be analyzed - \param ndata size of frame returned - \param dsize size of the memory slot to be analyzed - \returns pointer to the first packet of the last good frame (might be incomplete if npackets lower than the number of packets), or NULL if no frame is found - - */ - - virtual char *findNextFrame(char *data, int &ndata, int dsize) { - char *retval=NULL, *p=data; - int dd=0; - int fn, fnum=-1, np=0, pnum=-1; - while (dd<=(dsize-packetSize)) { - pnum=getPacketNumber(p); - fn=getFrameNumber(p); - //cout <<"fnum:"<nPackets) { - //cout << "Bad packet number " << pnum << " frame "<< fn << endl; - retval=NULL; - np=0; - } else if (pnum==1) { - retval=p; - if (np>0) - /*cout << "*Incomplete frame number " << fnum << endl;*/ - np=0; - fnum=fn; - } else if (fn!=fnum) { - if (fnum!=-1) { - /* cout << " **Incomplete frame number " << fnum << " pnum " << pnum << " " << getFrameNumber(p) << endl;*/ - retval=NULL; - } - np=0; - } - p+=packetSize; - dd+=packetSize; - np++; - //cout <<"fnum:"<0){ - //cprintf(BG_RED, "Too few packets for this frame! fnum:%d, pnum:%d np:%d\n",fnum,pnum,np); - cout << "Too few packets for this frame! "<< fnum << " " << pnum << " " << np <nPackets) { - cout << "too many packets!!!!!!!!!!" << endl; - delete [] data; - return NULL; - } else if (retval!=NULL) { - // cout << "+" << endl;; - for (int ip=0; ipnPackets) { - cout << "*******too many packets!!!!!!!!!!" << endl; - delete [] data; - return NULL; - } else { - // cout << "." << endl;; - np++; - } - } - } - delete [] data; - return NULL; - }; - - - /** - - Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! - \param filebin input file stream (binary) - \param fnum frame number of frame returned - \returns pointer to the first packet of the last good frame, NULL if no frame is found or last frame is incomplete - - */ - - virtual char *readNextFrame(ifstream &filebin, int& fnum) { - char *data=new char[packetSize*nPackets]; - char *retval=0; - int np=0, nd; - fnum = -1; - - if (filebin.is_open()) { - while (filebin.read(data+np*packetSize,packetSize)) { - - if (np==(nPackets-1)) { - - fnum=getFrameNumber(data); //cout << "fnum:"<nPackets) { - cout << "too many packets!!!!!!!!!!" << endl; - delete [] data; - return NULL; - } else if (retval!=NULL) { - // cout << "+" << endl;; - for (int ip=0; ipnPackets) { - cout << "*******too many packets!!!!!!!!!!" << endl; - delete [] data; - return NULL; - } else { - // cout << "." << endl;; - np++; - //cout<<"np:"< -using namespace std; -// #undef cbf_failnez -// #define cbf_failnez(x) \ -// { \ -// int err; \ -// err = (x); \ -// if (err) { \ -// fprintf(stderr,"\nCBFlib fatal error %x \n",err); \ -// exit(-1); \ -// } \ -// } - -void *WriteToTiff(float * imgData, const char * imgname, int nrow, int ncol){ - int sampleperpixel=1; - // unsigned char * buff=NULL; - tsize_t linebytes; - // cout << "--" < -#include -#include -#include -#include -#include -#include - - -/*****************************************************************************/ -// -//CBFlib must be installed to use this program -// -/*****************************************************************************/ -#include "tiffio.h" - -#undef cbf_failnez -#define cbf_failnez(x) \ - { \ - int err; \ - err = (x); \ - if (err) { \ - fprintf(stderr,"\nCBFlib fatal error %x \n",err); \ - exit(-1); \ - } \ - } - -void *WriteToTiff(float * imgData, const char * imgname, int nrow, int ncol); - -float *ReadFromTiff( const char * imgname, uint32 &nrow, uint32 &ncol); - -#endif diff --git a/slsDetectorGui/.gitignore b/slsDetectorGui/.gitignore old mode 100644 new mode 100755 diff --git a/slsDetectorGui/CMakeLists.txt b/slsDetectorGui/CMakeLists.txt old mode 100644 new mode 100755 index bad299e19..aad448d94 --- a/slsDetectorGui/CMakeLists.txt +++ b/slsDetectorGui/CMakeLists.txt @@ -1,6 +1,15 @@ - set(CMAKE_AUTOMOC ON) +set(ENV{QMAKESPEC} "/afs/psi.ch/intranet/Controls/Software/Trolltech/RHEL7-x86_64/Qt-4.8.2/mkspecs/linux-g++") +set(ENV{PATH} "/afs/psi.ch/intranet/Controls/Software/Trolltech/RHEL7-x86_64/Qt-4.8.2/bin:$PATH") + +link_directories( + /afs/psi.ch/intranet/Controls/Software/Trolltech/RHEL7-x86_64/Qt-4.8.2/lib + /afs/psi.ch/intranet/Controls/Software/Trolltech/RHEL7-x86_64/qwt-6.0.1/lib + /afs/psi.ch/intranet/Controls/Software/Trolltech/RHEL7-x86_64/qwtplot3d/lib + /afs/psi.ch/project/sls_det_software/dhanya_softwareDevelopment/mySoft/slsDetectorPackage/build/bin +) + set(SOURCES slsDetectorPlotting/src/SlsQt1DPlot.cxx slsDetectorPlotting/src/SlsQt1DZoomer.cxx @@ -14,9 +23,6 @@ set(SOURCES src/qTabMeasurement.cpp src/qTabDataOutput.cpp src/qTabPlot.cpp - src/qTabActions.cpp - src/qActionsWidget.cpp - src/qScanWidget.cpp src/qTabAdvanced.cpp src/qTabSettings.cpp src/qTabDebugging.cpp @@ -33,8 +39,6 @@ set(FORMS forms/form_tab_advanced.ui forms/form_tab_settings.ui forms/form_tab_debugging.ui - forms/form_action.ui - forms/form_scan.ui ) qt4_wrap_ui(FORMS_H ${FORMS}) @@ -56,15 +60,12 @@ set(HEADERS include/qTabMeasurement.h include/qTabDataOutput.h include/qTabPlot.h - include/qTabActions.h - include/qActionsWidget.h - include/qScanWidget.h include/qTabAdvanced.h include/qTabSettings.h include/qTabDebugging.h include/qTabDeveloper.h include/qTabMessages.h - include/gitInfoGui.h + ../slsSupportLib/include/versionAPI.h include/qServer.h ) set(RESOURCES @@ -75,13 +76,7 @@ qt4_add_resources(RESOURCES_SRCS ${RESOURCES}) include_directories( include slsDetectorPlotting/include - ../slsDetectorSoftware/commonFiles - ../slsDetectorSoftware/slsReceiverInterface - ../slsDetectorSoftware/slsDetector - ../slsDetectorSoftware/slsDetectorAnalysis - ../slsDetectorSoftware/multiSlsDetector - ../slsDetectorSoftware/usersFunctions - ../slsReceiverSoftware/include + ../slsSupportLib/include ${QT_INCLUDE_DIR} ${QT_QTCORE_INCLUDE_DIR} ${QT_QTGUI_INCLUDE_DIR} @@ -90,7 +85,7 @@ include_directories( ) add_definitions( - -DDACS_INT -DVERBOSE -DPRINT_LOG + -DPRINT_LOG #-DVERBOSE ) add_executable(slsDetectorGui @@ -100,34 +95,43 @@ add_executable(slsDetectorGui ${RESOURCES_SRCS} ) -set_target_properties(slsDetectorGui PROPERTIES - LINKER_LANGUAGE CXX - RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin -) - - -target_link_libraries(slsDetectorGui +target_link_libraries(slsDetectorGui PUBLIC + slsProjectOptions + slsProjectWarnings + slsSupportLib slsDetectorShared ${QT_QTCORE_LIBRARIES} ${QT_QTGUI_LIBRARIES} ${QWT_LIBRARIES} pthread - zmq + ${ZeroMQ_LIBRARIES} rt png z Qt4::QtOpenGL Qt4::QtSvg +) +set_target_properties(slsDetectorGui PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin ) add_executable(gui_client client/qClient.h client/qClient.cpp ) + +target_link_libraries(gui_client PUBLIC + slsProjectOptions + slsProjectWarnings + slsSupportLib + slsDetectorShared + pthread + rt +) + set_target_properties(gui_client PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin ) -install(TARGETS slsDetectorGui gui_client - RUNTIME DESTINATION bin) +install(TARGETS slsDetectorGui gui_client DESTINATION bin) diff --git a/slsDetectorGui/Makefile b/slsDetectorGui/Makefile deleted file mode 100644 index d91ea4f7d..000000000 --- a/slsDetectorGui/Makefile +++ /dev/null @@ -1,68 +0,0 @@ -# LEO: Won't compile without libSlsDetector - -include ../Makefile.include - -$(info ) -$(info ##################################) -$(info # In slsDetectorGui Makefile #) -$(info ##################################) -$(info ) - - -DESTDIR ?= ../bin -LIBDIR ?= ../bin -PROG = $(DESTDIR)/slsDetectorGui -DOCDIR ?= docs - -LIBRARYDIR ?= ../slsDetectorSoftware -LIBRARYRXRDIR ?= ../slsReceiverSoftware -INCLUDES ?= $(LIBRARYDIR)/commonFiles -I$(LIBRARYRXRDIR)/MySocketTCP -I$(LIBRARYDIR)/slsReceiverInterface -I$(LIBRARYDIR)/slsDetector -I$(LIBRARYDIR)/slsDetectorAnalysis -I$(LIBRARYDIR)/multiSlsDetector -I$(LIBRARYDIR)/usersFunctions -I$(LIBRARYRXRDIR)/includes - -LDFLAGDET ?= -L$(LIBDIR) -Wl,-rpath=$(LIBDIR) -lSlsDetector - - - -#ifeq ( $(EIGERSLS), yes) -# LDFLAG += $(EIGERFLAGS) -#else ifeq ( $(ROOTSLS), yes) -# LDFLAG += $(ROOTFLAGS) -#endif - -.PHONY: all lib clean mm doc htmldoc guiclient - - -all: lib Makefile.gui $(PROG) guiclient - -lib: - cd $(LIBRARYDIR) && $(MAKE) DESTDIR=$(DESTDIR) - @echo "" - @echo "#######################################" - @echo "# Back in slsDetectorGui Makefile #" - @echo "#######################################" - @echo "" - - -clean: - if test -e Makefile.gui; then $(MAKE) -f Makefile.gui clean; $(MAKE) -f Makefile.gui mocclean; rm Makefile.gui; rm $(DESTDIR)/slsDetectorGui; else $(MAKE) Makefile.gui; $(MAKE) -f Makefile.gui clean; $(MAKE) -f Makefile.gui mocclean; rm $(DESTDIR)/slsDetectorGui; fi - cd client && $(MAKE) clean -# cd manual && make clean - - -Makefile.gui: mm - -mm: - qmake -set QT_INSTALL_PREFIX $(QTDIR) && qmake -o Makefile.gui INCLUDES='$(INCLUDES)' DESTDIR=$(DESTDIR) SLSDETLIB=$(DESTDIR) SUBLIBS='$(LDFLAGDET)' LIBDIR='$(LIBDIR)' - -doc: - cd manual && $(MAKE) DESTDIR=$(DOCDIR) - -htmldoc: - cd manual && $(MAKE) html DESTDIR=$(DOCDIR) - -$(PROG): Makefile $(DIR) src/*.cpp include/*.h slsDetectorPlotting/include/*.h slsDetectorPlotting/src/*.cxx # forms/include/*.h - $(MAKE) -f Makefile.gui SLSDETLIB=$(DESTDIR) DESTDIR=$(DESTDIR) SUBLIBS='$(LDFLAGDET)' INCLUDES='$(INCLUDES)' LIBDIR='$(LIBDIR)' - -guiclient: -# echo $(WD) - cd client && $(MAKE) DESTDIR=$(DESTDIR) - diff --git a/slsDetectorGui/client/Makefile b/slsDetectorGui/client/Makefile deleted file mode 100644 index 60f412844..000000000 --- a/slsDetectorGui/client/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -CC = g++ -CLAGS += -DVERBOSE #VERYBOSE -LDLIBS += -lm -lstdc++ -pthread - -LDIR = ../../slsDetectorSoftware -RDIR = ../../slsReceiverSoftware -DDIR = ../../bin -INCLUDES = -I $(LDIR)/commonFiles -I $(LDIR)/slsDetector -I ../include -I $(RDIR)/include -SRC_CLNT = qClient.cpp $(RDIR)/src/MySocketTCP.cpp -DEPSINCLUDES= qClient.h $(RDIR)/include/MySocketTCP.h $(LDIR)/slsDetector/slsDetectorBase.h $(LDIR)/commonFiles/sls_detector_defs.h - - -all: client - -client: $(OBJS) $(DDIR)/gui_client - -OBJS = $(SRC_CLNT:%.cpp=%.o) - - -$(DDIR)/gui_client : $(SRC_CLNT) $(DEPSINCLUDES) Makefile - $(CXX) -o $@ -c $< $(INCLUDES) $(FLAGS) $(LDLIBS) - - - -clean: - rm -rf $(DDIR)/gui_client *.o - - - - - diff --git a/slsDetectorGui/client/qClient.cpp b/slsDetectorGui/client/qClient.cpp old mode 100644 new mode 100755 index f12ced4e1..fee2b0c21 --- a/slsDetectorGui/client/qClient.cpp +++ b/slsDetectorGui/client/qClient.cpp @@ -1,237 +1,124 @@ -/* - * qClient.cpp - * - * Created on: Feb 27, 2013 - * Author: Dhanya Maliakal - */ -// Qt Project Class Headers #include "qClient.h" -// Project Class Headers -#include "MySocketTCP.h" -#include "slsDetectorBase.h" -// C++ Include Headers +#include "ClientSocket.h" +#include "logger.h" +#include "sls_detector_exceptions.h" + #include #include -using namespace std; - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int main(int argc, char *argv[]){ - qClient* cl = 0; - try { - cl = new qClient(argv[1]); - } catch(...) { - return 0; - } - cl->executeLine(argc-2, argv+2); - delete cl; - - return 0; +int main(int argc, char *argv[]) { + qClient *cl = 0; + cl = new qClient(argv[1]); + cl->executeLine(argc - 2, argv + 2); + delete cl; + return 0; } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -qClient::qClient(char* hostname): - mySocket(0), - myStopSocket(0){ - - try { - // control socket - mySocket = new MySocketTCP(hostname, DEFAULT_GUI_PORTNO); - // stop socket - myStopSocket = new MySocketTCP(hostname, DEFAULT_GUI_PORTNO+1); - } catch(...) { - if (mySocket == 0) - cout << "Error: could not connect to control server:" << - hostname << " with port " << DEFAULT_GUI_PORTNO << endl; - else - cout << "Error: could not connect to stop server:" << - hostname << " with port " << DEFAULT_GUI_PORTNO + 1 << endl; - throw; - } +qClient::qClient(char *h) + : controlPort(DEFAULT_GUI_PORTNO), stopPort(DEFAULT_GUI_PORTNO + 1) { + hostname.assign(h); } +qClient::~qClient() {} -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qClient::executeLine(int narg, char *args[]) { -qClient::~qClient() { - if(mySocket) delete mySocket; - if(myStopSocket) delete myStopSocket; + std::string retval = ""; + std::string cmd = args[0]; + + // validate command structure + if (narg < 1) { + throw sls::RuntimeError("No command parsed. " + printCommands()); + } + + // help + if (cmd == "help") { + retval = printCommands(); + } + + // file name + else if (cmd == "status") { + + if (narg > 1) { + std::string argument = args[1]; + // start acquisition + if (argument == "start") + startAcquisition(); + else if (argument == "stop") + stopAcquisition(); + else { + throw sls::RuntimeError("Could not parse arguments. " + + printCommands()); + } + } + retval = getStatus(); + } + + else if (cmd == "acquire") { + startAcquisition(true); + retval = getStatus(); + } + + else if (cmd == "exit") { + exitServer(); + retval.assign("Server exited successfully"); + } + + // unrecognized command + else { + throw sls::RuntimeError("Unrecognized command. " + printCommands()); + } + + // print result + FILE_LOG(logINFO) << cmd << ": " << retval; } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qClient::executeLine(int narg, char *args[]){ - - string retval = ""; - string cmd = args[0]; - string argument; - - - //validate command structure - if(narg<1){ - cout << "Error: no command parsed" << endl; - return FAIL; - } - - - //help - if (cmd == "help"){ - retval = printCommands(); - } - - //file name - else if (cmd == "status"){ - - if(narg>1){ - argument = args[1]; - //start acquisition - if(argument == "start") - startAcquisition(); - else if (argument == "stop") - stopAcquisition(); - else{ - cprintf(RED,"Error: could not parse arguments: %s\n", argument.c_str()); - printCommands(); - return FAIL; - } - } - retval = getStatus(); - } - - - else if (cmd == "acquire"){ - startAcquisition(true); - retval = getStatus(); - } - - - else if (cmd == "exit"){ - return exitServer(); - } - - - //unrecognized command - else{ - cout << "Error: unrecognized command" << endl; - return FAIL; - } - - - //print result - cout << cmd << ": " << retval << endl; - - return OK; +std::string qClient::printCommands() { + std::ostringstream os; + os << "\nexit \t exits servers in gui" << std::endl; + os << "status \t gets status of acquisition in gui. - can be running or " + "idle" + << std::endl; + os << "status i starts/stops acquistion in gui-non blocking. i is start " + "or stop" + << std::endl; + os << "acquire starts acquistion in gui-blocking" << std::endl; + return os.str(); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +std::string qClient::getStatus() { + int fnum = qDefs::F_GUI_GET_RUN_STATUS; + int retvals[2] = {static_cast(ERROR), 0}; + auto client = sls::GuiSocket(hostname, controlPort); + client.sendCommandThenRead(fnum, nullptr, 0, retvals, sizeof(retvals)); -string qClient::printCommands(){ - ostringstream os; - os << "\nexit \t exits servers in gui" << std::endl; - os << "status \t gets status of acquisition in gui. - can be running or idle" << std::endl; - os << "status i starts/stops acquistion in gui-non blocking. i is start or stop" << std::endl; - os << "acquire starts acquistion in gui-blocking" << std::endl; - return os.str(); + runStatus status = static_cast(retvals[0]); + int progress = retvals[1]; + return std::to_string(progress) + std::string("% ") + + slsDetectorDefs::runStatusType(status); } +void qClient::startAcquisition(bool blocking) { + int fnum = qDefs::F_GUI_START_ACQUISITION; + if (blocking) + fnum = qDefs::F_GUI_START_AND_READ_ALL; -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -string qClient::getStatus(){ - int fnum = F_GET_RUN_STATUS; - int ret = FAIL; - runStatus retval=ERROR; - int progress = 0; - char answer[100]; - - if (myStopSocket->Connect() >= 0) { - myStopSocket->SendDataOnly(&fnum,sizeof(fnum)); - myStopSocket->ReceiveDataOnly(&ret,sizeof(ret)); - myStopSocket->ReceiveDataOnly(&retval,sizeof(retval)); - myStopSocket->ReceiveDataOnly(&progress,sizeof(progress)); - myStopSocket->Disconnect(); - }else - exit(-1); - - - sprintf(answer,"%d%% ",progress); - strcat(answer,slsDetectorBase::runStatusType((runStatus)retval).c_str()); - - return string(answer); + auto client = sls::GuiSocket(hostname.c_str(), controlPort); + client.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); } +void qClient::stopAcquisition() { + int fnum = qDefs::F_GUI_STOP_ACQUISITION; -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qClient::startAcquisition(bool blocking){ - int fnum = F_START_ACQUISITION; - if(blocking) fnum = F_START_AND_READ_ALL; - int ret = FAIL; - - if (mySocket->Connect() >= 0) { - mySocket->SendDataOnly(&fnum,sizeof(fnum)); - mySocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret == FAIL){ - mySocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Gui returned error: " << mess << std::endl; - } - mySocket->Disconnect(); - }else - exit(-1); - - return ret; + auto client = sls::GuiSocket(hostname, stopPort); + client.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qClient::stopAcquisition(){ - int fnum = F_STOP_ACQUISITION; - int ret = FAIL; - - if (myStopSocket->Connect() >= 0) { - myStopSocket->SendDataOnly(&fnum,sizeof(fnum)); - myStopSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret == FAIL){ - myStopSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Gui returned error: " << mess << std::endl; - } - myStopSocket->Disconnect(); - }else - exit(-1); - - return ret; -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qClient::exitServer(){ - int fnum = F_EXIT_SERVER; - int ret = FAIL; - - if (myStopSocket->Connect() >= 0) { - myStopSocket->SendDataOnly(&fnum,sizeof(fnum)); - myStopSocket->ReceiveDataOnly(&ret,sizeof(ret)); - myStopSocket->ReceiveDataOnly(mess,sizeof(mess)); - cout << mess << endl; - myStopSocket->Disconnect(); - }else - exit(-1); - - return ret; -} +void qClient::exitServer() { + int fnum = qDefs::F_GUI_EXIT_SERVER; + // closes both control and stop server + auto client = sls::GuiSocket(hostname, controlPort); + client.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + } diff --git a/slsDetectorGui/client/qClient.h b/slsDetectorGui/client/qClient.h old mode 100644 new mode 100755 index fbec87a95..726be3fbf --- a/slsDetectorGui/client/qClient.h +++ b/slsDetectorGui/client/qClient.h @@ -1,65 +1,70 @@ -/* - * qClient.h - * - * Created on: Feb 27, 2013 - * Author: Dhanya Maliakal - */ -#ifndef QCLIENT_H -#define QCLIENT_H +#pragma once +#include "qDefs.h" -/** Qt Project Class Headers */ -/** Project Class Headers */ -class MySocketTCP; #include "sls_detector_defs.h" -/** C++ Include Headers */ + #include #include -using namespace std; /** *@short Sets up the gui server */ -class qClient: public virtual slsDetectorDefs{ +class qClient : public virtual slsDetectorDefs { + public: + /** + * The constructor + * @param h hostname + */ + qClient(char *h); + /** + * Destructor + */ + virtual ~qClient(); -public: - /** \short The constructor*/ - qClient(char* hostname); - /** Destructor */ - virtual ~qClient(); + /** + * Execute command + * @param narg number of arguments + * @param args argument list + */ + void executeLine(int narg, char *args[]); - /**Execute command*/ - int executeLine(int narg, char *args[]); + private: + /** + * Print list of commands + * @returns string of result + */ + std::string printCommands(); -private: - /** Print list of commands */ - string printCommands(); + /** + * Gets run status + * @returns status + */ + std::string getStatus(); - /** Start Acquisition - * @param blocking true if its a blocking acquistion - */ - int startAcquisition(bool blocking = false); + /** + * Start Acquisition + * @param blocking true if its a blocking acquistion + */ + void startAcquisition(bool blocking = false); - /** Stops Acquisition */ - int stopAcquisition(); + /** + * Stops Acquisition + */ + void stopAcquisition(); - /** Gets run status */ - string getStatus(); + /** + * Exits Server + */ + void exitServer(); - /** Exits Server */ - int exitServer(); + /** hostname */ + std::string hostname; - /** client socket */ - MySocketTCP *mySocket; - - /** client socket */ - MySocketTCP *myStopSocket; - - char mess[MAX_STR_LENGTH]; + /** control port */ + int controlPort; + /** stop port */ + int stopPort; }; - - - -#endif /* QCLIENT_H */ diff --git a/slsDetectorGui/doxy.config b/slsDetectorGui/doxy.config old mode 100644 new mode 100755 index 877d4c456..c5684c098 --- a/slsDetectorGui/doxy.config +++ b/slsDetectorGui/doxy.config @@ -84,13 +84,7 @@ INPUT = \ include/qTabDataOutput.h\ src/qTabDataOutput.cpp\ include/qTabPlot.h\ - src/qTabPlot.cpp\ - include/qTabActions.h\ - src/qTabActions.cpp\ - include/qActionsWidget.h\ - src/qActionsWidget.cpp\ - include/qScanWidget.h\ - src/qScanWidget.cpp\ + src/qTabPlot.cpp\ include/qTabAdvanced.h\ src/qTabAdvanced.cpp\ include/qTabSettings.h\ diff --git a/slsDetectorGui/forms/form_action.ui b/slsDetectorGui/forms/form_action.ui deleted file mode 100644 index 33d93c35e..000000000 --- a/slsDetectorGui/forms/form_action.ui +++ /dev/null @@ -1,169 +0,0 @@ - - - ActionsObject - - - - 0 - 0 - 680 - 25 - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 1000 - 1000 - - - - Form - - - - 0 - - - 0 - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 20 - 20 - - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 40 - 20 - - - - - - - - - None - - - - - Custom Script - - - - - - - - false - - - - - - - false - - - Additional Parameter: - - - - - - - false - - - Browse - - - - :/icons/images/browse.png:/icons/images/browse.png - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 5 - 20 - - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 5 - 20 - - - - - - - - false - - - - 0 - 0 - - - - - - - - - - - diff --git a/slsDetectorGui/forms/form_detectormain.ui b/slsDetectorGui/forms/form_detectormain.ui old mode 100644 new mode 100755 index 1cdc2001b..aaac9ffff --- a/slsDetectorGui/forms/form_detectormain.ui +++ b/slsDetectorGui/forms/form_detectormain.ui @@ -10,7 +10,7 @@ 0 0 800 - 848 + 851 @@ -236,8 +236,6 @@ - - @@ -271,7 +269,7 @@ 36 - 422 + 425 diff --git a/slsDetectorGui/forms/form_scan.ui b/slsDetectorGui/forms/form_scan.ui deleted file mode 100644 index bd00b8c6e..000000000 --- a/slsDetectorGui/forms/form_scan.ui +++ /dev/null @@ -1,488 +0,0 @@ - - - ScanObject - - - - 0 - 0 - 724 - 125 - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 1000 - 1000 - - - - Form - - - - 0 - - - 5 - - - 0 - - - - - false - - - - 0 - 0 - - - - - 180 - 0 - - - - - - - - 0 - - - 5 - - - 0 - - - 2 - - - 0 - - - 5 - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 10 - 20 - - - - - - - - <nobr> -Defines scan range for a <b>Constant Step Size</b> with the following constraints: -</nobr><br><nobr> -1. <b>Number of Steps</b> >=2. -</nobr><br><nobr> -2. <b>Size</b> not equal to 0. -</nobr><br><nobr> -3. <b>From</b> not equal to <b>To</b>. -</nobr><br> - - - Constant Step Size - - - true - - - - - - - <nobr>Measures only at specific values listed by the user.</nobr><br> -<nobr>Number of entries is restricted to <b>Number of Steps</b> field.</nobr> - - - Specific Values - - - false - - - - - - - - 0 - 0 - - - - <nobr>Measures only at the specific values listed in a file.</nobr><br> -<nobr>Select the file, where these values are listed.</nobr> - - - Values from File - - - false - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 10 - 20 - - - - - - - - - - - - - - - - - - - - 0 - - - - - false - - - - 0 - 0 - - - - Precision: - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 5 - 20 - - - - - - - - false - - - - 0 - 0 - - - - 0 - - - 10 - - - 0 - - - - - - - - - 0 - - - - - false - - - - 0 - 0 - - - - Additional Parameter: - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 5 - 20 - - - - - - - - false - - - - 0 - 0 - - - - - - - - - - 0 - - - - - false - - - - 0 - 0 - - - - Number of Steps: - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 5 - 20 - - - - - - - - false - - - - 0 - 0 - - - - false - - - 0 - - - 1000000 - - - 0 - - - - - - - - - - None - - - - - Energy Scan (eV) - - - - - Threshold Scan - - - - - Trimbits Scan - - - - - Position Scan - - - - - Custom Script - - - - - - - - 0 - - - - - false - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 5 - 20 - - - - - - - - false - - - Browse - - - - :/icons/images/browse.png:/icons/images/browse.png - - - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 30 - 20 - - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 40 - 20 - - - - - - - - comboScript - dispScript - btnBrowse - dispParameter - spinSteps - spinPrecision - radioRange - radioCustom - radioFile - - - - - - diff --git a/slsDetectorGui/forms/form_tab_advanced.ui b/slsDetectorGui/forms/form_tab_advanced.ui old mode 100644 new mode 100755 index 0e980a746..4044e0e41 --- a/slsDetectorGui/forms/form_tab_advanced.ui +++ b/slsDetectorGui/forms/form_tab_advanced.ui @@ -51,7 +51,7 @@ QTabWidget::North - 3 + 4 Qt::ElideLeft @@ -60,693 +60,18 @@ Logs - - - - 5 - 10 - 746 - 66 - - - - Calibration Logs - - - - - 25 - 20 - 345 - 31 - - - - - 42 - - - - - - 0 - 0 - - - - Energy Calibration - - - - - - - - 0 - 0 - - - - Angular Calibration - - - - - - Trimming - - - - 5 - 10 - 495 - 66 - - - - Trimbits Plot - - - true - - - false - - - - - 230 - 15 - 259 - 44 - - - - - 17 - - - - - <nobr> -Updates plot with Trimbits from Shared Memory, not from Detector. -</nobr> - - - false - - - Refresh - - - - :/icons/images/refresh.png:/icons/images/refresh.png - - - - 24 - 16 - - - - - - - - <nobr> -Plots Trimbits from Detector. This will take time. -</nobr> - - - Get Trimbits - - - - :/icons/images/download.png:/icons/images/download.png - - - - - - - - - 25 - 20 - 211 - 31 - - - - - - - Data Graph - - - true - - - - - - - Histogram - - - - - - - - - true - - - - 5 - 85 - 746 - 226 - - - - Trimming - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - false - - - true - - - true - - - - - 25 - 25 - 696 - 208 - - - - - 12 - - - - - - 0 - 0 - - - - Trimming Method: - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 20 - 20 - - - - - - - - - 0 - 0 - - - - Exposure Time: - - - - - - - true - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - Exposure time of each frame. - #exptime# - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - false - - - 9 - - - -1.000000000000000 - - - 2000000000.000000000000000 - - - 1.000000000000000 - - - - - - - true - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - Qt::LeftToRight - - - 2 - - - - hr - - - - - min - - - - - s - - - - - ms - - - - - us - - - - - ns - - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 20 - 20 - - - - - - - - Qt::Horizontal - - - QSizePolicy::Expanding - - - - 50 - 20 - - - - - - - - - 0 - 0 - - - - <nobr> -Trimfile to which the resulting trimbits will be written. -</nobr><br><nobr> -An extension given by the modules serial number will be attached. -</nobr> - - - Output Trim File: - - - - - - - <nobr> -Trimfile to which the resulting trimbits will be written. -</nobr><br><nobr> -An extension given by the modules serial number will be attached. -</nobr> - - - - - - - - 0 - 0 - - - - <nobr> -Trimfile to which the resulting trimbits will be written. -</nobr><br><nobr> -An extension given by the modules serial number will be attached. -</nobr> - - - Browse - - - - :/icons/images/browse.png:/icons/images/browse.png - - - - - - - 0 - - - - - - - - 0 - 0 - - - - Start Trimming - - - - :/icons/images/start.png:/icons/images/start.png - - - - - - - true - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - Exposure time of each frame. - #exptime# - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - false - - - 3 - - - -1.000000000000000 - - - 10000.000000000000000 - - - 560.000000000000000 - - - - - - - - 0 - 0 - - - - Sets the Threshold DAC - - - Threshold (DACu): - - - - - - - true - - - - 0 - 0 - - - - - 0 - 0 - - - - Optimize Settings - - - - - - - - 0 - 0 - - - - Resolution (a.u.): - - - - - - - - 0 - 0 - - - - Number of measurements (not in real time) that will be acquired. - #frames# - - - - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - false - - - - - - 1 - - - 9 - - - 4 - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - Adjust to Fix Count Level - - - - - Equalize to Median - - - - - - - - - 0 - 0 - - - - Counts/ Channel: - - - - - - - - 0 - 0 - - - - Number of measurements (not in real time) that will be acquired. - #frames# - - - - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - false - - - - - - 0 - - - 16000000 - - - 500 - - - - - - false - 518 + 10 10 233 66 @@ -761,7 +86,7 @@ An extension given by the modules serial number will be attached. false - + 12 @@ -977,7 +302,7 @@ An extension given by the modules serial number will be attached. 25 21 686 - 119 + 148 @@ -1357,7 +682,7 @@ An extension given by the modules serial number will be attached. 35 10 686 - 123 + 146 @@ -1943,7 +1268,7 @@ Exposure Time of a sub frame. Only for Eiger in 32 bit mode - + false @@ -1962,7 +1287,7 @@ Default value is 0. A value less than the required minimum is ignored. - + false @@ -2002,7 +1327,7 @@ Default value is 0. A value less than the required minimum is ignored. - + false @@ -2066,24 +1391,6 @@ Default value is 0. A value less than the required minimum is ignored. tabAdvancedSettings - chkEnergyLog - chkAngularLog - boxPlot - radioDataGraph - radioHistogram - btnRefresh - btnGetTrimbits - boxTrimming - comboMethod - chkOptimize - spinResolution - spinCounts - spinExpTime - comboExpUnit - spinThreshold - dispFile - btnFile - btnStart btnGetRoi btnSetRoi btnClearRoi diff --git a/slsDetectorGui/forms/form_tab_dataoutput.ui b/slsDetectorGui/forms/form_tab_dataoutput.ui old mode 100644 new mode 100755 index 0ebfddfe9..17d6f9659 --- a/slsDetectorGui/forms/form_tab_dataoutput.ui +++ b/slsDetectorGui/forms/form_tab_dataoutput.ui @@ -43,78 +43,12 @@ Options - - - - 17 - 21 - 192 - 137 - - - - - 6 - - - - - false - - - <nobr> -Compression using Root. Available only for Gotthard in Expert Mode. -</nobr><br><nobr> - #r_compression# -</nobr> - - - Unused - - - - - - - false - - - Angular Conversion - - - - - - - Discard Bad Channels - - - - - - - false - - - <nobr> -Compression using Root. Available only for Gotthard in Expert Mode. -</nobr><br><nobr> - #r_compression# -</nobr> - - - 10GbE - - - - - - 255 + 14 21 - 476 + 475 76 @@ -122,7 +56,7 @@ Compression using Root. Available only for Gotthard in Expert Mode. 6 - + Qt::Horizontal @@ -148,72 +82,7 @@ Compression using Root. Available only for Gotthard in Expert Mode. - - - - false - - - - 0 - 0 - - - - Flat field corrections. - #flatfield# filename - - - Browse - - - - :/icons/images/browse.png:/icons/images/browse.png - - - - - - - false - - - Qt::ClickFocus - - - Flat field corrections. - #flatfield# filename - - - - - - - Flat field corrections. - #flatfield# filename - - - Flat Field File: - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 10 - 20 - - - - - + false @@ -274,7 +143,7 @@ Directory where one saves the data. - + @@ -293,7 +162,7 @@ Directory where one saves the data. - + false @@ -327,28 +196,29 @@ Directory where one saves the data. + + + + false + + + <nobr> +Compression using Root. Available only for Gotthard in Expert Mode. +</nobr><br><nobr> + #r_compression# +</nobr> + + + 10GbE + + + - - - - 230 - 21 - 20 - 134 - - - - QFrame::Raised - - - Qt::Vertical - - - 244 + 3 92 491 72 @@ -360,7 +230,7 @@ Directory where one saves the data. 11 4 475 - 62 + 68 @@ -513,7 +383,7 @@ Directory where one saves the data. 12 20 714 - 68 + 70 @@ -885,9 +755,6 @@ Directory where one saves the data. - chkFlatField - dispFlatField - btnFlatField chkRate diff --git a/slsDetectorGui/forms/form_tab_debugging.ui b/slsDetectorGui/forms/form_tab_debugging.ui old mode 100644 new mode 100755 index e8ebcd632..333a1f501 --- a/slsDetectorGui/forms/form_tab_debugging.ui +++ b/slsDetectorGui/forms/form_tab_debugging.ui @@ -51,8 +51,8 @@ 15 110 - 141 - 51 + 149 + 58 @@ -62,17 +62,17 @@ Qt::NoFocus - Readout Firmware + Module Firmware - + Qt::NoFocus - Readout Software + Module Bus @@ -83,7 +83,7 @@ 15 185 - 656 + 147 36 @@ -107,144 +107,13 @@ - - - - 415 - 30 - 256 - 31 - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 100 - 16777215 - - - - Module: - - - - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - true - - - - All Modules - - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 10 - 20 - - - - - - - - - - 280 - 110 - 141 - 51 - - - - - - - Qt::NoFocus - - - Readout Bus - - - - - - - Qt::NoFocus - - - Readout Memory - - - - - - - - - 530 - 110 - 141 - 26 - - - - - - - Qt::NoFocus - - - Chip - - - - - 15 30 276 - 31 + 32 @@ -367,28 +236,6 @@ - - - - 530 - 135 - 141 - 26 - - - - - - - Qt::NoFocus - - - Module Firmware - - - - - @@ -402,19 +249,6 @@ Qt::Horizontal - - - - 5 - 165 - 676 - 16 - - - - Qt::Horizontal - - @@ -422,7 +256,7 @@ 45 25 686 - 31 + 34 @@ -461,7 +295,6 @@ btnGetInfo comboDetector - comboModule btnTest diff --git a/slsDetectorGui/forms/form_tab_measurement.ui b/slsDetectorGui/forms/form_tab_measurement.ui old mode 100644 new mode 100755 index f8a6853cf..034dcb733 --- a/slsDetectorGui/forms/form_tab_measurement.ui +++ b/slsDetectorGui/forms/form_tab_measurement.ui @@ -139,7 +139,7 @@ 390 8 362 - 342 + 281 @@ -154,10 +154,121 @@ 0 10 357 - 321 + 264 + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 10 + 20 + + + + + + + + false + + + + 0 + 0 + + + + <nobr> +Frame period between exposures. +</nobr><br><nobr> + #period# +</nobr> + + + Qt::LeftToRight + + + 2 + + + + hr + + + + + min + + + + + s + + + + + ms + + + + + us + + + + + ns + + + + + + + + + 0 + 0 + + + + Timing Mode of the detector. + #timing# + + + + None + + + + + Auto + + + + + Trigger Exposure Series + + + + + Gated with fixed number + + + + + Burst Trigger + + + + @@ -315,201 +426,6 @@ - - - - false - - - - 0 - 0 - - - - Number of Gate Signals per Frame. - #gates# - - - Number of Gates: - - - - - - - false - - - - 0 - 0 - - - - Number of Gate Signals per Frame. - #gates# - - - - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - false - - - - - - -1 - - - 2000000000 - - - 1 - - - - - - - false - - - - 0 - 0 - - - - <nobr> -The data are accumulated over several (frames) pump cycles. -</nobr> -<br> -<nobr> -Enabled only in <b>Expert Mode</b> and if<b> Number of Frames</b> > 1. -</nobr> -<br> -<nobr>Setting <b>Number of Probes</b> will reset <b>Number of Triggers</b> to 1. -</nobr> -<br> -Maximum value is 3. <br> -#probes# - - - - Number of Probes: - - - - - - - false - - - - 0 - 0 - - - - <nobr> -The data are accumulated over several (frames) pump cycles. -</nobr> -<br> -<nobr> -Enabled only in <b>Expert Mode</b> and if<b> Number of Frames</b> > 1. -</nobr> -<br> -<nobr>Setting <b>Number of Probes</b> will reset <b>Number of Triggers</b> to 1. -</nobr> -<br> -Maximum value is 3. <br> -#probes# - - - - - - - - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter - - - false - - - - - - -1 - - - 3 - - - 1 - - - - - - - - 0 - 0 - - - - Timing Mode of the detector. - #timing# - - - - None - - - - - Auto - - - - - Trigger Exposure Series - - - - - Trigger Readout - - - - - Gated with Fixed Number - - - - - Gated with Start Trigger - - - - - Burst Trigger - - - - @@ -727,78 +643,6 @@ Frame period between exposures. - - - - false - - - - 0 - 0 - - - - <nobr> -Frame period between exposures. -</nobr><br><nobr> - #period# -</nobr> - - - Qt::LeftToRight - - - 2 - - - - hr - - - - - min - - - - - s - - - - - ms - - - - - us - - - - - ns - - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 10 - 20 - - - - @@ -806,8 +650,65 @@ Frame period between exposures. + + + + false + + + Number of Triggers to be expected. + #cycles# + + + Number of Samples: + + + + + + + false + + + + 0 + 0 + + + + Number of Triggers to be expected. + #cycles# + + + + + + + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + + + false + + + + + + -1 + + + 2000000000 + + + 1 + + + + gridLayoutWidget + spinNumSamples @@ -967,7 +868,7 @@ Frame period between exposures. 30 298 318 - 31 + 34 @@ -1074,8 +975,6 @@ Frame period between exposures. spinNumTriggers spinDelay comboDelayUnit - spinNumGates - spinNumProbes diff --git a/slsDetectorGui/forms/form_tab_messages.ui b/slsDetectorGui/forms/form_tab_messages.ui old mode 100644 new mode 100755 diff --git a/slsDetectorGui/forms/form_tab_plot.ui b/slsDetectorGui/forms/form_tab_plot.ui old mode 100644 new mode 100755 diff --git a/slsDetectorGui/forms/form_tab_settings.ui b/slsDetectorGui/forms/form_tab_settings.ui old mode 100644 new mode 100755 index 7c9f8f3ed..c56af8243 --- a/slsDetectorGui/forms/form_tab_settings.ui +++ b/slsDetectorGui/forms/form_tab_settings.ui @@ -37,14 +37,14 @@ 30 20 316 - 171 + 135 - - + + - Settings: + Dynamic Range: @@ -142,43 +142,30 @@ - - - - false - - - eV - - - -100000 - - - 100000 - - - 100 - - - -1 - - - - - + + - Number of Modules: + Threshold: - - - - Dynamic Range: + + + + Qt::Horizontal - + + QSizePolicy::Fixed + + + + 20 + 20 + + + - + @@ -202,33 +189,32 @@ - - - - 1 + + + + Settings: - - - - Qt::Horizontal + + + + false - - QSizePolicy::Fixed + + eV - - - 20 - 20 - + + -100000 - - - - - - Threshold: + + 100000 + + + 100 + + + -1 @@ -238,7 +224,6 @@ comboSettings spinThreshold - spinNumModules comboDynamicRange diff --git a/slsDetectorGui/gitInfo.txt b/slsDetectorGui/gitInfo.txt deleted file mode 100644 index 634e5504f..000000000 --- a/slsDetectorGui/gitInfo.txt +++ /dev/null @@ -1,9 +0,0 @@ -Path: slsDetectorsPackage/slsDetectorGui -URL: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repository Root: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repsitory UUID: 907d1655d1f6cf2bb8cf6ccd7e91e82f479dd2ca -Revision: 525 -Branch: developer -Last Changed Author: Dhanya_Thattil -Last Changed Rev: 4101 -Last Changed Date: 2019-02-07 18:05:28.000000002 +0100 ./src/qTabSettings.cpp diff --git a/slsDetectorGui/images/add.png b/slsDetectorGui/images/add.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/browse.png b/slsDetectorGui/images/browse.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/calculate.png b/slsDetectorGui/images/calculate.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/close.png b/slsDetectorGui/images/close.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/download.png b/slsDetectorGui/images/download.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/erase.png b/slsDetectorGui/images/erase.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/leftArrow.png b/slsDetectorGui/images/leftArrow.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/mountain.png b/slsDetectorGui/images/mountain.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/new.png b/slsDetectorGui/images/new.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/refresh.png b/slsDetectorGui/images/refresh.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/refresher.png b/slsDetectorGui/images/refresher.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/remove.png b/slsDetectorGui/images/remove.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/rightArrow.png b/slsDetectorGui/images/rightArrow.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/save.png b/slsDetectorGui/images/save.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/saveAll.png b/slsDetectorGui/images/saveAll.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/setup.png b/slsDetectorGui/images/setup.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/start.png b/slsDetectorGui/images/start.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/stop.png b/slsDetectorGui/images/stop.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/images/upload.png b/slsDetectorGui/images/upload.png old mode 100644 new mode 100755 diff --git a/slsDetectorGui/include/gitInfoGui.h b/slsDetectorGui/include/gitInfoGui.h deleted file mode 100644 index a9ea779fb..000000000 --- a/slsDetectorGui/include/gitInfoGui.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "git@github.com:slsdetectorgroup/slsDetectorPackage.git" -#define GITREPUUID "907d1655d1f6cf2bb8cf6ccd7e91e82f479dd2ca" -#define GITAUTH "Dhanya_Thattil" -#define GITREV 0x4101 -#define GITDATE 0x20190207 -#define GITBRANCH "developer" diff --git a/slsDetectorGui/include/gitInfoGuiTmp.h b/slsDetectorGui/include/gitInfoGuiTmp.h deleted file mode 100644 index dfd9bb246..000000000 --- a/slsDetectorGui/include/gitInfoGuiTmp.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "" -#define GITREPUUID "" -#define GITAUTH "" -#define GITREV "" -#define GITDATE "" -#define GITBRANCH "" diff --git a/slsDetectorGui/include/icons.qrc b/slsDetectorGui/include/icons.qrc old mode 100644 new mode 100755 diff --git a/slsDetectorGui/include/qActionsWidget.h b/slsDetectorGui/include/qActionsWidget.h deleted file mode 100644 index 2e024c8a1..000000000 --- a/slsDetectorGui/include/qActionsWidget.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * qActionsWidget.h - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ - -#ifndef QACTIONSWIDGET_H_ -#define QACTIONSWIDGET_H_ - -#include "qDefs.h" - -/** Form Header */ -#include "ui_form_action.h" -/** Project Class Headers */ -class multiSlsDetector; -/** Qt Include Headers */ - -/** C++ Include Headers */ -#include -using namespace std; - - - -class qActionsWidget : public QWidget,private Ui::ActionsObject{ - Q_OBJECT - -public: - /** \short The constructor - * @param parent is the parent tab widget - * @param detector is the detector returned from the detector tab - */ - qActionsWidget(QWidget *parent, multiSlsDetector*& detector); - - ~qActionsWidget(); - - /**to update the widgets*/ - void Refresh(); - - - /**number of action widgets*/ - static int NUM_ACTION_WIDGETS; - - - -private: - /** The sls detector object */ - multiSlsDetector *myDet; - /**id of the action widget*/ - int id; - - /** Sets up the widget - */ - void SetupWidgetWindow(); - - /** Sets up all the slots and signals - * */ - void Initialization(); - - -private slots: -/** Sets the scan or script. Accordingly enables, disables other widgets - * @param mode value chosen - * */ -void SetMode(int mode); - -/** Browse for the script - * */ -void BrowsePath(); - -/** Sets the script file - * */ -void SetScriptFile(); - -/** Set Parameter - * */ -void SetParameter(); - -}; - - - - -#endif /* QACTIONSWIDGET_H_ */ - diff --git a/slsDetectorGui/include/qCloneWidget.h b/slsDetectorGui/include/qCloneWidget.h old mode 100644 new mode 100755 index 07d4cff4c..b7c93b2ad --- a/slsDetectorGui/include/qCloneWidget.h +++ b/slsDetectorGui/include/qCloneWidget.h @@ -1,71 +1,59 @@ -/* - * qCloneWidget.h - * - * Created on: May 18, 2012 - * Author: l_maliakal_d - */ +#pragma once -#ifndef QCLONEWIDGET_H_ -#define QCLONEWIDGET_H_ - -#include "qDefs.h" - - -/** Qt Project Class Headers */ class SlsQtH1D; #include "SlsQt1DPlot.h" #include "SlsQt2DPlotLayout.h" -/** Qt Include Headers */ -#include -#include -#include + #include -#include +#include #include +#include +#include #include -#include #include #include #include -#include +#include +#include +#include #include -#include -#include #include +#include #include -/** C++ Include Headers */ -#include + #include -using namespace std; +#include /** *@short Sets up the clone plot widget */ -class qCloneWidget:public QMainWindow{ - Q_OBJECT +class qCloneWidget : public QMainWindow { + Q_OBJECT -public: - /** \short The constructor + public: + /** + * The constructor */ - qCloneWidget(QWidget *parent,int id,QString title,QString xTitle, QString yTitle, QString zTitle, int numDim,string FilePath, - bool displayStats, QString min, QString max, QString sum); + qCloneWidget(QWidget *parent, int id, QString title, QString xTitle, QString yTitle, QString zTitle, int numDim, std::string FilePath, + bool displayStats, QString min, QString max, QString sum); - /** Destructor + /** + * Destructor */ - ~qCloneWidget(); + ~qCloneWidget(); - /** Sets up the widget window + /** + * Sets up the widget window * @param title title of the image with frame number * @param xTitle title of x axis * @param yTitle title of y axis * @param zTitle title of z axis * @param numDim 1D or 2D * */ - void SetupWidgetWindow(QString title, QString xTitle, QString yTitle, QString zTitle, int numDim); + void SetupWidgetWindow(QString title, QString xTitle, QString yTitle, QString zTitle, int numDim); - - - /** Get the 1D hist values to plot + /** + * Get the 1D hist values to plot * @param nHists Number of graphs in 1D * @param histNBins Total Number of X axis values/channels in 1D * @param histXAxis X Axis value in 1D @@ -73,10 +61,11 @@ public: * @param histTitle Title for all the graphs in 1D * @param lines style of plot if lines or dots * @param markers style of plot markers or not - * */ - void SetCloneHists(int nHists,int histNBins,double* histXAxis,double* histYAxis[],string histTitle[],bool lines,bool markers); + */ + void SetCloneHists(int nHists, int histNBins, double *histXAxis, double *histYAxis[], std::string histTitle[], bool lines, bool markers); - /** Get the 1D hist values to plot for angle plotting + /** + * Get the 1D hist values to plot for angle plotting * @param nHists Number of graphs in 1D * @param histNBins Total Number of X axis values/channels in 1D * @param histXAxis X Axis value in 1D @@ -84,10 +73,11 @@ public: * @param histTitle Title for all the graphs in 1D * @param lines style of plot if lines or dots * @param markers style of plot markers or not - * */ - void SetCloneHists(int nHists,int histNBins,double* histXAxis,double* histYAxis,string histTitle[],bool lines,bool markers); + */ + void SetCloneHists(int nHists, int histNBins, double *histXAxis, double *histYAxis, std::string histTitle[], bool lines, bool markers); - /** Get the 1D hist values to plot for angle plotting + /** + * Get the 1D hist values to plot for angle plotting * @param nbinsx number of bins in x axis * @param xmin minimum in x axis * @param xmax maximum in x axis @@ -95,70 +85,63 @@ public: * @param ymin minimum in y axis * @param ymax maximum in y axis * @param d data - * */ - void SetCloneHists2D(int nbinsx,double xmin,double xmax,int nbinsy, double ymin, double ymax, double *d); + */ + void SetCloneHists2D(int nbinsx, double xmin, double xmax, int nbinsy, double ymin, double ymax, double *d); - /**Set the range of the 1d plot + /** + * Set the range of the 1d plot * @param IsXYRange array of x,y,min,max if these values are set * @param XYRangeValues array of set values of x,y, min, max */ - void SetRange(bool IsXYRange[], double XYRangeValues[]); + void SetRange(bool IsXYRange[], double XYRangeValues[]); - /** Returns the 1d plot + /** + * Returns the 1d plot */ - SlsQt1DPlot* Get1dPlot(){return cloneplot1D;}; + SlsQt1DPlot *Get1dPlot(); -public slots: -/** Save Plots automatically by save all clones - * returns -1 if fail*/ -int SavePlotAutomatic(); - - -private: - /** clone window id*/ - int id; - /** Default Save file path */ - string filePath; - /** clone 1D Plot */ - SlsQt1DPlot* cloneplot1D; - /** clone 2D Plot */ - SlsQt2DPlotLayout* cloneplot2D; - /** vector of 1D hist values */ - QVector cloneplot1D_hists; - - /** markers for the plot*/ - QwtSymbol *marker; - QwtSymbol *nomarker; - - QMenuBar *menubar; - QAction *actionSave; - - QGridLayout *mainLayout; - QGroupBox *cloneBox; - QGridLayout *gridClone; - - QLabel *lblHistTitle; + public slots: + /** + * Save Plots automatically by save all clones + * returns -1 if fail + */ + int SavePlotAutomatic(); + private: /** Gets the current time stamp for the window title*/ - char* GetCurrentTimeStamp(); + char *GetCurrentTimeStamp(); /** Display Statistics */ void DisplayStats(bool enable, QString min, QString max, QString sum); + /** clone window id*/ + int id; + /** Default Save file path */ + std::string filePath; + /** clone 1D Plot */ + SlsQt1DPlot *cloneplot1D; + /** clone 2D Plot */ + SlsQt2DPlotLayout *cloneplot2D; + /** vector of 1D hist values */ + QVector cloneplot1D_hists; -private slots: -/** Save Plot */ -void SavePlot(); + /** markers for the plot*/ + QwtSymbol *marker; + QwtSymbol *nomarker; -protected: - void closeEvent(QCloseEvent* event); + QGridLayout *mainLayout; + QGroupBox *cloneBox; -signals: -void CloneClosedSignal(int); + QLabel *lblHistTitle; + private slots: + /** Save Plot */ + void SavePlot(); + + protected: + void closeEvent(QCloseEvent *event); + + signals: + void CloneClosedSignal(int); }; - - - -#endif /* QCLONEWIDGET_H_ */ diff --git a/slsDetectorGui/include/qDebugStream.h b/slsDetectorGui/include/qDebugStream.h old mode 100644 new mode 100755 index 4335dbd0a..4855dd53b --- a/slsDetectorGui/include/qDebugStream.h +++ b/slsDetectorGui/include/qDebugStream.h @@ -1,101 +1,80 @@ -/* - * qDebugStream.h - * - * Created on: Jun 28, 2012 - * Author: Anna Bergamaschi - */ - -#ifndef QDEBUGSTREAM_H_ -#define QDEBUGSTREAM_H_ - - -#include "qDefs.h" - +#pragma once #include -#include -#include #include - +#include +#include #include #include #include -using namespace std; #define STREAMEVENT 60001 -//------------------------------------------------------------------------------------------------------------------------------------------------- - -class qStreamEvent:public QEvent{ +class qStreamEvent : public QEvent { public: - qStreamEvent(QString s):QEvent(static_cast(STREAMEVENT)),str(s){ + qStreamEvent(QString s) : QEvent(static_cast(STREAMEVENT)), str(s) { #ifdef PRINT_LOG - printf("%s\n",str.toAscii().constData()); + printf("%s\n", str.toAscii().constData()); #endif } /** \returns the progress index */ - QString getString() {return str;} + QString getString() { return str; } + private: QString str; - }; -//------------------------------------------------------------------------------------------------------------------------------------------------- -class qDebugStream : public basic_streambuf { +class qDebugStream : public std::basic_streambuf { public: - qDebugStream(ostream &stream, QWidget* w) : m_stream(stream), log_window(w) { + qDebugStream(std::ostream &stream, QWidget *w) : m_stream(stream), log_window(w) { pthread_mutex_init(&mutex, NULL); m_old_buf = stream.rdbuf(); stream.rdbuf(this); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - ~qDebugStream(){ + ~qDebugStream() { // output anything that is left if (!m_string.empty()) { pthread_mutex_lock(&mutex); - const char* c_string = m_string.c_str(); + const char *c_string = m_string.c_str(); QApplication::postEvent(log_window, new qStreamEvent(c_string)); pthread_mutex_unlock(&mutex); } m_stream.rdbuf(m_old_buf); } -//------------------------------------------------------------------------------------------------------------------------------------------------- protected: - virtual int_type overflow(int_type v){ - if (v == '\n'){ + virtual int_type overflow(int_type v) { + if (v == '\n') { pthread_mutex_lock(&mutex); - const char* c_string = m_string.c_str(); + const char *c_string = m_string.c_str(); QApplication::postEvent(log_window, new qStreamEvent(c_string)); m_string.erase(m_string.begin(), m_string.end()); pthread_mutex_unlock(&mutex); - } - else + } else m_string += v; return v; } -//------------------------------------------------------------------------------------------------------------------------------------------------- - virtual streamsize xsputn(const char *p, streamsize n) { + virtual std::streamsize xsputn(const char *p, std::streamsize n) { pthread_mutex_lock(&mutex); m_string.append(p, p + n); //changed from uint because of 64 bit size_t pos = 0; - while (pos != string::npos){ + while (pos != std::string::npos) { pos = m_string.find('\n'); - if (pos != string::npos){ - string tmp(m_string.begin(), m_string.begin() + pos); - const char* c_tmp = tmp.c_str(); + if (pos != std::string::npos) { + std::string tmp(m_string.begin(), m_string.begin() + pos); + const char *c_tmp = tmp.c_str(); QApplication::postEvent(log_window, new qStreamEvent(c_tmp)); m_string.erase(m_string.begin(), m_string.begin() + pos + 1); } @@ -104,16 +83,13 @@ protected: return n; } -//------------------------------------------------------------------------------------------------------------------------------------------------- private: pthread_mutex_t mutex; - ostream &m_stream; - streambuf *m_old_buf; - string m_string; - QWidget* log_window; + std::ostream &m_stream; + std::streambuf *m_old_buf; + std::string m_string; + QWidget *log_window; }; -//------------------------------------------------------------------------------------------------------------------------------------------------- -#endif /* QDEBUGSTREAM_H_ */ diff --git a/slsDetectorGui/include/qDefs.h b/slsDetectorGui/include/qDefs.h old mode 100644 new mode 100755 index f1b7d2b51..3a241a4fa --- a/slsDetectorGui/include/qDefs.h +++ b/slsDetectorGui/include/qDefs.h @@ -1,301 +1,252 @@ -/* - * qDefs.h - * - * Created on: May 4, 2012 - * Author: l_maliakal_d - */ +#pragma once -#ifndef QDEFS_H -#define QDEFS_H - -#include "ansi.h" -#include "sls_detector_defs.h" -#include "slsDetector.h" #include "multiSlsDetector.h" -#include -#include -#include -#include +#include "sls_detector_defs.h" + #include -using namespace std; +#include -class qDefs:public QWidget{ -public: -//------------------------------------------------------------------------------------------------------------------------------------------------- +#include +#include +#include +#include - /** Empty Constructor - */ - qDefs(){}; -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -#define GOODBYE -200 -//------------------------------------------------------------------------------------------------------------------------------------------------- - - enum{ - OK, - FAIL - }; - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - enum MessageIndex{ - WARNING, - CRITICAL, - INFORMATION, - QUESTION - }; - -//------------------------------------------------------------------------------------------------------------------------------------------------- - /** unit of time - */ - enum timeUnit{ - HOURS, /** hr */ - MINUTES, /** min */ - SECONDS, /** s */ - MILLISECONDS, /** ms */ - MICROSECONDS, /** us */ - NANOSECONDS /** ns */ - }; - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - /** returns the unit in words - * @param unit is the time unit - */ - static string getUnitString(timeUnit unit){ - switch(unit){ - case HOURS: return string("hrs"); - case MINUTES: return string("min"); - case SECONDS: return string("sec"); - case MILLISECONDS: return string("msec"); - case MICROSECONDS: return string("usec"); - case NANOSECONDS: return string("nsec"); - default: return string("error"); - } - }; -//------------------------------------------------------------------------------------------------------------------------------------------------- - - /** returns the value in ns to send to server as the - * server class slsdetector accepts in ns. - * @param unit unit of time - * @param value time - * returns time value in ns - */ - static double getNSTime(timeUnit unit, double value){ - double valueNS=value; - switch(unit){ - case HOURS: valueNS*=60; - case MINUTES: valueNS*=60; - case SECONDS: valueNS*=1000; - case MILLISECONDS: valueNS*=1000; - case MICROSECONDS: valueNS*=1000; - case NANOSECONDS: - default:; - } - return valueNS; - }; - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - /** returns the time in the appropriate time unit - * @param unit unit of time - * @param value time in seconds - * returns the corresponding time value - */ - static double getCorrectTime(timeUnit& unit, double value){ - int intUnit = (int)SECONDS; - - /**0 ms*/ - if(!value){ - unit = MILLISECONDS; - return value; - } - - /** hr, min, sec */ - if(value>=1){ - double newVal = value; - while((newVal>=1)&&(intUnit>=(int)HOURS)){ - /** value retains the old value */ - value = newVal; - newVal = value/(double)60; - intUnit--; - } - /** returning the previous value*/ - unit = (timeUnit)(intUnit+1); - return value; - } - /** ms, us, ns */ - else{ - while((value<1)&&(intUnit<(int)NANOSECONDS)){ - value = value*(double)1000; - intUnit++; - } - unit = (timeUnit)(intUnit); - return value; - } - }; - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - /**displays an warning,error,info message - * @param message the message to be displayed - * @param source is the tab or the source of the message - * */ - static int Message(MessageIndex index, string message,string source) - { - static QMessageBox* msgBox; - size_t pos; - - //replace all \n with
- pos = 0; - while((pos = message.find("\n", pos)) != string::npos){ - message.replace(pos, 1, "
"); - pos += 1; - } - message.append(string("

Source:   ") + source + string("

")); - - switch(index){ - case WARNING: - msgBox= new QMessageBox(QMessageBox::Warning,"WARNING",tr(message.c_str()),QMessageBox::Ok, msgBox); - break; - case CRITICAL: - msgBox= new QMessageBox(QMessageBox::Critical,"CRITICAL",tr(message.c_str()),QMessageBox::Ok, msgBox); - break; - case INFORMATION: - msgBox= new QMessageBox(QMessageBox::Information,"INFORMATION",tr(message.c_str()),QMessageBox::Ok, msgBox); - break; - default: - msgBox= new QMessageBox(QMessageBox::Question,"QUESTION",tr(message.c_str()),QMessageBox::Ok| QMessageBox::Cancel, msgBox); - break; - } - //msgBox->setDetailedText(QString(source.c_str())); //close button doesnt work with this static function and this - if(msgBox->exec()==QMessageBox::Ok) return OK; else return FAIL; - } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - /** range of x and y axes - */ - enum range{ - XMINIMUM, - XMAXIMUM, - YMINIMUM, - YMAXIMUM - }; - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - /**gets error mask and displays the message if it exists - * @param myDet is the multidetector object - /returns error message else an empty string - * */ - static string checkErrorMessage(multiSlsDetector*& myDet, string title = "Main"){ - - - int errorLevel= (int)WARNING; - string retval=""; - size_t pos; - - - retval = myDet->getErrorMessage(errorLevel); - - if(!retval.empty()){ - //replace all \n with
- pos = 0; - while((pos = retval.find("\n", pos)) != string::npos){ - retval.replace(pos, 1, "
"); - pos += 1; - } - - //get rid of the last \n - if(retval.find_last_of("
")==retval.length()-1) - retval.erase((int)retval.find_last_of("
")-3,4); - - retval.insert(0,""); - retval.append(""); - - //display message - qDefs::Message((MessageIndex)errorLevel,retval,title); - } - - myDet->clearAllErrorMask(); - return retval; - }; - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - /**gets error mask and displays the message if it exists - * @param myDet is the slsdetector object - * @param show to display the error message - /returns error message else an empty string - * */ - static string checkErrorMessage(slsDetector*& myDet, string title = "Main", bool show = true){ - - - int errorLevel= (int)WARNING; - string retval=""; - size_t pos; - int64_t emask=0; - - emask = myDet->getErrorMask(); - retval = myDet->getErrorMessage(emask); - - if(!retval.empty()){ - //replace all \n with
- pos = 0; - while((pos = retval.find("\n", pos)) != string::npos){ - retval.replace(pos, 1, "
"); - pos += 1; - } - - //get rid of the last \n - if(retval.find_last_of("
")==retval.length()-1) - retval.erase((int)retval.find_last_of("
")-3,4); - - retval.insert(0,""); - retval.append(""); - - //display message - if(show) - qDefs::Message((MessageIndex)errorLevel,retval,title); - } - - myDet->clearErrorMask(); - - return retval; - }; - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - - /** scan arguments*/ - enum scanArgumentList{ - None, - Level0, - Level1, - FileIndex, - AllFrames - }; - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - - /** histogram arguments*/ - enum histogramArgumentList{ - Intensity, - histLevel0, - histLevel1 - }; - - -//------------------------------------------------------------------------------------------------------------------------------------------------- +class qDefs : public QWidget { + public: + /** + * Empty Constructor + */ + qDefs(){}; + +#define GOODBYE -200 + + /** Success or FAIL */ + enum { OK, FAIL }; + + /** + * Message Criticality + */ + enum MessageIndex { WARNING, CRITICAL, INFORMATION, QUESTION }; + + /** + * unit of time + */ + enum timeUnit { + HOURS, /** hr */ + MINUTES, /** min */ + SECONDS, /** s */ + MILLISECONDS, /** ms */ + MICROSECONDS, /** us */ + NANOSECONDS /** ns */ + }; + + /** + * range of x and y axes + */ + enum range { XMINIMUM, XMAXIMUM, YMINIMUM, YMAXIMUM }; + + /** + * function enums for the qServer and qClient + */ + enum guiFuncs { + F_GUI_GET_RUN_STATUS, + F_GUI_START_ACQUISITION, + F_GUI_STOP_ACQUISITION, + F_GUI_START_AND_READ_ALL, + F_GUI_EXIT_SERVER, + NUM_GUI_FUNCS + }; + + /** + * returns the unit in words + * @param unit is the time unit + */ + static std::string getUnitString(timeUnit unit) { + switch (unit) { + case HOURS: + return std::string("hrs"); + case MINUTES: + return std::string("min"); + case SECONDS: + return std::string("sec"); + case MILLISECONDS: + return std::string("msec"); + case MICROSECONDS: + return std::string("usec"); + case NANOSECONDS: + return std::string("nsec"); + default: + return std::string("error"); + } + }; + + /** + * returns the value in ns to send to server as the + * server class slsdetector accepts in ns. + * @param unit unit of time + * @param value time + * returns time value in ns + */ + static double getNSTime(timeUnit unit, double value) { + double valueNS = value; + switch (unit) { + case HOURS: + valueNS *= 60; + case MINUTES: + valueNS *= 60; + case SECONDS: + valueNS *= 1000; + case MILLISECONDS: + valueNS *= 1000; + case MICROSECONDS: + valueNS *= 1000; + case NANOSECONDS: + default: + break; + } + return valueNS; + }; + + /** + * returns the time in the appropriate time unit + * @param unit unit of time + * @param value time in seconds + * returns the corresponding time value + */ + static double getCorrectTime(timeUnit &unit, double value) { + int intUnit = (int)SECONDS; + + /**0 ms*/ + if (!value) { + unit = MILLISECONDS; + return value; + } + + /** hr, min, sec */ + if (value >= 1) { + double newVal = value; + while ((newVal >= 1) && (intUnit >= (int)HOURS)) { + /** value retains the old value */ + value = newVal; + newVal = value / (double)60; + intUnit--; + } + /** returning the previous value*/ + unit = (timeUnit)(intUnit + 1); + return value; + } + /** ms, us, ns */ + else { + while ((value < 1) && (intUnit < (int)NANOSECONDS)) { + value = value * (double)1000; + intUnit++; + } + unit = (timeUnit)(intUnit); + return value; + } + }; + + /** + * displays an warning,error,info message + * @param message the message to be displayed + * @param source is the tab or the source of the message + * */ + static int Message(MessageIndex index, std::string message, + std::string source) { + static QMessageBox *msgBox; + size_t pos; + + // replace all \n with
+ pos = 0; + while ((pos = message.find("\n", pos)) != std::string::npos) { + message.replace(pos, 1, "
"); + pos += 1; + } + message.append( + std::string( + "

Source:   ") + + source + std::string("

")); + + switch (index) { + case WARNING: + msgBox = + new QMessageBox(QMessageBox::Warning, "WARNING", + tr(message.c_str()), QMessageBox::Ok, msgBox); + break; + case CRITICAL: + msgBox = + new QMessageBox(QMessageBox::Critical, "CRITICAL", + tr(message.c_str()), QMessageBox::Ok, msgBox); + break; + case INFORMATION: + msgBox = + new QMessageBox(QMessageBox::Information, "INFORMATION", + tr(message.c_str()), QMessageBox::Ok, msgBox); + break; + default: + msgBox = new QMessageBox( + QMessageBox::Question, "QUESTION", tr(message.c_str()), + QMessageBox::Ok | QMessageBox::Cancel, msgBox); + break; + } + // msgBox->setDetailedText(QString(source.c_str())); //close button + // doesnt work with this static function and this + if (msgBox->exec() == QMessageBox::Ok) + return OK; + else + return FAIL; + } + + /** + * Wrap around to ignore non critical exceptions + */ + template struct NonDeduced { using type = CT; }; + + // only executing multiSlsDetector function + template + static void IgnoreNonCriticalExceptions(multiSlsDetector* det, const std::string loc, RT (multiSlsDetector::*somefunc)(CT...), + typename NonDeduced::type... Args) { + try { + ((det->*somefunc)(Args...)); + } + // catch them here as they are not critical + catch (const sls::NonCriticalError &e) { + Message(qDefs::WARNING, e.what(), loc); + } + }; + + // executing multiSlsDetector funtion and using return value to set QWidget function + template + static void IgnoreNonCriticalExceptions(W* wid, + void (W::*someQfunc)(WRT), + multiSlsDetector* det, const std::string loc, + RT (multiSlsDetector::*somefunc)(CT...), + typename NonDeduced::type... Args) { + try { + auto val = ((det->*somefunc)(Args...)); + (wid->*someQfunc)(static_cast(val)); + } + // catch them here as they are not critical + catch (const sls::NonCriticalError &e) { + Message(qDefs::WARNING, e.what(), loc); + } + }; + // executing multiSlsDetector funtion and returning its value (integers, where value cannot be -1) + template + static RT IgnoreNonCriticalExceptionsandReturn( + multiSlsDetector* det, const std::string loc, + RT (multiSlsDetector::*somefunc)(CT...), + typename NonDeduced::type... Args) { + try { + return ((det->*somefunc)(Args...)); + } + // catch them here as they are not critical + catch (const sls::NonCriticalError &e) { + Message(qDefs::WARNING, e.what(), loc); + return static_cast(-1); + } + }; }; - - -#endif /* QDEFS_H */ diff --git a/slsDetectorGui/include/qDetectorMain.h b/slsDetectorGui/include/qDetectorMain.h old mode 100644 new mode 100755 index 0af189fc0..a6e8d198e --- a/slsDetectorGui/include/qDetectorMain.h +++ b/slsDetectorGui/include/qDetectorMain.h @@ -1,202 +1,200 @@ -/* - * qDetectorMain.h - * Main Window of the GUI - * Created on: Apr 30, 2012 - * Author: l_maliakal_d - */ -#ifndef QDETECTORMAIN_H -#define QDETECTORMAIN_H +#pragma once #include "qDefs.h" - -/** Form Header */ -#include "ui_form_detectormain.h" -/** Qt Project Class Headers */ #include "qDrawPlot.h" -#include "qTabMeasurement.h" #include "qTabDataOutput.h" +#include "qTabMeasurement.h" +#include "ui_form_detectormain.h" class qTabPlot; -class qTabActions; class qTabAdvanced; class qTabSettings; class qTabDebugging; class qTabDeveloper; class qTabMessages; class qServer; -/** Project Class Headers */ + class multiSlsDetector; -/** Qt Include Headers */ -#include + #include #include +#include #include #include -using namespace std; /** To Over-ride the QTabWidget class to get the tabBar */ -class MyTabWidget:public QTabWidget{ -public: - MyTabWidget(QWidget* parent = 0) {setParent(parent);} +class MyTabWidget : public QTabWidget { + public: + MyTabWidget(QWidget *parent = 0) { setParent(parent); } /** Overridden method from QTabWidget */ - QTabBar* tabBar(){return QTabWidget::tabBar();} + QTabBar *tabBar() { return QTabWidget::tabBar(); } }; - /** *@short Main window of the GUI. */ -class qDetectorMain:public QMainWindow, private Ui::DetectorMainObject{ - Q_OBJECT +class qDetectorMain : public QMainWindow, private Ui::DetectorMainObject { + Q_OBJECT + public: + /** + * Main Window constructor. + * This is mainly used to create detector object and all the tabs + * @param argc number of command line arguments for server options + * @param argv server options + * @param app the qapplication3 + * @param parent makes the parent window 0 by default + */ + qDetectorMain(int argc, char **argv, QApplication *app, + QWidget *parent = 0); -public: - /** \short Main Window constructor. - * This is mainly used to create detector object and all the tabs - * @param argc number of command line arguments for server options - * @param argv server options - * @param app the qapplication3 - * @param ret OK or FAIL of constructor (from command line arguments) - * @param parent makes the parent window 0 by default - * */ - qDetectorMain(int argc, char **argv, QApplication *app, int& ret, QWidget *parent = 0); + /** + * Destructor + */ + ~qDetectorMain(); - /**Destructor - * */ - ~qDetectorMain(); + /** + * Starts or stops Acquisition From gui client + * @param start 1 for start and 0 to stop + * @returns success or fail + */ + int StartStopAcquisitionFromClient(bool start); - /** Starts or stops Acquisition From gui client - * @param start 1 for start and 0 to stop - /returns success or fail - */ - int StartStopAcquisitionFromClient(bool start); + /** + * Returns if plot is running + */ + bool isPlotRunning(); - /** Returns if plot is running - */ - bool isPlotRunning(){return myPlot->isRunning();}; + /** + * Returns progress bar value + */ + int GetProgress(); - /** Returns progress bar value */ - int GetProgress(){return tab_measurement->GetProgress();}; + /** + * Verifies if output directories for all the receivers exist + */ + int DoesOutputDirExist(); - /** Returns file path */ - QString GetFilePath(){QString s = QString(myDet->getFilePath().c_str());qDefs::checkErrorMessage(myDet); return s;}; + private slots: + /** + * Enables modes as selected -Debug, Expert, Dockable: calls setdockablemode + */ + void EnableModes(QAction *action); - /** Verifies if output directories for all the receivers exist */ - int DoesOutputDirExist(){return tab_dataoutput->VerifyOutputDirectory();}; + /** + * Executes actions in the utilities menu as selected + */ + void ExecuteUtilities(QAction *action); - bool isCurrentlyTabDeveloper(); + /** + * Executes actions in the utilities menu as selected + */ + void ExecuteHelp(QAction *action); -private: - /** The Qt Application */ - QApplication *theApp; - /** The sls detector object */ - multiSlsDetector *myDet; - /** sls detector id */ - int detID; - /** true for mythen and eiger */ - bool digitalDetector; - /** The Plot widget */ - qDrawPlot *myPlot; - /**Tab Widget */ - MyTabWidget *tabs; - /**Layout of the central Widget */ - QGridLayout *layoutTabs; - /** default height of Plot Window when docked */ - int heightPlotWindow; - /** default height of central widgetwhen plot Window when docked */ - int heightCentralWidget; - /** The default zooming tool tip */ - QString zoomToolTip; + /** + * Refreshes the tab each time the tab is changed. Also displays the next + * enabled tab + */ + void Refresh(int index); - /** The default tab heading color */ - QColor defaultTabColor; - /** enumeration of the tabs */ - enum {Measurement, Settings, DataOutput, Plot, Actions, Advanced, Debugging, Developer, Messages, NumberOfTabs }; - /* Scroll Area for the tabs**/ - QScrollArea *scroll[NumberOfTabs]; - /**Measurement tab */ - qTabMeasurement *tab_measurement; - /**DataOutput tab */ - qTabDataOutput *tab_dataoutput; - /**Plot tab */ - qTabPlot *tab_plot; - /**Actions tab */ - qTabActions *tab_actions; - /**Settings tab */ - qTabSettings *tab_settings; - /**Advanced tab */ - qTabAdvanced *tab_advanced; - /**Debugging tab */ - qTabDebugging *tab_debugging; - /**Developer tab */ - qTabDeveloper *tab_developer; - /**Messages tab */ - qTabMessages *tab_messages; + /** + * Resizes the main window if the plot is docked/undocked + * @param b bool TRUE if undocked(outside main window), FALSE docked + */ + void ResizeMainWindow(bool b); - /** server object*/ - qServer *myServer; + /** + * Enables/disables tabs depending on if acquisition is currently in + * progress + */ + void EnableTabs(); - /**if the developer tab should be enabled,known from command line */ - int isDeveloper; + /** + * Set the tool tip of mouse controlled zooming depening on if its + * enabled/disabled + */ + void SetZoomToolTip(bool disable); - /**Sets up the layout of the widget - * */ - void SetUpWidgetWindow(); + /** + * Uncheck the Listen to gui client mode when the server has exited + */ + void UncheckServer(); - /**Sets up detector - * @param fName file name of the config file at start up - * */ - void SetUpDetector(const string fName); + protected: + /** + * Adjust the resizing to resize plot + */ + void resizeEvent(QResizeEvent *event); - /**Sets up the signals and the slots - * */ - void Initialization(); + private: + /** + * Sets up the layout of the widget + */ + void SetUpWidgetWindow(); - /** Loads config file at start up - * */ - void LoadConfigFile(const string fName); + /** + * Sets up detector + * @param fName file name of the config file at start up + * @param multi detector ID + */ + void SetUpDetector(const std::string fName, int multiID); + /** + * Sets up the signals and the slots + */ + void Initialization(); -private slots: -/** Enables modes as selected -Debug, Expert, Dockable(calls setdockablemode()) - * */ -void EnableModes(QAction *action); - -/** Executes actions in the utilities menu as selected - * */ -void ExecuteUtilities(QAction *action); - -/** Executes actions in the utilities menu as selected - * */ -void ExecuteHelp(QAction *action); - -/** Refreshes the tab each time the tab is changed. Also displays the next enabled tab - * */ -void Refresh(int index); - -/** Resizes the main window if the plot is docked/undocked - * @param b bool TRUE if undocked(outside main window), FALSE docked - * */ -void ResizeMainWindow(bool b); - -/** Enables/disables tabs depending on if acquisition is currently in progress - * */ -void EnableTabs(); - -/** Set the tool tip of mouse controlled zooming depening on if its enabled/disabled - * */ -void SetZoomToolTip(bool disable); - -/** Uncheck the Listen to gui client mode when the server has exited - */ -void UncheckServer(); - -protected: -/** Adjust the resizing to resize plot, except for actions tab - * */ -void resizeEvent(QResizeEvent* event); - + /** + * Loads config file at start up + */ + void LoadConfigFile(const std::string fName); + /** enumeration of the tabs */ + enum { + MEASUREMENT, + SETTINGS, + DATAOUTPUT, + PLOT, + ADVANCED, + DEBUGGING, + DEVELOPER, + MESSAGES, + NumberOfTabs + }; + /** Detector Type */ + slsDetectorDefs::detectorType detType; + /** The sls detector object */ + multiSlsDetector* myDet; + /** The Plot widget */ + qDrawPlot* myPlot; + /**Tab Widget */ + MyTabWidget* tabs; + /**Measurement tab */ + qTabMeasurement* tabMeasurement; + /**DataOutput tab */ + qTabDataOutput* tabDataOutput; + /**Plot tab */ + qTabPlot* tabPlot; + /**Settings tab */ + qTabSettings* tabSettings; + /**Advanced tab */ + qTabAdvanced* tabAdvanced; + /**Debugging tab */ + qTabDebugging* tabDebugging; + /**Developer tab */ + qTabDeveloper* tabDeveloper; + /**Messages tab */ + qTabMessages* tabMessages; + /** server object*/ + qServer* myServer; + /**if the developer tab should be enabled,known from command line */ + int isDeveloper; + /** default height of Plot Window when docked */ + int heightPlotWindow; + /** default height of central widgetwhen plot Window when docked */ + int heightCentralWidget; + /** The default zooming tool tip */ + QString zoomToolTip; + /** The default tab heading color */ + QColor defaultTabColor; }; - -#endif /* QDETECTORMAIN_H */ diff --git a/slsDetectorGui/include/qDrawPlot.h b/slsDetectorGui/include/qDrawPlot.h old mode 100644 new mode 100755 index 54a4a2542..dc32c2630 --- a/slsDetectorGui/include/qDrawPlot.h +++ b/slsDetectorGui/include/qDrawPlot.h @@ -50,7 +50,7 @@ class qDrawPlot:public QWidget{ public: /** \short The constructor */ - qDrawPlot(QWidget *parent,multiSlsDetector*& detector); + qDrawPlot(QWidget *parent, multiSlsDetector* detector); /** Destructor */ ~qDrawPlot(); @@ -181,7 +181,7 @@ void SetLines(bool enable){lines = enable;}; /** sets markers */ void SetMarkers(bool enable){markers = enable;}; /** sets the scan argument to prepare the plot*/ -void SetScanArgument(int scanArg); +// void SetScanArgument(int scanArg); /** sets stop_signal to true */ void StopAcquisition(){ stop_signal = true; }; /** Set/unset pedestal */ diff --git a/slsDetectorGui/include/qScanWidget.h b/slsDetectorGui/include/qScanWidget.h deleted file mode 100644 index 329a211da..000000000 --- a/slsDetectorGui/include/qScanWidget.h +++ /dev/null @@ -1,193 +0,0 @@ -/* - * qScanWidget.h - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ - -#ifndef QSCANWIDGET_H_ -#define QSCANWIDGET_H_ - -#include "qDefs.h" - -/** Form Header */ -#include "ui_form_scan.h" -/** Project Class Headers */ -class multiSlsDetector; -/** Qt Include Headers */ -#include -/** C++ Include Headers */ -#include -#include -using namespace std; - - -class qScanWidget : public QWidget,private Ui::ScanObject{ - Q_OBJECT - -public: - /** \short The constructor - * @param parent is the parent tab widget - * @param detector is the detector returned from the detector tab - */ - qScanWidget(QWidget *parent, multiSlsDetector*& detector); - - ~qScanWidget(); - - /**to update the widgets*/ - void Refresh(); - - - /**number of scan widgets*/ - static int NUM_SCAN_WIDGETS; - -private: - /** The sls detector object */ - multiSlsDetector *myDet; - /**id of the scan widget*/ - int id; - /**type of steps*/ - enum sizeIndex{RangeValues, CustomValues, FileValues}; - enum modes{None,EnergyScan,ThresholdScan,TrimbitsScan,PositionScan,CustomScript,NumModes}; - static const string modeNames[NumModes]; - - /**values*/ - int actualNumSteps; - vector positions; - - /**non error font*/ - QPalette normal; - QPalette red; - QString customTip; - QString fileTip; - QString rangeTip; - - /**widgets needed for diff size types*/ - QButtonGroup *btnGroup; - QStackedLayout *stackedLayout; - QLabel *lblFrom; - QDoubleSpinBox *spinFrom; - QLabel *lblTo; - QDoubleSpinBox *spinTo; - QLabel *lblSize; - QDoubleSpinBox *spinSize; - QComboBox *comboCustom; - QPushButton *btnCustom; - QLineEdit *dispFile; - QPushButton *btnFile; - - - /** Sets up the widget - */ - void SetupWidgetWindow(); - - /** Sets up all the slots and signals */ - void Initialization(); - - /** Sets up all the parameters from server/client */ - void LoadPositions(); - - /** Sets up the scan parameters - * returns if it was set - */ - int SetScan(int mode); - -private slots: -/** Enables widgets depending on which size is clicked. - * Options: constant size,specific values,values from file - * */ -void EnableSizeWidgets(); - -/** Sets the scan or script. Accordingly enables, disables other widgets - * @param mode value chosen*/ -void SetMode(int mode); - -/** Browse for the script - * */ -void BrowsePath(); - -/** Sets the script file - * */ -void SetScriptFile(); - -/** Set Parameter - * */ -void SetParameter(); - -/** Set precision - * @param value value of precision to be set - * */ -void SetPrecision(int value); - -/** Set number of steps - * */ -void SetNSteps(); - -/**Checks if size is zero and return FAIL if it does - * */ -int RangeCheckSizeZero(); - -/**returns ok and number of steps if valid - * @param number of steps - * */ -int RangeCheckNumValid(int &num); - -/**returns fail if to is not exact - * */ -int RangeCheckToValid(); - -/** Sets number of steps if from changed - * */ -void RangeFromChanged(); - -/** Sets number of steps if to changed - * */ -void RangeToChanged(); - -/** Sets s of steps if size changed - * */ -void RangeSizeChanged(); - -/** Set range for scan - * */ -void SetRangeSteps(); - - -/** Range type: If size is changed, - * the Number of steps is calculated - * */ -//void RangeCalculateNumSteps(); - -/** Range type: If size is changed, the To is calculated - * */ -//void RangeCalculateTo(); - - -/** Set custom steps - * returns OK if set properly - * */ -int SetCustomSteps(); - -/** Delete custom steps - * */ -void DeleteCustomSteps(); - -/** Reads the file to get the steps - * */ -void SetFileSteps(); - -/** Browses for the file path for steps - * */ -void BrowseFileStepsPath(); - - - -signals: -void EnableScanBox(); -}; - - - - -#endif /* QSCANWIDGET_H_ */ - diff --git a/slsDetectorGui/include/qServer.h b/slsDetectorGui/include/qServer.h old mode 100644 new mode 100755 index bd26080c6..96f381b14 --- a/slsDetectorGui/include/qServer.h +++ b/slsDetectorGui/include/qServer.h @@ -1,137 +1,126 @@ -/* - * qServer.h.h - * - * Created on: Feb 27, 2013 - * Author: Dhanya Maliakal - */ -#ifndef QSERVER_H -#define QSERVER_H +#pragma once - -/** Qt Project Class Headers */ -#include "sls_detector_defs.h" #include "qDefs.h" +#include "sls_detector_defs.h" class qDetectorMain; -/** Project Class Headers */ -class multiSlsDetector; -class MySocketTCP; -/** Qt Include Headers */ -#include -/** C++ Include Headers */ +class multiSlsDetector; +class ServerSocket; + +#include + +#include /** *@short Sets up the gui server */ -class qServer: public QWidget, public virtual slsDetectorDefs{ - Q_OBJECT +class qServer : public QWidget, public virtual slsDetectorDefs { + Q_OBJECT + public: + /** + * The constructor + */ + qServer(qDetectorMain *t); + /** + * Destructor + */ + ~qServer(); -public: - /** \short The constructor */ - qServer(qDetectorMain *t); - /** Destructor */ - ~qServer(); + /** + * Create (Control and Stop) Gui Servers + */ + void CreateServers(); - /** Start or Stop Gui Server - * @param start is 1 to start and 0 to stop - */ - int StartStopServer(int start); + /** + * Destroy (Control and Stop) Gui Servers + */ + void DestroyServers(); -private: - /** assigns functions to the fnum enum */ - int FunctionTable(); + private: + /** + * Assigns functions to the fnum enum + */ + void FunctionTable(); - /** Decodes Function */ - int DecodeFunction(MySocketTCP* sock); + /** + * Decodes Function + * @param sock control or stop socket + * @returns OK or FAIL + */ + int DecodeFunction(ServerSocket *sock); - /** Exit Server */ - int ExitServer(); + /** + * Shut down Sockets + */ + void ShutDownSockets(); + /** + * Server thread + * @param pointer to control or stop socket + */ + void ServerThread(ServerSocket* sock); - /** - * Static function - Thread started which listens to client gui. - * Called by StartStopServer() - * @param this_pointer pointer to this object - */ - static void* StartServerThread(void *this_pointer); + /** + * Thread of stop server + */ + void StopServer(); - /** - * Thread started which listens to client gui. - * Called by startServerThread() - * - */ - int StartServer(); + /** + * Get Detector Status + * @returns success of operation + */ + int GetStatus(); - /** - * Static function - Thread started which listens to client gui to stop acquisition - * Called by StartStopServer() - * @param this_pointer pointer to this object - */ - static void* StopServerThread(void *this_pointer); + /** + * Starts Acquisition + * @returns success of operation + */ + int StartAcquisition(); - /** - * Thread started which listens to client gui to stop acquisition. - * Called by startServerThread() - * - */ - int StopServer(); + /** + * Stops Acquisition + * @returns success of operation + */ + int StopsAcquisition(); + /** + * Acquire - blocking + * @returns success of operation + */ + int Acquire(); + /** + * Exit Server + * @returns GOODBYE + */ + int ExitServer(); - /** Get Detector Status */ - int GetStatus(); + /** function list */ + std::vector flist; - /** Starts Acquisition */ - int StartAcquisition(); + /** if the gui server thread is running*/ + bool threadRunning; - /** Stops Acquisition */ - int StopsAcquisition(); + /** if thread started */ + bool threadStarted; - /** Acquire - blocking */ - int Acquire(); + /**The measurement tab object*/ + qDetectorMain *mainTab; + /** control port */ + int controlPort; + /** stop port */ + int stopPort; - /**The measurement tab object*/ - qDetectorMain *myMainTab; + /** control socket */ + ServerSocket *controlSocket; - /** tcp socket to gui client */ - MySocketTCP *mySocket; - /** tcp socket to gui client to stop or get status */ - MySocketTCP *myStopSocket; - - /** server port number*/ - int port_no; - - /** Lock Status if server locked to a client */ - int lockStatus; - - /** Function List */ - static const int NUMBER_OF_FUNCTIONS = 256; - int (qServer::*flist[NUMBER_OF_FUNCTIONS])(); - - - /** if the gui server thread is running*/ - static int gui_server_thread_running; - /** thread listening to gui client*/ - pthread_t gui_server_thread; - /** thread also listening to gui client to stop acquisition*/ - pthread_t gui_stop_server_thread; - - /** server started */ - int checkStarted; - int checkStopStarted; - - /** Message */ - char mess[MAX_STR_LENGTH]; - - -signals: - void ServerStoppedSignal(); + /** stop socket */ + ServerSocket *stopSocket; + signals: + // to update the Listening to Gui check box + void ServerStoppedSignal(); }; - - - -#endif /* QSERVER_H */ diff --git a/slsDetectorGui/include/qTabActions.h b/slsDetectorGui/include/qTabActions.h deleted file mode 100644 index d5d497fde..000000000 --- a/slsDetectorGui/include/qTabActions.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * qTabActions.h - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ - -#ifndef QTABACTIONS_H_ -#define QTABACTIONS_H_ - -#include "qDefs.h" - - -/* Qt Project Class Headers */ -#include "qActionsWidget.h" -#include "qScanWidget.h" -/** C++ Project Class Headers */ -class multiSlsDetector; -/** Qt Include Headers */ -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -/** - *@short sets up the acions parameters - */ -class qTabActions:public QWidget{ - Q_OBJECT - -public: - /** \short The constructor - * @param parent is the parent tab widget - * @param detector is the detector returned from the detector tab - */ - qTabActions(QWidget *parent,multiSlsDetector*& detector); - - /** Destructor - */ - ~qTabActions(); - - /** To refresh and update widgets - */ - void Refresh(); - - -public slots: - /** Disable Positions - * @param enable true if to disable - * */ - void EnablePositions(bool enable); - - -private: - /** The sls detector object */ - multiSlsDetector *myDet; - - slsDetectorDefs::detectorType detType; - - - enum actionIndex{ - ActionStart, - Scan0, - Scan1, - ActionBefore, - NumPositions, - HeaderBefore, - HeaderAfter, - ActionAfter, - ActionStop, - NumTotalActions}; - - QGridLayout *gridLayout; - QButtonGroup *group; - QPalette *palette; - - /** all action widget objects */ - qActionsWidget *actionWidget[6]; - qScanWidget *scanWidget[2]; - QWidget *positionWidget; - QPushButton *btnExpand[NumTotalActions]; - QLabel *lblName[NumTotalActions]; - - - /** NumPositions widget */ - QLabel *lblNumPos; - QLabel *lblPosList; - QSpinBox *spinNumPos; - QComboBox *comboPos; - QPushButton *btnDelete; - QCheckBox *chkInvert; - QCheckBox *chkSeparate; - QCheckBox *chkReturn; - - double *positions; - QPalette normal; - QIcon *iconPlus; - QIcon *iconMinus; - - - /** Sets up the widget */ - void SetupWidgetWindow(); - - /** Sets up all the slots and signals */ - void Initialization(); - - /** creates the Num Positions object */ - void CreatePositionsWidget(); - - /** Returns the index in each of the classes - * of actionwidget and scanwidget - * @param index the index in the list of all widgets - * returns actual index of the class - */ - int GetActualIndex(int index); - - /** Updates to green color if collapsed and mode not none - */ - void UpdateCollapseColors(); - - - - -private slots: - /** To Expand the Action Widget - * */ - void Expand(QAbstractButton *button); - - /** Sets the positions list and the number of positions - * */ - void SetPosition(); - - /** Deletes current position - * */ - void DeletePosition(); - - -signals: - void EnableScanBox(); - -}; - -#endif /* QTABACTIONS_H_ */ - diff --git a/slsDetectorGui/include/qTabAdvanced.h b/slsDetectorGui/include/qTabAdvanced.h old mode 100644 new mode 100755 index e07305d77..568b8bcb1 --- a/slsDetectorGui/include/qTabAdvanced.h +++ b/slsDetectorGui/include/qTabAdvanced.h @@ -1,24 +1,15 @@ -/* - * qTabAdvanced.h - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ - -#ifndef QTABADVANCED_H_ -#define QTABADVANCED_H_ +#pragma once #include "qDefs.h" #include "sls_detector_defs.h" -/** Form Header */ #include "ui_form_tab_advanced.h" -/** Project Class Headers */ + class multiSlsDetector; class slsDetector; -/** Qt Project Class Headers */ + class qDrawPlot; -/** Qt Include Header */ + #include #include /** @@ -28,239 +19,196 @@ class qTabAdvanced:public QWidget, private Ui::TabAdvancedObject{ Q_OBJECT public: - /** \short The constructor - * @param parent is the parent tab widget - * @param detector is the detector returned from the detector tab - * @param plot plot object reference + /** + * The constructor + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab */ - qTabAdvanced(QWidget *parent,multiSlsDetector*& detector, qDrawPlot*& plot); + qTabAdvanced(QWidget *parent, multiSlsDetector* detector); - /** Destructor + /** + * Destructor */ ~qTabAdvanced(); public slots: - /** To refresh and update widgets + /** + * To refresh and update widgets */ void Refresh(); private: - /** Sets up the widget + /** + * Sets up the widget */ void SetupWidgetWindow(); - /** Sets up all the slots and signals + /** + * Sets up all the slots and signals */ void Initialization(); - /** Add ROI Input + /** + * Add ROI Input * @param num number of inputs to add */ void AddROIInput(int num); - /** Checks for a few conditions before trimming - /returns OK or FAIL - */ - int validateBeforeTrimming(); - - /** update the setalltrimbits value from server + /** + * Update the setalltrimbits value from server */ void updateAllTrimbitsFromServer(); private slots: - /** Enable/Disable Energy and Calibration Logs - */ - void SetLogs(); - - /** Set acquisition time - */ - void SetExposureTime(); - - /** Set the Threshold dac value - */ - void SetThreshold(); - - /** Set output directory for trimming - */ - void SetOutputFile(); - - /** Browse output directory for trimming - */ - void BrowseOutputFile(); - - /** Enables trimming method and calls SetTrimmingMethod if enabled - * @param enable to enable trimming - */ - void EnableTrimming(bool enable); - - /** Enabling resolution and Counts if this is enabled - * @param enable to enable - */ - void SetOptimize(bool enable); - - /** Sets the trimming method - * @param mode trimming method - */ - void SetTrimmingMethod(int mode); - - /** Ensures the right trimming mode and Executes Trimming - */ - void StartTrimming(); - - /** Updates the plot with trimbits from detector/shared memory - */ - void UpdateTrimbitPlot(int id); - - /** Sets control port + /** + * Sets control port * @param port control port */ void SetControlPort(int port); - /** Sets stop port + /** + * Sets stop port * @param port stop port */ void SetStopPort(int port); - /** Sets receiver tcp port + /** + * Sets receiver tcp port * @param port receiver tcp port */ void SetRxrTCPPort(int port); - /** Sets receiver udp port + /** + * Sets receiver udp port * @param port receiver udp port */ void SetRxrUDPPort(int port); - /** Sets client zmq receiver port + /** + * Sets client zmq receiver port * @param port client zmq receiver port */ void SetCltZmqPort(int port); - /** Sets receiver zmq transmitting port + /** + * Sets receiver zmq transmitting port * @param port receiver zmq transmitting port */ void SetRxrZmqPort(int port); - /** Sets receiver online + /** + * Sets receiver online * @param index 1 for online and 0 for offline */ void SetReceiverOnline(int index); - /** Sets detector online + /** + * Sets detector online * @param index 1 for online and 0 for offline */ void SetOnline(int index); - /** Sets network parameters like receiver udp ip, + /** + * Sets network parameters like receiver udp ip, * receiver udp mac, detector ip and detector mac */ void SetNetworkParameters(); - /** Sets client zmq ip to listen to + /** + * Sets client zmq ip to listen to */ void SetClientZMQIP(); - /** Sets receiver zmq ip to stream from + /** + * Sets receiver zmq ip to stream from */ void SetReceiverZMQIP(); - /** Sets the receiver. which also sets the receiver parameters + /** + * Sets the receiver. which also sets the receiver parameters */ void SetReceiver(); - /** Add ROI Input if the value changed in the last slot + /** + * Add ROI Input if the value changed in the last slot */ - void AddROIInputSlot(){AddROIInput(1);}; + void AddROIInputSlot(); - /** Clears all the ROI inputs + /** + * Clears all the ROI inputs */ void clearROI(); - /** Gets ROIs from detector and updates it + /** + * Gets ROIs from detector and updates it */ void updateROIList(); - /** Sets ROI in detector + /** + * Sets ROI in detector */ void setROI(); - /** Clears ROI in detector + /** + * Clears ROI in detector */ void clearROIinDetector(); - /** Clears ROI in detector + /** + * Select Readout + * @param index position index of readout */ void SetDetector(int index); - /** Set all trimbits to a value + /** + * Set all trimbits to a value */ void SetAllTrimbits(); - /** Set storage cells */ + /** + * Set storage cells + * @param value value to set to + */ void SetNumStoragecells(int value); - /** Set sub frame exposure time */ + /** + * Set sub frame exposure time + */ void SetSubExposureTime(); - /** Set sub frame period */ - void SetSubPeriod(); + /** + * Set sub frame dead time + */ + void SetSubDeadTime(); private: + /** The multi detector object */ multiSlsDetector *myDet; - /** The sls detector object */ - slsDetector *det; - /** detector type */ slsDetectorDefs::detectorType detType; - /** The Plot widget */ - qDrawPlot *myPlot; - - QButtonGroup *btnGroup; - - /** Tool Tip for the output dir */ - QString outputDirTip; - QString errOutputTip; + /** Tool Tip */ QString errOnlineTip; QString detOnlineTip; QString rxrOnlineTip; QPalette red; - /** Trimming mode */ - slsDetectorDefs::trimMode trimmingMode; - static const int TRIMMING_DYNAMIC_RANGE = 32; - static const int TRIMMING_FRAME_NUMBER = 1; - static const int TRIMMING_TRIGGER_NUMBER = 1; - static const int TRIMMING_PROBE_NUMBER = 0; - - bool isEnergy; - bool isAngular; - /** ROI */ - vector lblFromX; - vector spinFromX; - vector lblFromY; - vector spinFromY; - vector lblToX; - vector spinToX; - vector lblToY; - vector spinToY; + std::vector lblFromX; + std::vector spinFromX; + std::vector lblFromY; + std::vector spinFromY; + std::vector lblToX; + std::vector spinToX; + std::vector lblToY; + std::vector spinToY; int numRois; - /** sub period tool tip variables*/ - QString acqSubPeriodTip; - QString errSubPeriodTip; - - void CheckAcqPeriodGreaterThanExp(); - - }; - -#endif /* QTABADVANCED_H_ */ diff --git a/slsDetectorGui/include/qTabDataOutput.h b/slsDetectorGui/include/qTabDataOutput.h old mode 100644 new mode 100755 index 9f0957cd8..a0b9964c3 --- a/slsDetectorGui/include/qTabDataOutput.h +++ b/slsDetectorGui/include/qTabDataOutput.h @@ -1,21 +1,11 @@ -/* - * qTabDataOutput.h - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ - -#ifndef QTABDATAOUTPUT_H_ -#define QTABDATAOUTPUT_H_ +#pragma once #include "qDefs.h" - -/** Form Header */ #include "ui_form_tab_dataoutput.h" -/** Project Class Headers */ + class multiSlsDetector; -/** Qt Include Headers */ + #include @@ -26,35 +16,132 @@ class qTabDataOutput:public QWidget, private Ui::TabDataOutputObject{ Q_OBJECT public: - /** \short The constructor - * @param parent is the parent tab widget - * @param detector is the detector returned from the detector tab + /** + * The constructor + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab */ - qTabDataOutput(QWidget *parent,multiSlsDetector*& detector); + qTabDataOutput(QWidget *parent,multiSlsDetector* detector); - /** Destructor + /** + * Destructor */ ~qTabDataOutput(); - /** To refresh and update widgets + /** + * To refresh and update widgets */ void Refresh(); - /** verify output directories - * /returns success or fail + /** + * Verify output directories + * @returns success or fail */ int VerifyOutputDirectory(); -private: + + private slots: + + /** + * Open dialog to choose the output directory + */ + void BrowseOutputDir(); + + /** + * Set output directory + */ + void SetOutputDir(); + + /** + * Get output directory + */ + void GetOutputDir(); + + /** + * Set rate correction + */ + void SetRateCorrection(int deadtime=0); + + /** + * Set default rate correction + */ + void SetDefaultRateCorrection(); + + /** + * Set update rate correction from server + */ + void UpdateRateCorrectionFromServer(); + + /** + * Enable/Disable 10GbE + */ + void EnableTenGigabitEthernet(bool enable, int get=0); + + /** + * Set speed + */ + void SetSpeed(); + + /** + * Set flags + */ + void SetFlags(); + + /** + * Set file format + */ + void SetFileFormat(int format); + + /** + * Set overwrite enable + */ + void SetOverwriteEnable(bool enable); + + + private: + + /** + * Sets up the widget + */ + void SetupWidgetWindow(); + + /** + * Sets up all the slots and signals + */ + void Initialization(); + + /** + * Populate the readouts + */ + void PopulateDetectors(); + + /** + * Update speed + */ + void UpdateSpeedFromServer(); + + /** + * Update flags + */ + void UpdateFlagsFromServer(); + + /** + * Update file format + */ + void UpdateFileFormatFromServer(); + + /** + * Update overwrite enable + */ + void UpdateFileOverwriteFromServer(); + + /** The sls detector object */ multiSlsDetector *myDet; /** detector type */ slsDetectorDefs::detectorType detType; - - QString flatFieldTip; - QString errFlatFieldTip; QString outDirTip; QPalette red; QPalette black; @@ -62,95 +149,11 @@ private: QPalette *black1; /** enum for the Eiger clock divider */ - enum {FullSpeed, HalfSpeed, QuarterSpeed, SuperSlowSpeed, NumberofSpeeds}; + enum {FULLSPEED, HALFSPEED, QUARTERSPEED, SUPERSLOWSPEED, NUMBEROFSPEEDS}; /** enum for the Eiger readout flags1 */ - enum {Continous, Storeinram}; + enum {CONTINUOUS, STOREINRAM}; /** enum for the Eiger readout flags2 */ - enum {Parallel, NonParallel, Safe}; + enum {PARALLEL, NONPARALLEL, SAFE}; - -/** methods */ - /** Sets up the widget */ - void SetupWidgetWindow(); - - /** Sets up all the slots and signals */ - void Initialization(); - - /** Populate the readouts - */ - void PopulateDetectors(); - - /** update speed */ - void UpdateSpeedFromServer(); - - /** update flags */ - void UpdateFlagsFromServer(); - - /** update flags */ - void SetupFileFormat(); - - /** update file format */ - void UpdateFileFormatFromServer(); - - /** update overwrite enable */ - void UpdateFileOverwriteFromServer(); - - -private slots: - -/** Open dialog to choose the output directory */ -void BrowseOutputDir(); - -/**set flat field file*/ -void SetFlatField(); - -/** update flat field correction from server */ -void UpdateFlatFieldFromServer(); - -/**browse flat field*/ -void BrowseFlatFieldPath(); - -/**rate correction*/ -void SetRateCorrection(int deadtime=0); - -/** default rate correction */ -void SetDefaultRateCorrection(); - -/** update rate correction from server */ -void UpdateRateCorrectionFromServer(); - -/**angular correction*/ -void SetAngularCorrection(); - -/**discard bad channels*/ -void DiscardBadChannels(); - -/** set output directory*/ -void SetOutputDir(); - -/** set output directory*/ -void GetOutputDir(); - -/** enable 10GbE */ -void EnableTenGigabitEthernet(bool enable, int get=0); - -/** set speed */ -void SetSpeed(); - -/** set flags */ -void SetFlags(); - -/** set file format */ -void SetFileFormat(int format); - -/** set overwrite enable */ -void SetOverwriteEnable(bool enable); - -signals: -/**signal to enable/disable positions in Actions*/ -void AngularConversionSignal(bool); }; - - -#endif /* QTABDATAOUTPUT_H_ */ diff --git a/slsDetectorGui/include/qTabDebugging.h b/slsDetectorGui/include/qTabDebugging.h old mode 100644 new mode 100755 index 484dfa87d..62ef866b5 --- a/slsDetectorGui/include/qTabDebugging.h +++ b/slsDetectorGui/include/qTabDebugging.h @@ -1,24 +1,13 @@ -/* - * qTabDebugging.h - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ - -#ifndef QTABDEBUGGING_H_ -#define QTABDEBUGGING_H_ +#pragma once #include "qDefs.h" - -/** Form Header */ #include "ui_form_tab_debugging.h" -/** Project Class Headers */ + class multiSlsDetector; class slsDetector; -/** Qt Include Headers */ -#include +#include /** @@ -28,76 +17,71 @@ class qTabDebugging:public QWidget, private Ui::TabDebuggingObject{ Q_OBJECT public: - /** \short The constructor - * @param parent is the parent tab widget - * @param detector is the detector returned from the detector tab + /** + * The constructor + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab */ - qTabDebugging(QWidget *parent,multiSlsDetector*& detector); + qTabDebugging(QWidget *parent, multiSlsDetector* detector); - /** Destructor + /** + * Destructor */ ~qTabDebugging(); - /** To refresh and update widgets + /** + * To refresh and update widgets */ void Refresh(); + +private slots: + + /** + * Updates the status depending on current detector + */ + void UpdateStatus(); + + /** + * Gets id and versions etc + */ + void + GetInfo(); + + /** + * Sets id and versions on the display widget + */ + void SetParameters(QTreeWidgetItem *item); + + /** + * Test detector + */ + void TestDetector(); + private: - /** Sets up the widget + /** + * Sets up the widget */ void SetupWidgetWindow(); - /** Sets up all the slots and signals + /** + * Sets up all the slots and signals */ void Initialization(); - -private slots: - /** Updates the module list depending on current detector - */ - void UpdateModuleList(); - - /** Updates the status depending on current detector - */ - void UpdateStatus(); - - /** Gets id and versions etc - */ - void GetInfo(); - - /** Sets id and versions on the display widget - */ - void SetParameters(QTreeWidgetItem *item); - - /** Test detector and module - */ - void TestDetector(); - -private: /** The multi sls detector object */ multiSlsDetector *myDet; /** detector type */ slsDetectorDefs::detectorType detType; - /**sls detecctor object */ - slsDetector *det; - /** Tree Widget displaying the detectors, modules */ QTreeWidget *treeDet; /** Widget displaying the serial numbers, mac addresses etc */ - QFrame *dispFrame; QLabel *lblDetectorId; - QLabel *lblDetectorSerial; QLabel *lblDetectorFirmware; QLabel *lblDetectorSoftware; - QLabel *lblModuleId; - QLabel *lblModuleFirmware; - QLabel *lblModuleSerial; QPalette *blue; }; - - -#endif /* QTABDEBUGGING_H_ */ diff --git a/slsDetectorGui/include/qTabDeveloper.h b/slsDetectorGui/include/qTabDeveloper.h old mode 100644 new mode 100755 index 10fc334aa..8e0940984 --- a/slsDetectorGui/include/qTabDeveloper.h +++ b/slsDetectorGui/include/qTabDeveloper.h @@ -1,18 +1,9 @@ -/* - * qTabDeveloper.h - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ - -#ifndef QTABDEVELOPER_H_ -#define QTABDEVELOPER_H_ +#pragma once #include "qDefs.h" -/** Project Class Headers */ class multiSlsDetector; -/** Qt Include Headers */ + #include #include #include @@ -26,10 +17,8 @@ class multiSlsDetector; #include class qDetectorMain; -/** C++ Include Headers */ #include #include -using namespace std; /**To override the spin box class to have an id and emit it*/ @@ -41,11 +30,8 @@ private: void valueChangedWithID() {emit editingFinished(myId);}; public: /** Overridden constructor from QDoubleSpinBox */ - MyDoubleSpinBox(int id,QWidget* parent = 0) - :QDoubleSpinBox(parent),myId(id){ - //setParent(parent); - connect(this,SIGNAL(editingFinished()), - this,SLOT(valueChangedWithID())); + MyDoubleSpinBox(int id,QWidget* parent = 0) :QDoubleSpinBox(parent), myId(id){ + connect(this, SIGNAL(editingFinished()), this, SLOT(valueChangedWithID())); } signals: void editingFinished(int myId); @@ -59,100 +45,104 @@ class qTabDeveloper:public QWidget { Q_OBJECT public: - /** \short The constructor - * @param parent is the parent tab widget - * @param detector is the detector returned from the detector tab + /** + * The constructor + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab */ - qTabDeveloper(qDetectorMain *parent,multiSlsDetector*& detector); + qTabDeveloper(QWidget *parent, multiSlsDetector* detector); - /** Destructor + /** + * Destructor */ ~qTabDeveloper(); - /** To stop ADC Timer when starting acquisition - */ - void StopADCTimer(){if(adcTimer) adcTimer->stop();}; - -private: - /** parent widget */ - qDetectorMain *thisParent; - /** The sls detector object */ - multiSlsDetector *myDet; - /** The sls detector object */ - slsDetector *det; - /** detector type */ - slsDetectorDefs::detectorType detType; - /**number of dac widgets*/ - static int NUM_DAC_WIDGETS; - /**number of adc widgets*/ - static int NUM_ADC_WIDGETS; - - static const int ADC_TIMEOUT = 5000; - - vectordacNames; - vectoradcNames; - - - /**widgets needed*/ - QGridLayout *layout; - QScrollArea *scroll; - QGroupBox *boxDacs; - QGroupBox *boxAdcs; - QLabel *lblDacs[20]; - QLabel *lblAdcs[20]; - MyDoubleSpinBox *spinDacs[20]; - QLabel *lblDacsmV[20]; - QLineEdit *spinAdcs[20]; - QLabel *lblHV; - QComboBox *comboHV; - QTimer *adcTimer; - QGridLayout *dacLayout; - QString tipHV; - QPalette red; - QComboBox *comboDetector; - /** Sets up the widget - */ - void SetupWidgetWindow(); - - /** Sets up all the slots and signals - */ - void Initialization(); - - /** Sets up the DAC Widgets - */ - void CreateDACWidgets(); - - /** Sets up the ADC Widgets - */ - void CreateADCWidgets(); - - /** Gets the sls index to set/get dac/adc - * @param index is the gui dac/adc index - * returns the sls index - */ - slsDetectorDefs::dacIndex getSLSIndex(int index); - public slots: - /** To refresh and update widgets + /** + * Refresh and update widgets */ void Refresh(); private slots: - /** Refreshes the adcs + /** + * Refreshes the adcs */ void RefreshAdcs(); - /** Set Dac values + /** + * Set Dac values * @param id id of dac */ void SetDacValues(int id); - /** Set High Voltage + /** + * Set High Voltage */ void SetHighVoltage(); + +private: + + /** + * Sets up the widget + */ + void SetupWidgetWindow(); + + /** + * Sets up all the slots and signals + */ + void Initialization(); + + /** + * Sets up the DAC Widgets + */ + void CreateDACWidgets(); + + /** + * Sets up the ADC Widgets + */ + void CreateADCWidgets(); + + /** + * Sets up HV widget + */ + void CreateHVWidget(); + + /** + * Gets the sls index to set/get dac/adc + * @param index is the gui dac/adc index + * @returns the sls index + */ + slsDetectorDefs::dacIndex getSLSIndex(int index); + + /** The sls detector object */ + multiSlsDetector *myDet; + /** detector type */ + slsDetectorDefs::detectorType detType; + /**number of dac widgets*/ + int numDACWidgets; + /**number of adc widgets*/ + int numADCWidgets; + + /** list of dac and adc names */ + std::vectordacNames; + std::vectoradcNames; + + + /**widgets needed*/ + QGroupBox *boxDacs; + QGroupBox *boxAdcs; + std::vectorlblDacs; + std::vectorlblAdcs; + std::vectorspinDacs; + std::vectorlblDacsmV; + std::vectorspinAdcs; + QLabel *lblHV; + QComboBox *comboHV; + QSpinBox *spinHV; + QGridLayout *dacLayout; + QString tipHV; + QPalette red; + QComboBox *comboDetector; }; - - -#endif /* QTABDEVELOPER_H_ */ diff --git a/slsDetectorGui/include/qTabMeasurement.h b/slsDetectorGui/include/qTabMeasurement.h old mode 100644 new mode 100755 index 362fba590..bd7f6553e --- a/slsDetectorGui/include/qTabMeasurement.h +++ b/slsDetectorGui/include/qTabMeasurement.h @@ -1,20 +1,11 @@ -/* - * qTabMeasurement.h - * - * Created on: May 2, 2012 - * Author: l_maliakal_d - */ -#ifndef QTABMEASUREMENT -#define QTABMEASUREMENT +#pragma once #include "qDefs.h" - -/** Form Header */ #include "ui_form_tab_measurement.h" -/** Project Class Headers */ + class multiSlsDetector; -/** Qt Project Class Headers */ + #include #include "qDrawPlot.h" class qDetectorMain; @@ -26,157 +17,172 @@ class qTabMeasurement:public QWidget, private Ui::TabMeasurementObject{ Q_OBJECT public: - /** \short The constructor - * This tab allows to change the detector settings, the threshold, the number of (non real time) measurements, - * the acquisition time, the file name, the start run index and shows the current progress of the measurement - * via a progress bar and labels inidicating the current position, scan variable, frame number etc. - * Contains the start and stop acquisition button - * @param parent is the parent tab widget - * @param detector is the detector returned from the detector tab - * @param plot plot object reference + /** + * The constructor + * This tab allows to change measurement parameters and to start/stop an acquisition + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab + * @param plot plot object reference */ - qTabMeasurement(qDetectorMain *parent,multiSlsDetector*& detector, qDrawPlot*& plot); + qTabMeasurement(QWidget *parent,multiSlsDetector* detector, qDrawPlot* plot); - /** Destructor + /** + * Destructor */ ~qTabMeasurement(); - /** To refresh and update widgets + /** + * Returns the status of the acquisition in gui */ - void Refresh(); + bool GetStartStatus(); - /** To enable expert mode - * @param enable to enable if true - */ - void SetExpertMode(bool enable); - - /** Returns the status of the acquisition in gui - */ - bool GetStartStatus(){return (!btnStart->isEnabled());}; - - /** Click the Start/Stop Acquisition button + /** + * Click the Start/Stop Acquisition button * This is used if this command came from gui client */ - void ClickStartStop(){startAcquisition();myPlot->SetClientInitiated();}; + void ClickStartStop(); - /** Returns progress bar value */ - int GetProgress(){return progressBar->value();}; + /** + * Returns progress bar value + */ + int GetProgress(); + + /** + * Refresh and update widgets + */ + void Refresh(); public slots: - /** update plot is finished, + /** + * Update plot is finished, * changes start/stop text and enables/disables all widgets */ void UpdateFinished(); - /** updates the current measurement + /** + * Updates the current measurement * @param val the value to be updated */ void SetCurrentMeasurement(int val); - - - -private: - /** Sets up the widget - */ - void SetupWidgetWindow(); - - /** Sets up the timing mode - */ - void SetupTimingMode(); - - /** Sets up all the slots and signals - */ - void Initialization(); - - /** Enables/Disables all the widgets - */ - void Enable(bool enable); - - /** Validates before enabling or disabling probes */ - void EnableProbes(); - - /** Get timing mode from detector - * @param startup is true when gui has just started up*/ - void GetModeFromDetector(bool startup = false); - - /** Checks if acquisition period is greater than exposure time - * and dsplays in red as a warning */ - void CheckAcqPeriodGreaterThanExp(); - - private slots: - /** Sets the timing mode - * @ param mode cane be None, Auto, Gated, Trigger Exposure Series, - * Trigger Frame, Trigger Readout, External Trigger Window - */ - void SetTimingMode(int mode); - /** Set number of measurements - * @param num number of measurements to be set */ + /** + * Set number of measurements + * @param num number of measurements to be set + */ void setNumMeasurements(int num); - /** Set file name - */ - void setFileName(); - - /** Set index of file name - * @param index index of selection - */ - void setRunIndex(int index); - - /** starts Acquisition - */ - void startAcquisition(); - - /** stops Acquisition - */ - void stopAcquisition(); - - /** Set number of frames + /** + * Set number of frames * @param val number of frames to be set */ void setNumFrames(int val); - /** Set acquisition time + /** + * Set acquisition time */ void setExposureTime(); - /** Set frame period between exposures + /** + * Set frame period between exposures */ void setAcquisitionPeriod(); - /** Set number of triggers + /** + * Set number of triggers * @param val number of triggers to be set */ void setNumTriggers(int val); - /** Set delay + /** + * Set delay */ void setDelay(); - /** Set number of gates - * @param val number of gates to be set + /** + * Set number of samples + * @param val number of samples to be set */ - void setNumGates(int val); + void setNumSamples(int val); - /** Set number of probes - * @param val number of probes to be set + /** + * Set file name */ - void setNumProbes(int val); + void setFileName(); - /** Update progress*/ - void UpdateProgress(); - - /** Enable write to file */ + /** + * Enable write to file + */ void EnableFileWrite(bool enable); + /** + * Set index of file name + * @param index index of selection + */ + void setRunIndex(int index); + + /** + * Update progress + */ + void UpdateProgress(); + + /** + * starts Acquisition + */ + void startAcquisition(); + + /** + * stops Acquisition + */ + void stopAcquisition(); + + /** + * Sets the timing mode + * @param mode timing mode + */ + void SetTimingMode(int mode); private: - /** parent widget */ - qDetectorMain *thisParent; + /** + * Sets up the widget + */ + void SetupWidgetWindow(); + + /** + * Sets up the timing mode + */ + void SetupTimingMode(); + + /** + * Sets up all the slots and signals + */ + void Initialization(); + + /** + * Get timing mode from detector + * @param startup is true when gui has just started up + */ + void GetTimingModeFromDetector(bool startup = false); + + /** + * Enables/Disables widgetframes to avoid setting measurement during an acquisition + */ + void Enable(bool enable); + + /** + * Checks if acquisition period is greater than exposure time + */ + void CheckAcqPeriodGreaterThanExp(); + + /** + * Verify if output directory existing error is set + * @returns OK or FAIL + */ + int VerifyOutputDirectoryError(); + /** The sls detector object */ multiSlsDetector *myDet; /** The Plot widget */ @@ -184,15 +190,13 @@ private: /** detector type */ slsDetectorDefs::detectorType detType; /** enum for the timing mode */ - enum{None, Auto, Trigger_Exp_Series, Trigger_Readout, Gated, Gated_Start, Burst_Trigger, NumTimingModes}; + enum{AUTO, TRIGGER, GATED, BURST_TRIGGER, NUM_TIMING_MODES}; /** timer to update the progress*/ QTimer *progressTimer; /** tool tip variables*/ QString acqPeriodTip; QString errPeriodTip; QPalette red; - /** expert mode */ - bool expertMode; /** to access items in settings combobox */ QStandardItemModel* model; @@ -201,7 +205,3 @@ signals: void StopSignal(); void CheckPlotIntervalSignal(); }; - - - -#endif /* QTABMEASUREMENT */ diff --git a/slsDetectorGui/include/qTabMessages.h b/slsDetectorGui/include/qTabMessages.h old mode 100644 new mode 100755 index 8dd7f611b..f32c6ff32 --- a/slsDetectorGui/include/qTabMessages.h +++ b/slsDetectorGui/include/qTabMessages.h @@ -1,26 +1,14 @@ -/* - * qTabMessages.h - * - * Created on: Jun 26, 2012 - * Author: l_maliakal_d - */ - -#ifndef QTABMESSAGES_H_ -#define QTABMESSAGES_H_ - +#pragma once #include "qDefs.h" - - - -/** Project Class Headers */ +#include "qDebugStream.h" class qDetectorMain; -/** Qt Include Headers */ + #include #include #include #include -#include "qDebugStream.h" + /** *@short sets up the Messages parameters @@ -29,17 +17,46 @@ class qTabMessages:public QWidget{ Q_OBJECT public: - /** \short The constructor - * @param det the qDetectorMain class reference + /** + * The constructor + * @param parent parent widget */ - qTabMessages(qDetectorMain* m); + qTabMessages(QWidget* parent); - /** Destructor + /** + * Destructor */ ~qTabMessages(); +private slots: + /** + * Stream log to textedit in GUI + */ + void customEvent(QEvent *e); + + /** + * Save Log to File + */ + void SaveLog(); + + /** + * Clear Log to File + */ + void ClearLog(); private: + + /** + * Sets up the widget + */ + void SetupWidgetWindow(); + + /** + * Sets up all the slots and signals + */ + void Initialization(); + + /** The qDetectorMain object */ qDetectorMain *myMainTab; @@ -51,36 +68,5 @@ private: /** To clear the log to file */ QPushButton *btnClear; - - /** This class creates the log */ - qDebugStream *qout; - qDebugStream *qerr; - - string errMsg; - -/** methods */ - /** Sets up the widget */ - void SetupWidgetWindow(); - - /** Sets up all the slots and signals */ - void Initialization(); - -private slots: -/** Stream log to textedit in GUI */ -void customEvent(QEvent *e); - -/** Save Log to File*/ -void SaveLog(); - -/** Clear Log to File*/ -void ClearLog(); - - - }; - - - - -#endif /* QTABMESSAGES_H_ */ diff --git a/slsDetectorGui/include/qTabPlot.h b/slsDetectorGui/include/qTabPlot.h old mode 100644 new mode 100755 index b2dbbd208..a73b72002 --- a/slsDetectorGui/include/qTabPlot.h +++ b/slsDetectorGui/include/qTabPlot.h @@ -35,7 +35,7 @@ public: * @param detector is the detector returned from the detector tab * @param plot plot object reference */ - qTabPlot(QWidget *parent,multiSlsDetector*& detector, qDrawPlot*& plot); + qTabPlot(QWidget *parent,multiSlsDetector* detector, qDrawPlot* plot); /** Destructor */ @@ -106,7 +106,7 @@ public slots: /** Enable Scan box */ - void EnableScanBox(); + void EnableScanBox(); private slots: diff --git a/slsDetectorGui/include/qTabSettings.h b/slsDetectorGui/include/qTabSettings.h old mode 100644 new mode 100755 index ddb0d4da6..fb2d2f422 --- a/slsDetectorGui/include/qTabSettings.h +++ b/slsDetectorGui/include/qTabSettings.h @@ -1,22 +1,10 @@ -/* - * qTabSettings.h - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ - -#ifndef QTABSETTINGS_H_ -#define QTABSETTINGS_H_ +#pragma once #include "qDefs.h" - -/** Form Header */ #include "ui_form_tab_settings.h" -/** Project Class Headers */ + class multiSlsDetector; -/** Qt Include Headers */ -#include /** *@short sets up the Settings parameters @@ -25,92 +13,77 @@ class qTabSettings:public QWidget, private Ui::TabSettingsObject{ Q_OBJECT public: - /** \short The constructor - * @param parent is the parent tab widget - * @param detector is the detector returned from the detector tab + /** + * The constructor + * @param parent is the parent tab widget + * @param detector is the detector returned from the detector tab */ - qTabSettings(QWidget *parent,multiSlsDetector*& detector); + qTabSettings(QWidget *parent, multiSlsDetector* detector); - /** Destructor + /** + * Destructor */ ~qTabSettings(); - /** To refresh and update widgets + /** + * Refresh and update widgets */ void Refresh(); - /** To enable expert mode - * @param enable to enable if true + +private slots: + /** + * Set settings according to selection + * @param index index of selection */ - void SetExpertMode(bool enable){expertMode = enable;}; + void SetSettings(int index); + /** + * Set dynamic range if possible + * @param index selection + */ + void SetDynamicRange(int index); + /** + * Set threshold energy + */ + void SetEnergy(); private: + + /** + * Sets up the widget + */ + void SetupWidgetWindow(); + + /** + * Sets up the detector settings + */ + void SetupDetectorSettings(); + + /** + * Sets up all the slots and signals + */ + void Initialization(); + + /** + * Get Settings + */ + void GetSettings(); + + /** + * Gets the dynamic range and sets it on the gui + */ + void GetDynamicRange(); + /** The sls detector object */ multiSlsDetector *myDet; /** detector type */ slsDetectorDefs::detectorType detType; - /** expert mode */ - bool expertMode; - - enum{Standard,Fast,HighGain,DynamicGain,LowGain,MediumGain,VeryHighGain,LowNoise, - DynamicHG0,FixGain1,FixGain2,ForceSwitchG1,ForceSwitchG2, VeryLowGain, - Undefined,Uninitialized,NumSettings}; - - /** To be able to index items on a combo box */ - QStandardItemModel* model; - QModelIndex index[NumSettings]; - QStandardItem* item[NumSettings]; - - /** Sets up the widget - */ - void SetupWidgetWindow(); - - /** Sets up the detector settings - */ - void SetupDetectorSettings(); - - /** Sets up all the slots and signals - */ - void Initialization(); - - /** Gets the dynamic range and sets it on the gui - * @param setvalue the value set by the gui when used as a check - */ - void GetDynamicRange(int setvalue = -1); - - - -private slots: -/** Set settings according to selection - * @param index index of selection - */ -void setSettings(int index); - -/** Set number of modules if possible - * @param index number of modules - */ -void SetNumberOfModules(int index); - -/** Set dynamic range if possible - * @param index selection - */ -void SetDynamicRange(int index); - -/** Set threshold energy - */ -void SetEnergy(); - - -signals: -/**Update Trimbits after Set Settings */ -void UpdateTrimbitSignal(int); + enum{STANDARD, FAST, HIGHGAIN, DYNAMICGAIN, LOWGAIN, MEDIUMGAIN, VERYHIGHGAIN, LOWNOISE, + DYNAMICHG0, FIXGAIN1, FIXGAIN2, FORCESWITCHG1, FORCESWITCHG2, VERLOWGAIN, + UNDEFINED, UNINITIALIZED, NUMSETTINGS}; }; - - - -#endif /* QTABSETTINGS_H_ */ diff --git a/slsDetectorGui/slsDetectorGui.pro b/slsDetectorGui/slsDetectorGui.pro deleted file mode 100644 index 753da18f6..000000000 --- a/slsDetectorGui/slsDetectorGui.pro +++ /dev/null @@ -1,162 +0,0 @@ -#When using yum for qt, comment out all lines with $(QTDIR) or $(QWTDIR), but export QWTDIR = /usr/include/qwt/ -#and leave "$(QWTDIR) \"uncommented in the INCLUDEPATH - -#When using epics, uncomment epics defines, libs and a line in INCLUDEPATH - - - -QT_INSTALL_PREFIX = $(QTDIR) -QMAKE_UIC = $(QTDIR)/bin/uic -QMAKE_MOC = $(QTDIR)/bin/moc -QMAKE_RCC = $(QTDIR)/bin/rcc -QMAKE_INCDIR_QT = $(QTDIR)/include/ -QMAKE_LIBS_QT = -L$(QTDIR)/lib -QMAKE_LIBS = -L$(QTDIR)/lib - - - - -#epics -#DEFINES += EPICS VERBOSE DACS_INT PRINT_LOG #VERYVERBOSE -#LIBS = -L$(QWTDIR)/lib -lqwt -L$(QWT3D)/lib -Wl,-R$(QWTDIR)/lib -L /usr/local/epics/base/lib/$(EPICS_HOST_ARCH)/ -Wl,-R/usr/local/epics/base/lib/$(EPICS_HOST_ARCH) -lca -lCom - -#default -DEFINES += VERBOSE DACS_INT PRINT_LOG #VERYVERBOSE CHECKINFERROR -LIBS = -L$(QWTDIR)/lib -lqwt -L$(QWT3D)/lib $(LDFLAGDET) - -CXXFLAGS += -g - - -QMAKE_CXXFLAGS_WARN_ON = -w -QMAKE_CFLAGS_WARN_ON = -w - - - - -DESTDIR ?= bin -MOC_DIR = mocs -OBJECTS_DIR = objs -UI_HEADERS_DIR = forms/include -SLSDETLIB ?= ../slsDetectorSoftware -RESOURCES += icons.qrc -CONFIG += debug no_include_pwd - - - -target.path += $(DESTDIR) -documentation.path = /$(DOCPATH) -documentation.files = docs/* -INSTALLS += target -INSTALLS += documentation -QMAKE_CLEAN += docs/*/* - - - -extralib.target = extra -extralib.commands = echo `tput setaf 6`; \ - echo 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; \ - echo 'x Compiling slsDetectorGui x'; \ - echo 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; \ - echo `./updateGitVersion.sh; tput sgr0` -extralib.depends = $(target) - -QMAKE_EXTRA_TARGETS += extralib -PRE_TARGETDEPS = extra - - - - -DEPENDPATH += \ - slsDetectorPlotting/include\ - include\ - forms/include - - -INCLUDEPATH += \ - $(QWTDIR)/include\ - $(QWTDIR) \ - $(QWTDIR)/src\ - $(QWT3D)/include\ - slsDetectorPlotting/include\ - ../slsReceiverSoftware/include\ - include\ - forms/include\ - /usr/include/qwt\ #these are not included for standard installations, also bin path should include qt4 bin, not qt3 bin - /usr/include/qt4\ - /usr/include/Qt\ - /usr/include/QtCore\ - /usr/include/QtGui\ - $(INCLUDES) - -#epics -# $(INCLUDES) /usr/local/epics/base/include/ -I /usr/local/epics/base/include/os/Linux/ - - - - - - -SOURCES = \ - slsDetectorPlotting/src/SlsQt1DPlot.cxx\ - slsDetectorPlotting/src/SlsQt1DZoomer.cxx\ - slsDetectorPlotting/src/SlsQt2DHist.cxx\ - slsDetectorPlotting/src/SlsQt2DPlot.cxx\ - slsDetectorPlotting/src/SlsQt2DPlotLayout.cxx\ - slsDetectorPlotting/src/SlsQtNumberEntry.cxx\ - src/qDetectorMain.cpp\ - src/qDrawPlot.cpp\ - src/qCloneWidget.cpp\ - src/qTabMeasurement.cpp\ - src/qTabDataOutput.cpp\ - src/qTabPlot.cpp\ - src/qTabActions.cpp\ - src/qActionsWidget.cpp\ - src/qScanWidget.cpp\ - src/qTabAdvanced.cpp\ - src/qTabSettings.cpp\ - src/qTabDebugging.cpp\ - src/qTabDeveloper.cpp\ - src/qTabMessages.cpp\ - src/qServer.cpp - -HEADERS = \ - slsDetectorPlotting/include/SlsQt1DPlot.h\ - slsDetectorPlotting/include/SlsQt1DZoomer.h\ - slsDetectorPlotting/include/SlsQt2DHist.h\ - slsDetectorPlotting/include/SlsQt2DPlot.h\ - slsDetectorPlotting/include/SlsQt2DPlotLayout.h\ - slsDetectorPlotting/include/SlsQt2DZoomer.h\ - slsDetectorPlotting/include/SlsQtValidators.h\ - slsDetectorPlotting/include/SlsQtNumberEntry.h\ - include/qDefs.h\ - include/qDebugStream.h\ - include/qDetectorMain.h\ - include/qDrawPlot.h\ - include/qCloneWidget.h\ - include/qTabMeasurement.h\ - include/qTabDataOutput.h\ - include/qTabPlot.h\ - include/qTabActions.h\ - include/qActionsWidget.h\ - include/qScanWidget.h\ - include/qTabAdvanced.h\ - include/qTabSettings.h\ - include/qTabDebugging.h\ - include/qTabDeveloper.h\ - include/qTabMessages.h\ - include/gitInfoGui.h\ - ../slsDetectorSoftware/commonFiles/sls_detector_defs.h\ - ../slsReceiverSoftware/include/sls_receiver_defs.h\ - include/qServer.h - - -FORMS = \ - forms/form_detectormain.ui\ - forms/form_tab_measurement.ui\ - forms/form_tab_dataoutput.ui\ - forms/form_tab_plot.ui\ - forms/form_tab_advanced.ui\ - forms/form_tab_settings.ui\ - forms/form_tab_debugging.ui\ - forms/form_action.ui\ - forms/form_scan.ui diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h old mode 100644 new mode 100755 index 554a17fab..6e48420fc --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DPlot.h @@ -13,9 +13,6 @@ #ifndef SLSQT1DPLOT_H #define SLSQT1DPLOT_H -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; #include "ansi.h" @@ -25,7 +22,7 @@ typedef int int32_t; #include #include "SlsQt1DZoomer.h" #include -using namespace std; + class QPen; class SlsQt1DPlot; diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DZoomer.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DZoomer.h old mode 100644 new mode 100755 index 3bcb35ee7..7b109ba58 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DZoomer.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt1DZoomer.h @@ -7,13 +7,6 @@ #ifndef SLSQT1DZOOMER_H #define SLSQT1DZOOMER_H -#ifndef IAN -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; -#endif - - #include #include #include diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h old mode 100644 new mode 100755 index a71a32676..a9b8a6028 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DHist.h @@ -9,14 +9,6 @@ #define SLSQT2DHIST_H -#ifndef IAN -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; -#endif - - - #if QT_VERSION >= 0x040000 #include #endif diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h old mode 100644 new mode 100755 index 8b1944392..619eb410f --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlot.h @@ -14,11 +14,6 @@ #ifndef SLSQT2DPLOT_H #define SLSQT2DPLOT_H -#ifndef IAN -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; -#endif diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlotLayout.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlotLayout.h old mode 100644 new mode 100755 index 2d2315f77..d40f7332d --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlotLayout.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DPlotLayout.h @@ -12,11 +12,6 @@ #ifndef SLSQT2DPLOTLAYOUT_H #define SLSQT2DPLOTLAYOUT_H -#ifndef IAN -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; -#endif #include diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DZoomer.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DZoomer.h old mode 100644 new mode 100755 index 5fed37f1a..d4f8d4376 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DZoomer.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQt2DZoomer.h @@ -9,11 +9,6 @@ #ifndef SLSQT2DZOOMER_H #define SLSQT2DZOOMER_H -#ifndef IAN -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; -#endif /**included by Dhanya on 05.12.2012 to avoid compile time errors with the latest gcc*/ diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQtNumberEntry.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQtNumberEntry.h old mode 100644 new mode 100755 index dbeb0a31e..fa152604b --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQtNumberEntry.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQtNumberEntry.h @@ -7,11 +7,6 @@ #ifndef SLSQTNUMBERENTRY_H #define SLSQTNUMBERENTRY_H -#ifndef IAN -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; -#endif #include diff --git a/slsDetectorGui/slsDetectorPlotting/include/SlsQtValidators.h b/slsDetectorGui/slsDetectorPlotting/include/SlsQtValidators.h old mode 100644 new mode 100755 index bd2d70efd..197b162a2 --- a/slsDetectorGui/slsDetectorPlotting/include/SlsQtValidators.h +++ b/slsDetectorGui/slsDetectorPlotting/include/SlsQtValidators.h @@ -7,12 +7,6 @@ #ifndef SLSQTVALIDATORS_H #define SLSQTVALIDATORS_H -#ifndef IAN -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; -#endif - #include #include diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cxx b/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cxx old mode 100644 new mode 100755 index 1382e0e50..a696ad3aa --- a/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cxx +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DPlot.cxx @@ -4,514 +4,567 @@ * @version 1.0 */ +#include "SlsQt1DPlot.h" #include -#include +#include +#include #include #include #include -#include -#include #include #include -#include -#include "SlsQt1DPlot.h" +#include +#include #if QWT_VERSION >= 0x060100 #define QwtLog10ScaleEngine QwtLogScaleEngine #endif -using namespace std; - -SlsQtH1D::SlsQtH1D(QString title,int n, double min, double max, double* data):QwtPlotCurve(title){ - Initailize(); - SetData(n,min,max,data); +SlsQtH1D::SlsQtH1D(QString title, int n, double min, double max, double *data) : QwtPlotCurve(title) { + Initailize(); + SetData(n, min, max, data); } -SlsQtH1D::SlsQtH1D(QString title,int n, double* data_x, double* data_y):QwtPlotCurve(title){ - Initailize(); - SetData(n,data_x,data_y); +SlsQtH1D::SlsQtH1D(QString title, int n, double *data_x, double *data_y) : QwtPlotCurve(title) { + Initailize(); + SetData(n, data_x, data_y); } -void SlsQtH1D::Initailize(){ - ndata=n_array=0; - x=y=0; - pen_ptr = new QPen(); - SetLineColor(); +void SlsQtH1D::Initailize() { + ndata = n_array = 0; + x = y = 0; + pen_ptr = new QPen(); + SetLineColor(); } -SlsQtH1D::~SlsQtH1D(){delete x;delete y;delete pen_ptr;} - -void SlsQtH1D::Attach(SlsQt1DPlot* p){ - attach((QwtPlot*) p); - p->NewHistogramAttached(this); +SlsQtH1D::~SlsQtH1D() { + delete x; + delete y; + delete pen_ptr; } -void SlsQtH1D::Detach(SlsQt1DPlot* p){ - detach(); - p->HistogramDetached(this); +void SlsQtH1D::Attach(SlsQt1DPlot *p) { + attach((QwtPlot *)p); + p->NewHistogramAttached(this); } +void SlsQtH1D::Detach(SlsQt1DPlot *p) { + detach(); + p->HistogramDetached(this); +} -int SlsQtH1D::SetLineColor(int c){ - static int last_color = 1; - if(c<0) c=(last_color+1)%3; - - switch(c){ - case 0: pen_ptr->setColor(Qt::black); break; - case 1: pen_ptr->setColor(Qt::red); break; - case 2: pen_ptr->setColor(Qt::blue); break; - case 3: pen_ptr->setColor(Qt::green); break; - case 4: pen_ptr->setColor(Qt::magenta); break; - case 5: pen_ptr->setColor(Qt::cyan); break; - case 6: pen_ptr->setColor(Qt::darkYellow); break; - case 7: pen_ptr->setColor(Qt::gray); break; - case 8: pen_ptr->setColor(Qt::darkBlue); break; - case 9: pen_ptr->setColor(Qt::darkGreen); break; - case 10: pen_ptr->setColor(Qt::darkMagenta); break; - } -/* if(c==0) pen_ptr->setColor(Qt::black); +int SlsQtH1D::SetLineColor(int c) { + static int last_color = 1; + if (c < 0) + c = (last_color + 1) % 3; + + switch (c) { + case 0: + pen_ptr->setColor(Qt::black); + break; + case 1: + pen_ptr->setColor(Qt::red); + break; + case 2: + pen_ptr->setColor(Qt::blue); + break; + case 3: + pen_ptr->setColor(Qt::green); + break; + case 4: + pen_ptr->setColor(Qt::magenta); + break; + case 5: + pen_ptr->setColor(Qt::cyan); + break; + case 6: + pen_ptr->setColor(Qt::darkYellow); + break; + case 7: + pen_ptr->setColor(Qt::gray); + break; + case 8: + pen_ptr->setColor(Qt::darkBlue); + break; + case 9: + pen_ptr->setColor(Qt::darkGreen); + break; + case 10: + pen_ptr->setColor(Qt::darkMagenta); + break; + } + /* if(c==0) pen_ptr->setColor(Qt::black); else if(c==1) pen_ptr->setColor(Qt::red); else pen_ptr->setColor(Qt::blue);*/ - setPen(*pen_ptr); + setPen(*pen_ptr); - return last_color=c; + return last_color = c; } -int SlsQtH1D::SetLineWidth(int w){ - pen_ptr->setWidth(w); - setPen(*pen_ptr); - return w; +int SlsQtH1D::SetLineWidth(int w) { + pen_ptr->setWidth(w); + setPen(*pen_ptr); + return w; } -void SlsQtH1D::SetLineStyle(int s){ - if(s==1) pen_ptr->setStyle(Qt::DashLine); - else if(s==2) pen_ptr->setStyle(Qt::DotLine); - else if(s==3) pen_ptr->setStyle(Qt::DashDotLine); - else if(s==4) pen_ptr->setStyle(Qt::DashDotDotLine); - else if(s==5) pen_ptr->setStyle(Qt::CustomDashLine); - else pen_ptr->setStyle(Qt::SolidLine); - setPen(*pen_ptr); +void SlsQtH1D::SetLineStyle(int s) { + if (s == 1) + pen_ptr->setStyle(Qt::DashLine); + else if (s == 2) + pen_ptr->setStyle(Qt::DotLine); + else if (s == 3) + pen_ptr->setStyle(Qt::DashDotLine); + else if (s == 4) + pen_ptr->setStyle(Qt::DashDotDotLine); + else if (s == 5) + pen_ptr->setStyle(Qt::CustomDashLine); + else + pen_ptr->setStyle(Qt::SolidLine); + setPen(*pen_ptr); } +void SlsQtH1D::SetData(int n, double xmin, double xmax, double *data) { + n = SetUpArrays(n); -void SlsQtH1D::SetData(int n, double xmin, double xmax, double *data){ - n = SetUpArrays(n); - - ndata=n; - if(xmin>xmax){ - double t=xmin; - xmin=xmax; - xmax=t; - } + ndata = n; + if (xmin > xmax) { + double t = xmin; + xmin = xmax; + xmax = t; + } - dx = (xmax-xmin)/n; - ymin=ymax= data ? data[0]:0; - firstXgt0=-1; - firstYgt0=-1; + dx = (xmax - xmin) / n; + ymin = ymax = data ? data[0] : 0; + firstXgt0 = -1; + firstYgt0 = -1; - for(int i=0;iy[i]) ymin = y[i]; - if(data&&ymax0&&(firstXgt0<0||firstXgt0>x[i])) firstXgt0=x[i]; - if(y[i]>0&&(firstYgt0<0||firstYgt0>y[i])) firstYgt0=y[i]; - } + for (int i = 0; i < ndata; i++) { + x[i] = i ? x[i - 1] + dx : xmin; + y[i] = data ? data[i] : 0; + if (data && ymin > y[i]) + ymin = y[i]; + if (data && ymax < y[i]) + ymax = y[i]; + if (x[i] > 0 && (firstXgt0 < 0 || firstXgt0 > x[i])) + firstXgt0 = x[i]; + if (y[i] > 0 && (firstYgt0 < 0 || firstYgt0 > y[i])) + firstYgt0 = y[i]; + } - // cout<0&&data_x[0]>data_x[n-1]) ? 1:0; - n = SetUpArrays(n); + int reverse = (data_x && n > 0 && data_x[0] > data_x[n - 1]) ? 1 : 0; + n = SetUpArrays(n); - ndata=n; - dx=-1; //signifies not regular intervals + ndata = n; + dx = -1; //signifies not regular intervals - ymin=ymax= data_y ? data_y[0]:0; + ymin = ymax = data_y ? data_y[0] : 0; - firstXgt0=-1; - firstYgt0=-1; + firstXgt0 = -1; + firstYgt0 = -1; - for(int i=0;iy[b]) ymin = y[b]; - if(data_y&&ymax0&&(firstXgt0<0||firstXgt0>x[b])) firstXgt0=x[b]; - if(y[b]>0&&(firstYgt0<0||firstYgt0>y[b])) firstYgt0=y[b]; - } + for (int i = 0; i < ndata; i++) { + int b = reverse ? n - i - 1 : i; + x[b] = data_x ? data_x[i] : 0; + y[b] = data_y ? data_y[i] : 0; + if (data_y && ymin > y[b]) + ymin = y[b]; + if (data_y && ymax < y[b]) + ymax = y[b]; + if (x[b] > 0 && (firstXgt0 < 0 || firstXgt0 > x[b])) + firstXgt0 = x[b]; + if (y[b] > 0 && (firstYgt0 < 0 || firstYgt0 > y[b])) + firstYgt0 = y[b]; + } -#if QWT_VERSION<0x060000 - setRawData(x,y,ndata); -#else - setRawSamples(x,y,ndata); -#endif + // #if QWT_VERSION<0x060000 + // setRawData(x,y,ndata); + // #else + setRawSamples(x, y, ndata); + // #endif } -int SlsQtH1D::SetUpArrays(int n){ - n = n<1 ? 1 : n; //overflow bin - - if(n+1>n_array){ - n_array = n+1; - if(x) delete x; - if(y) delete y; - x = new double [n_array]; - y = new double [n_array]; - } +int SlsQtH1D::SetUpArrays(int n) { + n = n < 1 ? 1 : n; //overflow bin - return n; + if (n + 1 > n_array) { + n_array = n + 1; + if (x) + delete x; + if (y) + delete y; + x = new double[n_array]; + y = new double[n_array]; + } + + return n; } -double SlsQtH1D::FillBin(int bx, double v) { - bx = CheckIndex(bx); - return SetBinContent(bx,y[bx]+v); +double SlsQtH1D::FillBin(int bx, double v) { + bx = CheckIndex(bx); + return SetBinContent(bx, y[bx] + v); } -double SlsQtH1D::Fill(double x, double v){return FillBin(FindBinIndex(x),v);} +double SlsQtH1D::Fill(double x, double v) { return FillBin(FindBinIndex(x), v); } -double SlsQtH1D::SetBinContent(int bx,double v){ - bx = CheckIndex(bx); - y[bx]=v; - if(bx0&&(firstYgt0<=0||y[bx]ymax) ymax = y[bx]; - } - return y[bx]; +double SlsQtH1D::SetBinContent(int bx, double v) { + bx = CheckIndex(bx); + y[bx] = v; + if (bx < ndata) { + if (y[bx] < ymin) + ymin = y[bx]; + if (y[bx] > 0 && (firstYgt0 <= 0 || y[bx] < firstYgt0)) + firstYgt0 = y[bx]; + if (y[bx] > ymax) + ymax = y[bx]; + } + return y[bx]; } -double SlsQtH1D::SetContent(double x,double v) {return SetBinContent(FindBinIndex(x),v); } +double SlsQtH1D::SetContent(double x, double v) { return SetBinContent(FindBinIndex(x), v); } -int SlsQtH1D::FindBinIndex(double px){ - if(dx>0) CheckIndex(int((px-x[0])/dx)); - - //find closest bin - int b=0; for(;bpx) break; +int SlsQtH1D::FindBinIndex(double px) { + if (dx > 0) + CheckIndex(int((px - x[0]) / dx)); - if(b==0) return 0; - else if(fabs(px-x[b-1]) px) + break; - return b; + if (b == 0) + return 0; + else if (fabs(px - x[b - 1]) < fabs(px - x[b])) + return b - 1; + + return b; } -int SlsQtH1D::CheckIndex(int bx){return (bx<0||bx>ndata) ? ndata : bx;}//ndata is the overflow bin - -SlsQtH1D* SlsQtH1D::Add(double v){ for(int bx=0;bx ndata) ? ndata : bx; } //ndata is the overflow bin +SlsQtH1D *SlsQtH1D::Add(double v) { + for (int bx = 0; bx < ndata; bx++) + FillBin(bx, v); + return this; +} //1d hist list stuff -SlsQtH1DList::SlsQtH1DList(SlsQtH1D* hist){ - the_hist = hist; - the_next = 0; +SlsQtH1DList::SlsQtH1DList(SlsQtH1D *hist) { + the_hist = hist; + the_next = 0; } -SlsQtH1DList::~SlsQtH1DList(){ - if(the_next) delete the_next; +SlsQtH1DList::~SlsQtH1DList() { + if (the_next) + delete the_next; } -SlsQtH1D* SlsQtH1DList::Add(SlsQtH1D* hist){ - // cout<<"Adding: "<the_hist) return hist; //already added - if(!hl->the_next) break; - hl=hl->the_next; - } - if(hl->the_hist) hl->the_next = new SlsQtH1DList(hist); - else hl->the_hist = hist; - - // Print(); - - return hist; -} - -void SlsQtH1DList::Print(){ - // cout<<"Printing List"<the_hist<<" "<the_next<the_next; - if(i>10) break; - } -} - -void SlsQtH1DList::Remove(SlsQtH1D* hist){ - // cout<<"Removing: "<the_hist!=hist) hl = hl->the_next; - else{ //match - if(!hl->the_next) hl->the_hist=0; // first the_hist is zero when there's no next - else{ - SlsQtH1DList* t = hl->the_next; - hl->the_hist = t->the_hist; - hl->the_next = t->the_next; - t->the_next = 0; - delete t; - } + while (hl) { + if (hist == hl->the_hist) + return hist; //already added + if (!hl->the_next) + break; + hl = hl->the_next; } - } - // Print(); + if (hl->the_hist) + hl->the_next = new SlsQtH1DList(hist); + else + hl->the_hist = hist; + + // Print(); + + return hist; } +void SlsQtH1DList::Print() { + SlsQtH1DList *hl = this; + int i = 0; + while (hl) { + std::cout << " " << i++ << ") " << hl << " " << hl->the_hist << " " << hl->the_next << '\n'; + hl = hl->the_next; + if (i > 10) + break; + } +} +void SlsQtH1DList::Remove(SlsQtH1D *hist) { + SlsQtH1DList *hl = this; + while (hl) { //every match will be removed + if (hl->the_hist != hist) + hl = hl->the_next; + else { //match + if (!hl->the_next) + hl->the_hist = 0; // first the_hist is zero when there's no next + else { + SlsQtH1DList *t = hl->the_next; + hl->the_hist = t->the_hist; + hl->the_next = t->the_next; + t->the_next = 0; + delete t; + } + } + } +} //1d plot stuff -SlsQt1DPlot::SlsQt1DPlot(QWidget *parent):QwtPlot(parent){ - // n_histograms_attached=0; - hline=vline=0; - hist_list = new SlsQtH1DList(); +SlsQt1DPlot::SlsQt1DPlot(QWidget *parent) : QwtPlot(parent) { + // n_histograms_attached=0; + hline = vline = 0; + hist_list = new SlsQtH1DList(); - UnknownStuff(); - alignScales(); - SetupZoom(); + UnknownStuff(); + alignScales(); + SetupZoom(); - // Assign a title + // Assign a title #ifndef IAN - insertLegend(new QwtLegend(), QwtPlot::BottomLegend); + insertLegend(new QwtLegend(), QwtPlot::BottomLegend); #else - insertLegend(new QwtLegend(), QwtPlot::RightLegend); + insertLegend(new QwtLegend(), QwtPlot::RightLegend); #endif - axisScaleEngine(QwtPlot::yLeft)->setAttribute(QwtScaleEngine::Floating); - axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating); + axisScaleEngine(QwtPlot::yLeft)->setAttribute(QwtScaleEngine::Floating); + axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating); } -SlsQt1DPlot::~SlsQt1DPlot(){ - delete hist_list; +SlsQt1DPlot::~SlsQt1DPlot() { + delete hist_list; - if(hline) delete hline; - if(vline) delete vline; + if (hline) + delete hline; + if (vline) + delete vline; } -void SlsQt1DPlot::CalculateNResetZoomBase(){ - if(hist_list->Hist()) zoomer->SetZoomBase(hist_list->Hist()); - SlsQtH1DList* hl = hist_list->Next(); - while(hl){ - if(hl->Hist()) zoomer->ExtendZoomBase(hl->Hist()); - hl=hl->Next(); - } +void SlsQt1DPlot::CalculateNResetZoomBase() { + if (hist_list->Hist()) + zoomer->SetZoomBase(hist_list->Hist()); + SlsQtH1DList *hl = hist_list->Next(); + while (hl) { + if (hl->Hist()) + zoomer->ExtendZoomBase(hl->Hist()); + hl = hl->Next(); + } } -void SlsQt1DPlot::NewHistogramAttached(SlsQtH1D* h){ - hist_list->Add(h); - CalculateNResetZoomBase(); - //commented out by dhanya to take off zooming every hist in 1d plots - //if(!hist_list->Next()) UnZoom(); - Update(); +void SlsQt1DPlot::NewHistogramAttached(SlsQtH1D *h) { + hist_list->Add(h); + CalculateNResetZoomBase(); + //commented out by dhanya to take off zooming every hist in 1d plots + //if(!hist_list->Next()) UnZoom(); + Update(); } -void SlsQt1DPlot::HistogramDetached(SlsQtH1D* h){ - hist_list->Remove(h); - CalculateNResetZoomBase(); - Update(); +void SlsQt1DPlot::HistogramDetached(SlsQtH1D *h) { + hist_list->Remove(h); + CalculateNResetZoomBase(); + Update(); } -void SlsQt1DPlot::Update(){ +void SlsQt1DPlot::Update() { replot(); } - -void SlsQt1DPlot::SetTitle(const char* title){ - setTitle(title); + +void SlsQt1DPlot::SetTitle(const char *title) { + setTitle(title); } -void SlsQt1DPlot::SetXTitle(const char* title){ - QwtText t(title); - t.setFont(QFont("Sans Serif",11,QFont::Normal)); - setAxisTitle(QwtPlot::xBottom,t); +void SlsQt1DPlot::SetXTitle(const char *title) { + QwtText t(title); + t.setFont(QFont("Sans Serif", 11, QFont::Normal)); + setAxisTitle(QwtPlot::xBottom, t); } -void SlsQt1DPlot::SetYTitle(const char* title){ - QwtText t(title); - t.setFont(QFont("Sans Serif",11,QFont::Normal)); - setAxisTitle(QwtPlot::yLeft,t); +void SlsQt1DPlot::SetYTitle(const char *title) { + QwtText t(title); + t.setFont(QFont("Sans Serif", 11, QFont::Normal)); + setAxisTitle(QwtPlot::yLeft, t); } -void SlsQt1DPlot::SetLogX(bool yes){ SetLog(QwtPlot::xBottom,yes);} -void SlsQt1DPlot::SetLogY(bool yes){ SetLog(QwtPlot::yLeft,yes);} -void SlsQt1DPlot::SetLog(int axisId, bool yes){ - if(axisId==QwtPlot::xBottom) zoomer->SetLogX(yes); - if(axisId==QwtPlot::yLeft) zoomer->SetLogY(yes); +void SlsQt1DPlot::SetLogX(bool yes) { SetLog(QwtPlot::xBottom, yes); } +void SlsQt1DPlot::SetLogY(bool yes) { SetLog(QwtPlot::yLeft, yes); } +void SlsQt1DPlot::SetLog(int axisId, bool yes) { + if (axisId == QwtPlot::xBottom) + zoomer->SetLogX(yes); + if (axisId == QwtPlot::yLeft) + zoomer->SetLogY(yes); - zoomer->ResetZoomBase(); //needs to be done before setting Engine + zoomer->ResetZoomBase(); //needs to be done before setting Engine - //the old ones are deleted by in the setAxisScaleFunction() function see: 128 of file qwt_plot_axis.cpp - if(yes) setAxisScaleEngine(axisId,new QwtLog10ScaleEngine()); - else setAxisScaleEngine(axisId,new QwtLinearScaleEngine()); + //the old ones are deleted by in the setAxisScaleFunction() function see: 128 of file qwt_plot_axis.cpp + if (yes) + setAxisScaleEngine(axisId, new QwtLog10ScaleEngine()); + else + setAxisScaleEngine(axisId, new QwtLinearScaleEngine()); - axisScaleEngine(QwtPlot::yLeft)->setAttribute(QwtScaleEngine::Floating); - axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating); + axisScaleEngine(QwtPlot::yLeft)->setAttribute(QwtScaleEngine::Floating); + axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating); - Update(); + Update(); } -void SlsQt1DPlot::UnZoom(){ - setAxisScale(QwtPlot::xBottom,zoomer->x(),zoomer->x()+zoomer->w()); - setAxisScale(QwtPlot::yLeft,zoomer->y(),zoomer->y()+zoomer->h()); +void SlsQt1DPlot::UnZoom() { + setAxisScale(QwtPlot::xBottom, zoomer->x(), zoomer->x() + zoomer->w()); + setAxisScale(QwtPlot::yLeft, zoomer->y(), zoomer->y() + zoomer->h()); - zoomer->setZoomBase();//Call replot for the attached plot before initializing the zoomer with its scales. - Update(); + zoomer->setZoomBase(); //Call replot for the attached plot before initializing the zoomer with its scales. + Update(); } -void SlsQt1DPlot::SetZoom(double xmin,double ymin,double x_width,double y_width){ - setAxisScale(QwtPlot::xBottom,xmin,xmin+x_width); - setAxisScale(QwtPlot::yLeft ,ymin,ymin+y_width); - Update(); +void SlsQt1DPlot::SetZoom(double xmin, double ymin, double x_width, double y_width) { + setAxisScale(QwtPlot::xBottom, xmin, xmin + x_width); + setAxisScale(QwtPlot::yLeft, ymin, ymin + y_width); + Update(); } -void SlsQt1DPlot::RemoveHLine(){ - if(hline) hline->detach(); - delete hline; - hline=0; +void SlsQt1DPlot::RemoveHLine() { + if (hline) + hline->detach(); + delete hline; + hline = 0; } -void SlsQt1DPlot::InsertHLine(double y){ - if(!hline){ - hline = new QwtPlotMarker(); - hline->setLabelAlignment(Qt::AlignRight|Qt::AlignTop); - hline->setLineStyle(QwtPlotMarker::HLine); - hline->attach(this); - } - hline->setYValue(y); +void SlsQt1DPlot::InsertHLine(double y) { + if (!hline) { + hline = new QwtPlotMarker(); + hline->setLabelAlignment(Qt::AlignRight | Qt::AlignTop); + hline->setLineStyle(QwtPlotMarker::HLine); + hline->attach(this); + } + hline->setYValue(y); } -void SlsQt1DPlot::RemoveVLine(){ - if(vline) vline->detach(); - delete vline; - vline=0; +void SlsQt1DPlot::RemoveVLine() { + if (vline) + vline->detach(); + delete vline; + vline = 0; } -void SlsQt1DPlot::InsertVLine(double x){ - if(!vline){ - vline = new QwtPlotMarker(); - vline->setLabelAlignment(Qt::AlignRight|Qt::AlignTop); - vline->setLineStyle(QwtPlotMarker::VLine); - vline->attach(this); - } - vline->setXValue(x); +void SlsQt1DPlot::InsertVLine(double x) { + if (!vline) { + vline = new QwtPlotMarker(); + vline->setLabelAlignment(Qt::AlignRight | Qt::AlignTop); + vline->setLineStyle(QwtPlotMarker::VLine); + vline->attach(this); + } + vline->setXValue(x); } +void SlsQt1DPlot::SetupZoom() { + // LeftButton for the zooming + // MidButton for the panning + // RightButton: zoom out by 1 + // Ctrl+RighButton: zoom out to full size - + zoomer = new SlsQt1DZoomer(canvas()); -void SlsQt1DPlot::SetupZoom(){ - // LeftButton for the zooming - // MidButton for the panning - // RightButton: zoom out by 1 - // Ctrl+RighButton: zoom out to full size - - zoomer = new SlsQt1DZoomer(canvas()); - #if QT_VERSION < 0x040000 - zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlButton); + zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlButton); #else - zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlModifier); + zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); #endif - zoomer->setMousePattern(QwtEventPattern::MouseSelect3,Qt::RightButton); + zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); - panner = new QwtPlotPanner((QwtPlotCanvas*)canvas()); + panner = new QwtPlotPanner((QwtPlotCanvas *)canvas()); panner->setAxisEnabled(QwtPlot::yRight, false); panner->setMouseButton(Qt::MidButton); - // Avoid jumping when labels with more/less digits - // appear/disappear when scrolling vertically + // Avoid jumping when labels with more/less digits + // appear/disappear when scrolling vertically - const QFontMetrics fm(axisWidget(QwtPlot::yLeft)->font()); - QwtScaleDraw *sd = axisScaleDraw(QwtPlot::yLeft); - sd->setMinimumExtent( fm.width("100.00") ); + const QFontMetrics fm(axisWidget(QwtPlot::yLeft)->font()); + QwtScaleDraw *sd = axisScaleDraw(QwtPlot::yLeft); + sd->setMinimumExtent(fm.width("100.00")); const QColor c(Qt::darkBlue); zoomer->setRubberBandPen(c); zoomer->setTrackerPen(c); } - // Set a plain canvas frame and align the scales to it -void SlsQt1DPlot::alignScales(){ +void SlsQt1DPlot::alignScales() { // The code below shows how to align the scales to // the canvas frame, but is also a good example demonstrating // why the spreaded API needs polishing. - ((QwtPlotCanvas*)canvas())->setFrameStyle(QFrame::Box | QFrame::Plain ); - ((QwtPlotCanvas*)canvas())->setLineWidth(1); + ((QwtPlotCanvas *)canvas())->setFrameStyle(QFrame::Box | QFrame::Plain); + ((QwtPlotCanvas *)canvas())->setLineWidth(1); - for(int i = 0; i < QwtPlot::axisCnt; i++ ){ - QwtScaleWidget *scaleWidget = (QwtScaleWidget *)axisWidget(i); - if(scaleWidget) scaleWidget->setMargin(0); - QwtScaleDraw *scaleDraw = (QwtScaleDraw *)axisScaleDraw(i); - if(scaleDraw) scaleDraw->enableComponent(QwtAbstractScaleDraw::Backbone, false); + for (int i = 0; i < QwtPlot::axisCnt; i++) { + QwtScaleWidget *scaleWidget = (QwtScaleWidget *)axisWidget(i); + if (scaleWidget) + scaleWidget->setMargin(0); + QwtScaleDraw *scaleDraw = (QwtScaleDraw *)axisScaleDraw(i); + if (scaleDraw) + scaleDraw->enableComponent(QwtAbstractScaleDraw::Backbone, false); } } -void SlsQt1DPlot::UnknownStuff(){ -#if QWT_VERSION<0x060000 - // Disable polygon clipping - //not supported for version 6 - QwtPainter::setDeviceClipping(false); - canvas()->setPaintAttribute(QwtPlotCanvas::PaintCached, false); - canvas()->setPaintAttribute(QwtPlotCanvas::PaintPacked, false); +void SlsQt1DPlot::UnknownStuff() { +#if QWT_VERSION < 0x060000 + // Disable polygon clipping + //not supported for version 6 + QwtPainter::setDeviceClipping(false); + canvas()->setPaintAttribute(QwtPlotCanvas::PaintCached, false); + canvas()->setPaintAttribute(QwtPlotCanvas::PaintPacked, false); #else - // We don't need the cache here - ((QwtPlotCanvas*)canvas())->setPaintAttribute(QwtPlotCanvas::BackingStore, false); + // We don't need the cache here + ((QwtPlotCanvas *)canvas())->setPaintAttribute(QwtPlotCanvas::BackingStore, false); #endif - - #if QT_VERSION >= 0x040000 #ifdef Q_WS_X11 - // Qt::WA_PaintOnScreen is only supported for X11, but leads - // to substantial bugs with Qt 4.2.x/Windows - canvas()->setAttribute(Qt::WA_PaintOnScreen, true); + // Qt::WA_PaintOnScreen is only supported for X11, but leads + // to substantial bugs with Qt 4.2.x/Windows + canvas()->setAttribute(Qt::WA_PaintOnScreen, true); #endif #endif } - - //Added by Dhanya on 19.06.2012 to disable zooming when any of the axes range has been set -void SlsQt1DPlot::DisableZoom(bool disableZoom){ +void SlsQt1DPlot::DisableZoom(bool disableZoom) { #ifdef VERBOSE - if(disableZoom) cout<<"Disabling zoom"<setMousePattern(QwtEventPattern::MouseSelect1,Qt::NoButton); + if (disableZoom) { + if (zoomer) { + zoomer->setMousePattern(QwtEventPattern::MouseSelect1, Qt::NoButton); #if QT_VERSION < 0x040000 - zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::NoButton, Qt::ControlButton); + zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::NoButton, Qt::ControlButton); #else - zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::NoButton, Qt::ControlModifier); + zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::NoButton, Qt::ControlModifier); #endif - zoomer->setMousePattern(QwtEventPattern::MouseSelect3,Qt::NoButton); - } - if(panner) panner->setMouseButton(Qt::NoButton); - }else { - if(zoomer){ - zoomer->setMousePattern(QwtEventPattern::MouseSelect1,Qt::LeftButton); + zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::NoButton); + } + if (panner) + panner->setMouseButton(Qt::NoButton); + } else { + if (zoomer) { + zoomer->setMousePattern(QwtEventPattern::MouseSelect1, Qt::LeftButton); #if QT_VERSION < 0x040000 - zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlButton); + zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlButton); #else - zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlModifier); + zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); #endif - zoomer->setMousePattern(QwtEventPattern::MouseSelect3,Qt::RightButton); - } - if(panner) panner->setMouseButton(Qt::MidButton); - } + zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); + } + if (panner) + panner->setMouseButton(Qt::MidButton); + } } - - - - diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DZoomer.cxx b/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DZoomer.cxx old mode 100644 new mode 100755 index 31386094e..18a03fc56 --- a/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DZoomer.cxx +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQt1DZoomer.cxx @@ -13,7 +13,6 @@ #include "SlsQt1DPlot.h" #include "SlsQt1DZoomer.h" -using namespace std; void SlsQt1DZoomer::ResetZoomBase(){ SetZoomBase(x0,y0,x1-x0,y1-y0); //for going between log and nonlog plots @@ -100,8 +99,6 @@ void SlsQt1DZoomer::ExtendZoomBase(SlsQtH1D* h){ if(h->GetFirstXgtZero()GetFirstXgtZero(); if(h->GetFirstYgtZero()GetFirstYgtZero(); - // cout<<"extend "< +#include #include +#include #include #include -#include #if QT_VERSION >= 0x040000 #include #endif #include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include #include +#include #include "SlsQt2DPlot.h" - -#if QWT_VERSION >= 0x060100 -#define QwtLog10ScaleEngine QwtLogScaleEngine -#endif -using namespace std; - -SlsQt2DPlot::SlsQt2DPlot(QWidget *parent):QwtPlot(parent){ - isLog=0; - - axisScaleEngine(QwtPlot::yLeft)->setAttribute(QwtScaleEngine::Floating); - axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating); - - d_spectrogram = new QwtPlotSpectrogram(); - - hist = new SlsQt2DHist(); - SetupZoom(); - SetupColorMap(); - - -#if QWT_VERSION<0x060000 - d_spectrogram->setData(*hist); -#else - d_spectrogram->setData(hist); +#if QWT_VERSION >= 0x060100 +#define QwtLog10ScaleEngine QwtLogScaleEngine #endif +SlsQt2DPlot::SlsQt2DPlot(QWidget *parent) : QwtPlot(parent) { + isLog = 0; - d_spectrogram->attach(this); + axisScaleEngine(QwtPlot::yLeft)->setAttribute(QwtScaleEngine::Floating); + axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating); - plotLayout()->setAlignCanvasToScales(true); + d_spectrogram = new QwtPlotSpectrogram(); - FillTestPlot(); - Update(); + hist = new SlsQt2DHist(); + SetupZoom(); + SetupColorMap(); +#if QWT_VERSION < 0x060000 + d_spectrogram->setData(*hist); +#else + d_spectrogram->setData(hist); +#endif + + d_spectrogram->attach(this); + + plotLayout()->setAlignCanvasToScales(true); + + FillTestPlot(); + Update(); } +void SlsQt2DPlot::SetupColorMap() { -void SlsQt2DPlot::SetupColorMap(){ - - - - - colorMapLinearScale = myColourMap(0); -#if QWT_VERSION<0x060000 - d_spectrogram->setColorMap(*colorMapLinearScale ); + colorMapLinearScale = myColourMap(0); +#if QWT_VERSION < 0x060000 + d_spectrogram->setColorMap(*colorMapLinearScale); #else - d_spectrogram->setColorMap(colorMapLinearScale ); + d_spectrogram->setColorMap(colorMapLinearScale); #endif - colorMapLogScale = myColourMap(1); -#if QWT_VERSION<0x060000 + colorMapLogScale = myColourMap(1); +#if QWT_VERSION < 0x060000 contourLevelsLinear = new QwtValueList(); - for(double level=0.5;level<10.0;level+=1.0 ) (*contourLevelsLinear) += level; + for (double level = 0.5; level < 10.0; level += 1.0) + (*contourLevelsLinear) += level; d_spectrogram->setContourLevels(*contourLevelsLinear); #else ; - - for(double level=0.5;level<10.0;level+=1.0 ) (contourLevelsLinear) += level; - d_spectrogram->setContourLevels(contourLevelsLinear); + + for (double level = 0.5; level < 10.0; level += 1.0) + (contourLevelsLinear) += level; + d_spectrogram->setContourLevels(contourLevelsLinear); #endif - - // -#if QWT_VERSION<0x060000 + // +#if QWT_VERSION < 0x060000 contourLevelsLog = new QwtValueList(); - for(double level=0.5;level<10.0;level+=1.0 ) (*contourLevelsLog) += (pow(10,2*level/10.0)-1)/99.0 * 10; - + for (double level = 0.5; level < 10.0; level += 1.0) + (*contourLevelsLog) += (pow(10, 2 * level / 10.0) - 1) / 99.0 * 10; + #else ; - - for(double level=0.5;level<10.0;level+=1.0 ) (contourLevelsLog) += (pow(10,2*level/10.0)-1)/99.0 * 10; + + for (double level = 0.5; level < 10.0; level += 1.0) + (contourLevelsLog) += (pow(10, 2 * level / 10.0) - 1) / 99.0 * 10; #endif - - // A color bar on the right axis + // A color bar on the right axis rightAxis = axisWidget(QwtPlot::yRight); - - rightAxis->setTitle("Intensity"); + + rightAxis->setTitle("Intensity"); rightAxis->setColorBarEnabled(true); enableAxis(QwtPlot::yRight); } -void SlsQt2DPlot::FillTestPlot(int mode){ - static int nx = 50; - static int ny = 50; - static double *the_data=0; - if(the_data==0) the_data = new double [nx*ny]; +void SlsQt2DPlot::FillTestPlot(int mode) { + static int nx = 50; + static int ny = 50; + static double *the_data = 0; + if (the_data == 0) + the_data = new double[nx * ny]; - double dmax = sqrt(pow(nx/2.0-0.5,2) + pow(ny/2.0-0.5,2)); - for(int i=0;iSetData(nx,200,822,ny,-0.5,ny-0.5,the_data); + hist->SetData(nx, 200, 822, ny, -0.5, ny - 0.5, the_data); } -void SlsQt2DPlot::SetupZoom(){ - // LeftButton for the zooming - // MidButton for the panning - // RightButton: zoom out by 1 - // Ctrl+RighButton: zoom out to full size +void SlsQt2DPlot::SetupZoom() { + // LeftButton for the zooming + // MidButton for the panning + // RightButton: zoom out by 1 + // Ctrl+RighButton: zoom out to full size - zoomer = new SlsQt2DZoomer(canvas()); + zoomer = new SlsQt2DZoomer(canvas()); zoomer->SetHist(hist); - -#if QT_VERSION < 0x040000 - zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlButton); -#else - zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlModifier); -#endif - zoomer->setMousePattern(QwtEventPattern::MouseSelect3,Qt::RightButton); - panner = new QwtPlotPanner(canvas()); +#if QT_VERSION < 0x040000 + zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlButton); +#else + zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); +#endif + zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); + + panner = new QwtPlotPanner(canvas()); panner->setAxisEnabled(QwtPlot::yRight, false); panner->setMouseButton(Qt::MidButton); - // Avoid jumping when labels with more/less digits - // appear/disappear when scrolling vertically + // Avoid jumping when labels with more/less digits + // appear/disappear when scrolling vertically - const QFontMetrics fm(axisWidget(QwtPlot::yLeft)->font()); - QwtScaleDraw *sd = axisScaleDraw(QwtPlot::yLeft); - sd->setMinimumExtent( fm.width("100.00") ); + const QFontMetrics fm(axisWidget(QwtPlot::yLeft)->font()); + QwtScaleDraw *sd = axisScaleDraw(QwtPlot::yLeft); + sd->setMinimumExtent(fm.width("100.00")); const QColor c(Qt::darkBlue); zoomer->setRubberBandPen(c); @@ -164,211 +159,200 @@ void SlsQt2DPlot::SetupZoom(){ //replot(); }*/ -void SlsQt2DPlot::UnZoom(bool replot){ -#if QWT_VERSION<0x060000 - zoomer->setZoomBase(QwtDoubleRect(hist->GetXMin(),hist->GetYMin(),hist->GetXMax()-hist->GetXMin(),hist->GetYMax()-hist->GetYMin())); +void SlsQt2DPlot::UnZoom(bool replot) { +#if QWT_VERSION < 0x060000 + zoomer->setZoomBase(QwtDoubleRect(hist->GetXMin(), hist->GetYMin(), hist->GetXMax() - hist->GetXMin(), hist->GetYMax() - hist->GetYMin())); #else - zoomer->setZoomBase(QRectF(hist->GetXMin(),hist->GetYMin(),hist->GetXMax()-hist->GetXMin(),hist->GetYMax()-hist->GetYMin())); -#endif - zoomer->setZoomBase(replot);//Call replot for the attached plot before initializing the zoomer with its scales. - // zoomer->zoom(0); + zoomer->setZoomBase(QRectF(hist->GetXMin(), hist->GetYMin(), hist->GetXMax() - hist->GetXMin(), hist->GetYMax() - hist->GetYMin())); +#endif + zoomer->setZoomBase(replot); //Call replot for the attached plot before initializing the zoomer with its scales. + // zoomer->zoom(0); } -void SlsQt2DPlot::SetZoom(double xmin,double ymin,double x_width,double y_width){ +void SlsQt2DPlot::SetZoom(double xmin, double ymin, double x_width, double y_width) { -#if QWT_VERSION<0x060000 - zoomer->setZoomBase(QwtDoubleRect(xmin,ymin,x_width,y_width)); +#if QWT_VERSION < 0x060000 + zoomer->setZoomBase(QwtDoubleRect(xmin, ymin, x_width, y_width)); #else - zoomer->setZoomBase(QRectF(xmin,ymin,x_width,y_width)); + zoomer->setZoomBase(QRectF(xmin, ymin, x_width, y_width)); #endif } -void SlsQt2DPlot::SetZMinMax(double zmin,double zmax){ - hist->SetMinMax(zmin,zmax); +void SlsQt2DPlot::SetZMinMax(double zmin, double zmax) { + hist->SetMinMax(zmin, zmax); } +QwtLinearColorMap *SlsQt2DPlot::myColourMap(QVector colourStops) { -QwtLinearColorMap* SlsQt2DPlot::myColourMap(QVector colourStops) { - -int ns=5; - -double r[]={0.00, 0.00, 0.87, 1.00, 0.51}; -double g[]={0.00, 0.81, 1.00, 0.20, 0.00}; - double b[] = { 0.51, 1.00, 0.12, 0.00, 0.00 }; + int ns = 5; - QColor c1,c2,c; - c1.setRgbF(r[0],g[0],b[0],0); - c2.setRgbF(r[ns-1],g[ns-1],b[ns-1]); - QwtLinearColorMap* copyMap = new QwtLinearColorMap(Qt::lightGray, c2); + double r[] = {0.00, 0.00, 0.87, 1.00, 0.51}; + double g[] = {0.00, 0.81, 1.00, 0.20, 0.00}; + double b[] = {0.51, 1.00, 0.12, 0.00, 0.00}; - for (int is=0; isaddColorStop(colourStops.value(is),c ); - } + QColor c1, c2, c; + c1.setRgbF(r[0], g[0], b[0], 0); + c2.setRgbF(r[ns - 1], g[ns - 1], b[ns - 1]); + QwtLinearColorMap *copyMap = new QwtLinearColorMap(Qt::lightGray, c2); - return copyMap; + for (int is = 0; is < ns - 1; is++) { + c.setRgbF(r[is], g[is], b[is]); + copyMap->addColorStop(colourStops.value(is), c); + } - + return copyMap; } -QwtLinearColorMap* SlsQt2DPlot::myColourMap(int log) { - -int ns=5; - - - QVector cs1(0); - QVector lcs1(0); - - - cs1.append(0.); - cs1.append(0.34); - cs1.append(0.61); - cs1.append(0.84); - cs1.append(1.); -if (log) { - for (int is=0; is cs1(0); + QVector lcs1(0); + + cs1.append(0.); + cs1.append(0.34); + cs1.append(0.61); + cs1.append(0.84); + cs1.append(1.); + if (log) { + for (int is = 0; is < ns; is++) { + lcs1.append((pow(10, 2 * cs1.value(is)) - 1) / 99.0); + } + return myColourMap(lcs1); + } + + return myColourMap(cs1); } - -void SlsQt2DPlot::Update(){ -#if QWT_VERSION<0x060000 - rightAxis->setColorMap(d_spectrogram->data().range(),d_spectrogram->colorMap()); +void SlsQt2DPlot::Update() { +#if QWT_VERSION < 0x060000 + rightAxis->setColorMap(d_spectrogram->data().range(), d_spectrogram->colorMap()); #else - if (isLog) - hist->SetMinimumToFirstGreaterThanZero(); + if (isLog) + hist->SetMinimumToFirstGreaterThanZero(); - const QwtInterval zInterval = d_spectrogram->data()->interval( Qt::ZAxis ); - - rightAxis->setColorMap(zInterval,myColourMap(isLog)); + const QwtInterval zInterval = d_spectrogram->data()->interval(Qt::ZAxis); + + rightAxis->setColorMap(zInterval, myColourMap(isLog)); #endif - if(!zoomer->zoomRectIndex()) UnZoom(); - -#if QWT_VERSION<0x060000 + if (!zoomer->zoomRectIndex()) + UnZoom(); +#if QWT_VERSION < 0x060000 - setAxisScale(QwtPlot::yRight,d_spectrogram->data().range().minValue(), - d_spectrogram->data().range().maxValue()); -#else + setAxisScale(QwtPlot::yRight, d_spectrogram->data().range().minValue(), + d_spectrogram->data().range().maxValue()); +#else - - setAxisScale(QwtPlot::yRight,zInterval.minValue(), zInterval.maxValue()); + setAxisScale(QwtPlot::yRight, zInterval.minValue(), zInterval.maxValue()); #ifdef VERYVERBOSE - cout << "axis scale set" << endl; + std::cout << "axis scale set\n"; #endif - plotLayout()->setAlignCanvasToScales(true); + plotLayout()->setAlignCanvasToScales(true); #ifdef VERYVERBOSE - cout << "layout" << endl; + std::cout << "layout\n"; #endif #endif #ifdef VERYVERBOSE - cout << "going to replot" << endl; + std::cout << "going to replot\n"; #endif - replot(); + replot(); #ifdef VERYVERBOSE - cout << "done" << endl; + std::cout << "done\n"; #endif } - - -void SlsQt2DPlot::showContour(bool on){ - d_spectrogram->setDisplayMode(QwtPlotSpectrogram::ContourMode,on); - Update(); +void SlsQt2DPlot::showContour(bool on) { + d_spectrogram->setDisplayMode(QwtPlotSpectrogram::ContourMode, on); + Update(); } -void SlsQt2DPlot::showSpectrogram(bool on){ - // static int io=0; - // FillTestPlot(io++); - d_spectrogram->setDisplayMode(QwtPlotSpectrogram::ImageMode, on); - d_spectrogram->setDefaultContourPen(on ? QPen() : QPen(Qt::NoPen)); - Update(); +void SlsQt2DPlot::showSpectrogram(bool on) { + // static int io=0; + // FillTestPlot(io++); + d_spectrogram->setDisplayMode(QwtPlotSpectrogram::ImageMode, on); + d_spectrogram->setDefaultContourPen(on ? QPen() : QPen(Qt::NoPen)); + Update(); } -void SlsQt2DPlot::InterpolatedPlot(bool on){ - hist->Interpolate(on); - Update(); +void SlsQt2DPlot::InterpolatedPlot(bool on) { + hist->Interpolate(on); + Update(); } - -void SlsQt2DPlot::LogZ(bool on){ - if(on){ -isLog=1; - //if(hist->GetMinimum()<=0) hist->SetMinimumToFirstGreaterThanZero(); -#if QWT_VERSION<0x060000 - d_spectrogram->setColorMap(*colorMapLogScale); +void SlsQt2DPlot::LogZ(bool on) { + if (on) { + isLog = 1; + //if(hist->GetMinimum()<=0) hist->SetMinimumToFirstGreaterThanZero(); +#if QWT_VERSION < 0x060000 + d_spectrogram->setColorMap(*colorMapLogScale); #else - d_spectrogram->setColorMap(myColourMap(isLog)); + d_spectrogram->setColorMap(myColourMap(isLog)); #endif - setAxisScaleEngine(QwtPlot::yRight,new QwtLog10ScaleEngine); -#if QWT_VERSION<0x060000 - d_spectrogram->setContourLevels(*contourLevelsLog); + setAxisScaleEngine(QwtPlot::yRight, new QwtLog10ScaleEngine); +#if QWT_VERSION < 0x060000 + d_spectrogram->setContourLevels(*contourLevelsLog); #else - d_spectrogram->setContourLevels(contourLevelsLog); + d_spectrogram->setContourLevels(contourLevelsLog); #endif - }else{ -isLog=0; + } else { + isLog = 0; -#if QWT_VERSION<0x060000 - d_spectrogram->setColorMap(*colorMapLinearScale); +#if QWT_VERSION < 0x060000 + d_spectrogram->setColorMap(*colorMapLinearScale); #else - d_spectrogram->setColorMap(myColourMap(isLog)); -#endif - - + d_spectrogram->setColorMap(myColourMap(isLog)); +#endif - setAxisScaleEngine(QwtPlot::yRight,new QwtLinearScaleEngine); - -#if QWT_VERSION<0x060000 - d_spectrogram->setContourLevels(*contourLevelsLinear); + setAxisScaleEngine(QwtPlot::yRight, new QwtLinearScaleEngine); + +#if QWT_VERSION < 0x060000 + d_spectrogram->setContourLevels(*contourLevelsLinear); #else - d_spectrogram->setContourLevels(contourLevelsLinear); -#endif - - } - Update(); - + d_spectrogram->setContourLevels(contourLevelsLinear); +#endif + } + Update(); } //Added by Dhanya on 19.06.2012 to disable zooming when any of the axes range has been set -void SlsQt2DPlot::DisableZoom(bool disableZoom){ +void SlsQt2DPlot::DisableZoom(bool disableZoom) { #ifdef VERBOSE - if(disableZoom) cout<<"Disabling zoom"<setMousePattern(QwtEventPattern::MouseSelect1,Qt::NoButton); + if (disableZoom) { + if (zoomer) { + zoomer->setMousePattern(QwtEventPattern::MouseSelect1, Qt::NoButton); #if QT_VERSION < 0x040000 - zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::NoButton, Qt::ControlButton); + zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::NoButton, Qt::ControlButton); #else - zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::NoButton, Qt::ControlModifier); + zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::NoButton, Qt::ControlModifier); #endif - zoomer->setMousePattern(QwtEventPattern::MouseSelect3,Qt::NoButton); - } - if(panner) panner->setMouseButton(Qt::NoButton); - }else { - if(zoomer){ - zoomer->setMousePattern(QwtEventPattern::MouseSelect1,Qt::LeftButton); + zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::NoButton); + } + if (panner) + panner->setMouseButton(Qt::NoButton); + } else { + if (zoomer) { + zoomer->setMousePattern(QwtEventPattern::MouseSelect1, Qt::LeftButton); #if QT_VERSION < 0x040000 - zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlButton); + zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlButton); #else - zoomer->setMousePattern(QwtEventPattern::MouseSelect2,Qt::RightButton, Qt::ControlModifier); + zoomer->setMousePattern(QwtEventPattern::MouseSelect2, Qt::RightButton, Qt::ControlModifier); #endif - zoomer->setMousePattern(QwtEventPattern::MouseSelect3,Qt::RightButton); - } - if(panner) panner->setMouseButton(Qt::MidButton); - } + zoomer->setMousePattern(QwtEventPattern::MouseSelect3, Qt::RightButton); + } + if (panner) + panner->setMouseButton(Qt::MidButton); + } } - /* void SlsQt2DPlot::printPlot(){ QPrinter printer; diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlotLayout.cxx b/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlotLayout.cxx old mode 100644 new mode 100755 index 220bf0f2c..805dac109 --- a/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlotLayout.cxx +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQt2DPlotLayout.cxx @@ -14,7 +14,7 @@ #include "SlsQt2DPlotLayout.h" -using namespace std; + SlsQt2DPlotLayout::SlsQt2DPlotLayout(QWidget *parent):QGroupBox(parent){ the_layout=0; diff --git a/slsDetectorGui/slsDetectorPlotting/src/SlsQtNumberEntry.cxx b/slsDetectorGui/slsDetectorPlotting/src/SlsQtNumberEntry.cxx old mode 100644 new mode 100755 index 7d061bbbf..ac847ae5f --- a/slsDetectorGui/slsDetectorPlotting/src/SlsQtNumberEntry.cxx +++ b/slsDetectorGui/slsDetectorPlotting/src/SlsQtNumberEntry.cxx @@ -27,7 +27,6 @@ #include "SlsQtNumberEntry.h" -using namespace std; SlsQtNumberEntry::SlsQtNumberEntry(QWidget *parent, int with_checkbox, char *start_string, int num_type, char* middle_string, int num2_type, int n_units, char** units, double* unit_factors,char* end_string):QWidget(parent){ SetupNumberEntry(with_checkbox,start_string,num_type,middle_string,num2_type,n_units,units,unit_factors,end_string); diff --git a/slsDetectorGui/src/qActionsWidget.cpp b/slsDetectorGui/src/qActionsWidget.cpp deleted file mode 100644 index f86fd795f..000000000 --- a/slsDetectorGui/src/qActionsWidget.cpp +++ /dev/null @@ -1,219 +0,0 @@ -/* - * qActionsWidget.cpp - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ -// Project Class Headers -#include "slsDetector.h" -#include "multiSlsDetector.h" -// Qt Project Class Headers -#include "qActionsWidget.h" -// Qt Include Headers -#include -// C++ Include Headers -#include -using namespace std; - -//------------------------------------------------------------------------------------------------------------------------------------------------- -int qActionsWidget::NUM_ACTION_WIDGETS(0); -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -qActionsWidget::qActionsWidget(QWidget *parent,multiSlsDetector*& detector): - QWidget(parent),myDet(detector){ - setupUi(this); - SetupWidgetWindow(); - Initialization(); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -qActionsWidget::~qActionsWidget(){ - delete myDet; -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qActionsWidget::SetupWidgetWindow(){ - id = NUM_ACTION_WIDGETS; - NUM_ACTION_WIDGETS++; - - setFixedHeight(25); - -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qActionsWidget::Initialization(){ - //mode - connect(comboScript, SIGNAL(currentIndexChanged(int)), this,SLOT(SetMode(int))); - //file - connect(dispScript, SIGNAL(editingFinished()), this, SLOT(SetScriptFile())); - connect(btnBrowse, SIGNAL(clicked()), this, SLOT(BrowsePath())); - //parameter - connect(dispParameter, SIGNAL(editingFinished()), this, SLOT(SetParameter())); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qActionsWidget::SetMode(int mode){ -#ifdef VERBOSE - cout << "Setting\taction:" << id << "\tmode:" << mode << endl; -#endif - //enabling/disabling - dispScript->setEnabled(mode); - btnBrowse->setEnabled(mode); - lblParameter->setEnabled(mode); - dispParameter->setEnabled(mode); - - QString fName = dispScript->text(); - //set the mode - if(mode) myDet->setActionScript(id,fName.toAscii().constData()); - else myDet->setActionScript(id,""); - //mode is not set when fname is blank - - if(!fName.isEmpty()){ - //check if mode didnt get set - if(mode!=myDet->getActionMode(id)){ - qDefs::Message(qDefs::WARNING,"The mode could not be changed.","qActionsWidget::SetMode"); - comboScript->setCurrentIndex(myDet->getActionMode(id)); - }//if mode got set and its custom script - else if(mode){ - //when the file name did not get set correctly - if(fName.compare(QString(myDet->getActionScript(id).c_str()))){ - qDefs::Message(qDefs::WARNING,"The file path could not be set.","qActionsWidget::SetMode"); - dispScript->setText(QString(myDet->getActionScript(id).c_str())); - SetScriptFile(); - } - } - } - qDefs::checkErrorMessage(myDet,"qActionsWidget::SetMode"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - -void qActionsWidget::BrowsePath(){ -#ifdef VERBOSE - cout << "Browsing Script File Path" << endl; -#endif - QString fName = dispScript->text(); - QString dir = fName.section('/',0,-2,QString::SectionIncludeLeadingSep); - if(dir.isEmpty()) dir = "/home"; - //dialog - fName = QFileDialog::getOpenFileName(this, - tr("Load Script File"),dir, - tr("Script Files(*.awk);;All Files(*)")); - //if empty, set the file name and it calls setscriptfile, else ignore - if (!fName.isEmpty()){ - dispScript->setText(fName); - SetScriptFile(); - } -} - -//------------------------------------------------------------------------------------------------------------------------------------------------- - -void qActionsWidget::SetScriptFile(){ - QString fName = dispScript->text(); -#ifdef VERBOSE - cout << "Setting\taction:" << id << "\tscript:" << fName.toAscii().constData() << endl; -#endif - bool set = false; - struct stat st_buf; - - //blank - if(fName.isEmpty()) - set = true; - else if(!fName.compare("none")) - set = true; - //not blank - else{ - //path doesnt exist - if(stat(fName.toAscii().constData(),&st_buf)){ - qDefs::Message(qDefs::WARNING,"The script file entered does not exist","qActionsWidget::SetScriptFile"); - dispScript->setText(QString(myDet->getActionScript(id).c_str())); - } - //if its not a file - else if (!S_ISREG (st_buf.st_mode)) { - qDefs::Message(qDefs::WARNING,"The script file path entered is not a file","qActionsWidget::SetScriptFile"); - dispScript->setText(QString(myDet->getActionScript(id).c_str())); - } - else - set=true; - } - - - //if blank or valid file - if(set){ - //scan and positions wouldnt get here - myDet->setActionScript(id,fName.toAscii().constData()); - if(fName.compare(QString(myDet->getActionScript(id).c_str()))){ - //did not get set, write what is was before - if(!fName.isEmpty()) - qDefs::Message(qDefs::WARNING,"The script file could not be set. Reverting to previous file.","qActionsWidget::SetScriptFile"); - dispScript->setText(QString(myDet->getActionScript(id).c_str())); - } - } - - //dont display if theres a none - if(!dispScript->text().compare("none")) dispScript->setText(""); - - qDefs::checkErrorMessage(myDet,"qActionsWidget::SetScriptFile"); - -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qActionsWidget::SetParameter(){ - QString parameter = dispParameter->text(); -#ifdef VERBOSE - cout << "Setting\taction:" << id << "\tparameter:" << parameter.toAscii().constData() << endl; -#endif - myDet->setActionParameter(id,parameter.toAscii().constData()); - //dont display if theres a none - if(!dispParameter->text().compare("none")) dispParameter->setText(""); - - qDefs::checkErrorMessage(myDet,"qActionsWidget::SetParameter"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qActionsWidget::Refresh(){ - int mode = (myDet->getActionMode(id)>0?1:0); - string script = myDet->getActionScript(id); - string parameter = myDet->getActionParameter(id); - - - //settings values and checking for none - if(QString(script.c_str()).compare("none")) - dispScript->setText(QString(script.c_str())); - if(mode)SetScriptFile(); - dispParameter->setText(QString(parameter.c_str())); - SetParameter(); - //set mode which also checks everything - comboScript->setCurrentIndex(mode); -#ifdef VERBOSE - cout << "Updated\taction:" << id << "\t" - "mode:"< #include #include -#include -#include "qwt_symbol.h" -/** C++ Include Headers */ +qCloneWidget::qCloneWidget(QWidget *parent, int id, QString title, QString xTitle, QString yTitle, QString zTitle, + int numDim, std::string FilePath, bool displayStats, QString min, QString max, QString sum) : QMainWindow(parent), id(id), filePath(FilePath), cloneplot1D(0), cloneplot2D(0) { + // Window title + char winTitle[300], currTime[50]; + strcpy(currTime, GetCurrentTimeStamp()); + sprintf(winTitle, "Snapshot:%d - %s", id, currTime); + setWindowTitle(QString(winTitle)); + marker = new QwtSymbol(); + nomarker = new QwtSymbol(); + marker->setStyle(QwtSymbol::Cross); + marker->setSize(5, 5); -//------------------------------------------------------------------------------------------------------------------------------------------------- - -qCloneWidget::qCloneWidget(QWidget *parent,int id,QString title,QString xTitle, QString yTitle, QString zTitle, - int numDim,string FilePath,bool displayStats, QString min, QString max, QString sum): - QMainWindow(parent),id(id),filePath(FilePath),cloneplot1D(0),cloneplot2D(0) - { - // Window title - char winTitle[300],currTime[50]; - strcpy(currTime,GetCurrentTimeStamp()); - sprintf(winTitle,"Snapshot:%d - %s",id,currTime); - setWindowTitle(QString(winTitle)); - - marker = new QwtSymbol(); - nomarker = new QwtSymbol(); - marker->setStyle(QwtSymbol::Cross); - marker->setSize(5,5); - - // Set up widget - SetupWidgetWindow(title,xTitle, yTitle, zTitle, numDim); - DisplayStats(displayStats,min,max,sum); + // Set up widget + SetupWidgetWindow(title, xTitle, yTitle, zTitle, numDim); + DisplayStats(displayStats, min, max, sum); } -//------------------------------------------------------------------------------------------------------------------------------------------------- -qCloneWidget::~qCloneWidget(){ - delete cloneplot1D; - delete cloneplot2D; - delete cloneBox; +qCloneWidget::~qCloneWidget() { + delete cloneplot1D; + delete cloneplot2D; + delete cloneBox; + cloneplot1D_hists.clear(); } -//------------------------------------------------------------------------------------------------------------------------------------------------- -void qCloneWidget::SetupWidgetWindow(QString title, QString xTitle, QString yTitle, QString zTitle, int numDim){ - - menubar = new QMenuBar(this); - actionSave = new QAction("&Save",this); - menubar->addAction(actionSave); - setMenuBar(menubar); - - - //Main Window Layout - QWidget *centralWidget = new QWidget(this); - mainLayout = new QGridLayout(centralWidget); - centralWidget->setLayout(mainLayout); - - //plot group box - cloneBox = new QGroupBox(this); - gridClone = new QGridLayout(cloneBox); - cloneBox->setLayout(gridClone); - cloneBox->setContentsMargins(0,0,0,0); - cloneBox->setAlignment(Qt::AlignHCenter); - cloneBox->setFont(QFont("Sans Serif",11,QFont::Normal)); - cloneBox->setTitle(title); - // According to dimensions, create appropriate 1D or 2Dplot - if(numDim==1){ - cloneplot1D = new SlsQt1DPlot(cloneBox); - - cloneplot1D->setFont(QFont("Sans Serif",9,QFont::Normal)); - cloneplot1D->SetXTitle(xTitle.toAscii().constData()); - cloneplot1D->SetYTitle(yTitle.toAscii().constData()); - - - cloneBox->setFlat(false); - cloneBox->setContentsMargins(0,30,0,0); - gridClone->addWidget(cloneplot1D,0,0); - - lblHistTitle = new QLabel(""); - mainLayout->addWidget(lblHistTitle,0,0); - - }else{ - cloneplot2D = new SlsQt2DPlotLayout(cloneBox); - cloneplot2D->setFont(QFont("Sans Serif",9,QFont::Normal)); - cloneplot2D->SetXTitle(xTitle); - cloneplot2D->SetYTitle(yTitle); - cloneplot2D->SetZTitle(zTitle); - cloneplot2D->setAlignment(Qt::AlignLeft); - - cloneBox->setFlat(true); - cloneBox->setContentsMargins(0,20,0,0); - gridClone->addWidget(cloneplot2D,0,0); - } - - // main window widgets - mainLayout->addWidget(cloneBox,1,0); - setCentralWidget(centralWidget); - - // Save - connect(actionSave,SIGNAL(triggered()),this,SLOT(SavePlot())); - - setMinimumHeight(300); - resize(500,350); +SlsQt1DPlot* qCloneWidget::Get1dPlot() { + return cloneplot1D; } -//------------------------------------------------------------------------------------------------------------------------------------------------- -void qCloneWidget::SetCloneHists(int nHists,int histNBins,double* histXAxis,double* histYAxis[],string histTitle[],bool lines,bool markers){ - //for each plot, create hists - for(int hist_num=0;hist_numcloneplot1D_hists.size()){ - cloneplot1D_hists.append(k=new SlsQtH1D("1d plot",histNBins,histXAxis,histYAxis[hist_num])); - k->SetLineColor(0); - }else{ - k=cloneplot1D_hists.at(hist_num); - k->SetData(histNBins,histXAxis,histYAxis[hist_num]); - } +void qCloneWidget::SetupWidgetWindow(QString title, QString xTitle, QString yTitle, QString zTitle, int numDim) { + + QMenuBar* menubar = new QMenuBar(this); + QAction* actionSave = new QAction("&Save", this); + menubar->addAction(actionSave); + setMenuBar(menubar); + + //Main Window Layout + QWidget *centralWidget = new QWidget(this); + mainLayout = new QGridLayout(centralWidget); + centralWidget->setLayout(mainLayout); + + //plot group box + cloneBox = new QGroupBox(this); + QGridLayout* gridClone = new QGridLayout(cloneBox); + cloneBox->setLayout(gridClone); + cloneBox->setContentsMargins(0, 0, 0, 0); + cloneBox->setAlignment(Qt::AlignHCenter); + cloneBox->setFont(QFont("Sans Serif", 11, QFont::Normal)); + cloneBox->setTitle(title); + // According to dimensions, create appropriate 1D or 2Dplot + if (numDim == 1) { + cloneplot1D = new SlsQt1DPlot(cloneBox); + + cloneplot1D->setFont(QFont("Sans Serif", 9, QFont::Normal)); + cloneplot1D->SetXTitle(xTitle.toAscii().constData()); + cloneplot1D->SetYTitle(yTitle.toAscii().constData()); + + cloneBox->setFlat(false); + cloneBox->setContentsMargins(0, 30, 0, 0); + gridClone->addWidget(cloneplot1D, 0, 0); + + lblHistTitle = new QLabel(""); + mainLayout->addWidget(lblHistTitle, 0, 0); + + } else { + cloneplot2D = new SlsQt2DPlotLayout(cloneBox); + cloneplot2D->setFont(QFont("Sans Serif", 9, QFont::Normal)); + cloneplot2D->SetXTitle(xTitle); + cloneplot2D->SetYTitle(yTitle); + cloneplot2D->SetZTitle(zTitle); + cloneplot2D->setAlignment(Qt::AlignLeft); + + cloneBox->setFlat(true); + cloneBox->setContentsMargins(0, 20, 0, 0); + gridClone->addWidget(cloneplot2D, 0, 0); + } + + // main window widgets + mainLayout->addWidget(cloneBox, 1, 0); + setCentralWidget(centralWidget); + + // Save + connect(actionSave, SIGNAL(triggered()), this, SLOT(SavePlot())); + + setMinimumHeight(300); + resize(500, 350); +} - //style of plot - if(lines) k->setStyle(QwtPlotCurve::Lines); - else k->setStyle(QwtPlotCurve::Dots); -#if QWT_VERSION<0x060000 - if(markers) k->setSymbol(*marker); - else k->setSymbol(*nomarker); +void qCloneWidget::SetCloneHists(int nHists, int histNBins, double *histXAxis, double *histYAxis[], std::string histTitle[], bool lines, bool markers) { + //for each plot, create hists + for (int hist_num = 0; hist_num < nHists; ++hist_num) { + SlsQtH1D *k; + if (hist_num + 1 > cloneplot1D_hists.size()) { + cloneplot1D_hists.append(k = new SlsQtH1D("1d plot", histNBins, histXAxis, histYAxis[hist_num])); + k->SetLineColor(0); + } else { + k = cloneplot1D_hists.at(hist_num); + k->SetData(histNBins, histXAxis, histYAxis[hist_num]); + } + + //style of plot + if (lines) + k->setStyle(QwtPlotCurve::Lines); + else + k->setStyle(QwtPlotCurve::Dots); +#if QWT_VERSION < 0x060000 + if (markers) + k->setSymbol(*marker); + else + k->setSymbol(*nomarker); #else - if(markers) k->setSymbol(marker); - else k->setSymbol(nomarker); + if (markers) + k->setSymbol(marker); + else + k->setSymbol(nomarker); #endif - //set title and attach plot - lblHistTitle->setText(QString(histTitle[0].c_str())); + //set title and attach plot + lblHistTitle->setText(QString(histTitle[0].c_str())); - k->Attach(cloneplot1D); - } - -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qCloneWidget::SetCloneHists(int nHists,int histNBins,double* histXAxis,double* histYAxis,string histTitle[],bool lines,bool markers){ - // for each plot create hists - for(int hist_num=0;hist_numcloneplot1D_hists.size()){ - cloneplot1D_hists.append(k=new SlsQtH1D("1d plot",histNBins,histXAxis,histYAxis)); - k->SetLineColor(hist_num+1); - }else{ - k=cloneplot1D_hists.at(hist_num); - k->SetData(histNBins,histXAxis,histYAxis); - } - //style of plot - if(lines) k->setStyle(QwtPlotCurve::Lines); - else k->setStyle(QwtPlotCurve::Dots); - if(markers) { - QwtSymbol *marker = new QwtSymbol(); - marker->setStyle(QwtSymbol::Cross); - marker->setSize(5,5); -#if QWT_VERSION<0x060000 - k->setSymbol(*marker); -#else - k->setSymbol(marker); -#endif - }else { - QwtSymbol *noMarker = new QwtSymbol(); -#if QWT_VERSION<0x060000 - k->setSymbol(*noMarker); -#else - k->setSymbol(noMarker); -#endif - } - //set title and attach plot - lblHistTitle->setText(QString(histTitle[0].c_str())); - k->Attach(cloneplot1D); - } -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qCloneWidget::SetCloneHists2D(int nbinsx,double xmin,double xmax,int nbinsy, double ymin, double ymax, double *d){ - cloneplot2D->GetPlot()->SetData(nbinsx,xmin,xmax,nbinsy,ymin,ymax,d); - cloneplot2D->UpdateNKeepSetRangeIfSet(); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - - -void qCloneWidget::SetRange(bool IsXYRange[],double XYRangeValues[]){ - double XYCloneRangeValues[4]; - - if(!IsXYRange[qDefs::XMINIMUM]){ - if(cloneplot1D) XYCloneRangeValues[qDefs::XMINIMUM]= cloneplot1D->GetXMinimum(); - else XYCloneRangeValues[qDefs::XMINIMUM]= cloneplot2D->GetPlot()->GetXMinimum(); - }else XYCloneRangeValues[qDefs::XMINIMUM]= XYRangeValues[qDefs::XMINIMUM]; - - if(!IsXYRange[qDefs::XMAXIMUM]){ - if(cloneplot1D) XYCloneRangeValues[qDefs::XMAXIMUM]= cloneplot1D->GetXMaximum(); - else XYCloneRangeValues[qDefs::XMINIMUM]= cloneplot2D->GetPlot()->GetXMaximum(); - }else XYCloneRangeValues[qDefs::XMAXIMUM]= XYRangeValues[qDefs::XMAXIMUM]; - - if(!IsXYRange[qDefs::YMINIMUM]){ - if(cloneplot1D) XYCloneRangeValues[qDefs::YMINIMUM]= cloneplot1D->GetYMinimum(); - else XYCloneRangeValues[qDefs::XMINIMUM]= cloneplot2D->GetPlot()->GetYMinimum(); - }else XYCloneRangeValues[qDefs::YMINIMUM]= XYRangeValues[qDefs::YMINIMUM]; - - if(!IsXYRange[qDefs::YMAXIMUM]){ - if(cloneplot1D) XYCloneRangeValues[qDefs::YMAXIMUM]= cloneplot1D->GetYMaximum(); - else XYCloneRangeValues[qDefs::XMINIMUM]= cloneplot2D->GetPlot()->GetYMaximum(); - }else XYCloneRangeValues[qDefs::YMAXIMUM]= XYRangeValues[qDefs::YMAXIMUM]; - - if(cloneplot1D){ - cloneplot1D->SetXMinMax(XYCloneRangeValues[qDefs::XMINIMUM],XYCloneRangeValues[qDefs::XMAXIMUM]); - cloneplot1D->SetYMinMax(XYCloneRangeValues[qDefs::YMINIMUM],XYCloneRangeValues[qDefs::YMAXIMUM]); - }else{ - cloneplot2D->GetPlot()->SetXMinMax(XYRangeValues[qDefs::XMINIMUM],XYRangeValues[qDefs::XMAXIMUM]); - cloneplot2D->GetPlot()->SetYMinMax(XYRangeValues[qDefs::YMINIMUM],XYRangeValues[qDefs::YMAXIMUM]); - cloneplot2D->GetPlot()->Update(); - } -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -char* qCloneWidget::GetCurrentTimeStamp(){ - char output[30]; - char *result; - - //using sys cmds to get output or str - FILE* sysFile = popen("date", "r"); - fgets(output, sizeof(output), sysFile); - pclose(sysFile); - - result = output + 0; - return result; -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - -void qCloneWidget::SavePlot(){ - char cID[10]; - sprintf(cID,"%d",id); - //title - QString fName = QString(filePath.c_str()); - if(cloneBox->title().contains('.')){ - fName.append(QString('/')+cloneBox->title()); - fName.replace(".dat",".png"); - fName.replace(".raw",".png"); - }else fName.append(QString("/Snapshot_unknown_title.png")); - //save - QImage img(cloneBox->size().width(),cloneBox->size().height(),QImage::Format_RGB32); - QPainter painter(&img); - cloneBox->render(&painter); - - fName = QFileDialog::getSaveFileName(this,tr("Save Snapshot "),fName,tr("PNG Files (*.png);;XPM Files(*.xpm);;JPEG Files(*.jpg)"),0,QFileDialog::ShowDirsOnly); - if (!fName.isEmpty()) { - if((img.save(fName))) - qDefs::Message(qDefs::INFORMATION,"The SnapShot has been successfully saved","qCloneWidget::SavePlot"); - else - qDefs::Message(qDefs::WARNING,"Attempt to save snapshot failed.\n" - "Formats: .png, .jpg, .xpm.","qCloneWidget::SavePlot"); + k->Attach(cloneplot1D); } } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qCloneWidget::SavePlotAutomatic(){ - char cID[10]; - sprintf(cID,"%d",id); - //title - QString fName = QString(filePath.c_str()); - if(cloneBox->title().contains('.')){ - fName.append(QString('/')+cloneBox->title()); - fName.replace(".dat",".png"); - fName.replace(".raw",".png"); - }else fName.append(QString("/Snapshot_unknown_title.png")); - cout<<"fname:"<size().width(),cloneBox->size().height(),QImage::Format_RGB32); - QPainter painter(&img); - cloneBox->render(&painter); - if(img.save(fName)) - return 0; - else return -1; - +void qCloneWidget::SetCloneHists(int nHists, int histNBins, double *histXAxis, double *histYAxis, std::string histTitle[], bool lines, bool markers) { + // for each plot create hists + for (int hist_num = 0; hist_num < nHists; ++hist_num) { + SlsQtH1D *k; + if (hist_num + 1 > cloneplot1D_hists.size()) { + cloneplot1D_hists.append(k = new SlsQtH1D("1d plot", histNBins, histXAxis, histYAxis)); + k->SetLineColor(hist_num + 1); + } else { + k = cloneplot1D_hists.at(hist_num); + k->SetData(histNBins, histXAxis, histYAxis); + } + //style of plot + if (lines) + k->setStyle(QwtPlotCurve::Lines); + else + k->setStyle(QwtPlotCurve::Dots); + if (markers) { + QwtSymbol *marker = new QwtSymbol(); + marker->setStyle(QwtSymbol::Cross); + marker->setSize(5, 5); +#if QWT_VERSION < 0x060000 + k->setSymbol(*marker); +#else + k->setSymbol(marker); +#endif + } else { + QwtSymbol *noMarker = new QwtSymbol(); +#if QWT_VERSION < 0x060000 + k->setSymbol(*noMarker); +#else + k->setSymbol(noMarker); +#endif + } + //set title and attach plot + lblHistTitle->setText(QString(histTitle[0].c_str())); + k->Attach(cloneplot1D); + } } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qCloneWidget::closeEvent(QCloseEvent* event){ - emit CloneClosedSignal(id); - event->accept(); +void qCloneWidget::SetCloneHists2D(int nbinsx, double xmin, double xmax, int nbinsy, double ymin, double ymax, double *d) { + cloneplot2D->GetPlot()->SetData(nbinsx, xmin, xmax, nbinsy, ymin, ymax, d); + cloneplot2D->UpdateNKeepSetRangeIfSet(); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qCloneWidget::SetRange(bool IsXYRange[], double XYRangeValues[]) { + double XYCloneRangeValues[4]; + if (!IsXYRange[qDefs::XMINIMUM]) { + if (cloneplot1D) + XYCloneRangeValues[qDefs::XMINIMUM] = cloneplot1D->GetXMinimum(); + else + XYCloneRangeValues[qDefs::XMINIMUM] = cloneplot2D->GetPlot()->GetXMinimum(); + } else + XYCloneRangeValues[qDefs::XMINIMUM] = XYRangeValues[qDefs::XMINIMUM]; -void qCloneWidget::DisplayStats(bool enable, QString min, QString max, QString sum){ - if(enable){ - QWidget *widgetStatistics = new QWidget(this); - widgetStatistics->setFixedHeight(15); - QHBoxLayout *hl1 = new QHBoxLayout; - hl1->setSpacing(0); - hl1->setContentsMargins(0, 0, 0, 0); - QLabel *lblMin = new QLabel("Min: "); - lblMin->setFixedWidth(40); - lblMin->setAlignment(Qt::AlignRight); - QLabel *lblMax = new QLabel("Max: "); - lblMax->setFixedWidth(40); - lblMax->setAlignment(Qt::AlignRight); - QLabel *lblSum = new QLabel("Sum: "); - lblSum->setFixedWidth(40); - lblSum->setAlignment(Qt::AlignRight); - QLabel *lblMinDisp = new QLabel(min); - lblMinDisp->setAlignment(Qt::AlignLeft); - QLabel *lblMaxDisp = new QLabel(max); - lblMaxDisp->setAlignment(Qt::AlignLeft); - QLabel *lblSumDisp = new QLabel(sum); - lblSumDisp->setAlignment(Qt::AlignLeft); - hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - hl1->addWidget(lblMin); - hl1->addWidget(lblMinDisp); - hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Expanding,QSizePolicy::Fixed)); - hl1->addWidget(lblMax); - hl1->addWidget(lblMaxDisp); - hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Expanding,QSizePolicy::Fixed)); - hl1->addWidget(lblSum); - hl1->addWidget(lblSumDisp); - hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - widgetStatistics->setLayout(hl1); - mainLayout->addWidget(widgetStatistics,2,0); - widgetStatistics->show(); + if (!IsXYRange[qDefs::XMAXIMUM]) { + if (cloneplot1D) + XYCloneRangeValues[qDefs::XMAXIMUM] = cloneplot1D->GetXMaximum(); + else + XYCloneRangeValues[qDefs::XMAXIMUM] = cloneplot2D->GetPlot()->GetXMaximum(); + } else + XYCloneRangeValues[qDefs::XMAXIMUM] = XYRangeValues[qDefs::XMAXIMUM]; - } + if (!IsXYRange[qDefs::YMINIMUM]) { + if (cloneplot1D) + XYCloneRangeValues[qDefs::YMINIMUM] = cloneplot1D->GetYMinimum(); + else + XYCloneRangeValues[qDefs::YMINIMUM] = cloneplot2D->GetPlot()->GetYMinimum(); + } else + XYCloneRangeValues[qDefs::YMINIMUM] = XYRangeValues[qDefs::YMINIMUM]; + + if (!IsXYRange[qDefs::YMAXIMUM]) { + if (cloneplot1D) + XYCloneRangeValues[qDefs::YMAXIMUM] = cloneplot1D->GetYMaximum(); + else + XYCloneRangeValues[qDefs::YMAXIMUM] = cloneplot2D->GetPlot()->GetYMaximum(); + } else + XYCloneRangeValues[qDefs::YMAXIMUM] = XYRangeValues[qDefs::YMAXIMUM]; + + if (cloneplot1D) { + cloneplot1D->SetXMinMax(XYCloneRangeValues[qDefs::XMINIMUM], XYCloneRangeValues[qDefs::XMAXIMUM]); + cloneplot1D->SetYMinMax(XYCloneRangeValues[qDefs::YMINIMUM], XYCloneRangeValues[qDefs::YMAXIMUM]); + } else { + cloneplot2D->GetPlot()->SetXMinMax(XYRangeValues[qDefs::XMINIMUM], XYRangeValues[qDefs::XMAXIMUM]); + cloneplot2D->GetPlot()->SetYMinMax(XYRangeValues[qDefs::YMINIMUM], XYRangeValues[qDefs::YMAXIMUM]); + cloneplot2D->GetPlot()->Update(); + } } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qCloneWidget::SavePlot() { + char cID[10]; + sprintf(cID, "%d", id); + //title + QString fName = QString(filePath.c_str()); + if (cloneBox->title().contains('.')) { + fName.append(QString('/') + cloneBox->title()); + fName.replace(".dat", ".png"); + fName.replace(".raw", ".png"); + } else + fName.append(QString("/Snapshot_unknown_title.png")); + //save + QImage img(cloneBox->size().width(), cloneBox->size().height(), QImage::Format_RGB32); + QPainter painter(&img); + cloneBox->render(&painter); + + fName = QFileDialog::getSaveFileName(this, tr("Save Snapshot "), fName, tr("PNG Files (*.png);;XPM Files(*.xpm);;JPEG Files(*.jpg)"), 0, QFileDialog::ShowDirsOnly); + if (!fName.isEmpty()) { + if ((img.save(fName))) { + qDefs::Message(qDefs::INFORMATION, "The SnapShot has been successfully saved", "qCloneWidget::SavePlot"); + FILE_LOG(logINFO) << "The SnapShot has been successfully saved"; + } else { + qDefs::Message(qDefs::WARNING, "Attempt to save snapshot failed.\n" + "Formats: .png, .jpg, .xpm.", + "qCloneWidget::SavePlot"); + FILE_LOG(logWARNING) << "Attempt to save snapshot failed"; + } + } +} +int qCloneWidget::SavePlotAutomatic() { + char cID[10]; + sprintf(cID, "%d", id); + //title + QString fName = QString(filePath.c_str()); + if (cloneBox->title().contains('.')) { + fName.append(QString('/') + cloneBox->title()); + fName.replace(".dat", ".png"); + fName.replace(".raw", ".png"); + } else + fName.append(QString("/Snapshot_unknown_title.png")); + FILE_LOG(logDEBUG) << "fname:" << fName.toAscii().constData(); + //save + QImage img(cloneBox->size().width(), cloneBox->size().height(), QImage::Format_RGB32); + QPainter painter(&img); + cloneBox->render(&painter); + if (img.save(fName)) + return 0; + else + return -1; +} + + +void qCloneWidget::closeEvent(QCloseEvent *event) { + emit CloneClosedSignal(id); + event->accept(); +} + + +char *qCloneWidget::GetCurrentTimeStamp() { + char output[30]; + char *result; + + //using sys cmds to get output or str + FILE *sysFile = popen("date", "r"); + fgets(output, sizeof(output), sysFile); + pclose(sysFile); + + result = output + 0; + return result; +} + + +void qCloneWidget::DisplayStats(bool enable, QString min, QString max, QString sum) { + if (enable) { + QWidget *widgetStatistics = new QWidget(this); + widgetStatistics->setFixedHeight(15); + QHBoxLayout *hl1 = new QHBoxLayout; + hl1->setSpacing(0); + hl1->setContentsMargins(0, 0, 0, 0); + QLabel *lblMin = new QLabel("Min: "); + lblMin->setFixedWidth(40); + lblMin->setAlignment(Qt::AlignRight); + QLabel *lblMax = new QLabel("Max: "); + lblMax->setFixedWidth(40); + lblMax->setAlignment(Qt::AlignRight); + QLabel *lblSum = new QLabel("Sum: "); + lblSum->setFixedWidth(40); + lblSum->setAlignment(Qt::AlignRight); + QLabel *lblMinDisp = new QLabel(min); + lblMinDisp->setAlignment(Qt::AlignLeft); + QLabel *lblMaxDisp = new QLabel(max); + lblMaxDisp->setAlignment(Qt::AlignLeft); + QLabel *lblSumDisp = new QLabel(sum); + lblSumDisp->setAlignment(Qt::AlignLeft); + hl1->addItem(new QSpacerItem(20, 20, QSizePolicy::Fixed, QSizePolicy::Fixed)); + hl1->addWidget(lblMin); + hl1->addWidget(lblMinDisp); + hl1->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Fixed)); + hl1->addWidget(lblMax); + hl1->addWidget(lblMaxDisp); + hl1->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Fixed)); + hl1->addWidget(lblSum); + hl1->addWidget(lblSumDisp); + hl1->addItem(new QSpacerItem(20, 20, QSizePolicy::Fixed, QSizePolicy::Fixed)); + widgetStatistics->setLayout(hl1); + mainLayout->addWidget(widgetStatistics, 2, 0); + widgetStatistics->show(); + } +} + diff --git a/slsDetectorGui/src/qDetectorMain.cpp b/slsDetectorGui/src/qDetectorMain.cpp old mode 100644 new mode 100755 index c2f6013a3..debfae231 --- a/slsDetectorGui/src/qDetectorMain.cpp +++ b/slsDetectorGui/src/qDetectorMain.cpp @@ -1,908 +1,758 @@ -/********************************************************************** - * TO DO - * 1. settcpsocket is done with slsdetector.maybe do for all detectors connected: mythen - * ********************************************************************/ -// Qt Project Class Headers #include "qDetectorMain.h" -#include "qTabDataOutput.h" -#include "qTabPlot.h" -#include "qTabActions.h" +#include "qDefs.h" +#include "qServer.h" #include "qTabAdvanced.h" -#include "qTabSettings.h" +#include "qTabDataOutput.h" #include "qTabDebugging.h" #include "qTabDeveloper.h" #include "qTabMessages.h" -#include "qServer.h" -// Project Class Headers -#include "slsDetector.h" +#include "qTabPlot.h" +#include "qTabSettings.h" + #include "multiSlsDetector.h" #include "sls_detector_defs.h" -#include "gitInfoGui.h" -// Qt Include Headers -#include +#include "versionAPI.h" + #include #include -// C++ Include Headers -#include -#include +#include + #include -using namespace std; +#include +#include +#include - -//------------------------------------------------------------------------------------------------------------------------------------------------- - -int main (int argc, char **argv) { - QApplication *theApp = new QApplication(argc, argv); - // QApplication *theApp = new QApplication(argc, argv); - theApp->setStyle(new QPlastiqueStyle);//not default when desktop is windows - theApp->setWindowIcon(QIcon( ":/icons/images/mountain.png" )); - int ret = 1; - qDetectorMain *det=new qDetectorMain(argc, argv, theApp,ret,0); - if (ret == 1) - return EXIT_FAILURE; - det->show(); - //theApp->connect( theApp, SIGNAL(lastWindowClosed()), theApp, SLOT(quit())); - return theApp->exec(); +int main(int argc, char **argv) { + QApplication *theApp = new QApplication(argc, argv); + theApp->setStyle(new QPlastiqueStyle); + theApp->setWindowIcon(QIcon(":/icons/images/mountain.png")); + try { + qDetectorMain *det = new qDetectorMain(argc, argv, theApp, 0); + det->show(); + theApp->exec(); + } catch (const std::exception &e) { + qDefs::Message(qDefs::CRITICAL, + std::string(e.what()) + "\nExiting Gui :'( ", "main"); + } + return 0; } +qDetectorMain::qDetectorMain(int argc, char **argv, QApplication *app, + QWidget *parent) + : QMainWindow(parent), detType(slsDetectorDefs::GENERIC), isDeveloper(0), + heightPlotWindow(0), heightCentralWidget(0) { -//------------------------------------------------------------------------------------------------------------------------------------------------- + // options + std::string fname = ""; + int64_t tempval = 0; + int multiId = 0; + // parse command line for config + static struct option long_options[] = { + // These options set a flag. + //{"verbose", no_argument, &verbose_flag, 1}, + // These options don’t set a flag. We distinguish them by their indices. + {"developer", no_argument, 0, 'd'}, + {"config", required_argument, 0, 'f'}, + {"id", required_argument, 0, 'i'}, + {"version", no_argument, 0, 'v'}, + {"help", no_argument, 0, 'h'}, + {0, 0, 0, 0}}; -qDetectorMain::qDetectorMain(int argc, char **argv, QApplication *app, int& ret, QWidget *parent) : - QMainWindow(parent), theApp(app),myDet(0),detID(0),myPlot(0),tabs(0),isDeveloper(0){ + // getopt_long stores the option index here + optind = 1; + int option_index = 0; + int c = 0; - // options - string fname = ""; - int64_t tempval = 0; + while (c != -1) { + c = getopt_long(argc, argv, "hvdf:i:", long_options, &option_index); + // Detect the end of the options + if (c == -1) + break; + switch (c) { - //parse command line for config - static struct option long_options[] = { - // These options set a flag. - //{"verbose", no_argument, &verbose_flag, 1}, - // These options don’t set a flag. We distinguish them by their indices. - { "developer", no_argument, 0, 'd' }, - { "config", required_argument, 0, 'f' }, - { "id", required_argument, 0, 'i' }, - {"version", no_argument, 0, 'v'}, - { "help", no_argument, 0, 'h' }, - { 0, 0, 0, 0 } - }; + case 'f': + fname = optarg; + FILE_LOG(logDEBUG) + << long_options[option_index].name << " " << optarg; + break; + case 'd': + isDeveloper = 1; + break; - // getopt_long stores the option index here. - int option_index = 0; - int c = 0; + case 'i': + multiId = atoi(optarg); + break; - while ( c != -1 ){ - c = getopt_long (argc, argv, "hvdf:i:", long_options, &option_index); + case 'v': + tempval = APIGUI; + FILE_LOG(logINFO) << "SLS Detector GUI " << GITBRANCH << " (0x" + << std::hex << tempval << ")"; + return; - // Detect the end of the options. - if (c == -1) - break; + case 'h': + default: + std::string help_message = + "\n" + std::string(argv[0]) + "\n" + + "Usage: " + std::string(argv[0]) + " [arguments]\n" + + "Possible arguments are:\n" + + "\t-d, --developer : Enables the developer tab\n" + + "\t-f, --config : Loads config from file\n" + + "\t-i, --id : Sets the multi detector id to " + "i. Default: 0. Required \n" + + "\t only when more than one multi " + "detector object is needed.\n\n"; + FILE_LOG(logERROR) << help_message; + exit(EXIT_FAILURE); + } + } - switch(c){ - - case 'f': - fname=string(optarg); -#ifdef VERYVERBOSE - cout << long_options[option_index].name << " " << optarg << endl; -#endif - break; - - case 'd' : - isDeveloper = 1; - break; - - case 'i' : - detID=atoi(optarg); - break; - - case 'v': - tempval = GITDATE; - cout << "SLS Detector GUI " << GITBRANCH << " (0x" << hex << tempval << ")" << endl; - return; - - case 'h': - default: - string help_message = "\n" - + string(argv[0]) + "\n" - + "Usage: " + string(argv[0]) + " [arguments]\n" - + "Possible arguments are:\n" - + "\t-d, --developer : Enables the developer tab\n" - + "\t-f, --config : Loads config from file\n" - + "\t-i, --id : Sets the multi detector id to i. Default: 0. Required \n" - + "\t only when more than one multi detector object is needed.\n\n"; - cout << help_message << endl; - return; - - } - } - - setupUi(this); - SetUpDetector(fname); - SetUpWidgetWindow(); - Initialization(); - ret = 0; + setupUi(this); + SetUpDetector(fname, multiId); + SetUpWidgetWindow(); + Initialization(); } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -qDetectorMain::~qDetectorMain(){ - if(myDet) delete myDet; - if (menubar) delete menubar; - if (centralwidget) delete centralwidget; +qDetectorMain::~qDetectorMain() { + if (myDet) + delete myDet; + if (myPlot) + delete myPlot; + if (tabs) + delete tabs; + if (tabMeasurement) + delete tabMeasurement; + if (tabDataOutput) + delete tabDataOutput; + if (tabPlot) + delete tabPlot; + if (tabSettings) + delete tabSettings; + if (tabAdvanced) + delete tabAdvanced; + if (tabDebugging) + delete tabDebugging; + if (tabDeveloper) + delete tabDeveloper; + if (tabMessages) + delete tabMessages; + if (myServer) + delete myServer; } +bool qDetectorMain::isPlotRunning() { return myPlot->isRunning(); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qDetectorMain::SetUpWidgetWindow(){ - -// Layout - layoutTabs= new QGridLayout; - centralwidget->setLayout(layoutTabs); - -//plot setup - myPlot = new qDrawPlot(dockWidgetPlot,myDet); cout<<"DockPlot ready"<setWidget(myPlot); - -//tabs setup - tabs = new MyTabWidget(this); - layoutTabs->addWidget(tabs); - - -// creating all the other tab widgets - tab_measurement = new qTabMeasurement (this, myDet,myPlot); cout<<"Measurement ready"<setFrameShape(QFrame::NoFrame); - } - // setting the tab widgets to the scrollareas - scroll[Measurement] ->setWidget(tab_measurement); - scroll[DataOutput] ->setWidget(tab_dataoutput); - scroll[Plot] ->setWidget(tab_plot); - scroll[Actions] ->setWidget(tab_actions); - scroll[Settings] ->setWidget(tab_settings); - scroll[Advanced] ->setWidget(tab_advanced); - scroll[Debugging] ->setWidget(tab_debugging); - scroll[Developer] ->setWidget(tab_developer); - // inserting all the tabs - tabs->insertTab(Measurement, scroll[Measurement], "Measurement"); - tabs->insertTab(DataOutput, scroll[DataOutput], "Data Output"); - tabs->insertTab(Plot, scroll[Plot], "Plot"); - tabs->insertTab(Actions, scroll[Actions], "Actions"); - tabs->insertTab(Settings, scroll[Settings], "Settings"); - tabs->insertTab(Advanced, scroll[Advanced], "Advanced"); - tabs->insertTab(Debugging, scroll[Debugging], "Debugging"); - tabs->insertTab(Developer, scroll[Developer], "Developer"); - //no scroll buttons this way - tabs->insertTab(Messages, tab_messages, "Messages"); - -//swap tabs so that messages is last tab - tabs->tabBar()->moveTab(tabs->indexOf(tab_measurement), Measurement); - tabs->tabBar()->moveTab(tabs->indexOf(tab_settings), Settings); - tabs->tabBar()->moveTab(tabs->indexOf(tab_dataoutput), DataOutput); - tabs->tabBar()->moveTab(tabs->indexOf(tab_plot), Plot); - tabs->tabBar()->moveTab(tabs->indexOf(tab_actions), Actions); - tabs->tabBar()->moveTab(tabs->indexOf(tab_advanced), Advanced); - tabs->tabBar()->moveTab(tabs->indexOf(tab_debugging), Debugging); - tabs->tabBar()->moveTab(tabs->indexOf(tab_developer), Developer); - tabs->tabBar()->moveTab(tabs->indexOf(tab_messages), Messages); - tabs->setCurrentIndex(Measurement); - -//other tab properties - // Default tab color - defaultTabColor = tabs->tabBar()->tabTextColor(DataOutput); - //Set the current tab(measurement) to blue as it is the current one - tabs->tabBar()->setTabTextColor(0,QColor(0,0,200,255)); - // increase the width so it uses all the empty space for the tab titles - tabs->tabBar()->setFixedWidth(width()+61); - - // mode setup - to set up the tabs initially as disabled, not in form so done here -#ifdef VERBOSE - cout << "Setting Debug Mode to 0\nSetting Expert Mode to 0\nSetting Developer Mode to " << isDeveloper << "\nSetting Dockable Mode to false\n" << endl; -#endif - tabs->setTabEnabled(Debugging,false); - tabs->setTabEnabled(Advanced,false); - tabs->setTabEnabled(Developer,isDeveloper); - actionLoadTrimbits->setVisible(false); - actionSaveTrimbits->setVisible(false); - actionLoadCalibration->setVisible(false); - actionSaveCalibration->setVisible(false); - - dockWidgetPlot->setFloating(false); - dockWidgetPlot->setFeatures(QDockWidget::NoDockWidgetFeatures); - -// Other setup - //Height of plot and central widget - heightPlotWindow = dockWidgetPlot->size().height(); - heightCentralWidget = centralwidget->size().height(); - // Default zoom Tool Tip - zoomToolTip = dockWidgetPlot->toolTip(); - +int qDetectorMain::GetProgress() { return tabMeasurement->GetProgress(); } +int qDetectorMain::DoesOutputDirExist() { + return tabDataOutput->VerifyOutputDirectory(); } +void qDetectorMain::SetUpWidgetWindow() { -//------------------------------------------------------------------------------------------------------------------------------------------------- + // Layout + QGridLayout *layoutTabs = new QGridLayout; + centralwidget->setLayout(layoutTabs); + // plot setup + myPlot = new qDrawPlot(dockWidgetPlot, myDet); + FILE_LOG(logDEBUG) << "DockPlot ready"; + dockWidgetPlot->setWidget(myPlot); -void qDetectorMain::SetUpDetector(const string fName){ + // tabs setup + tabs = new MyTabWidget(this); + layoutTabs->addWidget(tabs); + // creating all the other tab widgets + tabMeasurement = new qTabMeasurement(this, myDet, myPlot); + tabDataOutput = new qTabDataOutput(this, myDet); + tabPlot = new qTabPlot(this, myDet, myPlot); + tabSettings = new qTabSettings(this, myDet); + tabAdvanced = new qTabAdvanced(this, myDet); + tabDebugging = new qTabDebugging(this, myDet); + tabDeveloper = new qTabDeveloper(this, myDet); + myServer = new qServer(this); - //instantiate detector and set window title - myDet = new multiSlsDetector(detID); + // creating the scroll area widgets for the tabs + QScrollArea *scroll[NumberOfTabs]; + for (int i = 0; i < NumberOfTabs; ++i) { + scroll[i] = new QScrollArea; + scroll[i]->setFrameShape(QFrame::NoFrame); + } + // setting the tab widgets to the scrollareas + scroll[MEASUREMENT]->setWidget(tabMeasurement); + scroll[DATAOUTPUT]->setWidget(tabDataOutput); + scroll[PLOT]->setWidget(tabPlot); + scroll[SETTINGS]->setWidget(tabSettings); + scroll[ADVANCED]->setWidget(tabAdvanced); + scroll[DEBUGGING]->setWidget(tabDebugging); + scroll[DEVELOPER]->setWidget(tabDeveloper); + // inserting all the tabs + tabs->insertTab(MEASUREMENT, scroll[MEASUREMENT], "Measurement"); + tabs->insertTab(DATAOUTPUT, scroll[DATAOUTPUT], "Data Output"); + tabs->insertTab(PLOT, scroll[PLOT], "Plot"); + tabs->insertTab(SETTINGS, scroll[SETTINGS], "Settings"); + tabs->insertTab(ADVANCED, scroll[ADVANCED], "Advanced"); + tabs->insertTab(DEBUGGING, scroll[DEBUGGING], "Debugging"); + tabs->insertTab(DEVELOPER, scroll[DEVELOPER], "Developer"); + // no scroll buttons this way + tabs->insertTab(MESSAGES, tabMessages, "Messages"); - //create messages tab to capture config file loading logs - tab_messages = new qTabMessages (this); cout<<"Messages ready"<tabBar()->moveTab(tabs->indexOf(tabMeasurement), MEASUREMENT); + tabs->tabBar()->moveTab(tabs->indexOf(tabSettings), SETTINGS); + tabs->tabBar()->moveTab(tabs->indexOf(tabDataOutput), DATAOUTPUT); + tabs->tabBar()->moveTab(tabs->indexOf(tabPlot), PLOT); + tabs->tabBar()->moveTab(tabs->indexOf(tabAdvanced), ADVANCED); + tabs->tabBar()->moveTab(tabs->indexOf(tabDebugging), DEBUGGING); + tabs->tabBar()->moveTab(tabs->indexOf(tabDeveloper), DEVELOPER); + tabs->tabBar()->moveTab(tabs->indexOf(tabMessages), MESSAGES); + tabs->setCurrentIndex(MEASUREMENT); - //loads the config file at startup - if(!fName.empty()) LoadConfigFile(fName); + // other tab properties + // Default tab color + defaultTabColor = tabs->tabBar()->tabTextColor(DATAOUTPUT); + // Set the current tab(measurement) to blue as it is the current one + tabs->tabBar()->setTabTextColor(0, QColor(0, 0, 200, 255)); + // increase the width so it uses all the empty space for the tab titles + tabs->tabBar()->setFixedWidth(width() + 61); - //gets the hostname if it worked - string host = myDet->getHostname(); - qDefs::checkErrorMessage(myDet,"qDetectorMain::SetUpDetector"); + // mode setup - to set up the tabs initially as disabled, not in form so + // done here + FILE_LOG(logINFO) + << "Dockable Mode: 0, Debug Mode: 0, Expert Mode: 0, Developer Mode: " + << isDeveloper; + tabs->setTabEnabled(DEBUGGING, false); + tabs->setTabEnabled(ADVANCED, false); + tabs->setTabEnabled(DEVELOPER, isDeveloper); + actionLoadTrimbits->setVisible(false); + actionSaveTrimbits->setVisible(false); - //if hostname doesnt exist even in shared memory - if(!host.length()){ - cout << endl << "No Detector Connected." << endl; - qDefs::Message(qDefs::CRITICAL,"No Detectors Connected. ","qDetectorMain::SetUpDetector"); - exit(-1); - } + dockWidgetPlot->setFloating(false); + dockWidgetPlot->setFeatures(QDockWidget::NoDockWidgetFeatures); - //check if the detector is not even connected - string offline = myDet->checkOnline(); - qDefs::checkErrorMessage(myDet,"qDetectorMain::SetUpDetector"); - - if(!offline.empty()){ - qDefs::Message(qDefs::CRITICAL,string("The detector(s) ")+offline+string(" is/are not connected. Exiting GUI."),"qDetectorMain::SetUpDetector"); - cout << "The detector(s) " << host << " is/are not connected. Exiting GUI." << endl; - exit(-1); - } - - // Check if type valid. If not, exit - slsDetectorDefs::detectorType detType = myDet->getDetectorsType(); - qDefs::checkErrorMessage(myDet,"qDetectorMain::SetUpDetector"); - - switch(detType){ - case slsDetectorDefs::MYTHEN: break; - case slsDetectorDefs::EIGER: break; - case slsDetectorDefs::GOTTHARD: - case slsDetectorDefs::AGIPD: - case slsDetectorDefs::PROPIX: - case slsDetectorDefs::MOENCH: - case slsDetectorDefs::JUNGFRAU: - case slsDetectorDefs::JUNGFRAUCTB: - actionLoadTrimbits->setText("Load Settings"); actionSaveTrimbits->setText("Save Settings"); - break; - default: - string detName = myDet->slsDetectorBase::getDetectorType(detType); - qDefs::checkErrorMessage(myDet,"qDetectorMain::SetUpDetector"); - cout << "ERROR: " + host + " has unknown detector type \"" + detName + "\". Exiting GUI." << endl; - string errorMess = host+string(" has unknown detector type \"")+ - detName+string("\". Exiting GUI."); - qDefs::Message(qDefs::CRITICAL,errorMess,"qDetectorMain::SetUpDetector"); - exit(-1); - } - setWindowTitle("SLS Detector GUI : "+ - QString(slsDetectorBase::getDetectorType(detType).c_str())+ " - "+QString(host.c_str())); -//#ifdef VERBOSE - cout << endl << "Type : " << slsDetectorBase::getDetectorType(detType) << "\nDetector : " << host << endl; -//#endif - myDet->setOnline(slsDetectorDefs::ONLINE_FLAG); - if(detType != slsDetectorDefs::MYTHEN) - myDet->setReceiverOnline(slsDetectorDefs::ONLINE_FLAG); - qDefs::checkErrorMessage(myDet,"qDetectorMain::SetUpDetector"); + // Other setup + // Height of plot and central widget + heightPlotWindow = dockWidgetPlot->size().height(); + heightCentralWidget = centralwidget->size().height(); + // Default zoom Tool Tip + zoomToolTip = dockWidgetPlot->toolTip(); } +void qDetectorMain::SetUpDetector(const std::string fName, int multiID) { -//------------------------------------------------------------------------------------------------------------------------------------------------- + // instantiate detector and set window title + myDet = new multiSlsDetector(multiID); + // create messages tab to capture config file loading logs + tabMessages = new qTabMessages(this); -void qDetectorMain::Initialization(){ -// Dockable Plot - connect(dockWidgetPlot, SIGNAL(topLevelChanged(bool)), this,SLOT(ResizeMainWindow(bool))); -// tabs - connect(tabs, SIGNAL(currentChanged(int)), this, SLOT(Refresh(int)));//( QWidget*))); - // Measurement tab - connect(tab_measurement, SIGNAL(StartSignal()), this,SLOT(EnableTabs())); - connect(tab_measurement, SIGNAL(StopSignal()), myPlot,SLOT(StopAcquisition())); - connect(tab_measurement, SIGNAL(CheckPlotIntervalSignal()), tab_plot,SLOT(SetFrequency())); - // Data Output Tab - connect(tab_dataoutput, SIGNAL(AngularConversionSignal(bool)), tab_actions,SLOT(EnablePositions(bool))); - //enable scanbox( for angles) - connect(tab_dataoutput, SIGNAL(AngularConversionSignal(bool)), tab_plot,SLOT(EnableScanBox())); - // Plot tab - connect(tab_plot, SIGNAL(DisableZoomSignal(bool)), this,SLOT(SetZoomToolTip(bool))); - // Actions tab (only for scan) - connect(tab_actions, SIGNAL(EnableScanBox()), tab_plot,SLOT(EnableScanBox())); - //settings to advanced tab(int is always 0 to only refresh) - connect(tab_settings, SIGNAL(UpdateTrimbitSignal(int)), tab_advanced,SLOT(UpdateTrimbitPlot(int))); -// Plotting - // When the acquisition is finished, must update the meas tab - connect(myPlot, SIGNAL(UpdatingPlotFinished()), this, SLOT(EnableTabs())); - connect(myPlot, SIGNAL(UpdatingPlotFinished()), tab_measurement, SLOT(UpdateFinished())); - //This should not be called as it will change file name to measurement when run finished - //connect(myPlot, SIGNAL(UpdatingPlotFinished()), tab_plot, SLOT(Refresh())); - connect(myPlot, SIGNAL(SetCurrentMeasurementSignal(int)), tab_measurement, SLOT(SetCurrentMeasurement(int))); + // loads the config file at startup + if (!fName.empty()) + LoadConfigFile(fName); + // validate detector type (for GUI) and update menu + detType = myDet->getDetectorTypeAsEnum(); + switch (detType) { + case slsDetectorDefs::EIGER: + break; + case slsDetectorDefs::GOTTHARD: + case slsDetectorDefs::JUNGFRAU: + actionLoadTrimbits->setText("Load Settings"); + actionSaveTrimbits->setText("Save Settings"); + case slsDetectorDefs::MOENCH: + actionLoadTrimbits->setEnabled(false); + actionSaveTrimbits->setEnabled(false); + break; + default: + std::string errorMess = + myDet->getHostname() + std::string(" has ") + + myDet->getDetectorTypeAsString() + std::string(" detector type (") + + std::to_string(detType) + std::string("). Exiting GUI."); + throw sls::RuntimeError(errorMess.c_str()); + } -// menubar - // Modes Menu - connect(menuModes, SIGNAL(triggered(QAction*)), this,SLOT(EnableModes(QAction*))); - // Utilities Menu - connect(menuUtilities, SIGNAL(triggered(QAction*)), this,SLOT(ExecuteUtilities(QAction*))); - // Help Menu - connect(menuHelp, SIGNAL(triggered(QAction*)), this,SLOT(ExecuteHelp(QAction*))); + std::string title = + "SLS Detector GUI : " + myDet->getDetectorTypeAsString() + " - " + + myDet->getHostname(); + // Plotting + // When the acquisition is finished, must update the meas tab + connect(myPlot, SIGNAL(UpdatingPlotFinished()), this, SLOT(EnableTabs())); + connect(myPlot, SIGNAL(UpdatingPlotFinished()), tabMeasurement, + SLOT(UpdateFinished())); + connect(myPlot, SIGNAL(SetCurrentMeasurementSignal(int)), tabMeasurement, + SLOT(SetCurrentMeasurement(int))); + // menubar + // Modes Menu + connect(menuModes, SIGNAL(triggered(QAction *)), this, + SLOT(EnableModes(QAction *))); + // Utilities Menu + connect(menuUtilities, SIGNAL(triggered(QAction *)), this, + SLOT(ExecuteUtilities(QAction *))); + // Help Menu + connect(menuHelp, SIGNAL(triggered(QAction *)), this, + SLOT(ExecuteHelp(QAction *))); -//server - connect(myServer, SIGNAL(ServerStoppedSignal()), this,SLOT(UncheckServer())); + // server + connect(myServer, SIGNAL(ServerStoppedSignal()), this, + SLOT(UncheckServer())); } +void qDetectorMain::LoadConfigFile(const std::string fName) { + FILE_LOG(logINFO) << "Loading config file at start up:" << fName; -//------------------------------------------------------------------------------------------------------------------------------------------------- + struct stat st_buf; + QString file = QString(fName.c_str()); - -void qDetectorMain::LoadConfigFile(const string fName){ -#ifdef VERBOSE - cout << "Loading config file at start up:" << fName << endl; -#endif - struct stat st_buf; - QString file = QString(fName.c_str()); - - //path doesnt exist - if(stat(fName.c_str(),&st_buf)) - qDefs::Message(qDefs::WARNING,string("Start up configuration failed to load. The following file does not exist:
")+fName,"qDetectorMain::LoadConfigFile"); - - //not a file - else if (!S_ISREG (st_buf.st_mode)) - qDefs::Message(qDefs::WARNING,string("Start up configuration failed to load. The following file is not a recognized file format:
")+fName,"qDetectorMain::LoadConfigFile"); - - else{ - //could not load config file - if(myDet->readConfigurationFile(fName)==slsDetectorDefs::FAIL) - qDefs::Message(qDefs::WARNING,string("Could not load all the Configuration Parameters from file:
")+fName,"qDetectorMain::LoadConfigFile"); - //successful - else - qDefs::Message(qDefs::INFORMATION,"
The Configuration Parameters have been loaded successfully at start up.","qDetectorMain::LoadConfigFile"); - - qDefs::checkErrorMessage(myDet,"qDetectorMain::LoadConfigFile"); - } + // path doesnt exist + if (stat(fName.c_str(), &st_buf)) { + qDefs::Message( + qDefs::WARNING, + std::string("Start up configuration failed to load. The " + "following file does not exist:
") + + fName, + "qDetectorMain::LoadConfigFile"); + FILE_LOG(logWARNING) << "Config file does not exist"; + } + // not a file + else if (!S_ISREG(st_buf.st_mode)) { + qDefs::Message( + qDefs::WARNING, + std::string( + "Start up configuration failed to load. The following " + "file is not a recognized file format:
") + + fName, + "qDetectorMain::LoadConfigFile"); + FILE_LOG(logWARNING) << "File not recognized"; + } else { + qDefs::IgnoreNonCriticalExceptions(myDet, "qDetectorMain::LoadConfigFile", + &multiSlsDetector::readConfigurationFile, fName); + } } +void qDetectorMain::EnableModes(QAction *action) { + bool enable; + // listen to gui client + if (action == actionListenGuiClient) { + disconnect(menuModes, SIGNAL(triggered(QAction *)), this, + SLOT(EnableModes(QAction *))); + if (actionListenGuiClient->isChecked()) + myServer->CreateServers(); + else + myServer->DestroyServers(); + connect(menuModes, SIGNAL(triggered(QAction *)), this, + SLOT(EnableModes(QAction *))); + } + // Set DebugMode + else if (action == actionDebug) { + enable = actionDebug->isChecked(); + tabs->setTabEnabled(DEBUGGING, enable); + FILE_LOG(logINFO) << "Debug Mode: " + << slsDetectorDefs::stringEnable(enable); -//------------------------------------------------------------------------------------------------------------------------------------------------- + } + // Set ExpertMode(comes here only if its a digital detector) + else if (action == actionExpert) { + enable = actionExpert->isChecked(); -void qDetectorMain::EnableModes(QAction *action){ - bool enable; + tabs->setTabEnabled(ADVANCED, enable); + // moench don't have settings + if (detType != slsDetectorDefs::MOENCH) { + actionLoadTrimbits->setVisible(enable); + actionSaveTrimbits->setVisible(enable); + } + FILE_LOG(logINFO) << "Expert Mode: " + << slsDetectorDefs::stringEnable(enable); + } - //listen to gui client - if(action==actionListenGuiClient){ - - myServer->StartStopServer(actionListenGuiClient->isChecked()); - - //disconnect(menuModes, SIGNAL(triggered(QAction*)), this,SLOT(EnableModes(QAction*))); - //actionListenGuiClient->setChecked(myServer->StartStopServer(actionListenGuiClient->isChecked())); - //connect(menuModes, SIGNAL(triggered(QAction*)), this,SLOT(EnableModes(QAction*))); - } - //Set DebugMode - else if(action==actionDebug){ - enable = actionDebug->isChecked(); - tabs->setTabEnabled(Debugging,enable); -#ifdef VERBOSE - cout << "Setting Debug Mode to " << enable << endl; -#endif - } - - //Set ExpertMode(comes here only if its a digital detector) - else if(action==actionExpert){ - enable = actionExpert->isChecked(); - - tabs->setTabEnabled(Advanced,enable); - actionLoadTrimbits->setVisible(enable); - actionSaveTrimbits->setVisible(enable); - actionLoadCalibration->setVisible(enable); - actionSaveCalibration->setVisible(enable); - tab_measurement->SetExpertMode(enable); - tab_settings->SetExpertMode(enable); -#ifdef VERBOSE - cout << "Setting Expert Mode to " << enable << endl; -#endif - } - - //Set DockableMode - else{ - enable = actionDockable->isChecked(); - if(enable) - dockWidgetPlot->setFeatures(QDockWidget::DockWidgetFloatable); - else{ - dockWidgetPlot->setFloating(false); - dockWidgetPlot->setFeatures(QDockWidget::NoDockWidgetFeatures); - } -#ifdef VERBOSE - cout << "Setting Dockable Mode to " << enable << endl; -#endif - } + // Set DockableMode + else { + enable = actionDockable->isChecked(); + if (enable) { + dockWidgetPlot->setFeatures(QDockWidget::DockWidgetFloatable); + } else { + dockWidgetPlot->setFloating(false); + dockWidgetPlot->setFeatures(QDockWidget::NoDockWidgetFeatures); + } + FILE_LOG(logINFO) << "Dockable Mode: " + << slsDetectorDefs::stringEnable(enable); + } } +void qDetectorMain::ExecuteUtilities(QAction *action) { + bool refreshTabs = false; + try { + if (action == actionOpenSetup) { + FILE_LOG(logDEBUG) << "Loading Setup"; + QString fName = QString(myDet->getFilePath().c_str()); + fName = QFileDialog::getOpenFileName( + this, tr("Load Detector Setup"), fName, + tr("Detector Setup files (*.det);;All Files(*)")); + // Gets called when cancelled as well + if (!fName.isEmpty()) { + refreshTabs = true; + myDet->retrieveDetectorSetup( + std::string(fName.toAscii().constData())); + qDefs::Message( + qDefs::INFORMATION, + "The Setup Parameters have been loaded successfully.", + "qDetectorMain::ExecuteUtilities"); + FILE_LOG(logINFO) << "Setup Parameters loaded successfully"; + } + } -//------------------------------------------------------------------------------------------------------------------------------------------------- + else if (action == actionSaveSetup) { + FILE_LOG(logDEBUG) << "Saving Setup"; + QString fName = QString(myDet->getFilePath().c_str()); + fName = QFileDialog::getSaveFileName( + this, tr("Save Current Detector Setup"), fName, + tr("Detector Setup files (*.det);;All Files(*) ")); + // Gets called when cancelled as well + if (!fName.isEmpty()) { + myDet->dumpDetectorSetup( + std::string(fName.toAscii().constData())); + qDefs::Message( + qDefs::INFORMATION, + "The Setup Parameters have been saved successfully.", + "qDetectorMain::ExecuteUtilities"); + FILE_LOG(logINFO) << "Setup Parameters saved successfully"; + } + } + else if (action == actionOpenConfiguration) { + FILE_LOG(logDEBUG) << "Loading Configuration"; + QString fName = QString(myDet->getFilePath().c_str()); + fName = QFileDialog::getOpenFileName( + this, tr("Load Detector Configuration"), fName, + tr("Configuration files (*.config);;All Files(*)")); + // Gets called when cancelled as well + if (!fName.isEmpty()) { + refreshTabs = true; + myDet->readConfigurationFile( + std::string(fName.toAscii().constData())); + qDefs::Message(qDefs::INFORMATION, + "The Configuration Parameters have been " + "configured successfully.", + "qDetectorMain::ExecuteUtilities"); + FILE_LOG(logINFO) + << "Configuration Parameters loaded successfully"; + } + } -void qDetectorMain::ExecuteUtilities(QAction *action){ - bool refreshTabs = false; - if(action==actionOpenSetup){ -#ifdef VERBOSE - cout << "Loading Setup" << endl; -#endif - QString fName = QString(myDet->getFilePath().c_str()); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - fName = QFileDialog::getOpenFileName(this, - tr("Load Detector Setup"),fName, - tr("Detector Setup files (*.det);;All Files(*)")); - // Gets called when cancelled as well - if (!fName.isEmpty()){ - if(myDet->retrieveDetectorSetup(string(fName.toAscii().constData()))!=slsDetectorDefs::FAIL){ - qDefs::Message(qDefs::INFORMATION,"The Setup Parameters have been loaded successfully.","qDetectorMain::ExecuteUtilities"); - refreshTabs=true; - }else qDefs::Message(qDefs::WARNING,string("Could not load the Setup Parameters from file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - } - } - else if(action==actionSaveSetup){ -#ifdef VERBOSE - cout << "Saving Setup" << endl; -#endif - QString fName = QString(myDet->getFilePath().c_str()); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - fName = QFileDialog::getSaveFileName(this, - tr("Save Current Detector Setup"),fName, - tr("Detector Setup files (*.det);;All Files(*) ")); - // Gets called when cancelled as well - if (!fName.isEmpty()){ - if(myDet->dumpDetectorSetup(string(fName.toAscii().constData()))!=slsDetectorDefs::FAIL) - qDefs::Message(qDefs::INFORMATION,"The Setup Parameters have been saved successfully.","qDetectorMain::ExecuteUtilities"); - else qDefs::Message(qDefs::WARNING,string("Could not save the Setup Parameters from file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - } - } - else if(action==actionOpenConfiguration){ -#ifdef VERBOSE - cout << "Loading Configuration" << endl; -#endif - QString fName = QString(myDet->getFilePath().c_str()); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - fName = QFileDialog::getOpenFileName(this, - tr("Load Detector Configuration"),fName, - tr("Configuration files (*.config);;All Files(*)")); - // Gets called when cancelled as well - if (!fName.isEmpty()){ - if(myDet->readConfigurationFile(string(fName.toAscii().constData()))!=slsDetectorDefs::FAIL){ - qDefs::Message(qDefs::INFORMATION,"The Configuration Parameters have been configured successfully.","qDetectorMain::ExecuteUtilities"); - refreshTabs=true; - }else qDefs::Message(qDefs::WARNING,string("Could not load all the Configuration Parameters from file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - } - } - else if(action==actionSaveConfiguration){ -#ifdef VERBOSE - cout << "Saving Configuration" << endl; -#endif - QString fName = QString(myDet->getFilePath().c_str()); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - fName = QFileDialog::getSaveFileName(this, - tr("Save Current Detector Configuration"),fName, - tr("Configuration files (*.config) ;;All Files(*)")); - // Gets called when cancelled as well - if (!fName.isEmpty()){ - if(myDet->writeConfigurationFile(string(fName.toAscii().constData()))!=slsDetectorDefs::FAIL) - qDefs::Message(qDefs::INFORMATION,"The Configuration Parameters have been saved successfully.","qDetectorMain::ExecuteUtilities"); - else qDefs::Message(qDefs::WARNING,string("Could not save the Configuration Parameters from file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - } - } - else if(action==actionLoadTrimbits){ - QString fName = QString( (myDet->getSettingsDir()).c_str()); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - //gotthard - if(actionLoadTrimbits->text().contains("Settings")){ -#ifdef VERBOSE - cout << "Loading Settings" << endl; -#endif - fName = QFileDialog::getOpenFileName(this, - tr("Load Detector Settings"),fName, - tr("Settings files (*.settings settings.sn*);;All Files(*)")); - // Gets called when cancelled as well - if (!fName.isEmpty()){ - if(myDet->loadSettingsFile(string(fName.toAscii().constData()),-1)!=slsDetectorDefs::FAIL) - qDefs::Message(qDefs::INFORMATION,"The Settings have been loaded successfully.","qDetectorMain::ExecuteUtilities"); - else qDefs::Message(qDefs::WARNING,string("Could not load the Settings from file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - } + else if (action == actionSaveConfiguration) { + FILE_LOG(logDEBUG) << "Saving Configuration"; + QString fName = QString(myDet->getFilePath().c_str()); + fName = QFileDialog::getSaveFileName( + this, tr("Save Current Detector Configuration"), fName, + tr("Configuration files (*.config) ;;All Files(*)")); + // Gets called when cancelled as well + if (!fName.isEmpty()) { + myDet->writeConfigurationFile( + std::string(fName.toAscii().constData())); + qDefs::Message(qDefs::INFORMATION, + "The Configuration Parameters have been saved " + "successfully.", + "qDetectorMain::ExecuteUtilities"); + FILE_LOG(logINFO) + << "Configuration Parameters saved successfully"; + } + } - }//mythen and eiger - else{ -#ifdef VERBOSE - cout << "Loading Trimbits" << endl; -#endif - //so that even nonexisting files can be selected - QFileDialog *fileDialog = new QFileDialog(this, - tr("Load Detector Trimbits"),fName, - tr("Trimbit files (*.trim noise.sn*);;All Files(*)")); - fileDialog->setFileMode(QFileDialog::AnyFile ); - if ( fileDialog->exec() == QDialog::Accepted ) - fName = fileDialog->selectedFiles()[0]; + else if (action == actionLoadTrimbits) { + QString fName = QString((myDet->getSettingsDir()).c_str()); + // gotthard + if (actionLoadTrimbits->text().contains("Settings")) { + FILE_LOG(logDEBUG) << "Loading Settings"; + fName = QFileDialog::getOpenFileName( + this, tr("Load Detector Settings"), fName, + tr("Settings files (*.settings settings.sn*);;All " + "Files(*)")); + // Gets called when cancelled as well + if (!fName.isEmpty()) { + myDet->loadSettingsFile( + std::string(fName.toAscii().constData()), -1); + qDefs::Message( + qDefs::INFORMATION, + "The Settings have been loaded successfully.", + "qDetectorMain::ExecuteUtilities"); + FILE_LOG(logINFO) << "Settings loaded successfully"; + } - // Gets called when cancelled as well - if (!fName.isEmpty()){ - if(myDet->loadSettingsFile(string(fName.toAscii().constData()),-1)!=slsDetectorDefs::FAIL) - qDefs::Message(qDefs::INFORMATION,"The Trimbits have been loaded successfully.","qDetectorMain::ExecuteUtilities"); - else qDefs::Message(qDefs::WARNING,string("Could not load the Trimbits from file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - } - } - } - else if(action==actionSaveTrimbits){ - //gotthard - if(actionLoadTrimbits->text().contains("Settings")){ -#ifdef VERBOSE - cout << "Saving Settings" << endl; -#endif - //different output directory so as not to overwrite - QString fName = QString( (myDet->getSettingsDir()).c_str() ); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - fName = QFileDialog::getSaveFileName(this, - tr("Save Current Detector Settings"),fName, - tr("Settings files (*.settings settings.sn*);;All Files(*) ")); - // Gets called when cancelled as well - if (!fName.isEmpty()){ - if(myDet->saveSettingsFile(string(fName.toAscii().constData()),-1)!=slsDetectorDefs::FAIL) - qDefs::Message(qDefs::INFORMATION,"The Settings have been saved successfully.","qDetectorMain::ExecuteUtilities"); - else qDefs::Message(qDefs::WARNING,string("Could not save the Settings to file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - } - }//mythen and eiger - else{ -#ifdef VERBOSE - cout << "Saving Trimbits" << endl; -#endif//different output directory so as not to overwrite - QString fName = QString( (myDet->getSettingsDir()).c_str() ); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - fName = QFileDialog::getSaveFileName(this, - tr("Save Current Detector Trimbits"),fName, - tr("Trimbit files (*.trim noise.sn*) ;;All Files(*)")); - // Gets called when cancelled as well - if (!fName.isEmpty()){ - if(myDet->saveSettingsFile(string(fName.toAscii().constData()),-1)!=slsDetectorDefs::FAIL) - qDefs::Message(qDefs::INFORMATION,"The Trimbits have been saved successfully.","qDetectorMain::ExecuteUtilities"); - else qDefs::Message(qDefs::WARNING,string("Could not save the Trimbits to file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - } - } - } - else if(action==actionLoadCalibration){ -#ifdef VERBOSE - cout << "Loading Calibration Data" << endl; -#endif - QString fName = QString( (myDet->getCalDir()).c_str() ); - qDefs::checkErrorMessage(myDet); + } // mythen and eiger + else { + FILE_LOG(logDEBUG) << "Loading Trimbits"; + // so that even nonexisting files can be selected + QFileDialog *fileDialog = new QFileDialog( + this, tr("Load Detector Trimbits"), fName, + tr("Trimbit files (*.trim noise.sn*);;All Files(*)")); + fileDialog->setFileMode(QFileDialog::AnyFile); + if (fileDialog->exec() == QDialog::Accepted) + fName = fileDialog->selectedFiles()[0]; - //so that even nonexisting files can be selected - QFileDialog *fileDialog = new QFileDialog(this, - tr("Load Detector Calibration Data"),fName, - tr("Calibration files (*.cal calibration.sn*);;All Files(*)")); - fileDialog->setFileMode(QFileDialog::AnyFile ); - if ( fileDialog->exec() == QDialog::Accepted ) - fName = fileDialog->selectedFiles()[0]; + // Gets called when cancelled as well + if (!fName.isEmpty()) { + myDet->loadSettingsFile( + std::string(fName.toAscii().constData()), -1); + qDefs::Message( + qDefs::INFORMATION, + "The Trimbits have been loaded successfully.", + "qDetectorMain::ExecuteUtilities"); + FILE_LOG(logINFO) << "Trimbits loaded successfully"; + } + } + } - // Gets called when cancelled as well - if (!fName.isEmpty()){ - if(myDet->loadCalibrationFile(string(fName.toAscii().constData()),-1)!=slsDetectorDefs::FAIL) - qDefs::Message(qDefs::INFORMATION,"The Calibration Data have been loaded successfully.","qDetectorMain::ExecuteUtilities"); - else qDefs::Message(qDefs::WARNING,string("Could not load the Calibration data from file:\n")+ fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - } - } - else if(action==actionSaveCalibration){ -#ifdef VERBOSE - cout << "Saving Calibration Data" << endl; -#endif//different output directory so as not to overwrite - QString fName = QString( (myDet->getCalDir()).c_str() ); - qDefs::checkErrorMessage(myDet); - fName = QFileDialog::getSaveFileName(this, - tr("Save Current Detector Calibration Data"),fName, - tr("Calibration files (*.cal calibration.sn*);;All Files(*) ")); - // Gets called when cancelled as well - if (!fName.isEmpty()){ - if(myDet->saveCalibrationFile(string(fName.toAscii().constData()),-1)!=slsDetectorDefs::FAIL) - qDefs::Message(qDefs::INFORMATION,"The Calibration Data have been saved successfully.","qDetectorMain::ExecuteUtilities"); - else qDefs::Message(qDefs::WARNING,string("Could not save the Calibration data to file:\n")+fName.toAscii().constData(),"qDetectorMain::ExecuteUtilities"); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteUtilities"); - } - } + else if (action == actionSaveTrimbits) { + // gotthard + if (actionLoadTrimbits->text().contains("Settings")) { + FILE_LOG(logDEBUG) << "Saving Settings"; + // different output directory so as not to overwrite + QString fName = QString((myDet->getSettingsDir()).c_str()); + fName = QFileDialog::getSaveFileName( + this, tr("Save Current Detector Settings"), fName, + tr("Settings files (*.settings settings.sn*);;All " + "Files(*) ")); + // Gets called when cancelled as well + if (!fName.isEmpty()) { + myDet->saveSettingsFile( + std::string(fName.toAscii().constData()), -1); + qDefs::Message(qDefs::INFORMATION, + "The Settings have been saved successfully.", + "qDetectorMain::ExecuteUtilities"); + FILE_LOG(logINFO) << "Settings saved successfully"; + } + } // mythen and eiger + else { + FILE_LOG(logDEBUG) << "Saving Trimbits"; + // different output directory so as not to overwrite + QString fName = QString((myDet->getSettingsDir()).c_str()); + fName = QFileDialog::getSaveFileName( + this, tr("Save Current Detector Trimbits"), fName, + tr("Trimbit files (*.trim noise.sn*) ;;All Files(*)")); + // Gets called when cancelled as well + if (!fName.isEmpty()) { + myDet->saveSettingsFile( + std::string(fName.toAscii().constData()), -1); + qDefs::Message(qDefs::INFORMATION, + "The Trimbits have been saved successfully.", + "qDetectorMain::ExecuteUtilities"); + FILE_LOG(logINFO) << "Trimbits saved successfully"; + } + } + } + } catch (const sls::NonCriticalError &e) { + qDefs::Message(qDefs::WARNING, e.what(), + "qDetectorMain::ExecuteUtilities"); + } - Refresh(tabs->currentIndex()); - if(refreshTabs){ - tab_actions->Refresh(); - tab_measurement->Refresh(); - tab_settings->Refresh(); - tab_dataoutput->Refresh(); - if(tab_advanced->isEnabled()) tab_advanced->Refresh(); - if(tab_debugging->isEnabled()) tab_debugging->Refresh(); - if(tab_developer->isEnabled()) tab_developer->Refresh(); - - tab_plot->Refresh(); - } + Refresh(tabs->currentIndex()); + if (refreshTabs) { + tabMeasurement->Refresh(); + tabSettings->Refresh(); + tabDataOutput->Refresh(); + if (tabAdvanced->isEnabled()) + tabAdvanced->Refresh(); + if (tabDebugging->isEnabled()) + tabDebugging->Refresh(); + if (tabDeveloper->isEnabled()) + tabDeveloper->Refresh(); + tabPlot->Refresh(); + } } +void qDetectorMain::ExecuteHelp(QAction *action) { + if (action == actionAbout) { + FILE_LOG(logINFO) << "About Common GUI for Eiger, Gotthard, Jungfrau " + "and Moench detectors"; -//------------------------------------------------------------------------------------------------------------------------------------------------- + char version[200]; + long long unsigned int retval = APIGUI; + sprintf(version, "%llx", retval); + std::string thisGUIVersion{version}; + sprintf(version, "%lx", + myDet->getId(slsDetectorDefs::THIS_SOFTWARE_VERSION)); + std::string thisClientVersion{version}; -void qDetectorMain::ExecuteHelp(QAction *action){ - if(action==actionAbout){ -#ifdef VERBOSE - cout << "About: Common GUI for Mythen, Eiger, Gotthard, Jungfrau, Moench and Propix detectors" << endl; -#endif - char version[200]; - long long unsigned int retval= GITDATE; - sprintf(version,"%llx",retval); - string thisGUIVersion = string(version); - - sprintf(version,"%llx",(long long unsigned int)myDet->getId(slsDetectorDefs::THIS_SOFTWARE_VERSION)); - qDefs::checkErrorMessage(myDet,"qDetectorMain::ExecuteHelp"); - string thisClientVersion = string(version); - - //

A heading

- qDefs::Message(qDefs::INFORMATION,"

" - "SLS Detector GUI version:   " + thisGUIVersion+"
" - "SLS Detector Client version: "+thisClientVersion+"

" - "Common GUI to control the SLS Detectors: " - "Mythen, Eiger, Gotthard, Jungfrau, Moench and Propix.

" - "It can be operated in parallel with the command line interface:
" - "sls_detector_put,
sls_detector_get,
sls_detector_acquire and
sls_detector_help.

" - "The GUI Software is still in progress. " - "Please report bugs to dhanya.maliakal@psi.ch or anna.bergamaschi@psi.ch.<\\p>","qDetectorMain::ExecuteHelp"); - } + qDefs::Message(qDefs::INFORMATION, + "

" + "SLS Detector GUI version:   " + + thisGUIVersion + + "
" + "SLS Detector Client version: " + + thisClientVersion + + "

" + "Common GUI to control the SLS Detectors: " + "Eiger, Gotthard, Jungfrau and Moench.

" + "It can be operated in parallel with the command " + "line interface:
" + "sls_detector_put,
sls_detector_get,
sls_" + "detector_acquire and
sls_detector_help.

" + "Please report bugs to:
" + "Dhanya.Thattil@psi.ch,
" + "Erik.Froejdh@psi.ch or
" + "Anna.Bergamaschi@psi.ch.<\\p>", + "qDetectorMain::ExecuteHelp"); + } } +void qDetectorMain::Refresh(int index) { + FILE_LOG(logDEBUG) << "Refresh Main Tab"; -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qDetectorMain::Refresh(int index){ - myDet->setOnline(slsDetectorDefs::ONLINE_FLAG); - myDet->setReceiverOnline(slsDetectorDefs::ONLINE_FLAG); - qDefs::checkErrorMessage(myDet,"qDetectorMain::Refresh"); - if(!tabs->isTabEnabled(index)) - tabs->setCurrentIndex((index++)<(tabs->count()-1)?index:Measurement); - else{ - switch(tabs->currentIndex()){ - case Measurement: tab_measurement->Refresh(); break; - case Settings: tab_settings->Refresh(); break; - case DataOutput: tab_dataoutput->Refresh(); break; - case Plot: tab_plot->Refresh(); break; - case Actions: tab_actions->Refresh(); break; - case Advanced: tab_advanced->Refresh(); break; - case Debugging: tab_debugging->Refresh(); break; - case Developer: tab_developer->Refresh(); break; - case Messages: break; - } - } - for(int i=0;itabBar()->setTabTextColor(i,defaultTabColor); - tabs->tabBar()->setTabTextColor(index,QColor(0,0,200,255)); + if (!tabs->isTabEnabled(index)) + tabs->setCurrentIndex((index++) < (tabs->count() - 1) ? index + : MEASUREMENT); + else { + switch (tabs->currentIndex()) { + case MEASUREMENT: + tabMeasurement->Refresh(); + break; + case SETTINGS: + tabSettings->Refresh(); + break; + case DATAOUTPUT: + tabDataOutput->Refresh(); + break; + case PLOT: + tabPlot->Refresh(); + break; + case ADVANCED: + tabAdvanced->Refresh(); + break; + case DEBUGGING: + tabDebugging->Refresh(); + break; + case DEVELOPER: + tabDeveloper->Refresh(); + break; + case MESSAGES: + break; + } + } + for (int i = 0; i < NumberOfTabs; ++i) + tabs->tabBar()->setTabTextColor(i, defaultTabColor); + tabs->tabBar()->setTabTextColor(index, QColor(0, 0, 200, 255)); } +void qDetectorMain::ResizeMainWindow(bool b) { + FILE_LOG(logDEBUG1) << "Resizing Main Window: height:" << height(); -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qDetectorMain::ResizeMainWindow(bool b){ -#ifdef VERBOSE - cout << "Resizing Main Window: height:" << height() << endl; -#endif - // undocked from the main window - if(b){ - // sets the main window height to a smaller maximum to get rid of space - setMaximumHeight(height()-heightPlotWindow-9); - dockWidgetPlot->setMinimumHeight(0); - cout << "undocking it from main window" << endl; - } - else{ - setMaximumHeight(QWIDGETSIZE_MAX); - // the minimum for plot will be set when the widget gets resized automatically - } + // undocked from the main window + if (b) { + // sets the main window height to a smaller maximum to get rid of space + setMaximumHeight(height() - heightPlotWindow - 9); + dockWidgetPlot->setMinimumHeight(0); + FILE_LOG(logINFO) << "Undocking from main window"; + } else { + setMaximumHeight(QWIDGETSIZE_MAX); + // the minimum for plot will be set when the widget gets resized + // automatically + } } +void qDetectorMain::resizeEvent(QResizeEvent *event) { + if (!dockWidgetPlot->isFloating()) { + dockWidgetPlot->setMinimumHeight(height() - centralwidget->height() - + 50); + centralwidget->setMaximumHeight(heightCentralWidget); + } -//------------------------------------------------------------------------------------------------------------------------------------------------- + // adjusting tab width + if (width() >= 800) { + tabs->tabBar()->setFixedWidth(width() + 61); + } else { + tabs->tabBar()->setMinimumWidth(0); + tabs->tabBar()->setExpanding(true); + tabs->tabBar()->setUsesScrollButtons(true); + } - -void qDetectorMain::resizeEvent(QResizeEvent* event){ - if(!dockWidgetPlot->isFloating()){ - if(tabs->currentIndex()== Actions){ - dockWidgetPlot->setMinimumHeight(heightPlotWindow-100); - centralwidget->setMaximumHeight(QWIDGETSIZE_MAX); - - } - else{ - dockWidgetPlot->setMinimumHeight(height()-centralwidget->height()-50); - centralwidget->setMaximumHeight(heightCentralWidget); - } - } - - //adjusting tab width - if(width()>=800){ tabs->tabBar()->setFixedWidth(width()+61);} - else { tabs->tabBar()->setMinimumWidth(0); - tabs->tabBar()->setExpanding(true); - tabs->tabBar()->setUsesScrollButtons(true); - } - - event->accept(); + event->accept(); } +void qDetectorMain::EnableTabs() { + FILE_LOG(logDEBUG1) << "Entering EnableTabs function"; -//------------------------------------------------------------------------------------------------------------------------------------------------- + bool enable; + enable = !(tabs->isTabEnabled(DATAOUTPUT)); + // or use the Enable/Disable button + // normal tabs + tabs->setTabEnabled(DATAOUTPUT, enable); + tabs->setTabEnabled(SETTINGS, enable); + tabs->setTabEnabled(MESSAGES, enable); -void qDetectorMain::EnableTabs(){ -#ifdef VERBOSE - cout << "Entering EnableTabs function" << endl; -#endif + // actions check + actionOpenSetup->setEnabled(enable); + actionSaveSetup->setEnabled(enable); + actionOpenConfiguration->setEnabled(enable); + actionSaveConfiguration->setEnabled(enable); + actionMeasurementWizard->setEnabled(enable); + actionDebug->setEnabled(enable); + actionExpert->setEnabled(enable); + // special tabs + tabs->setTabEnabled(DEBUGGING, enable && (actionDebug->isChecked())); + tabs->setTabEnabled(DEVELOPER, enable && isDeveloper); + // expert + bool expertTab = enable && (actionExpert->isChecked()); + tabs->setTabEnabled(ADVANCED, expertTab); + actionLoadTrimbits->setVisible(expertTab); + actionSaveTrimbits->setVisible(expertTab); - bool enable; - enable=!(tabs->isTabEnabled(DataOutput)); + // moved to here, so that its all in order, instead of signals and different + // threads + if (!enable) { + // tabMeasurement->Refresh(); too slow to refresh + tabSettings->Refresh(); + tabDataOutput->Refresh(); + if (tabAdvanced->isEnabled()) + tabAdvanced->Refresh(); + if (tabDebugging->isEnabled()) + tabDebugging->Refresh(); + if (tabDeveloper->isEnabled()) + tabDeveloper->Refresh(); + tabPlot->Refresh(); - // or use the Enable/Disable button - // normal tabs - tabs->setTabEnabled(DataOutput,enable); - tabs->setTabEnabled(Actions,enable); - tabs->setTabEnabled(Settings,enable); - tabs->setTabEnabled(Messages,enable); - - //actions check - actionOpenSetup->setEnabled(enable); - actionSaveSetup->setEnabled(enable); - actionOpenConfiguration->setEnabled(enable); - actionSaveConfiguration->setEnabled(enable); - actionMeasurementWizard->setEnabled(enable); - actionDebug->setEnabled(enable); - actionExpert->setEnabled(enable); - - - // special tabs - tabs->setTabEnabled(Debugging,enable && (actionDebug->isChecked())); - tabs->setTabEnabled(Developer,enable && isDeveloper); - //expert - bool expertTab = enable && (actionExpert->isChecked()); - tabs->setTabEnabled(Advanced,expertTab); - actionLoadTrimbits->setVisible(expertTab); - actionSaveTrimbits->setVisible(expertTab); - actionLoadCalibration->setVisible(expertTab); - actionSaveCalibration->setVisible(expertTab); - - - //moved to here, so that its all in order, instead of signals and different threads - if(!enable) { - myDet->setOnline(slsDetectorDefs::ONLINE_FLAG); - myDet->setReceiverOnline(slsDetectorDefs::ONLINE_FLAG); - qDefs::checkErrorMessage(myDet,"qDetectorMain::EnableTabs"); - //refresh all the required tabs - tab_actions->Refresh();// angular, positions, - - //too slow to refresh - /*tab_measurement->Refresh();*/ - - tab_settings->Refresh(); - tab_dataoutput->Refresh(); - if(tab_advanced->isEnabled()) tab_advanced->Refresh(); - if(tab_debugging->isEnabled()) tab_debugging->Refresh(); - if(tab_developer->isEnabled()) tab_developer->Refresh(); - - tab_plot->Refresh(); - - //stop the adc timer in gotthard - if(isDeveloper) - tab_developer->StopADCTimer(); - //set the plot type first(acccss shared memory) - tab_plot->SetScanArgument(); - //sets running to true - myPlot->StartStopDaqToggle(); - } - else{//to enable scan box - tab_plot->Refresh(); - //to start adc timer - if(tab_developer->isEnabled()) - tab_developer->Refresh(); - } + // set the plot type first(acccss shared memory) + tabPlot->SetScanArgument(); + // sets running to true + myPlot->StartStopDaqToggle(); + } else { // to enable scan box + tabPlot->Refresh(); + // to start adc timer + if (tabDeveloper->isEnabled()) + tabDeveloper->Refresh(); + } } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qDetectorMain::SetZoomToolTip(bool disable){ - if(disable) - dockWidgetPlot->setToolTip("To Enable mouse-controlled zooming capabilities,\ndisable min and max for all axes. "); - else - dockWidgetPlot->setToolTip(zoomToolTip); +void qDetectorMain::SetZoomToolTip(bool disable) { + if (disable) + dockWidgetPlot->setToolTip( + "To Enable mouse-controlled " + "zooming capabilities,\ndisable min and max for all axes. "); + else + dockWidgetPlot->setToolTip(zoomToolTip); } +int qDetectorMain::StartStopAcquisitionFromClient(bool start) { + FILE_LOG(logINFO) << (start ? "Start" : "Stop") + << " Acquisition From Clien"; -//------------------------------------------------------------------------------------------------------------------------------------------------- + if (tabMeasurement->GetStartStatus() != start) { + tabMeasurement->ClickStartStop(); + while (myPlot->GetClientInitiated()) + ; + } - -int qDetectorMain::StartStopAcquisitionFromClient(bool start){ -#ifdef VERBOSE - cout << "Start/Stop Acquisition From Client:" << start << endl; -#endif - - if (tab_measurement->GetStartStatus() != start){ - if(start){ - if(!myPlot->isRunning()){ - //refresh all the required tabs - all these are done in button click anyway - /* tab_actions->Refresh(); - //too slow to refresh - //tab_measurement->Refresh(); - tab_settings->Refresh(); - tab_dataoutput->Refresh(); - if(tab_advanced->isEnabled()) tab_advanced->Refresh(); - if(tab_debugging->isEnabled()) tab_debugging->Refresh(); - if(tab_developer->isEnabled()) tab_developer->Refresh(); - - tab_plot->Refresh();*/ - } - } - //click start/stop - tab_measurement->ClickStartStop(); - while(myPlot->GetClientInitiated()); - } - - return slsDetectorDefs::OK; + return slsDetectorDefs::OK; } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qDetectorMain::UncheckServer(){ -#ifdef VERBOSE - cout << "Unchecking Mode : Listen to Gui Client" << endl; -#endif - disconnect(menuModes, SIGNAL(triggered(QAction*)), this,SLOT(EnableModes(QAction*))); - actionListenGuiClient->setChecked(false); - connect(menuModes, SIGNAL(triggered(QAction*)), this,SLOT(EnableModes(QAction*))); +void qDetectorMain::UncheckServer() { + actionListenGuiClient->setChecked(false); } - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -bool qDetectorMain::isCurrentlyTabDeveloper(){ - return (tabs->currentIndex()==Developer); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/slsDetectorGui/src/qDrawPlot.cpp b/slsDetectorGui/src/qDrawPlot.cpp old mode 100644 new mode 100755 index 87492eeea..5ba504819 --- a/slsDetectorGui/src/qDrawPlot.cpp +++ b/slsDetectorGui/src/qDrawPlot.cpp @@ -1,30 +1,24 @@ -/* - * qDrawPlot.cpp - * - * Created on: May 7, 2012 - * Author: Dhanya Maliakal - */ // Qt Project Class Headers #include "qDrawPlot.h" #include "qCloneWidget.h" #include "slsDetector.h" -#include"fileIOStatic.h" + // Project Class Headers -#include "slsDetector.h" #include "multiSlsDetector.h" -#include "postProcessing.h" +#include "slsDetector.h" +// #include "postProcessing.h" // Qt Include Headers +#include #include #include #include -#include //#include "qwt_double_interval.h" #include "qwt_series_data.h" // C++ Include Headers +#include #include -#include #include -using namespace std; +#include @@ -32,392 +26,390 @@ using namespace std; const double qDrawPlot::PLOT_TIMER_MS = DEFAULT_STREAMING_TIMER_IN_MS; -qDrawPlot::qDrawPlot(QWidget *parent,multiSlsDetector*& detector): - QWidget(parent),myDet(detector),plot1D_hists(0){ - SetupWidgetWindow(); - Initialization(); - StartStopDaqToggle(); //as default +qDrawPlot::qDrawPlot(QWidget *parent, multiSlsDetector *detector) : QWidget(parent), myDet(detector), plot1D_hists(0) { + SetupWidgetWindow(); + Initialization(); + StartStopDaqToggle(); //as default } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -qDrawPlot::~qDrawPlot(){ - // Clear plot - Clear1DPlot(); - for(QVector::iterator h = plot1D_hists.begin();h!=plot1D_hists.end();h++) delete *h; - plot1D_hists.clear(); - if(lastImageArray) delete[] lastImageArray; lastImageArray=0; - if(gainImageArray) delete[] gainImageArray; gainImageArray=0; - StartOrStopThread(0); - delete myDet; myDet = 0; - for(int i=0;i::iterator h = plot1D_hists.begin(); h != plot1D_hists.end(); ++h) + delete *h; + plot1D_hists.clear(); + if (lastImageArray) + delete[] lastImageArray; + lastImageArray = 0; + if (gainImageArray) + delete[] gainImageArray; + gainImageArray = 0; + StartOrStopThread(0); + delete myDet; + myDet = 0; + for (int i = 0; i < MAXCloneWindows; ++i) + if (winClone[i]) { + delete winClone[i]; + winClone[i] = NULL; + } } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::SetupWidgetWindow(){ +void qDrawPlot::SetupWidgetWindow() { #ifdef VERBOSE - cout << "Setting up plot variables" << endl; + std::cout << "Setting up plot variables\n"; #endif - // Depending on whether the detector is 1d or 2d - detType = myDet->getDetectorsType(); - switch(detType){ - case slsDetectorDefs::MYTHEN: - case slsDetectorDefs::GOTTHARD: - originally2D = false; - break; - case slsDetectorDefs::EIGER: - case slsDetectorDefs::PROPIX: - case slsDetectorDefs::MOENCH: - case slsDetectorDefs::JUNGFRAU: - case slsDetectorDefs::JUNGFRAUCTB: - originally2D = true; - break; - default: - cout << "ERROR: Detector Type is Generic" << endl; - exit(-1); - } + // Depending on whether the detector is 1d or 2d + detType = myDet->getDetectorTypeAsEnum(); + switch (detType) { + case slsDetectorDefs::GOTTHARD: + originally2D = false; + break; + case slsDetectorDefs::EIGER: + case slsDetectorDefs::MOENCH: + case slsDetectorDefs::JUNGFRAU: + originally2D = true; + break; + default: + std::cout << "ERROR: Detector Type is Generic\n"; + exit(-1); + } + //initialization + data_pause_over = true; -//initialization - data_pause_over = true; + currentMeasurement = 0; + currentFrame = 0; + numFactor = 0; + currentScanDivLevel = 0; + currentScanValue = 0; + number_of_exposures = 0; + number_of_frames = 0; + acquisitionPeriod = 0; + exposureTime = 0; + currentFileIndex = 0; + currentFrameIndex = 0; - currentMeasurement = 0; - currentFrame = 0; - numFactor = 0; - currentScanDivLevel = 0; - currentScanValue = 0; - number_of_exposures = 0; - number_of_frames = 0; - acquisitionPeriod = 0; - exposureTime = 0; - currentFileIndex = 0; - currentFrameIndex = 0; + stop_signal = 0; + pthread_mutex_init(&last_image_complete_mutex, NULL); - stop_signal = 0; - pthread_mutex_init(&last_image_complete_mutex,NULL); + // Default titles- only for the initial picture + imageXAxisTitle = "Pixel"; + imageYAxisTitle = "Pixel"; + imageZAxisTitle = "Intensity"; + histXAxisTitle = "Channel Number"; + histYAxisTitle = "Counts"; + for (int i = 0; i < MAX_1DPLOTS; ++i) { + histTitle[i] = ""; + //char temp_title[2000]; + //sprintf(temp_title,"Frame -%d",i); + //histTitle[i] = temp_title; + } + imageTitle = ""; + plotTitle = ""; + plotTitle_prefix = ""; + plot_in_scope = 0; - // Default titles- only for the initial picture - imageXAxisTitle="Pixel"; - imageYAxisTitle="Pixel"; - imageZAxisTitle="Intensity"; - histXAxisTitle="Channel Number"; - histYAxisTitle="Counts"; - for(int i=0;igetTotalNumberOfChannelsInclGapPixels(slsDetectorDefs::X); + nPixelsY = myDet->getTotalNumberOfChannelsInclGapPixels(slsDetectorDefs::Y); + if (detType == slsDetectorDefs::MOENCH) { + npixelsy_jctb = (myDet->setTimer(slsDetectorDefs::SAMPLES, -1) * 2) / 25; // for moench 03 + nPixelsX = npixelsx_jctb; + nPixelsY = npixelsy_jctb; + } - nPixelsX = myDet->getTotalNumberOfChannelsInclGapPixels(slsDetectorDefs::X); - nPixelsY = myDet->getTotalNumberOfChannelsInclGapPixels(slsDetectorDefs::Y); - if (detType == slsDetectorDefs::JUNGFRAUCTB) { - npixelsy_jctb = (myDet->setTimer(slsDetectorDefs::SAMPLES_JCTB, -1) * 2)/25;// for moench 03 - nPixelsX = npixelsx_jctb; - nPixelsY = npixelsy_jctb; - } + std::cout << "nPixelsX:" << nPixelsX << '\n'; + std::cout << "nPixelsY:" << nPixelsY << '\n'; - cout<<"nPixelsX:"<setStyle(QwtSymbol::Cross); + marker->setSize(5, 5); + noMarker = new QwtSymbol(); - //marker - lines = true; - markers = false; - marker = new QwtSymbol(); - marker->setStyle(QwtSymbol::Cross); - marker->setSize(5,5); - noMarker = new QwtSymbol(); + //for save automatically, + saveAll = false; + saveError = false; + lastSavedFrame = -1; + lastSavedMeasurement = -1; - //for save automatically, - saveAll = false; - saveError = false; - lastSavedFrame = -1; - lastSavedMeasurement = -1; + // This is so that it initially stop and plots + running = 1; - // This is so that it initially stop and plots - running = 1; + XYRangeChanged = false; + XYRangeValues[0] = 0; + XYRangeValues[1] = 0; + XYRangeValues[2] = 0; + XYRangeValues[3] = 0; + IsXYRange[0] = false; + IsXYRange[1] = false; + IsXYRange[2] = false; + IsXYRange[3] = false; - XYRangeChanged = false; - XYRangeValues[0] = 0; - XYRangeValues[1] = 0; - XYRangeValues[2] = 0; - XYRangeValues[3] = 0; - IsXYRange[0] = false; - IsXYRange[1] = false; - IsXYRange[2] = false; - IsXYRange[3] = false; + timerValue = PLOT_TIMER_MS; + frameFactor = 0; + isFrameEnabled = false; + isTriggerEnabled = false; - timerValue = PLOT_TIMER_MS; - frameFactor=0; - isFrameEnabled = false; - isTriggerEnabled = false; + scanArgument = qDefs::None; + histogramArgument = qDefs::Intensity; + anglePlot = false; + alreadyDisplayed = false; - scanArgument = qDefs::None; - histogramArgument = qDefs::Intensity; - anglePlot = false; - alreadyDisplayed = false; + //filepath and file name + filePath = QString(myDet->getFilePath().c_str()); + fileName = QString(myDet->getFileName().c_str()); - //filepath and file name - filePath = QString(myDet->getFilePath().c_str()); - fileName = QString(myDet->getFileName().c_str()); + backwardScanPlot = false; + fileSaveEnable = myDet->enableWriteToFile(); - backwardScanPlot = false; - fileSaveEnable= myDet->enableWriteToFile(); + //pedestal + pedestal = false; + pedestalVals = 0; + tempPedestalVals = 0; + pedestalCount = 0; + startPedestalCal = false; - //pedestal - pedestal = false; - pedestalVals = 0; - tempPedestalVals = 0; - pedestalCount = 0; - startPedestalCal = false; + //accumulate + accumulate = false; + resetAccumulate = false; - //accumulate - accumulate = false; - resetAccumulate = false; + clientInitiated = false; - clientInitiated = false; + //binary plot output + binary = false; + binaryFrom = 0; + binaryTo = 0; - //binary plot output - binary = false; - binaryFrom = 0; - binaryTo = 0; - - //histogram - histogram = false; - histFrom = 0; - histTo = 0; - histSize = 0; - /* + //histogram + histogram = false; + histFrom = 0; + histTo = 0; + histSize = 0; + /* grid = new QwtPlotGrid; grid->enableXMin(true); grid->enableYMin(true); grid->setMajPen(QPen(Qt::black, 0, Qt::DotLine)); grid->setMinPen(QPen(Qt::gray, 0 , Qt::DotLine)); */ - plotHistogram = new QwtPlotHistogram(); - plotHistogram->setStyle(QwtPlotHistogram::Columns);//Options:Outline,Columns, Lines + plotHistogram = new QwtPlotHistogram(); + plotHistogram->setStyle(QwtPlotHistogram::Columns); //Options:Outline,Columns, Lines + plotRequired = false; - plotRequired = false; + //widget related initialization -//widget related initialization + // clone + for (int i = 0; i < MAXCloneWindows; ++i) + winClone[i] = 0; - // clone - for(int i=0;isetLayout(layout); - // Setting up window - setFont(QFont("Sans Serif",9)); - layout = new QGridLayout; - this->setLayout(layout); + histFrameIndexTitle = new QLabel(""); + histFrameIndexTitle->setFixedHeight(10); + boxPlot = new QGroupBox(""); + layout->addWidget(boxPlot, 1, 0); + boxPlot->setAlignment(Qt::AlignHCenter); + boxPlot->setFont(QFont("Sans Serif", 11, QFont::Normal)); + boxPlot->setTitle("Sample Plot"); + data_pause_timer = new QTimer(this); + connect(data_pause_timer, SIGNAL(timeout()), this, SLOT(UpdatePause())); - histFrameIndexTitle = new QLabel(""); - histFrameIndexTitle->setFixedHeight(10); - boxPlot = new QGroupBox(""); - layout->addWidget(boxPlot,1,0); - boxPlot->setAlignment(Qt::AlignHCenter); - boxPlot->setFont(QFont("Sans Serif",11,QFont::Normal)); - boxPlot->setTitle("Sample Plot"); - data_pause_timer = new QTimer(this); - connect(data_pause_timer, SIGNAL(timeout()), this, SLOT(UpdatePause())); + //display statistics + displayStatistics = false; + widgetStatistics = new QWidget(this); + widgetStatistics->setFixedHeight(15); + QHBoxLayout *hl1 = new QHBoxLayout; + hl1->setSpacing(0); + hl1->setContentsMargins(0, 0, 0, 0); + QLabel *lblMin = new QLabel("Min: "); + lblMin->setFixedWidth(40); + lblMin->setAlignment(Qt::AlignRight); + QLabel *lblMax = new QLabel("Max: "); + lblMax->setFixedWidth(40); + lblMax->setAlignment(Qt::AlignRight); + QLabel *lblSum = new QLabel("Sum: "); + lblSum->setFixedWidth(40); + lblSum->setAlignment(Qt::AlignRight); + lblMinDisp = new QLabel("-"); + lblMinDisp->setAlignment(Qt::AlignLeft); + lblMaxDisp = new QLabel("-"); + lblMaxDisp->setAlignment(Qt::AlignLeft); + lblSumDisp = new QLabel("-"); + lblSumDisp->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); + lblSumDisp->setAlignment(Qt::AlignLeft); + hl1->addItem(new QSpacerItem(20, 20, QSizePolicy::Fixed, QSizePolicy::Fixed)); + hl1->addWidget(lblMin); + hl1->addWidget(lblMinDisp); + hl1->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Fixed)); + hl1->addWidget(lblMax); + hl1->addWidget(lblMaxDisp); + hl1->addItem(new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Fixed)); + hl1->addWidget(lblSum); + hl1->addWidget(lblSumDisp); + hl1->addItem(new QSpacerItem(20, 20, QSizePolicy::Fixed, QSizePolicy::Fixed)); + widgetStatistics->setLayout(hl1); + layout->addWidget(widgetStatistics, 2, 0); + widgetStatistics->hide(); + // setting default plot titles and settings + plot1D = new SlsQt1DPlot(boxPlot); - //display statistics - displayStatistics = false; - widgetStatistics = new QWidget(this); - widgetStatistics->setFixedHeight(15); - QHBoxLayout *hl1 = new QHBoxLayout; - hl1->setSpacing(0); - hl1->setContentsMargins(0, 0, 0, 0); - QLabel *lblMin = new QLabel("Min: "); - lblMin->setFixedWidth(40); - lblMin->setAlignment(Qt::AlignRight); - QLabel *lblMax = new QLabel("Max: "); - lblMax->setFixedWidth(40); - lblMax->setAlignment(Qt::AlignRight); - QLabel *lblSum = new QLabel("Sum: "); - lblSum->setFixedWidth(40); - lblSum->setAlignment(Qt::AlignRight); - lblMinDisp = new QLabel("-"); - lblMinDisp->setAlignment(Qt::AlignLeft); - lblMaxDisp = new QLabel("-"); - lblMaxDisp->setAlignment(Qt::AlignLeft); - lblSumDisp = new QLabel("-"); - lblSumDisp->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed); - lblSumDisp->setAlignment(Qt::AlignLeft); - hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - hl1->addWidget(lblMin); - hl1->addWidget(lblMinDisp); - hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Expanding,QSizePolicy::Fixed)); - hl1->addWidget(lblMax); - hl1->addWidget(lblMaxDisp); - hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Expanding,QSizePolicy::Fixed)); - hl1->addWidget(lblSum); - hl1->addWidget(lblSumDisp); - hl1->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - widgetStatistics->setLayout(hl1); - layout->addWidget(widgetStatistics,2,0); - widgetStatistics->hide(); + plot1D->setFont(QFont("Sans Serif", 9, QFont::Normal)); + plot1D->SetXTitle(histXAxisTitle.toAscii().constData()); + plot1D->SetYTitle(histYAxisTitle.toAscii().constData()); + plot1D->hide(); + SlsQtH1D *h; + histNBins = nPixelsX; + nHists = 1; + if (histXAxis) + delete[] histXAxis; + histXAxis = new double[nPixelsX]; + if (histYAxis[0]) + delete[] histYAxis[0]; + histYAxis[0] = new double[nPixelsX]; + for (unsigned int px = 0; px < nPixelsX; ++px) { + histXAxis[px] = px; + histYAxis[0][px] = 0; + } + Clear1DPlot(); + plot1D->SetXTitle("X Axis"); + plot1D->SetYTitle("Y Axis"); + plot1D_hists.append(h = new SlsQtH1D("", histNBins, histXAxis, histYAxis[0])); + h->SetLineColor(0); + SetStyle(h); + h->Attach(plot1D); + Clear1DPlot(); - // setting default plot titles and settings - plot1D = new SlsQt1DPlot(boxPlot); + plot2D = new SlsQt2DPlotLayout(boxPlot); + //default plot + lastImageArray = new double[nPixelsY * nPixelsX]; + for (unsigned int px = 0; px < nPixelsX; ++px) + for (unsigned int py = 0; py < nPixelsY; ++py) + lastImageArray[py * nPixelsX + px] = sqrt(pow(0 + 1, 2) * pow(double(px) - nPixelsX / 2, 2) / pow(nPixelsX / 2, 2) / pow(1 + 1, 2) + pow(double(py) - nPixelsY / 2, 2) / pow(nPixelsY / 2, 2)) / sqrt(2); + plot2D->setFont(QFont("Sans Serif", 9, QFont::Normal)); + plot2D->GetPlot()->SetData(nPixelsX, -0.5, nPixelsX - 0.5, nPixelsY, startPixel, endPixel, lastImageArray); + plot2D->setTitle(GetImageTitle()); + plot2D->SetXTitle(imageXAxisTitle); + plot2D->SetYTitle(imageYAxisTitle); + plot2D->SetZTitle(imageZAxisTitle); + plot2D->setAlignment(Qt::AlignLeft); + boxPlot->setFlat(true); + boxPlot->setContentsMargins(0, 15, 0, 0); - plot1D->setFont(QFont("Sans Serif",9,QFont::Normal)); - plot1D->SetXTitle(histXAxisTitle.toAscii().constData()); - plot1D->SetYTitle(histYAxisTitle.toAscii().constData()); - plot1D->hide(); + plotLayout = new QGridLayout(boxPlot); + plotLayout->setContentsMargins(0, 0, 0, 0); + plotLayout->addWidget(plot1D, 0, 0, 4, 4); + plotLayout->addWidget(plot2D, 0, 0, 4, 4); - SlsQtH1D* h; - histNBins = nPixelsX; - nHists = 1; - if(histXAxis) delete [] histXAxis; histXAxis = new double [nPixelsX]; - if(histYAxis[0]) delete [] histYAxis[0];histYAxis[0] = new double [nPixelsX]; - for(unsigned int px=0;pxSetXTitle("X Axis"); - plot1D->SetYTitle("Y Axis"); - plot1D_hists.append(h=new SlsQtH1D("",histNBins,histXAxis,histYAxis[0])); - h->SetLineColor(0); - SetStyle(h); - h->Attach(plot1D); - Clear1DPlot(); + //gainplot + gainplot2D = new SlsQt2DPlotLayout(boxPlot); + gainImageArray = new double[nPixelsY * nPixelsX]; + for (unsigned int px = 0; px < nPixelsX; ++px) + for (unsigned int py = 0; py < nPixelsY; ++py) + gainImageArray[py * nPixelsX + px] = sqrt(pow(0 + 1, 2) * pow(double(px) - nPixelsX / 2, 2) / pow(nPixelsX / 2, 2) / pow(1 + 1, 2) + pow(double(py) - nPixelsY / 2, 2) / pow(nPixelsY / 2, 2)) / sqrt(2); + gainplot2D->setFont(QFont("Sans Serif", 9, QFont::Normal)); + gainplot2D->GetPlot()->SetData(nPixelsX, -0.5, nPixelsX - 0.5, nPixelsY, startPixel, endPixel, gainImageArray); + gainplot2D->setTitle(GetImageTitle()); + gainplot2D->setAlignment(Qt::AlignLeft); + gainplot2D->GetPlot()->enableAxis(0, false); + gainplot2D->GetPlot()->enableAxis(1, false); + gainplot2D->GetPlot()->enableAxis(2, false); + plotLayout->addWidget(gainplot2D, 0, 4, 1, 1); + gainplot2D->hide(); + gainPlotEnable = false; + gainDataEnable = false; - plot2D = new SlsQt2DPlotLayout(boxPlot); - //default plot - lastImageArray = new double[nPixelsY*nPixelsX]; - for(unsigned int px=0;pxsetFont(QFont("Sans Serif",9,QFont::Normal)); - plot2D->GetPlot()->SetData(nPixelsX,-0.5,nPixelsX-0.5,nPixelsY,startPixel,endPixel,lastImageArray); - plot2D->setTitle(GetImageTitle()); - plot2D->SetXTitle(imageXAxisTitle); - plot2D->SetYTitle(imageYAxisTitle); - plot2D->SetZTitle(imageZAxisTitle); - plot2D->setAlignment(Qt::AlignLeft); - boxPlot->setFlat(true); - boxPlot->setContentsMargins(0,15,0,0); + // callbacks + // Setting the callback function to get data from detector class + myDet->registerDataCallback(&(GetDataCallBack), this); // also enables data streaming in client and receiver (if receiver exists) + //Setting the callback function to alert when acquisition finished from detector class + myDet->registerAcquisitionFinishedCallback(&(GetAcquisitionFinishedCallBack), this); + //Setting the callback function to alert when each measurement finished from detector class + myDet->registerMeasurementFinishedCallback(&(GetMeasurementFinishedCallBack), this); + //Setting the callback function to get progress from detector class(using receivers) + myDet->registerProgressCallback(&(GetProgressCallBack), this); - plotLayout = new QGridLayout(boxPlot); - plotLayout->setContentsMargins(0,0,0,0); - plotLayout->addWidget(plot1D,0,0,4,4); - plotLayout->addWidget(plot2D,0,0,4,4); - - - //gainplot - gainplot2D = new SlsQt2DPlotLayout(boxPlot); - gainImageArray = new double[nPixelsY*nPixelsX]; - for(unsigned int px=0;pxsetFont(QFont("Sans Serif",9,QFont::Normal)); - gainplot2D->GetPlot()->SetData(nPixelsX,-0.5,nPixelsX-0.5,nPixelsY,startPixel,endPixel,gainImageArray); - gainplot2D->setTitle(GetImageTitle()); - gainplot2D->setAlignment(Qt::AlignLeft); - gainplot2D->GetPlot()->enableAxis(0,false); - gainplot2D->GetPlot()->enableAxis(1,false); - gainplot2D->GetPlot()->enableAxis(2,false); - plotLayout->addWidget(gainplot2D,0,4,1,1); - gainplot2D->hide(); - gainPlotEnable = false; - gainDataEnable = false; - - - - // callbacks - // Setting the callback function to get data from detector class - myDet->registerDataCallback(&(GetDataCallBack),this); // also enables data streaming in client and receiver (if receiver exists) - //Setting the callback function to alert when acquisition finished from detector class - myDet->registerAcquisitionFinishedCallback(&(GetAcquisitionFinishedCallBack),this); - //Setting the callback function to alert when each measurement finished from detector class - myDet->registerMeasurementFinishedCallback(&(GetMeasurementFinishedCallBack),this); - //Setting the callback function to get progress from detector class(using receivers) - myDet->registerProgressCallback(&(GetProgressCallBack),this); - - qDefs::checkErrorMessage(myDet,"qDrawPlot::SetupWidgetWindow"); + qDefs::checkErrorMessage(myDet, "qDrawPlot::SetupWidgetWindow"); } - //------------------------------------------------------------------------------------------------------------------------------------------------- +void qDrawPlot::Initialization() { + connect(this, SIGNAL(UpdatePlotSignal()), this, SLOT(UpdatePlot())); + connect(this, SIGNAL(InterpolateSignal(bool)), plot2D, SIGNAL(InterpolateSignal(bool))); + connect(this, SIGNAL(ContourSignal(bool)), plot2D, SIGNAL(ContourSignal(bool))); + connect(this, SIGNAL(LogzSignal(bool)), plot2D, SLOT(SetZScaleToLog(bool))); + connect(this, SIGNAL(LogySignal(bool)), plot1D, SLOT(SetLogY(bool))); + connect(this, SIGNAL(ResetZMinZMaxSignal(bool, bool, double, double)), plot2D, SLOT(ResetZMinZMax(bool, bool, double, double))); -void qDrawPlot::Initialization(){ - connect(this, SIGNAL(UpdatePlotSignal()), this, SLOT(UpdatePlot())); - connect(this, SIGNAL(InterpolateSignal(bool)),plot2D, SIGNAL(InterpolateSignal(bool))); - connect(this, SIGNAL(ContourSignal(bool)), plot2D, SIGNAL(ContourSignal(bool))); - connect(this, SIGNAL(LogzSignal(bool)), plot2D, SLOT(SetZScaleToLog(bool))); - connect(this, SIGNAL(LogySignal(bool)), plot1D, SLOT(SetLogY(bool))); - connect(this, SIGNAL(ResetZMinZMaxSignal(bool,bool,double,double)),plot2D, SLOT(ResetZMinZMax(bool,bool,double,double))); + connect(this, SIGNAL(AcquisitionErrorSignal(QString)), this, SLOT(ShowAcquisitionErrorMessage(QString))); - connect(this, SIGNAL(AcquisitionErrorSignal(QString)), this, SLOT(ShowAcquisitionErrorMessage(QString))); - - - connect(this, SIGNAL(GainPlotSignal(bool)), this, SLOT(EnableGainPlot(bool))); + connect(this, SIGNAL(GainPlotSignal(bool)), this, SLOT(EnableGainPlot(bool))); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::StartStopDaqToggle(bool stop_if_running){ +void qDrawPlot::StartStopDaqToggle(bool stop_if_running) { #ifdef VERYVERBOSE - cout << "Entering StartStopDaqToggle(" << stop_if_running << ")" <setTimer(slsDetectorDefs::FRAME_NUMBER,-1)); int numTriggers = (isTriggerEnabled)*((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,-1)); numFrames = ((numFrames==0)?1:numFrames); numTriggers = ((numTriggers==0)?1:numTriggers); number_of_frames = numFrames * numTriggers; - cout << "\tNumber of Frames per Scan/Measurement:" << number_of_frames << endl; + std::cout << "\tNumber of Frames per Scan/Measurement:" << number_of_frames <<'\n'; //get #scansets for level 0 and level 1 int numScan0 = myDet->getScanSteps(0); numScan0 = ((numScan0==0)?1:numScan0); int numScan1 = myDet->getScanSteps(1); numScan1 = ((numScan1==0)?1:numScan1); @@ -425,1851 +417,1583 @@ void qDrawPlot::StartStopDaqToggle(bool stop_if_running){ number_of_exposures = number_of_frames * numScan0 * numScan1; if(anglePlot) number_of_exposures = numScan0 * numScan1;// * numPos; - cout << "\tNumber of Exposures Per Measurement:" << number_of_exposures << endl; + std::cout << "\tNumber of Exposures Per Measurement:" << number_of_exposures <<'\n'; */ - // ExposureTime - exposureTime= ((double)(myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME,-1))*1E-9); - cout << "\tExposure Time:" << setprecision (10) << exposureTime << endl; - // Acquisition Period - acquisitionPeriod= ((double)(myDet->setTimer(slsDetectorDefs::FRAME_PERIOD,-1))*1E-9); - cout << "\tAcquisition Period:" << setprecision (10) << acquisitionPeriod << endl; - cout << "\tFile Index:" << myDet->getFileIndex() << endl; - //to take the first data if frameFactor - numFactor = 0; + // ExposureTime + exposureTime = ((double)(myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME, -1)) * 1E-9); + std::cout << "\tExposure Time:" << std::setprecision(10) << exposureTime << '\n'; + // Acquisition Period + acquisitionPeriod = ((double)(myDet->setTimer(slsDetectorDefs::FRAME_PERIOD, -1)) * 1E-9); + std::cout << "\tAcquisition Period:" << std::setprecision(10) << acquisitionPeriod << '\n'; + std::cout << "\tFile Index:" << myDet->getFileIndex() << '\n'; + //to take the first data if frameFactor + numFactor = 0; - //for save automatically, - saveError = false; - lastSavedFrame = -1; - lastSavedMeasurement = -1; + //for save automatically, + saveError = false; + lastSavedFrame = -1; + lastSavedMeasurement = -1; - //update file path and file name - filePath = QString(myDet->getFilePath().c_str()); - fileName = QString(myDet->getFileName().c_str()); - //update index - currentFileIndex = myDet->getFileIndex(); - currentFrameIndex = 0; + //update file path and file name + filePath = QString(myDet->getFilePath().c_str()); + fileName = QString(myDet->getFileName().c_str()); + //update index + currentFileIndex = myDet->getFileIndex(); + currentFrameIndex = 0; - StartDaq(true); - running=!running; + StartDaq(true); + running = !running; - qDefs::checkErrorMessage(myDet,"qDrawPlot::StartStopDaqToggle"); - } - - /** if this is set during client initation */ - clientInitiated = false; + qDefs::checkErrorMessage(myDet, "qDrawPlot::StartStopDaqToggle"); + } + /** if this is set during client initation */ + clientInitiated = false; } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::StartDaq(bool start){ - if(start){ +void qDrawPlot::StartDaq(bool start) { + if (start) { #ifdef VERBOSE - cout << "Start Daq(true) function" << endl; + std::cout << "Start Daq(true) function" << '\n'; #endif - ResetDaqForGui(); - StartDaqForGui(); - }else{ + ResetDaqForGui(); + StartDaqForGui(); + } else { #ifdef VERBOSE - cout << "Start Daq(false) function" << endl; + std::cout << "Start Daq(false) function" << '\n'; #endif - StopDaqForGui(); - } + StopDaqForGui(); + } } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -int qDrawPlot::ResetDaqForGui(){ - if(!StopDaqForGui()) return 0; - cout << "Resetting image number" << endl; - lastImageNumber = 0; - return 1; +int qDrawPlot::ResetDaqForGui() { + if (!StopDaqForGui()) + return 0; + std::cout << "Resetting image number" << '\n'; + lastImageNumber = 0; + return 1; } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -bool qDrawPlot::StartOrStopThread(bool start){ +bool qDrawPlot::StartOrStopThread(bool start) { #ifdef VERYVERBOSE - cout << "StartOrStopThread:" << start << endl; + std::cout << "StartOrStopThread:" << start << '\n'; #endif - static bool firstTime = true; - static bool gui_acquisition_thread_running = 0; - static pthread_t gui_acquisition_thread; - static pthread_mutex_t gui_acquisition_start_stop_mutex = PTHREAD_MUTEX_INITIALIZER; + static bool firstTime = true; + static bool gui_acquisition_thread_running = 0; + static pthread_t gui_acquisition_thread; + static pthread_mutex_t gui_acquisition_start_stop_mutex = PTHREAD_MUTEX_INITIALIZER; - pthread_mutex_lock(&gui_acquisition_start_stop_mutex); - //stop part, before start or restart - if(gui_acquisition_thread_running){ - cout << "Stopping current acquisition thread ...." << endl; - stop_signal = 1;//sorta useless right now - gui_acquisition_thread_running = 0; - } + pthread_mutex_lock(&gui_acquisition_start_stop_mutex); + //stop part, before start or restart + if (gui_acquisition_thread_running) { + std::cout << "Stopping current acquisition thread ...." << '\n'; + stop_signal = 1; //sorta useless right now + gui_acquisition_thread_running = 0; + } - //start part - if(start){ - progress = 0; - //sets up the measurement parameters - SetupMeasurement(); + //start part + if (start) { + progress = 0; + //sets up the measurement parameters + SetupMeasurement(); - //refixing all the zooming - plot2D->GetPlot()->SetXMinMax(-0.5,nPixelsX+0.5); - plot2D->GetPlot()->SetYMinMax(startPixel,endPixel); - plot2D->GetPlot()->SetZoom(-0.5,startPixel,nPixelsX,endPixel-startPixel); - if (boxPlot->title() == "Sample Plot") - plot2D->GetPlot()->UnZoom(); - else - plot2D->GetPlot()->UnZoom(false); - /*XYRangeChanged = true;*/ - boxPlot->setTitle("Old_Plot.raw"); + //refixing all the zooming + plot2D->GetPlot()->SetXMinMax(-0.5, nPixelsX + 0.5); + plot2D->GetPlot()->SetYMinMax(startPixel, endPixel); + plot2D->GetPlot()->SetZoom(-0.5, startPixel, nPixelsX, endPixel - startPixel); + if (boxPlot->title() == "Sample Plot") + plot2D->GetPlot()->UnZoom(); + else + plot2D->GetPlot()->UnZoom(false); + /*XYRangeChanged = true;*/ + boxPlot->setTitle("Old_Plot.raw"); - cprintf(BLUE, "Starting new acquisition thread ....\n"); - // Start acquiring data from server - if(!firstTime) pthread_join(gui_acquisition_thread,NULL);//wait until he's finished, ie. exits - pthread_create(&gui_acquisition_thread, NULL,DataStartAcquireThread, (void*) this); - // This is set here and later reset to zero when all the plotting is done - // This is manually done instead of keeping track of thread because - // this thread returns immediately after executing the acquire command - gui_acquisition_thread_running=1; + cprintf(BLUE, "Starting new acquisition thread ....\n"); + // Start acquiring data from server + if (!firstTime) + pthread_join(gui_acquisition_thread, NULL); //wait until he's finished, ie. exits + pthread_create(&gui_acquisition_thread, NULL, DataStartAcquireThread, (void *)this); + // This is set here and later reset to zero when all the plotting is done + // This is manually done instead of keeping track of thread because + // this thread returns immediately after executing the acquire command + gui_acquisition_thread_running = 1; #ifdef VERYVERBOSE - cout << "Started acquiring thread" << endl; + std::cout << "Started acquiring thread" << '\n'; #endif - } - pthread_mutex_unlock(&gui_acquisition_start_stop_mutex); - return gui_acquisition_thread_running; + } + pthread_mutex_unlock(&gui_acquisition_start_stop_mutex); + return gui_acquisition_thread_running; } - //------------------------------------------------------------------------------------------------------------------------------------------------- +// void qDrawPlot::SetScanArgument(int scanArg){ +// #ifdef VERYVERBOSE +// std::cout << "SetScanArgument function:" << scanArg << " running:" << running <<'\n'; +// #endif +// scanArgument = scanArg; -void qDrawPlot::SetScanArgument(int scanArg){ -#ifdef VERYVERBOSE - cout << "SetScanArgument function:" << scanArg << " running:" << running << endl; -#endif - scanArgument = scanArg; +// LockLastImageArray(); - LockLastImageArray(); +// if(plot_in_scope==1) Clear1DPlot(); - if(plot_in_scope==1) Clear1DPlot(); +// // Number of Exposures - must be calculated here to get npixelsy for allframes/frameindex scans +// int numFrames = (isFrameEnabled)*((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,-1)); +// int numTriggers = (isTriggerEnabled)*((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,-1)); +// int numStoragecells = 0; +// if (detType == slsDetectorDefs::JUNGFRAU) +// numStoragecells = (int)myDet->setTimer(slsDetectorDefs::STORAGE_CELL_NUMBER, -1); +// numFrames = ((numFrames==0)?1:numFrames); +// numTriggers = ((numTriggers==0)?1:numTriggers); +// numStoragecells = ((numStoragecells<=0)?1:numStoragecells+1); +// number_of_frames = numFrames * numTriggers * numStoragecells; +// std::cout << "\tNumber of Frames per Scan/Measurement:" << number_of_frames <<'\n'; +// //get #scansets for level 0 and level 1 +// int numScan0 = myDet->getScanSteps(0); numScan0 = ((numScan0==0)?1:numScan0); +// int numScan1 = myDet->getScanSteps(1); numScan1 = ((numScan1==0)?1:numScan1); +// //int numPos=myDet->getPositions(); +// number_of_exposures = number_of_frames * numScan0 * numScan1; +// if(anglePlot) number_of_exposures = numScan0 * numScan1;// * numPos; +// std::cout << "\tNumber of Exposures Per Measurement:" << number_of_exposures <<'\n'; - // Number of Exposures - must be calculated here to get npixelsy for allframes/frameindex scans - int numFrames = (isFrameEnabled)*((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,-1)); - int numTriggers = (isTriggerEnabled)*((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,-1)); - int numStoragecells = 0; - if (detType == slsDetectorDefs::JUNGFRAU) - numStoragecells = (int)myDet->setTimer(slsDetectorDefs::STORAGE_CELL_NUMBER, -1); - numFrames = ((numFrames==0)?1:numFrames); - numTriggers = ((numTriggers==0)?1:numTriggers); - numStoragecells = ((numStoragecells<=0)?1:numStoragecells+1); - number_of_frames = numFrames * numTriggers * numStoragecells; - cout << "\tNumber of Frames per Scan/Measurement:" << number_of_frames << endl; - //get #scansets for level 0 and level 1 - int numScan0 = myDet->getScanSteps(0); numScan0 = ((numScan0==0)?1:numScan0); - int numScan1 = myDet->getScanSteps(1); numScan1 = ((numScan1==0)?1:numScan1); - //int numPos=myDet->getPositions(); +// maxPixelsY = 0; +// minPixelsY = 0; +// nPixelsX = myDet->getTotalNumberOfChannelsInclGapPixels(slsDetectorDefs::X); +// nPixelsY = myDet->getTotalNumberOfChannelsInclGapPixels(slsDetectorDefs::Y); +// if (detType == slsDetectorDefs::MOENCH) { +// npixelsy_jctb = (myDet->setTimer(slsDetectorDefs::SAMPLES, -1) * 2)/25; // for moench 03 +// nPixelsX = npixelsx_jctb; +// nPixelsY = npixelsy_jctb; +// } - number_of_exposures = number_of_frames * numScan0 * numScan1; - if(anglePlot) number_of_exposures = numScan0 * numScan1;// * numPos; - cout << "\tNumber of Exposures Per Measurement:" << number_of_exposures << endl; +// //cannot do this in between measurements , so update instantly +// if(scanArgument==qDefs::Level0){ +// //no need to check if numsteps=0,cuz otherwise this mode wont be set in plot tab +// int numSteps = myDet->getScanSteps(0); +// double *values = new double[numSteps]; +// myDet->getScanSteps(0,values); +// maxPixelsY = values[numSteps-1]; +// minPixelsY = values[0]; +// nPixelsY = numSteps; +// }else if(scanArgument==qDefs::Level1) { +// //no need to check if numsteps=0,cuz otherwise this mode wont be set in plot tab +// int numSteps = myDet->getScanSteps(1); +// double *values = new double[numSteps]; +// myDet->getScanSteps(1,values); - maxPixelsY = 0; - minPixelsY = 0; - nPixelsX = myDet->getTotalNumberOfChannelsInclGapPixels(slsDetectorDefs::X); - nPixelsY = myDet->getTotalNumberOfChannelsInclGapPixels(slsDetectorDefs::Y); - if (detType == slsDetectorDefs::JUNGFRAUCTB) { - npixelsy_jctb = (myDet->setTimer(slsDetectorDefs::SAMPLES_JCTB, -1) * 2)/25; // for moench 03 - nPixelsX = npixelsx_jctb; - nPixelsY = npixelsy_jctb; - } +// maxPixelsY = values[numSteps-1]; +// minPixelsY = values[0]; +// nPixelsY = numSteps; +// }else if(scanArgument==qDefs::AllFrames) +// nPixelsY = number_of_exposures; +// else if(scanArgument==qDefs::FileIndex) +// nPixelsY = number_of_frames; - //cannot do this in between measurements , so update instantly - if(scanArgument==qDefs::Level0){ - //no need to check if numsteps=0,cuz otherwise this mode wont be set in plot tab - int numSteps = myDet->getScanSteps(0); - double *values = new double[numSteps]; - myDet->getScanSteps(0,values); +// if(minPixelsY>maxPixelsY){ +// double temp = minPixelsY; +// minPixelsY = maxPixelsY; +// maxPixelsY = temp; +// backwardScanPlot = true; +// }else backwardScanPlot = false; - maxPixelsY = values[numSteps-1]; - minPixelsY = values[0]; - nPixelsY = numSteps; - }else if(scanArgument==qDefs::Level1) { - //no need to check if numsteps=0,cuz otherwise this mode wont be set in plot tab - int numSteps = myDet->getScanSteps(1); - double *values = new double[numSteps]; - myDet->getScanSteps(1,values); +// //1d +// if(histXAxis) delete [] histXAxis; histXAxis = new double [nPixelsX]; - maxPixelsY = values[numSteps-1]; - minPixelsY = values[0]; - nPixelsY = numSteps; - }else if(scanArgument==qDefs::AllFrames) - nPixelsY = number_of_exposures; - else if(scanArgument==qDefs::FileIndex) - nPixelsY = number_of_frames; +// if(histYAxis[0]) delete [] histYAxis[0]; histYAxis[0] = new double [nPixelsX]; +// //2d +// if(lastImageArray) delete [] lastImageArray; lastImageArray = new double[nPixelsY*nPixelsX]; +// if(gainImageArray) delete [] gainImageArray; gainImageArray = new double[nPixelsY*nPixelsX]; - if(minPixelsY>maxPixelsY){ - double temp = minPixelsY; - minPixelsY = maxPixelsY; - maxPixelsY = temp; - backwardScanPlot = true; - }else backwardScanPlot = false; +// //initializing 1d x axis +// for(unsigned int px=0;pxmyDet->setReceiverOnline() == slsDetectorDefs::ONLINE_FLAG) { -void* qDrawPlot::DataStartAcquireThread(void *this_pointer){ - // stream data from receiver to the gui - if(((qDrawPlot*)this_pointer)->myDet->setReceiverOnline() == slsDetectorDefs::ONLINE_FLAG) { + // if receiver data up streaming not on, switch it on + if (((qDrawPlot *)this_pointer)->myDet->enableDataStreamingFromReceiver() != 1) { + // switch on receiver + if (((qDrawPlot *)this_pointer)->myDet->enableDataStreamingFromReceiver(1) != 1) { + qDefs::checkErrorMessage(((qDrawPlot *)this_pointer)->myDet, "qDrawPlot::DataStartAcquireThread"); + return this_pointer; + } + } + } - // if receiver data up streaming not on, switch it on - if (((qDrawPlot*)this_pointer)->myDet->enableDataStreamingFromReceiver() != 1) { - // switch on receiver - if (((qDrawPlot*)this_pointer)->myDet->enableDataStreamingFromReceiver(1) != 1) { - qDefs::checkErrorMessage(((qDrawPlot*)this_pointer)->myDet,"qDrawPlot::DataStartAcquireThread"); - return this_pointer; - } - } - } + if (((qDrawPlot *)this_pointer)->myDet->getAcquiringFlag() == true) { + ((qDrawPlot *)this_pointer)->myDet->setAcquiringFlag(false); + } + ((qDrawPlot *)this_pointer)->myDet->acquire(); - if (((qDrawPlot*)this_pointer)->myDet->getAcquiringFlag() == true) { - ((qDrawPlot*)this_pointer)->myDet->setAcquiringFlag(false); - } - ((qDrawPlot*)this_pointer)->myDet->acquire(1); - - return this_pointer; + return this_pointer; } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -int qDrawPlot::GetDataCallBack(detectorData *data, int fIndex, int subIndex, void *this_pointer){ - ((qDrawPlot*)this_pointer)->GetData(data,fIndex, subIndex); - return 0; +int qDrawPlot::GetDataCallBack(detectorData *data, int fIndex, int subIndex, void *this_pointer) { + ((qDrawPlot *)this_pointer)->GetData(data, fIndex, subIndex); + return 0; } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -int qDrawPlot::GetData(detectorData *data,int fIndex, int subIndex){ +int qDrawPlot::GetData(detectorData *data, int fIndex, int subIndex) { #ifdef VERYVERBOSE - cout << "******Entering GetDatafunction********" << endl; - cout << "fIndex " << fIndex << endl; - cout << "subIndex " << subIndex << endl; - cout << "fname " << data->fileName << endl; - cout << "npoints " << data->npoints << endl; - cout << "npy " << data->npy << endl; - cout << "progress " << data->progressIndex << endl; - if (data->values != NULL) cout << "values " << data->values << endl; - cout << "errors " << data->errors << endl; - cout << "angle " << data->angles << endl; - cout << "databytes " << data->databytes << endl; - cout << "dynamicRange " << data->dynamicRange << endl; - cout << "fileIndex " << data->fileIndex << endl; + std::cout << "******Entering GetDatafunction********\n"; + std::cout << "fIndex " << fIndex << '\n'; + std::cout << "subIndex " << subIndex << '\n'; + std::cout << "fname " << data->fileName << '\n'; + std::cout << "npoints " << data->npoints << '\n'; + std::cout << "npy " << data->npy << '\n'; + std::cout << "progress " << data->progressIndex << '\n'; + if (data->values != NULL) + std::cout << "values " << data->values << '\n'; + std::cout << "databytes " << data->databytes << '\n'; + std::cout << "dynamicRange " << data->dynamicRange << '\n'; + std::cout << "fileIndex " << data->fileIndex << '\n'; #endif - if(!stop_signal){ + if (!stop_signal) { - //set progress - progress=(int)data->progressIndex; - currentFrameIndex = fileIOStatic::getIndicesFromFileName(string(data->fileName),currentFileIndex); - currentFileIndex = data->fileIndex; - //happens if receiver sends a null and empty file name - /*if(string(data->fileName).empty()){ - cout << "Received empty file name. Exiting function without updating data for plot." << endl; - return -1; - }*/ + //set progress + progress = (int)data->progressIndex; + //TODO! + // currentFrameIndex = fileIOStatic::getIndicesFromFileName(std::string(data->fileName),currentFileIndex); + currentFileIndex = data->fileIndex; + //happens if receiver sends a null and empty file name + /*if(std::string(data->fileName).empty()){ + std::cout << "Received empty file name. Exiting function without updating data for plot." <<'\n'; + return -1; + }*/ #ifdef VERYVERBOSE - cout << "progress:" << progress << endl; + std::cout << "progress:" << progress << '\n'; #endif - // secondary title necessary to differentiate between frames when not saving data - char temp_title[2000]; - //findex is the frame index given by receiver, cannot be derived from file name - if(fIndex!=-1){ - currentFrameIndex=fIndex; - sprintf(temp_title,"#%d",fIndex); - if((detType==slsDetectorDefs::EIGER) && (subIndex != -1)) - sprintf(temp_title,"#%d %d",fIndex,subIndex); - }else{ - if(fileSaveEnable) strcpy(temp_title,"#%d"); - else sprintf(temp_title,"#%d",currentFrame); - } - if(subIndex != -1) - sprintf(temp_title,"#%d %d",fIndex,subIndex); + // secondary title necessary to differentiate between frames when not saving data + char temp_title[2000]; + //findex is the frame index given by receiver, cannot be derived from file name + if (fIndex != -1) { + currentFrameIndex = fIndex; + sprintf(temp_title, "#%d", fIndex); + if ((detType == slsDetectorDefs::EIGER) && (subIndex != -1)) + sprintf(temp_title, "#%d %d", fIndex, subIndex); + } else { + if (fileSaveEnable) + strcpy(temp_title, "#%d"); + else + sprintf(temp_title, "#%d", currentFrame); + } + if (subIndex != -1) + sprintf(temp_title, "#%d %d", fIndex, subIndex); - //Plot Disabled - if(!plotEnable) - return 0; + //Plot Disabled + if (!plotEnable) + return 0; + if (scanArgument == qDefs::None) { + //if the time is not over, RETURN + if (!data_pause_over) { + return 0; + } + data_pause_over = false; + data_pause_timer->start((int)(timerValue)); + } + // convert char* to double + if (data->values == NULL) { + data->values = new double[nPixelsX * nPixelsY]; + if (gainDataEnable) { + data->dgainvalues = new double[nPixelsX * nPixelsY]; + toDoublePixelData(data->values, data->cvalues, nPixelsX * nPixelsY, data->databytes, data->dynamicRange, data->dgainvalues); + } else + toDoublePixelData(data->values, data->cvalues, nPixelsX * nPixelsY, data->databytes, data->dynamicRange); + } - //angle plotting - if(anglePlot){ + //if scan + //alframes + if (scanArgument == qDefs::AllFrames) { + LockLastImageArray(); + //set title + plotTitle = QString(plotTitle_prefix) + QString(data->fileName).section('/', -1); + //variables + lastImageNumber = currentFrame + 1; + //title + imageTitle = temp_title; + //copy data + memcpy(lastImageArray + (currentScanDivLevel * nPixelsX), data->values, nPixelsX * sizeof(double)); + plotRequired = true; + UnlockLastImageArray(); + currentFrame++; + currentScanDivLevel++; + emit UpdatePlotSignal(); + return 0; + } + //file index + if (scanArgument == qDefs::FileIndex) { + LockLastImageArray(); + //set title + plotTitle = QString(plotTitle_prefix) + QString(data->fileName).section('/', -1); + //variables + if (currentFrameIndex == 0) + currentScanDivLevel = 0; + lastImageNumber = currentFrame + 1; + //title + imageTitle = temp_title; + //copy data + for (unsigned int px = 0; px < nPixelsX; ++px) + lastImageArray[currentScanDivLevel * nPixelsX + px] += data->values[px]; + plotRequired = true; + UnlockLastImageArray(); + currentFrame++; + currentScanDivLevel++; + emit UpdatePlotSignal(); + return 0; + } + //level0 + if (scanArgument == qDefs::Level0) { + std::cout << "Should not end up here! 0\n"; + // LockLastImageArray(); + // //set title + // plotTitle = QString(plotTitle_prefix) + QString(data->fileName).section('/', -1); + // //get scanvariable0 + // int ci = 0, fi = 0, p = 0, di = 0; + // double cs0 = 0, cs1 = 0; + // fileIOStatic::getVariablesFromFileName(std::string(data->fileName), ci, fi, p, cs0, cs1, di); + // //variables + // if (cs0 != currentScanValue) { + // if (backwardScanPlot) + // currentScanDivLevel--; + // else + // currentScanDivLevel++; + // } + // currentScanValue = cs0; + // lastImageNumber = currentFrame + 1; + // //title + // imageTitle = temp_title; + // //copy data + // for (unsigned int px = 0; px < nPixelsX; ++px) + // lastImageArray[currentScanDivLevel * nPixelsX + px] += data->values[px]; + // plotRequired = true; + // UnlockLastImageArray(); + // currentFrame++; + // emit UpdatePlotSignal(); + return 0; + } + if (scanArgument == qDefs::Level1) { + std::cout << "Should not end up here! 1\n"; + // LockLastImageArray(); + // //set title + // plotTitle = QString(plotTitle_prefix) + QString(data->fileName).section('/', -1); + // //get scanvariable1 + // int ci = 0, fi = 0, p = 0, di = 0; + // double cs0 = 0, cs1 = 0; + // fileIOStatic::getVariablesFromFileName(std::string(data->fileName), ci, fi, p, cs0, cs1, di); + // //variables + // if (cs1 != currentScanValue) { + // if (backwardScanPlot) + // currentScanDivLevel--; + // else + // currentScanDivLevel++; + // } + // currentScanValue = cs1; + // lastImageNumber = currentFrame + 1; + // //title + // imageTitle = temp_title; + // //copy data + // for (unsigned int px = 0; px < nPixelsX; ++px) + // lastImageArray[currentScanDivLevel * nPixelsX + px] += data->values[px]; + // plotRequired = true; + // UnlockLastImageArray(); + // currentFrame++; + // emit UpdatePlotSignal(); + return 0; + } - // convert char* to double - if(data->values==NULL) { - data->values = new double[nPixelsX*nPixelsY]; - toDoublePixelData(data->values, data->cvalues, nPixelsX*nPixelsY, data->databytes, data->dynamicRange); - } + //normal measurement or 1d scans + LockLastImageArray(); + /*if(!pthread_mutex_trylock(&(last_image_complete_mutex))){*/ + //set title + plotTitle = QString(plotTitle_prefix) + QString(data->fileName).section('/', -1); + // only if you got the lock, do u need to remember lastimagenumber to plot + lastImageNumber = currentFrame + 1; + //cout<<"got last imagenumber:"<fileName).section('/',-1); - // Title - histTitle[0] = temp_title; + //histogram + if (histogram) { + resetAccumulate = false; + lastImageNumber = currentFrame + 1; - if(data->angles==NULL){ - cout<<"\n\nWARNING:RETURNED NULL instead of angles."<values,nAnglePixelsX*sizeof(double)); - SetHistXAxisTitle("Channel Number"); + int numValues = nPixelsX; + if (originally2D) + numValues = nPixelsX * nPixelsY; - } - else{ - lastImageNumber= currentFrame+1; - nAnglePixelsX = data->npoints; - histNBins = nAnglePixelsX; - nHists=1; - if(histXAngleAxis) delete [] histXAngleAxis; histXAngleAxis = new double[nAnglePixelsX]; - if(histYAngleAxis) delete [] histYAngleAxis; histYAngleAxis = new double[nAnglePixelsX]; -#ifdef CHECKINFERROR - int k = 0; - for(int i = 0; i < data->npoints; i++){ - if(isinf(data->values[i])){ - //cout << "*** ERROR: value at " << i << " infinity" << endl; - k++; - data->values[i] = -1; - } - } - if (k>0) { - cout << "*** ERROR: value at " << k << " places have infinity values!" << endl; - double m1,m2,s1; - GetStatistics(m1,m2,s1,data->angles,nAnglePixelsX); - cout << "angle min:" << m1 << endl; - cout << "angle max:" << m2 << endl; - cout << "angle sum:" << s1 << endl; - GetStatistics(m1,m2,s1,data->values,nAnglePixelsX); - cout << "value min:" << m1 << endl; - cout << "value max:" << m2 << endl; - cout << "value sum:" << s1 << endl; - } -#endif - memcpy(histXAngleAxis,data->angles,nAnglePixelsX*sizeof(double)); - memcpy(histYAngleAxis,data->values,nAnglePixelsX*sizeof(double)); - SetHistXAxisTitle("Angles"); - } - plotRequired = true; - UnlockLastImageArray(); - currentFrame++; -#ifdef VERYVERBOSE - cout << "Exiting GetData Function " << endl; -#endif - emit UpdatePlotSignal(); - return 0; - } + //clean up graph + if (histogramArgument == qDefs::Intensity) { + for (int j = 0; j < histogramSamples.size(); ++j) { + histogramSamples[j].value = 0; + } + } + int val = 0; + for (int i = 0; i < numValues; ++i) { + //frequency of intensity + if (histogramArgument == qDefs::Intensity) { + //ignore outside limits + if ((data->values[i] < histFrom) || (data->values[i] > histTo)) + continue; + //check for intervals, increment if validates + for (int j = 0; j < histogramSamples.size(); ++j) { + if (histogramSamples[j].interval.contains(data->values[i])) + histogramSamples[j].value += 1; + } + } + //get sum of data pixels + else + val += data->values[i]; + } - //nth frame or delay decision (data copied later on) - if (detType == slsDetectorDefs::MYTHEN){ - //Nth Frame - if(frameFactor){ - //plots if numfactor becomes 0 - if(!numFactor) numFactor=frameFactor-1; - //return if not - else{ - numFactor--; - return 0; - } - } + if (histogramArgument != qDefs::Intensity) { + std::cout << "histogramArgument != qDefs::Intensity\n"; + // val /= numValues; - //Not Nth Frame, to check time out(NOT for Scans and angle plots) - else{ - if (scanArgument == qDefs::None) { - //if the time is not over, RETURN - if(!data_pause_over){ - return 0; - } - data_pause_over=false; - data_pause_timer->start((int)(timerValue)); - } - } - } + // //find scan value + // int ci = 0, fi = 0; + // double cs0 = 0, cs1 = 0; + // fileIOStatic::getVariablesFromFileName(std::string(data->fileName), ci, fi, cs0, cs1); - // convert char* to double - if(data->values == NULL) { - data->values = new double[nPixelsX*nPixelsY]; - if (gainDataEnable) { - data->dgainvalues = new double[nPixelsX*nPixelsY]; - toDoublePixelData(data->values, data->cvalues, nPixelsX*nPixelsY, data->databytes, data->dynamicRange, data->dgainvalues); - } - else - toDoublePixelData(data->values, data->cvalues, nPixelsX*nPixelsY, data->databytes, data->dynamicRange); - } + // int scanval = -1; + // if (cs0 != -1) + // scanval = cs0; + // else + // scanval = cs1; - //if scan - //alframes - if(scanArgument==qDefs::AllFrames){ - LockLastImageArray(); - //set title - plotTitle=QString(plotTitle_prefix)+QString(data->fileName).section('/',-1); - //variables - lastImageNumber= currentFrame+1; - //title - imageTitle = temp_title; - //copy data - memcpy(lastImageArray+(currentScanDivLevel*nPixelsX),data->values,nPixelsX*sizeof(double)); - plotRequired = true; - UnlockLastImageArray(); - currentFrame++; - currentScanDivLevel++; - emit UpdatePlotSignal(); - return 0; - } - //file index - if(scanArgument==qDefs::FileIndex){ - LockLastImageArray(); - //set title - plotTitle=QString(plotTitle_prefix)+QString(data->fileName).section('/',-1); - //variables - if(currentFrameIndex == 0) currentScanDivLevel = 0; - lastImageNumber= currentFrame+1; - //title - imageTitle = temp_title; - //copy data - for(unsigned int px=0;pxvalues[px]; - plotRequired = true; - UnlockLastImageArray(); - currentFrame++; - currentScanDivLevel++; - emit UpdatePlotSignal(); - return 0; - } - //level0 - if(scanArgument==qDefs::Level0){ - LockLastImageArray(); - //set title - plotTitle=QString(plotTitle_prefix)+QString(data->fileName).section('/',-1); - //get scanvariable0 - int ci = 0, fi = 0, p = 0, di = 0; double cs0 = 0 , cs1 = 0; - fileIOStatic::getVariablesFromFileName(string(data->fileName), ci, fi, p, cs0, cs1, di); - //variables - if(cs0!=currentScanValue) { - if(backwardScanPlot) currentScanDivLevel--; - else currentScanDivLevel++; - } - currentScanValue = cs0; - lastImageNumber= currentFrame+1; - //title - imageTitle = temp_title; - //copy data - for(unsigned int px=0;pxvalues[px]; - plotRequired = true; - UnlockLastImageArray(); - currentFrame++; - emit UpdatePlotSignal(); - return 0; - } - //level1 - if(scanArgument==qDefs::Level1){ - LockLastImageArray(); - //set title - plotTitle=QString(plotTitle_prefix)+QString(data->fileName).section('/',-1); - //get scanvariable1 - int ci = 0, fi = 0, p = 0, di = 0; double cs0 = 0 , cs1 = 0; - fileIOStatic::getVariablesFromFileName(string(data->fileName), ci, fi, p, cs0, cs1, di); - //variables - if(cs1!=currentScanValue){ - if(backwardScanPlot) currentScanDivLevel--; - else currentScanDivLevel++; - } - currentScanValue = cs1; - lastImageNumber= currentFrame+1; - //title - imageTitle = temp_title; - //copy data - for(unsigned int px=0;pxvalues[px]; - plotRequired = true; - UnlockLastImageArray(); - currentFrame++; - emit UpdatePlotSignal(); - return 0; - } + // //ignore outside limits + // if ((scanval < histFrom) || (scanval > histTo) || (scanval == -1)) + // scanval = -1; + // //check for intervals, increment if validates + // for (int j = 0; j < histogramSamples.size(); ++j) { + // if (histogramSamples[j].interval.contains(scanval)) { + // histogramSamples[j].value = val; + // cout << "j:" << j << " scanval:" << scanval << " val:" << val << endl; + // } + // } + } + } + //not histogram + else { + // Persistency + if (currentPersistency < persistency) + currentPersistency++; + else + currentPersistency = persistency; + nHists = currentPersistency + 1; + histNBins = nPixelsX; + // copy data + for (int i = currentPersistency; i > 0; i--) + memcpy(histYAxis[i], histYAxis[i - 1], nPixelsX * sizeof(double)); - //normal measurement or 1d scans - LockLastImageArray(); - /*if(!pthread_mutex_trylock(&(last_image_complete_mutex))){*/ - //set title - plotTitle=QString(plotTitle_prefix)+QString(data->fileName).section('/',-1); - // only if you got the lock, do u need to remember lastimagenumber to plot - lastImageNumber= currentFrame+1; - //cout<<"got last imagenumber:"<values[px]; + memcpy(histYAxis[0], data->values, nPixelsX * sizeof(double)); + pedestalCount++; + } + //calculate the pedestal value + if (pedestalCount == NUM_PEDESTAL_FRAMES) { + cout << "Pedestal Calculated" << '\n'; + for (unsigned int px = 0; px < nPixelsX; ++px) + tempPedestalVals[px] = tempPedestalVals[px] / (double)NUM_PEDESTAL_FRAMES; + memcpy(pedestalVals, tempPedestalVals, nPixelsX * sizeof(double)); + startPedestalCal = 0; + } + } - //histogram - if(histogram){ - resetAccumulate = false; - lastImageNumber= currentFrame+1; + //normal data + if (((!pedestal) & (!accumulate) & (!binary)) || (resetAccumulate)) { + memcpy(histYAxis[0], data->values, nPixelsX * sizeof(double)); + resetAccumulate = false; + } + //pedestal or accumulate + else { + double temp; //cannot overwrite cuz of accumulate + for (unsigned int px = 0; px < (nPixelsX * nPixelsY); ++px) { + temp = data->values[px]; + if (pedestal) + temp = data->values[px] - (pedestalVals[px]); + if (binary) { + if ((temp >= binaryFrom) && (temp <= binaryTo)) + temp = 1; + else + temp = 0; + } + if (accumulate) + temp += histYAxis[0][px]; + //after all processing + histYAxis[0][px] = temp; + } + } + } + } + //2d + else { + // Titles + imageTitle = temp_title; - int numValues = nPixelsX; - if(originally2D) - numValues = nPixelsX*nPixelsY; + //jungfrau mask gain + if (data->dgainvalues != NULL) { + memcpy(gainImageArray, data->dgainvalues, nPixelsX * nPixelsY * sizeof(double)); + gainPlotEnable = true; + } else + gainPlotEnable = false; - //clean up graph - if(histogramArgument == qDefs::Intensity){ - for(int j=0;jvalues[px]; + memcpy(lastImageArray, data->values, nPixelsX * nPixelsY * sizeof(double)); + pedestalCount++; + } + //calculate the pedestal value + if (pedestalCount == NUM_PEDESTAL_FRAMES) { + std::cout << "Pedestal Calculated" << '\n'; + for (unsigned int px = 0; px < (nPixelsX * nPixelsY); ++px) + tempPedestalVals[px] = tempPedestalVals[px] / (double)NUM_PEDESTAL_FRAMES; + memcpy(pedestalVals, tempPedestalVals, nPixelsX * nPixelsY * sizeof(double)); + startPedestalCal = 0; + } + } - } - } - - int val = 0 ; - for(int i=0;ivalues[i] < histFrom) || (data->values[i] > histTo)) - continue; - //check for intervals, increment if validates - for(int j=0;jvalues[i])) - histogramSamples[j].value += 1; - - } - } - //get sum of data pixels - else - val += data->values[i]; - - } - - - if(histogramArgument != qDefs::Intensity){ - val /= numValues; - - //find scan value - int ci = 0, fi = 0; double cs0 = 0 , cs1 = 0; - fileIOStatic::getVariablesFromFileName(string(data->fileName), ci, fi, cs0, cs1); - - int scanval=-1; - if(cs0 != -1) - scanval = cs0; - else scanval = cs1; - - //ignore outside limits - if ((scanval < histFrom) || (scanval > histTo) || (scanval == -1)) - scanval = -1; - //check for intervals, increment if validates - for(int j=0;j0;i--) - memcpy(histYAxis[i],histYAxis[i-1],nPixelsX*sizeof(double)); - - //recalculating pedestal - if(startPedestalCal){ - //start adding frames to get to the pedestal value - if(pedestalCountvalues[px]; - memcpy(histYAxis[0],data->values,nPixelsX*sizeof(double)); - pedestalCount++; - } - //calculate the pedestal value - if(pedestalCount==NUM_PEDESTAL_FRAMES){ - cout << "Pedestal Calculated" << endl; - for(unsigned int px=0;pxvalues,nPixelsX*sizeof(double)); - resetAccumulate = false; - } - //pedestal or accumulate - else{ - double temp;//cannot overwrite cuz of accumulate - for(unsigned int px=0;px<(nPixelsX*nPixelsY);px++){ - temp = data->values[px]; - if(pedestal) - temp = data->values[px] - (pedestalVals[px]); - if(binary) { - if ((temp >= binaryFrom) && (temp <= binaryTo)) - temp = 1; - else - temp = 0; - } - if(accumulate) - temp += histYAxis[0][px]; - //after all processing - histYAxis[0][px] = temp; - } - } - } - } - //2d - else{ - // Titles - imageTitle = temp_title; - - //jungfrau mask gain - if(data->dgainvalues != NULL) { - memcpy(gainImageArray, data->dgainvalues, nPixelsX*nPixelsY*sizeof(double)); - gainPlotEnable = true; - }else - gainPlotEnable = false; - - - //recalculating pedestal - if(startPedestalCal){ - //start adding frames to get to the pedestal value - if(pedestalCountvalues[px]; - memcpy(lastImageArray,data->values,nPixelsX*nPixelsY*sizeof(double)); - pedestalCount++; - } - //calculate the pedestal value - if(pedestalCount==NUM_PEDESTAL_FRAMES){ - cout << "Pedestal Calculated" << endl; - for(unsigned int px=0;px<(nPixelsX*nPixelsY);px++) - tempPedestalVals[px] = tempPedestalVals[px]/(double)NUM_PEDESTAL_FRAMES; - memcpy(pedestalVals,tempPedestalVals,nPixelsX*nPixelsY*sizeof(double)); - startPedestalCal = 0; - } - } - - //normal data - if(((!pedestal)&(!accumulate)&(!binary)) || (resetAccumulate)){ - memcpy(lastImageArray,data->values,nPixelsX*nPixelsY*sizeof(double)); - resetAccumulate = false; - } - //pedestal or accumulate or binary - else{ - double temp; - for(unsigned int px=0;px<(nPixelsX*nPixelsY);px++){ - temp = data->values[px]; - if(pedestal) - temp = data->values[px] - (pedestalVals[px]); - if(binary) { - if ((temp >= binaryFrom) && (temp <= binaryTo)) - temp = 1; - else - temp = 0; - } - if(accumulate) - temp += lastImageArray[px]; - //after all processing - lastImageArray[px] = temp; - } - } - - } - /* pthread_mutex_unlock(&(last_image_complete_mutex)); - }*/ - plotRequired = true; - UnlockLastImageArray(); + //normal data + if (((!pedestal) & (!accumulate) & (!binary)) || (resetAccumulate)) { + memcpy(lastImageArray, data->values, nPixelsX * nPixelsY * sizeof(double)); + resetAccumulate = false; + } + //pedestal or accumulate or binary + else { + double temp; + for (unsigned int px = 0; px < (nPixelsX * nPixelsY); ++px) { + temp = data->values[px]; + if (pedestal) + temp = data->values[px] - (pedestalVals[px]); + if (binary) { + if ((temp >= binaryFrom) && (temp <= binaryTo)) + temp = 1; + else + temp = 0; + } + if (accumulate) + temp += lastImageArray[px]; + //after all processing + lastImageArray[px] = temp; + } + } + } + /* pthread_mutex_unlock(&(last_image_complete_mutex)); + }*/ + plotRequired = true; + UnlockLastImageArray(); #ifdef VERYVERBOSE - cprintf(BLUE,"currentframe:%d \tcurrentframeindex:%d\n",currentFrame,currentFrameIndex); + cprintf(BLUE, "currentframe:%d \tcurrentframeindex:%d\n", currentFrame, currentFrameIndex); #endif - currentFrame++; - emit UpdatePlotSignal(); - } - + currentFrame++; + emit UpdatePlotSignal(); + } #ifdef VERYVERBOSE - cout << "Exiting GetData function" << endl; + std::cout << "Exiting GetData function" << '\n'; #endif - return 0; + return 0; } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -int qDrawPlot::GetAcquisitionFinishedCallBack(double currentProgress,int detectorStatus, void *this_pointer){ - ((qDrawPlot*)this_pointer)->AcquisitionFinished(currentProgress,detectorStatus); +int qDrawPlot::GetAcquisitionFinishedCallBack(double currentProgress, int detectorStatus, void *this_pointer) { + ((qDrawPlot *)this_pointer)->AcquisitionFinished(currentProgress, detectorStatus); #ifdef VERYVERBOSE - cout << "acquisition finished callback worked ok" << endl; + std::cout << "acquisition finished callback worked ok\n"; #endif - return 0; + return 0; } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -int qDrawPlot::AcquisitionFinished(double currentProgress, int detectorStatus){ +int qDrawPlot::AcquisitionFinished(double currentProgress, int detectorStatus) { #ifdef VERBOSE - cout << "\nEntering Acquisition Finished with status " ; + std::cout << "\nEntering Acquisition Finished with status "; #endif - QString status = QString(slsDetectorBase::runStatusType(slsDetectorDefs::runStatus(detectorStatus)).c_str()); + QString status = QString(slsDetectorDefs::runStatusType(slsDetectorDefs::runStatus(detectorStatus)).c_str()); #ifdef VERBOSE - cout << status.toAscii().constData() << " and progress " << currentProgress << endl; + std::cout << status.toAscii().constData() << " and progress " << currentProgress << '\n'; #endif - //error or stopped - if((stop_signal)||(detectorStatus==slsDetectorDefs::ERROR)){ + //error or stopped + if ((stop_signal) || (detectorStatus == slsDetectorDefs::ERROR)) { #ifdef VERBOSE - cout << "Error in Acquisition" << endl << endl; + std::cout << "Error in Acquisition\n\n"; #endif - //stop_signal = 1;//just to be sure - emit AcquisitionErrorSignal(status); - } + //stop_signal = 1;//just to be sure + emit AcquisitionErrorSignal(status); + } #ifdef VERBOSE - //all measurements are over - else if(currentProgress==100){ - cout << "Acquisition Finished" << endl << endl; - } + //all measurements are over + else if (currentProgress == 100) { + std::cout << "Acquisition Finished\n"; + } #endif - StartStopDaqToggle(true); - //this lets the measurement tab know its over, and to enable tabs - emit UpdatingPlotFinished(); + StartStopDaqToggle(true); + //this lets the measurement tab know its over, and to enable tabs + emit UpdatingPlotFinished(); - //calculate s curve inflection point - int l1=0,l2=0,j; - if((histogram)&&(histogramArgument != qDefs::Intensity)){ - for(j=0;j l2){ - cout << "***** s curve inflectionfound at " << histogramSamples[j].interval.maxValue() << "" - "or j at " << j << " with l1 " << l1 << " and l2 " << l2 << endl; - } - } - } + //calculate s curve inflection point + int l1 = 0, l2 = 0, j; + if ((histogram) && (histogramArgument != qDefs::Intensity)) { + for (j = 0; j < histogramSamples.size() - 2; ++j) { + l1 = histogramSamples[j + 1].value - histogramSamples[j].value; + l2 = histogramSamples[j + 2].value - histogramSamples[j + 1].value; + if (l1 > l2) { + std::cout << "***** s curve inflectionfound at " << histogramSamples[j].interval.maxValue() << "" + "or j at " + << j << " with l1 " << l1 << " and l2 " << l2 << '\n'; + } + } + } - return 0; + return 0; } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -int qDrawPlot::GetProgressCallBack(double currentProgress, void *this_pointer){ - ((qDrawPlot*)this_pointer)->progress= currentProgress; - return 0; +int qDrawPlot::GetProgressCallBack(double currentProgress, void *this_pointer) { + ((qDrawPlot *)this_pointer)->progress = currentProgress; + return 0; } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::ShowAcquisitionErrorMessage(QString status){ - if(!alreadyDisplayed){ - alreadyDisplayed = true; - qDefs::Message(qDefs::WARNING,string("
The acquisiton has ended abruptly. " - "Current Detector Status: ")+status.toAscii().constData()+ - string("."),"qDrawPlot::ShowAcquisitionErrorMessage"); - } +void qDrawPlot::ShowAcquisitionErrorMessage(QString status) { + if (!alreadyDisplayed) { + alreadyDisplayed = true; + qDefs::Message(qDefs::WARNING, std::string("The acquisiton has ended abruptly. " + "Current Detector Status: ") + + status.toAscii().constData() + std::string("."), + "qDrawPlot::ShowAcquisitionErrorMessage"); + } } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -int qDrawPlot::GetMeasurementFinishedCallBack(int currentMeasurementIndex, int fileIndex, void *this_pointer){ - ((qDrawPlot*)this_pointer)->MeasurementFinished(currentMeasurementIndex, fileIndex); - return 0; +int qDrawPlot::GetMeasurementFinishedCallBack(int currentMeasurementIndex, int fileIndex, void *this_pointer) { + ((qDrawPlot *)this_pointer)->MeasurementFinished(currentMeasurementIndex, fileIndex); + return 0; } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -int qDrawPlot::MeasurementFinished(int currentMeasurementIndex, int fileIndex){ +int qDrawPlot::MeasurementFinished(int currentMeasurementIndex, int fileIndex) { #ifdef VERBOSE - cout << "Entering Measurement Finished with currentMeasurement " << currentMeasurementIndex << " and fileIndex " << fileIndex << endl; + std::cout << "Entering Measurement Finished with currentMeasurement " << currentMeasurementIndex << " and fileIndex " << fileIndex << '\n'; #endif - //to make sure it plots the last frame - while(plotRequired){ - usleep(2000); - } + //to make sure it plots the last frame + while (plotRequired) { + usleep(2000); + } - currentMeasurement = currentMeasurementIndex+1; - currentFileIndex = fileIndex; + currentMeasurement = currentMeasurementIndex + 1; + currentFileIndex = fileIndex; #ifdef VERBOSE - cout << "currentMeasurement:" << currentMeasurement << endl; + std::cout << "currentMeasurement:" << currentMeasurement << '\n'; #endif - emit SetCurrentMeasurementSignal(currentMeasurement); - SetupMeasurement(); - /*if((myDet->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG) && (myDet->getFramesCaughtByReceiver() == 0)) + emit SetCurrentMeasurementSignal(currentMeasurement); + SetupMeasurement(); + /*if((myDet->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG) && (myDet->getFramesCaughtByReceiver() == 0)) boxPlot->setTitle("OLD_plot.raw");*/ - return 0; + return 0; } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::SelectPlot(int i){ //1 for 1D otherwise 2D - if(i==1){ - //Clear1DPlot(); it clears the last measurement - plot1D->SetXTitle(histXAxisTitle.toAscii().constData()); - plot1D->SetYTitle(histYAxisTitle.toAscii().constData()); - plot1D->show(); - plot2D->hide(); - boxPlot->setFlat(false); - plot_in_scope=1; - layout->addWidget(histFrameIndexTitle,0,0); - plotLayout->setContentsMargins(10,10,10,10); - }else{ - plot2D->SetXTitle(imageXAxisTitle); - plot2D->SetYTitle(imageYAxisTitle); - plot2D->SetZTitle(imageZAxisTitle); - plot1D->hide(); - plot2D->show(); - boxPlot->setFlat(true); - plot_in_scope=2; - histFrameIndexTitle->setText(""); - layout->removeWidget(histFrameIndexTitle); - plotLayout->setContentsMargins(0,0,0,0); - - } +void qDrawPlot::SelectPlot(int i) { //1 for 1D otherwise 2D + if (i == 1) { + //Clear1DPlot(); it clears the last measurement + plot1D->SetXTitle(histXAxisTitle.toAscii().constData()); + plot1D->SetYTitle(histYAxisTitle.toAscii().constData()); + plot1D->show(); + plot2D->hide(); + boxPlot->setFlat(false); + plot_in_scope = 1; + layout->addWidget(histFrameIndexTitle, 0, 0); + plotLayout->setContentsMargins(10, 10, 10, 10); + } else { + plot2D->SetXTitle(imageXAxisTitle); + plot2D->SetYTitle(imageYAxisTitle); + plot2D->SetZTitle(imageZAxisTitle); + plot1D->hide(); + plot2D->show(); + boxPlot->setFlat(true); + plot_in_scope = 2; + histFrameIndexTitle->setText(""); + layout->removeWidget(histFrameIndexTitle); + plotLayout->setContentsMargins(0, 0, 0, 0); + } } - //------------------------------------------------------------------------------------------------------------------------------------------------- +void qDrawPlot::Clear1DPlot() { + for (QVector::iterator h = plot1D_hists.begin(); h != plot1D_hists.end(); ++h) { + (*h)->Detach(plot1D); + //do not delete *h or h. + } -void qDrawPlot::Clear1DPlot(){ - for(QVector::iterator h = plot1D_hists.begin(); h!=plot1D_hists.end();h++){ - (*h)->Detach(plot1D); - //do not delete *h or h. - } - - plotHistogram->detach(); + plotHistogram->detach(); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::UpdatePlot(){ +void qDrawPlot::UpdatePlot() { #ifdef VERYVERBOSE - cout << "Entering UpdatePlot function" << endl; + std::cout << "Entering UpdatePlot function\n"; #endif - // only if no plot isnt enabled - if(plotEnable && plotRequired){ - LockLastImageArray(); - //so that it doesnt plot every single thing + // only if no plot isnt enabled + if (plotEnable && plotRequired) { + LockLastImageArray(); + //so that it doesnt plot every single thing #ifdef VERYVERBOSE - cprintf(GREEN,"Updating Plot\n"); + cprintf(GREEN, "Updating Plot\n"); #endif - //so as to not plot it again and to let measurment finished know its done plotting it - //1-d plot stuff - if(plot_in_scope==1){ + //so as to not plot it again and to let measurment finished know its done plotting it + //1-d plot stuff + if (plot_in_scope == 1) { #ifdef VERYVERBOSE - cout << "Last Image Number:" << lastImageNumber << endl; + std::cout << "Last Image Number:" << lastImageNumber << '\n'; #endif - if(histNBins){ - Clear1DPlot(); - plot1D->SetXTitle(histXAxisTitle.toAscii().constData()); - plot1D->SetYTitle(histYAxisTitle.toAscii().constData()); + if (histNBins) { + Clear1DPlot(); + plot1D->SetXTitle(histXAxisTitle.toAscii().constData()); + plot1D->SetYTitle(histYAxisTitle.toAscii().constData()); - //histogram - if(histogram){ - plotHistogram->setData(new QwtIntervalSeriesData(histogramSamples)); - plotHistogram->setPen(QPen(Qt::red)); - plotHistogram->setBrush(QBrush(Qt::red,Qt::Dense4Pattern));//Qt::SolidPattern - histFrameIndexTitle->setText(GetHistTitle(0)); - plotHistogram->attach(plot1D); - //refixing all the zooming + //histogram + if (histogram) { + plotHistogram->setData(new QwtIntervalSeriesData(histogramSamples)); + plotHistogram->setPen(QPen(Qt::red)); + plotHistogram->setBrush(QBrush(Qt::red, Qt::Dense4Pattern)); //Qt::SolidPattern + histFrameIndexTitle->setText(GetHistTitle(0)); + plotHistogram->attach(plot1D); + //refixing all the zooming - plot1D->SetXMinMax(startPixel,endPixel); - plot1D->SetYMinMax(0,plotHistogram->boundingRect().height()); - plot1D->SetZoomBase(startPixel,0,endPixel-startPixel,plotHistogram->boundingRect().height()); + plot1D->SetXMinMax(startPixel, endPixel); + plot1D->SetYMinMax(0, plotHistogram->boundingRect().height()); + plot1D->SetZoomBase(startPixel, 0, endPixel - startPixel, plotHistogram->boundingRect().height()); - } - //not histogram - else{ - for(int hist_num=0;hist_num<(int)nHists;hist_num++){ - SlsQtH1D* h; - if(hist_num+1>plot1D_hists.size()){ - if(anglePlot) - plot1D_hists.append(h=new SlsQtH1D("",histNBins,histXAngleAxis,histYAngleAxis)); - else - plot1D_hists.append(h=new SlsQtH1D("",histNBins,histXAxis,GetHistYAxis(hist_num))); - h->SetLineColor(hist_num); - }else{ - h=plot1D_hists.at(hist_num); - if(anglePlot) - h->SetData(histNBins,histXAngleAxis,histYAngleAxis); - else - h->SetData(histNBins,histXAxis,GetHistYAxis(hist_num)); - } - SetStyle(h); - histFrameIndexTitle->setText(GetHistTitle(0)); - //h->setTitle(GetHistTitle(hist_num)); - h->Attach(plot1D); - //refixing all the zooming - //if((firstPlot) || (anglePlot)){ - /*plot1D->SetXMinMax(h->minXValue(),h->maxXValue()); + } + //not histogram + else { + for (int hist_num = 0; hist_num < (int)nHists; ++hist_num) { + SlsQtH1D *h; + if (hist_num + 1 > plot1D_hists.size()) { + if (anglePlot) + plot1D_hists.append(h = new SlsQtH1D("", histNBins, histXAngleAxis, histYAngleAxis)); + else + plot1D_hists.append(h = new SlsQtH1D("", histNBins, histXAxis, GetHistYAxis(hist_num))); + h->SetLineColor(hist_num); + } else { + h = plot1D_hists.at(hist_num); + if (anglePlot) + h->SetData(histNBins, histXAngleAxis, histYAngleAxis); + else + h->SetData(histNBins, histXAxis, GetHistYAxis(hist_num)); + } + SetStyle(h); + histFrameIndexTitle->setText(GetHistTitle(0)); + //h->setTitle(GetHistTitle(hist_num)); + h->Attach(plot1D); + //refixing all the zooming + //if((firstPlot) || (anglePlot)){ + /*plot1D->SetXMinMax(h->minXValue(),h->maxXValue()); plot1D->SetYMinMax(h->minYValue(),h->maxYValue()); plot1D->SetZoomBase(h->minXValue(),h->minYValue(), h->maxXValue()-h->minXValue(),h->maxYValue()-h->minYValue());*/ - // firstPlot = false; - //} - } + // firstPlot = false; + //} + } - /**moved from below (had applied to histograms as well) to here, */ - // update range if required - if(XYRangeChanged){ - if(!IsXYRange[qDefs::XMINIMUM]) XYRangeValues[qDefs::XMINIMUM]= plot1D->GetXMinimum(); - if(!IsXYRange[qDefs::XMAXIMUM]) XYRangeValues[qDefs::XMAXIMUM]= plot1D->GetXMaximum(); - if(!IsXYRange[qDefs::YMINIMUM]) XYRangeValues[qDefs::YMINIMUM]= plot1D->GetYMinimum(); - if(!IsXYRange[qDefs::YMAXIMUM]) XYRangeValues[qDefs::YMAXIMUM]= plot1D->GetYMaximum(); - plot1D->SetXMinMax(XYRangeValues[qDefs::XMINIMUM],XYRangeValues[qDefs::XMAXIMUM]); - plot1D->SetYMinMax(XYRangeValues[qDefs::YMINIMUM],XYRangeValues[qDefs::YMAXIMUM]); - //Should not be reset for histogram, - //that is the only way to zoom in (new plots are zoomed out as its different each time) - if(!histogram) - XYRangeChanged = false; - } - /**moved from below (had applied to histograms as well) to here, */ - //Display Statistics - if(displayStatistics){ - double min=0,max=0,sum=0; - if(anglePlot) - GetStatistics(min,max,sum,histYAngleAxis,histNBins); - else - GetStatistics(min,max,sum,histYAxis[0],histNBins); - lblMinDisp->setText(QString("%1").arg(min)); - lblMaxDisp->setText(QString("%1").arg(max)); - lblSumDisp->setText(QString("%1").arg(sum)); - } - } + /**moved from below (had applied to histograms as well) to here, */ + // update range if required + if (XYRangeChanged) { + if (!IsXYRange[qDefs::XMINIMUM]) + XYRangeValues[qDefs::XMINIMUM] = plot1D->GetXMinimum(); + if (!IsXYRange[qDefs::XMAXIMUM]) + XYRangeValues[qDefs::XMAXIMUM] = plot1D->GetXMaximum(); + if (!IsXYRange[qDefs::YMINIMUM]) + XYRangeValues[qDefs::YMINIMUM] = plot1D->GetYMinimum(); + if (!IsXYRange[qDefs::YMAXIMUM]) + XYRangeValues[qDefs::YMAXIMUM] = plot1D->GetYMaximum(); + plot1D->SetXMinMax(XYRangeValues[qDefs::XMINIMUM], XYRangeValues[qDefs::XMAXIMUM]); + plot1D->SetYMinMax(XYRangeValues[qDefs::YMINIMUM], XYRangeValues[qDefs::YMAXIMUM]); + //Should not be reset for histogram, + //that is the only way to zoom in (new plots are zoomed out as its different each time) + if (!histogram) + XYRangeChanged = false; + } + /**moved from below (had applied to histograms as well) to here, */ + //Display Statistics + if (displayStatistics) { + double min = 0, max = 0, sum = 0; + if (anglePlot) + GetStatistics(min, max, sum, histYAngleAxis, histNBins); + else + GetStatistics(min, max, sum, histYAxis[0], histNBins); + lblMinDisp->setText(QString("%1").arg(min)); + lblMaxDisp->setText(QString("%1").arg(max)); + lblSumDisp->setText(QString("%1").arg(sum)); + } + } - if(saveAll) SavePlotAutomatic(); - - } - }//2-d plot stuff - else{ - if(lastImageArray){ - if(nPixelsX>0&&nPixelsY>0){ - plot2D->GetPlot()->SetData(nPixelsX,-0.5,nPixelsX-0.5,nPixelsY,startPixel,endPixel,lastImageArray); - plot2D->setTitle(GetImageTitle()); - plot2D->SetXTitle(imageXAxisTitle); - plot2D->SetYTitle(imageYAxisTitle); - plot2D->SetZTitle(imageZAxisTitle); - plot2D->UpdateNKeepSetRangeIfSet(); //keep a "set" z range, and call Update(); - if (gainPlotEnable) { - gainplot2D->GetPlot()->SetData(nPixelsX,-0.5,nPixelsX-0.5,nPixelsY,startPixel,endPixel,gainImageArray); - gainplot2D->setTitle(GetImageTitle()); - gainplot2D->show(); - }else { - gainplot2D->hide(); - } - } - // update range if required - if(XYRangeChanged){ - if(!IsXYRange[qDefs::XMINIMUM]) XYRangeValues[qDefs::XMINIMUM]= plot2D->GetPlot()->GetXMinimum(); - if(!IsXYRange[qDefs::XMAXIMUM]) XYRangeValues[qDefs::XMAXIMUM]= plot2D->GetPlot()->GetXMaximum(); - if(!IsXYRange[qDefs::YMINIMUM]) XYRangeValues[qDefs::YMINIMUM]= plot2D->GetPlot()->GetYMinimum(); - if(!IsXYRange[qDefs::YMAXIMUM]) XYRangeValues[qDefs::YMAXIMUM]= plot2D->GetPlot()->GetYMaximum(); - plot2D->GetPlot()->SetXMinMax(XYRangeValues[qDefs::XMINIMUM],XYRangeValues[qDefs::XMAXIMUM]); - plot2D->GetPlot()->SetYMinMax(XYRangeValues[qDefs::YMINIMUM],XYRangeValues[qDefs::YMAXIMUM]); - gainplot2D->GetPlot()->SetXMinMax(XYRangeValues[qDefs::XMINIMUM],XYRangeValues[qDefs::XMAXIMUM]); - gainplot2D->GetPlot()->SetYMinMax(XYRangeValues[qDefs::YMINIMUM],XYRangeValues[qDefs::YMAXIMUM]); - XYRangeChanged = false; - } - plot2D->GetPlot()->Update(); - if (gainPlotEnable) { - gainplot2D->GetPlot()->Update(); - gainplot2D->setFixedWidth(plot2D->width()/4); - gainplot2D->setFixedHeight(plot2D->height()/4); - gainplot2D->show(); - }else - gainplot2D->hide(); - //Display Statistics - if(displayStatistics){ - double min=0,max=0,sum=0; - GetStatistics(min,max,sum,lastImageArray,nPixelsX*nPixelsY); - lblMinDisp->setText(QString("%1").arg(min)); - lblMaxDisp->setText(QString("%1").arg(max)); - lblSumDisp->setText(QString("%1").arg(sum)); - } - if(saveAll) SavePlotAutomatic(); - } - } - //set plot title - boxPlot->setTitle(plotTitle); - //to notify the measurement finished when its done - plotRequired = false; - UnlockLastImageArray(); - } + if (saveAll) + SavePlotAutomatic(); + } + } //2-d plot stuff + else { + if (lastImageArray) { + if (nPixelsX > 0 && nPixelsY > 0) { + plot2D->GetPlot()->SetData(nPixelsX, -0.5, nPixelsX - 0.5, nPixelsY, startPixel, endPixel, lastImageArray); + plot2D->setTitle(GetImageTitle()); + plot2D->SetXTitle(imageXAxisTitle); + plot2D->SetYTitle(imageYAxisTitle); + plot2D->SetZTitle(imageZAxisTitle); + plot2D->UpdateNKeepSetRangeIfSet(); //keep a "set" z range, and call Update(); + if (gainPlotEnable) { + gainplot2D->GetPlot()->SetData(nPixelsX, -0.5, nPixelsX - 0.5, nPixelsY, startPixel, endPixel, gainImageArray); + gainplot2D->setTitle(GetImageTitle()); + gainplot2D->show(); + } else { + gainplot2D->hide(); + } + } + // update range if required + if (XYRangeChanged) { + if (!IsXYRange[qDefs::XMINIMUM]) + XYRangeValues[qDefs::XMINIMUM] = plot2D->GetPlot()->GetXMinimum(); + if (!IsXYRange[qDefs::XMAXIMUM]) + XYRangeValues[qDefs::XMAXIMUM] = plot2D->GetPlot()->GetXMaximum(); + if (!IsXYRange[qDefs::YMINIMUM]) + XYRangeValues[qDefs::YMINIMUM] = plot2D->GetPlot()->GetYMinimum(); + if (!IsXYRange[qDefs::YMAXIMUM]) + XYRangeValues[qDefs::YMAXIMUM] = plot2D->GetPlot()->GetYMaximum(); + plot2D->GetPlot()->SetXMinMax(XYRangeValues[qDefs::XMINIMUM], XYRangeValues[qDefs::XMAXIMUM]); + plot2D->GetPlot()->SetYMinMax(XYRangeValues[qDefs::YMINIMUM], XYRangeValues[qDefs::YMAXIMUM]); + gainplot2D->GetPlot()->SetXMinMax(XYRangeValues[qDefs::XMINIMUM], XYRangeValues[qDefs::XMAXIMUM]); + gainplot2D->GetPlot()->SetYMinMax(XYRangeValues[qDefs::YMINIMUM], XYRangeValues[qDefs::YMAXIMUM]); + XYRangeChanged = false; + } + plot2D->GetPlot()->Update(); + if (gainPlotEnable) { + gainplot2D->GetPlot()->Update(); + gainplot2D->setFixedWidth(plot2D->width() / 4); + gainplot2D->setFixedHeight(plot2D->height() / 4); + gainplot2D->show(); + } else + gainplot2D->hide(); + //Display Statistics + if (displayStatistics) { + double min = 0, max = 0, sum = 0; + GetStatistics(min, max, sum, lastImageArray, nPixelsX * nPixelsY); + lblMinDisp->setText(QString("%1").arg(min)); + lblMaxDisp->setText(QString("%1").arg(max)); + lblSumDisp->setText(QString("%1").arg(sum)); + } + if (saveAll) + SavePlotAutomatic(); + } + } + //set plot title + boxPlot->setTitle(plotTitle); + //to notify the measurement finished when its done + plotRequired = false; + UnlockLastImageArray(); + } #ifdef VERYVERBOSE - cout << "Exiting UpdatePlot function" << endl; + std::cout << "Exiting UpdatePlot function\n"; #endif } - //------------------------------------------------------------------------------------------------------------------------------------------------- +void qDrawPlot::ClonePlot() { + int i; -void qDrawPlot::ClonePlot(){ - int i; + //check for space for more clone widget references + bool found = false; + for (i = 0; i < MAXCloneWindows; ++i) + if (!winClone[i]) { + found = true; + break; + } + // no space + if (!found) { + std::cout << "Too many clones\n"; + exit(-1); + } - //check for space for more clone widget references - bool found = false; - for(i=0;igetFilePath(); + qDefs::checkErrorMessage(myDet, "qDrawPlot::ClonePlot"); + } + LockLastImageArray(); - //get file path while acquisition runnign without accessing shared memory - string sFilePath; - if(running) sFilePath = filePath.toAscii().constData(); - else { - sFilePath = myDet->getFilePath(); - qDefs::checkErrorMessage(myDet,"qDrawPlot::ClonePlot"); - } + // create clone & copy data + if (plot_in_scope == 1) { + winClone[i] = new qCloneWidget(this, i, boxPlot->title(), histXAxisTitle, histYAxisTitle, "", + (int)plot_in_scope, sFilePath, displayStatistics, lblMinDisp->text(), lblMaxDisp->text(), lblSumDisp->text()); + if (!anglePlot) + winClone[i]->SetCloneHists((int)nHists, histNBins, histXAxis, histYAxis, histTitle, lines, markers); + else + winClone[i]->SetCloneHists((int)nHists, histNBins, histXAngleAxis, histYAngleAxis, histTitle, lines, markers); + } else { + winClone[i] = new qCloneWidget(this, i, boxPlot->title(), imageXAxisTitle, imageYAxisTitle, imageZAxisTitle, + (int)plot_in_scope, sFilePath, displayStatistics, lblMinDisp->text(), lblMaxDisp->text(), lblSumDisp->text()); + winClone[i]->SetCloneHists2D(nPixelsX, -0.5, nPixelsX - 0.5, nPixelsY, startPixel, endPixel, lastImageArray); + } + // update range + found = false; + for (int index = 0; index < 4; ++index) + if (IsXYRange[index]) { + found = true; + break; + } + if (found) + winClone[i]->SetRange(IsXYRange, XYRangeValues); - LockLastImageArray(); + UnlockLastImageArray(); + winClone[i]->show(); - // create clone & copy data - if(plot_in_scope==1){ - winClone[i] = new qCloneWidget(this,i,boxPlot->title(),histXAxisTitle,histYAxisTitle,"", - (int)plot_in_scope,sFilePath,displayStatistics,lblMinDisp->text(),lblMaxDisp->text(),lblSumDisp->text()); - if(!anglePlot) - winClone[i]->SetCloneHists((int)nHists,histNBins,histXAxis,histYAxis,histTitle,lines,markers); - else - winClone[i]->SetCloneHists((int)nHists,histNBins,histXAngleAxis,histYAngleAxis,histTitle,lines,markers); - - }else{ - winClone[i] = new qCloneWidget(this,i,boxPlot->title(),imageXAxisTitle, imageYAxisTitle, imageZAxisTitle, - (int)plot_in_scope,sFilePath,displayStatistics,lblMinDisp->text(),lblMaxDisp->text(),lblSumDisp->text()); - winClone[i]->SetCloneHists2D(nPixelsX,-0.5,nPixelsX-0.5,nPixelsY,startPixel,endPixel,lastImageArray); - } - - // update range - found =false; - for(int index=0;index<4;index++) - if(IsXYRange[index]){ - found=true; - break; - } - if(found) - winClone[i]->SetRange(IsXYRange,XYRangeValues); - - - UnlockLastImageArray(); - - winClone[i]->show(); - - // to remember which all clone widgets were closed - connect(winClone[i], SIGNAL(CloneClosedSignal(int)),this, SLOT(CloneCloseEvent(int))); + // to remember which all clone widgets were closed + connect(winClone[i], SIGNAL(CloneClosedSignal(int)), this, SLOT(CloneCloseEvent(int))); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::SaveClones(){ - char errID[200]; - string errMessage= "The Snapshots with ID's: "; - bool success = true; - for(int i=0;iSavePlotAutomatic()){ - success = false; - sprintf(errID,"%d",i); - errMessage.append(string(errID)+string(", ")); - } - } - if(success) - qDefs::Message(qDefs::INFORMATION,"The Snapshots have all been saved successfully in .png.","Dock"); - else - qDefs::Message(qDefs::WARNING,errMessage + string("were not saved."),"qDrawPlot::SaveClones"); +void qDrawPlot::SaveClones() { + char errID[200]; + std::string errMessage = "The Snapshots with ID's: "; + bool success = true; + for (int i = 0; i < MAXCloneWindows; ++i) + if (winClone[i]) { + if (winClone[i]->SavePlotAutomatic()) { + success = false; + sprintf(errID, "%d", i); + errMessage.append(std::string(errID) + std::string(", ")); + } + } + if (success) + qDefs::Message(qDefs::INFORMATION, "The Snapshots have all been saved successfully in .png.", "Dock"); + else + qDefs::Message(qDefs::WARNING, errMessage + std::string("were not saved."), "qDrawPlot::SaveClones"); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::CloseClones(){ - for(int i=0;iclose(); - +void qDrawPlot::CloseClones() { + for (int i = 0; i < MAXCloneWindows; ++i) + if (winClone[i]) + winClone[i]->close(); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::CloneCloseEvent(int id){ - winClone[id]=0; +void qDrawPlot::CloneCloseEvent(int id) { + winClone[id] = 0; #ifdef VERBOSE - cout << "Closing Clone Window id:" << id << endl; + std::cout << "Closing Clone Window id:" << id << '\n'; #endif } - //------------------------------------------------------------------------------------------------------------------------------------------------- +void qDrawPlot::SavePlot() { + // render image + QImage savedImage(size().width(), size().height(), QImage::Format_RGB32); + QPainter painter(&savedImage); + render(&painter); -void qDrawPlot::SavePlot(){ - // render image - QImage savedImage(size().width(),size().height(),QImage::Format_RGB32); - QPainter painter(&savedImage); - render(&painter); + QString fName; + if (running) + fName = filePath; + else { + fName = QString(myDet->getFilePath().c_str()); + qDefs::checkErrorMessage(myDet, "qDrawPlot::SavePlot"); + } - QString fName; - if(running) fName = filePath; - else { - fName = QString(myDet->getFilePath().c_str()); - qDefs::checkErrorMessage(myDet,"qDrawPlot::SavePlot"); - } + if (boxPlot->title().contains('.')) { + fName.append(QString('/') + boxPlot->title()); + fName.replace(".dat", ".png"); + fName.replace(".raw", ".png"); + } else + fName.append(QString("/Image.png")); - if(boxPlot->title().contains('.')){ - fName.append(QString('/')+boxPlot->title()); - fName.replace(".dat",".png"); - fName.replace(".raw",".png"); - }else fName.append(QString("/Image.png")); + fName = QFileDialog::getSaveFileName(0, tr("Save Image"), fName, tr("PNG Files (*.png);;XPM Files(*.xpm);;JPEG Files(*.jpg)"), 0, QFileDialog::ShowDirsOnly); - fName = QFileDialog::getSaveFileName(0,tr("Save Image"),fName,tr("PNG Files (*.png);;XPM Files(*.xpm);;JPEG Files(*.jpg)"),0,QFileDialog::ShowDirsOnly); - - if (!fName.isEmpty()) { - if(savedImage.save(fName)) - qDefs::Message(qDefs::INFORMATION,"The Image has been successfully saved","qDrawPlot::SavePlot"); - else - qDefs::Message(qDefs::WARNING,"Attempt to save image failed.\n" - "Formats: .png, .jpg, .xpm.","qDrawPlot::SavePlot"); - } + if (!fName.isEmpty()) { + if (savedImage.save(fName)) + qDefs::Message(qDefs::INFORMATION, "The Image has been successfully saved", "qDrawPlot::SavePlot"); + else + qDefs::Message(qDefs::WARNING, "Attempt to save image failed.\n" + "Formats: .png, .jpg, .xpm.", + "qDrawPlot::SavePlot"); + } } - //------------------------------------------------------------------------------------------------------------------------------------------------- +void qDrawPlot::SavePlotAutomatic() { + //no need to save the same plot many times + if ((currentFrame > lastSavedFrame) && (currentMeasurement >= lastSavedMeasurement)) { -void qDrawPlot::SavePlotAutomatic(){ - //no need to save the same plot many times - if((currentFrame>lastSavedFrame)&&(currentMeasurement>=lastSavedMeasurement)){ + QString qFilePath; + if (running) + qFilePath = filePath; + else { + qFilePath = QString(myDet->getFilePath().c_str()); + qDefs::checkErrorMessage(myDet, "qDrawPlot::SavePlotAutomatic"); + } - QString qFilePath; - if(running) qFilePath = filePath; - else { - qFilePath = QString(myDet->getFilePath().c_str()); - qDefs::checkErrorMessage(myDet,"qDrawPlot::SavePlotAutomatic"); - } - - - lastSavedFrame = currentFrame; - lastSavedMeasurement = currentMeasurement; - char cID[10]; - sprintf(cID,"%d",lastSavedFrame); - //title - QString fName = qFilePath; - if(boxPlot->title().contains('.')){ - fName.append(QString('/')+boxPlot->title()); - fName.replace(".dat",".png"); - fName.replace(".raw",".png"); - }else fName.append(QString("/Image_unknown_title.png")); - //save - QImage img(size().width(),size().height(),QImage::Format_RGB32); - QPainter painter(&img); - render(&painter); - //if error while saving - if(!img.save(fName)){ - //mention the error only the first time - if(!saveError){ - //so it doesnt repeat again - saveError = true; - connect(this,SIGNAL(saveErrorSignal(QString)),this,SLOT(ShowSaveErrorMessage(QString))); - emit saveErrorSignal(fName); - } - } - } + lastSavedFrame = currentFrame; + lastSavedMeasurement = currentMeasurement; + char cID[10]; + sprintf(cID, "%d", lastSavedFrame); + //title + QString fName = qFilePath; + if (boxPlot->title().contains('.')) { + fName.append(QString('/') + boxPlot->title()); + fName.replace(".dat", ".png"); + fName.replace(".raw", ".png"); + } else + fName.append(QString("/Image_unknown_title.png")); + //save + QImage img(size().width(), size().height(), QImage::Format_RGB32); + QPainter painter(&img); + render(&painter); + //if error while saving + if (!img.save(fName)) { + //mention the error only the first time + if (!saveError) { + //so it doesnt repeat again + saveError = true; + connect(this, SIGNAL(saveErrorSignal(QString)), this, SLOT(ShowSaveErrorMessage(QString))); + emit saveErrorSignal(fName); + } + } + } } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::ShowSaveErrorMessage(QString fileName){ - qDefs::Message(qDefs::WARNING,string("Automatic Saving: Could not save the first file:\n")+ - string(fileName.toAscii().constData()) + string("\n\nNote: Will not show future file save errors for this acquisition."),"qDrawPlot::ShowSaveErrorMessage"); - +void qDrawPlot::ShowSaveErrorMessage(QString fileName) { + qDefs::Message(qDefs::WARNING, std::string("Automatic Saving: Could not save the first file:\n") + std::string(fileName.toAscii().constData()) + std::string("\n\nNote: Will not show future file save errors for this acquisition."), "qDrawPlot::ShowSaveErrorMessage"); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::SetPersistency(int val){ - for(int i=0;i<=val;i++) - if(!histYAxis[i]) histYAxis[i] = new double [nPixelsX]; - persistency = val; +void qDrawPlot::SetPersistency(int val) { + for (int i = 0; i <= val; ++i) + if (!histYAxis[i]) + histYAxis[i] = new double[nPixelsX]; + persistency = val; } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::EnablePlot(bool enable){ +void qDrawPlot::EnablePlot(bool enable) { #ifdef VERBOSE - cout << "Plotting set to:" << enable << endl; + std::cout << "Plotting set to:" << enable << '\n'; #endif - plotEnable = enable; - //if no plot, cant do setting range. - // not true vice versa where plot was false and now set it to true - Clear1DPlot(); - -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qDrawPlot::DisableZoom(bool disable){ - if(plot_in_scope==1) - plot1D->DisableZoom(disable); - else - plot2D->GetPlot()->DisableZoom(disable); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qDrawPlot::UpdateTrimbitPlot(bool fromDetector,bool Histogram){ - int ret,actualPixelsX; - double min=0,max=0,sum=0; -#ifdef VERBOSE - if(fromDetector) cout << "Geting Trimbits from Detector" << endl; - else cout << "Getting Trimbits from Shared Memory" << endl; -#endif - - LockLastImageArray(); - - if(detType == slsDetectorDefs::MYTHEN){ - - //get trimbits - actualPixelsX = myDet->getTotalNumberOfChannels(slsDetectorDefs::X); - if(histTrimbits) delete [] histTrimbits; histTrimbits = new double[actualPixelsX]; - ret = myDet->getChanRegs(histTrimbits,fromDetector); - // cout << "got it!" << endl; - if(!ret){ - qDefs::Message(qDefs::WARNING,"No Trimbit data found in shared memory.","qDrawPlot::UpdateTrimbitPlot"); - UnlockLastImageArray(); - return qDefs::FAIL; - } -#ifdef VERBOSE - cout << "Got Trimbits" << endl; -#endif - - qDefs::checkErrorMessage(myDet,"qDrawPlot::UpdateTrimbitPlot"); - - //clear/select plot and set titles - Select1DPlot(); - Clear1DPlot(); - - //Display Statistics - if(displayStatistics){ - GetStatistics(min,max,sum,histTrimbits,actualPixelsX); - lblMinDisp->setText(QString("%1").arg(min)); - lblMaxDisp->setText(QString("%1").arg(max)); - lblSumDisp->setText(QString("%1").arg(sum)); - } - - - if(!Histogram){ - cout << "Data Graph:" << nPixelsX << endl; - - //initialize - nPixelsX = actualPixelsX; - if(histXAxis) delete [] histXAxis; histXAxis = new double [nPixelsX]; - if(histYAxis[0]) delete [] histYAxis[0]; histYAxis[0]= new double [nPixelsX]; - //initializing - for(unsigned int px=0;pxsetTitle("Trimbits_Plot_Data Graph"); - plot1D->SetXTitle("Channel Number"); - plot1D->SetYTitle("Trimbits"); - //set plot parameters - plot1D->SetXMinMax(0,nPixelsX); - /*plot1D->SetYMinMax(0,plotHistogram->boundingRect().height()); plot1D->SetZoomBase(0,0,nPixelsX,plot1D->GetYMaximum());*/ - //for some reason this plothistogram works as well. - plot1D->SetZoomBase(0,0,nPixelsX,plotHistogram->boundingRect().height()); - SlsQtH1D* h; - plot1D_hists.append(h=new SlsQtH1D("",nPixelsX,histXAxis,histYAxis[0])); - h->SetLineColor(0); - histFrameIndexTitle->setText(GetHistTitle(0)); - //attach plot - h->Attach(plot1D); - //refixing all the zooming - /*plot1D->SetXMinMax(h->minXValue(),h->maxXValue()); - plot1D->SetYMinMax(h->minYValue(),h->maxYValue()); - plot1D->SetZoomBase(h->minXValue(),h->minYValue(), - h->maxXValue()-h->minXValue(),h->maxYValue()-h->minYValue());*/ - } - - else{ - cout << "Histogram: " << TRIM_HISTOGRAM_XMAX << endl; - - //create intervals - histogramSamples.resize(TRIM_HISTOGRAM_XMAX+1); - for(unsigned int i=0; i= 0)){//if(histogramSamples[j].interval.contains(data->values[i])) - value = (int) histTrimbits[i]; - histogramSamples[value].value += 1; - } - else cout<<"OUT OF BOUNDS:"<setTitle("Trimbits_Plot_Histogram"); - plot1D->SetXTitle("Trimbits"); - plot1D->SetYTitle("Frequency"); - plotHistogram->setData(new QwtIntervalSeriesData(histogramSamples)); - plotHistogram->setPen(QPen(Qt::red)); - plotHistogram->setBrush(QBrush(Qt::red,Qt::Dense4Pattern));//Qt::SolidPattern - histFrameIndexTitle->setText(GetHistTitle(0)); - plotHistogram->attach(plot1D); - //refixing all the zooming - plot1D->SetXMinMax(0,TRIM_HISTOGRAM_XMAX+1); - plot1D->SetYMinMax(0,plotHistogram->boundingRect().height()); - plot1D->SetZoomBase(0,0,actualPixelsX,plotHistogram->boundingRect().height()); - } - } - - - /**needs to be changed */ - else if(detType == slsDetectorDefs::EIGER){ - - //defining axes - nPixelsX = 100;/**??*/ - nPixelsY = 100; - if(lastImageArray) delete [] lastImageArray; lastImageArray = new double[nPixelsY*nPixelsX]; - //initializing 2d array - memset(lastImageArray, 0 ,nPixelsY * nPixelsX * sizeof(double)); - /* - for(int py=0;py<(int)nPixelsY;py++) - for(int px=0;px<(int)nPixelsX;px++) - lastImageArray[py*nPixelsX+px] = 0; - */ - //get trimbits - ret = 1;/*myDet->getChanRegs(lastImageArray,fromDetector);*/ - if(!ret){ - qDefs::Message(qDefs::WARNING,"No Trimbit data found in shared memory.","qDrawPlot::UpdateTrimbitPlot"); - UnlockLastImageArray(); - return qDefs::FAIL; - } - //clear/select plot and set titles - Select2DPlot(); - plot2D->GetPlot()->SetData(nPixelsX,-0.5,nPixelsX-0.5,nPixelsY,-0.5,nPixelsY-0.5,lastImageArray); - plot2D->setTitle("Image"); - plot2D->SetXTitle("Pixel"); - plot2D->SetYTitle("Pixel"); - plot2D->SetZTitle("Trimbits"); - plot2D->UpdateNKeepSetRangeIfSet(); -#ifdef VERBOSE - cout << "Trimbits Plot updated" << endl; -#endif - - //Display Statistics - if(displayStatistics){ - GetStatistics(min,max,sum,lastImageArray,nPixelsX*nPixelsY); - lblMinDisp->setText(QString("%1").arg(min)); - lblMaxDisp->setText(QString("%1").arg(max)); - lblSumDisp->setText(QString("%1").arg(sum)); - } - - } - - UnlockLastImageArray(); -#ifdef VERBOSE - cout << "Trimbits Plot updated" << endl; -#endif - return qDefs::OK; -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qDrawPlot::SetPedestal(bool enable){ -#ifdef VERBOSE - cout << "Setting Pedestal to " << enable << endl; -#endif - if(enable){ - pedestal = true; - if(pedestalVals == 0) - RecalculatePedestal(); - }else{ - pedestal = false; - } -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qDrawPlot::RecalculatePedestal(){ -#ifdef VERBOSE - cout << "Recalculating Pedestal" << endl; -#endif - LockLastImageArray(); - startPedestalCal = 1; - pedestalCount = 0; - - //create array - if(pedestalVals) delete [] pedestalVals; pedestalVals = new double[nPixelsX*nPixelsY]; - if(tempPedestalVals) delete [] tempPedestalVals; tempPedestalVals = new double[nPixelsX*nPixelsY]; - //reset all values - for(unsigned int px=0;px<(nPixelsX*nPixelsY);px++) - pedestalVals[px] = 0; - for(unsigned int px=0;px<(nPixelsX*nPixelsY);px++) - tempPedestalVals[px] = 0; - UnlockLastImageArray(); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qDrawPlot::SetAccumulate(bool enable){ -#ifdef VERBOSE - cout << "Setting Accumulate to " << enable << endl; -#endif - accumulate = enable; + plotEnable = enable; + //if no plot, cant do setting range. + // not true vice versa where plot was false and now set it to true + Clear1DPlot(); } //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::ResetAccumulate(){ -#ifdef VERBOSE - cout << "Resetting Accumulation" << endl; -#endif - LockLastImageArray(); - resetAccumulate = true; - UnlockLastImageArray(); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qDrawPlot::SetPlotTimer(double time){ - timerValue = time; - if(myDet->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG){ - time = myDet->setReceiverReadTimer(timerValue); -#ifdef VERBOSE - cout << "Receiver read timer set to : " << time << endl; -#endif - qDefs::checkErrorMessage(myDet,"qDrawPlot::SetPlotTimer"); - } +void qDrawPlot::DisableZoom(bool disable) { + if (plot_in_scope == 1) + plot1D->DisableZoom(disable); + else + plot2D->GetPlot()->DisableZoom(disable); } //------------------------------------------------------------------------------------------------------------------------------------------------- + int qDrawPlot::UpdateTrimbitPlot(bool fromDetector,bool Histogram){ + int ret; + double min=0,max=0,sum=0; + #ifdef VERBOSE + if(fromDetector) std::cout << "Geting Trimbits from Detector" <<'\n'; + else std::cout << "Getting Trimbits from Shared Memory" <<'\n'; + #endif -void qDrawPlot::SetFrameFactor(int frame){ - frameFactor = frame; - if(myDet->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG){ - frame = myDet->setReadReceiverFrequency(frame); + LockLastImageArray(); + + if(detType == slsDetectorDefs::EIGER){ + + //defining axes + nPixelsX = 100;/**??*/ + nPixelsY = 100; + if(lastImageArray) delete [] lastImageArray; lastImageArray = new double[nPixelsY*nPixelsX]; + //initializing 2d array + memset(lastImageArray, 0 ,nPixelsY * nPixelsX * sizeof(double)); + /* + for(int py=0;py<(int)nPixelsY;++py) + for(int px=0;px<(int)nPixelsX;++px) + lastImageArray[py*nPixelsX+px] = 0; + */ + //get trimbits + ret = 1;/*myDet->getChanRegs(lastImageArray,fromDetector);*/ + if(!ret){ + qDefs::Message(qDefs::WARNING,"No Trimbit data found in shared memory.","qDrawPlot::UpdateTrimbitPlot"); + UnlockLastImageArray(); + return qDefs::FAIL; + } + //clear/select plot and set titles + Select2DPlot(); + plot2D->GetPlot()->SetData(nPixelsX,-0.5,nPixelsX-0.5,nPixelsY,-0.5,nPixelsY-0.5,lastImageArray); + plot2D->setTitle("Image"); + plot2D->SetXTitle("Pixel"); + plot2D->SetYTitle("Pixel"); + plot2D->SetZTitle("Trimbits"); + plot2D->UpdateNKeepSetRangeIfSet(); + #ifdef VERBOSE + std::cout << "Trimbits Plot updated" <<'\n'; + #endif + + //Display Statistics + if(displayStatistics){ + GetStatistics(min,max,sum,lastImageArray,nPixelsX*nPixelsY); + lblMinDisp->setText(QString("%1").arg(min)); + lblMaxDisp->setText(QString("%1").arg(max)); + lblSumDisp->setText(QString("%1").arg(sum)); + } + + } + + UnlockLastImageArray(); + #ifdef VERBOSE + std::cout << "Trimbits Plot updated" <<'\n'; + #endif + return qDefs::OK; + } + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qDrawPlot::SetPedestal(bool enable) { #ifdef VERBOSE - cout << "Receiver read frequency set to : " << frame << endl; + std::cout << "Setting Pedestal to " << enable << '\n'; #endif - } + if (enable) { + pedestal = true; + if (pedestalVals == 0) + RecalculatePedestal(); + } else { + pedestal = false; + } } //------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qDrawPlot::UpdateAfterCloning(bool points, bool logy, bool interpolate, bool contour, bool logz){ +void qDrawPlot::RecalculatePedestal() { #ifdef VERBOSE - cout << endl << "**Updating Plot After Cloning" << endl; + std::cout << "Recalculating Pedestal\n"; #endif + LockLastImageArray(); + startPedestalCal = 1; + pedestalCount = 0; - //1d - if(plot_in_scope == 1){ - SetMarkers(points); - emit LogySignal(logy); - } - //2d - else{ - emit InterpolateSignal(interpolate); - emit ContourSignal(contour); - emit LogzSignal(logz); - } - + //create array + if (pedestalVals) + delete[] pedestalVals; + pedestalVals = new double[nPixelsX * nPixelsY]; + if (tempPedestalVals) + delete[] tempPedestalVals; + tempPedestalVals = new double[nPixelsX * nPixelsY]; + //reset all values + for (unsigned int px = 0; px < (nPixelsX * nPixelsY); ++px) + pedestalVals[px] = 0; + for (unsigned int px = 0; px < (nPixelsX * nPixelsY); ++px) + tempPedestalVals[px] = 0; + UnlockLastImageArray(); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::SetBinary(bool enable, int from, int to){ +void qDrawPlot::SetAccumulate(bool enable) { #ifdef VERBOSE - if(!enable) - cout << "Disabling Binary output " << endl; - else - cout << "Enabling Binary output from " << from << " to " << to << endl; + std::cout << "Setting Accumulate to " << enable << '\n'; #endif - binary = enable; - binaryFrom = from; - binaryTo = to; + accumulate = enable; } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qDrawPlot::DisplayStatistics(bool enable){ +void qDrawPlot::ResetAccumulate() { #ifdef VERBOSE - if(!enable) - cout << "Disabling Statistics Display" << endl; - else - cout << "Enabling Statistics Display" << endl; + std::cout << "Resetting Accumulation" << '\n'; #endif - if(enable) widgetStatistics->show(); - else widgetStatistics->hide(); - - displayStatistics = enable; - lblMinDisp->setText("-"); - lblMaxDisp->setText("-"); - lblSumDisp->setText("-"); + LockLastImageArray(); + resetAccumulate = true; + UnlockLastImageArray(); } - //------------------------------------------------------------------------------------------------------------------------------------------------- +void qDrawPlot::SetPlotTimer(double time) { + // timerValue = time; + // if(myDet->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG){ + // time = myDet->setReceiverReadTimer(timerValue); + // #ifdef VERBOSE + // std::cout << "Receiver read timer set to : " << time <<'\n'; + // #endif + // qDefs::checkErrorMessage(myDet,"qDrawPlot::SetPlotTimer"); + // } +} -void qDrawPlot::GetStatistics(double &min, double &max, double &sum, double* array, int size){ +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qDrawPlot::SetFrameFactor(int frame) { + // frameFactor = frame; + // if(myDet->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG){ + // frame = myDet->setReadReceiverFrequency(frame); + // #ifdef VERBOSE + // std::cout << "Receiver read frequency set to : " << frame <<'\n'; + // #endif + // } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qDrawPlot::UpdateAfterCloning(bool points, bool logy, bool interpolate, bool contour, bool logz) { +#ifdef VERBOSE + std::cout << "**Updating Plot After Cloning\n"; +#endif + + //1d + if (plot_in_scope == 1) { + SetMarkers(points); + emit LogySignal(logy); + } + //2d + else { + emit InterpolateSignal(interpolate); + emit ContourSignal(contour); + emit LogzSignal(logz); + } +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qDrawPlot::SetBinary(bool enable, int from, int to) { +#ifdef VERBOSE + if (!enable) + std::cout << "Disabling Binary output \n"; + else + std::cout << "Enabling Binary output from " << from << " to " << to << '\n'; +#endif + binary = enable; + binaryFrom = from; + binaryTo = to; +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qDrawPlot::DisplayStatistics(bool enable) { +#ifdef VERBOSE + if (!enable) + std::cout << "Disabling Statistics Display\n"; + else + std::cout << "Enabling Statistics Display\n"; +#endif + if (enable) + widgetStatistics->show(); + else + widgetStatistics->hide(); + + displayStatistics = enable; + lblMinDisp->setText("-"); + lblMaxDisp->setText("-"); + lblSumDisp->setText("-"); +} + +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qDrawPlot::GetStatistics(double &min, double &max, double &sum, double *array, int size) { #ifdef VERYVERBOSE - cout << "Calculating Statistics" << endl; + std::cout << "Calculating Statistics\n"; #endif - for(int i=0; i < size; i++){ - //calculate min - if(array[i] < min) - min = array[i]; - //calculate max - if(array[i] > max) - max = array[i]; - //calculate sum - sum += array[i]; - } + for (int i = 0; i < size; ++i) { + //calculate min + if (array[i] < min) + min = array[i]; + //calculate max + if (array[i] > max) + max = array[i]; + //calculate sum + sum += array[i]; + } } - //------------------------------------------------------------------------------------------------------------------------------------------------- - void qDrawPlot::EnableGainPlot(bool e) { #ifdef VERBOSE - cout << "Setting Gain Data enable to " << e << endl; + std::cout << "Setting Gain Data enable to " << e << '\n'; #endif - gainDataEnable = e; + gainDataEnable = e; } - //------------------------------------------------------------------------------------------------------------------------------------------------- -void qDrawPlot::toDoublePixelData(double* dest, char* source,int size, int databytes, int dr, double* gaindest) { - int ichan=0; - int ibyte=0; - int halfbyte=0; - char cbyte = '\0'; - int mask=0x00ffffff; +void qDrawPlot::toDoublePixelData(double *dest, char *source, int size, int databytes, int dr, double *gaindest) { + int ichan = 0; + int ibyte = 0; + int halfbyte = 0; + char cbyte = '\0'; - switch(dr) { + switch (dr) { - case 4: - for (ibyte = 0; ibyte < databytes; ++ibyte) { - cbyte = source[ibyte]; - for (halfbyte = 1; halfbyte >= 0; --halfbyte) { - dest[ichan] = (cbyte >> (halfbyte * 4)) & 0xf; - ++ichan; - } - } - break; + case 4: + for (ibyte = 0; ibyte < databytes; ++ibyte) { + cbyte = source[ibyte]; + for (halfbyte = 1; halfbyte >= 0; --halfbyte) { + dest[ichan] = (cbyte >> (halfbyte * 4)) & 0xf; + ++ichan; + } + } + break; - case 8: - for (ichan = 0; ichan < databytes; ++ichan) { - dest[ichan] = *((u_int8_t*)source); - ++source; - } - break; + case 8: + for (ichan = 0; ichan < databytes; ++ichan) { + dest[ichan] = *((u_int8_t *)source); + ++source; + } + break; - case 16: - if (detType == slsDetectorDefs::JUNGFRAU || detType == slsDetectorDefs::JUNGFRAUCTB) { + case 16: + if (detType == slsDetectorDefs::JUNGFRAU || detType == slsDetectorDefs::MOENCH) { - // show gain plot - if(gaindest!=NULL) { - for (ichan = 0; ichan < size; ++ichan) { - if ( (*((u_int16_t*)source)) == 0xFFFF ) { - gaindest[ichan] = 0xFFFF; - dest[ichan] = 0xFFFF; - } - else{ - gaindest[ichan] = (((*((u_int16_t*)source)) & 0xC000) >> 14); - dest[ichan] = ((*((u_int16_t*)source)) & 0x3FFF); - } - source += 2; - } - } + // show gain plot + if (gaindest != NULL) { + for (ichan = 0; ichan < size; ++ichan) { + if ((*((u_int16_t *)source)) == 0xFFFF) { + gaindest[ichan] = 0xFFFF; + dest[ichan] = 0xFFFF; + } else { + gaindest[ichan] = (((*((u_int16_t *)source)) & 0xC000) >> 14); + dest[ichan] = ((*((u_int16_t *)source)) & 0x3FFF); + } + source += 2; + } + } - // only data plot - else { - for (ichan = 0; ichan < size; ++ichan) { - /*if ( (*((u_int16_t*)source)) == 0xFFFF ) + // only data plot + else { + for (ichan = 0; ichan < size; ++ichan) { + /*if ( (*((u_int16_t*)source)) == 0xFFFF ) dest[ichan] = 0xFFFF; else*/ - dest[ichan] = ((*((u_int16_t*)source)) & 0x3FFF); - source += 2; - } - } - break; - } + dest[ichan] = ((*((u_int16_t *)source)) & 0x3FFF); + source += 2; + } + } + break; + } + // other detectors + for (ichan = 0; ichan < size; ++ichan) { + dest[ichan] = *((u_int16_t *)source); + source += 2; + } + break; - // other detectors - for (ichan = 0; ichan < size; ++ichan) { - dest[ichan] = *((u_int16_t*)source); - source += 2; - } - break; - - default: - if (detType == slsDetectorDefs::MYTHEN) { - for (ichan = 0; ichan < size; ++ichan) { - dest[ichan] = (*((u_int32_t*)source) & mask); - source += 4; - } - break; - } - - // other detectors - for (ichan = 0; ichan < size; ++ichan) { - dest[ichan] = *((u_int32_t*)source); - source += 4; - } - break; - } - + default: + for (ichan = 0; ichan < size; ++ichan) { + dest[ichan] = *((u_int32_t *)source); + source += 4; + } + break; + } } - diff --git a/slsDetectorGui/src/qScanWidget.cpp b/slsDetectorGui/src/qScanWidget.cpp deleted file mode 100644 index df21eb056..000000000 --- a/slsDetectorGui/src/qScanWidget.cpp +++ /dev/null @@ -1,1247 +0,0 @@ -/* - * qScanWidget.cpp - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ -// Project Class Headers -#include "slsDetector.h" -#include "multiSlsDetector.h" -// Qt Project Class Headers -#include "qScanWidget.h" -// Qt Include Headers -#include -#include - -// C++ Include Headers -#include -#include -#include -#include -using namespace std; - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qScanWidget::NUM_SCAN_WIDGETS(0); -const string qScanWidget::modeNames[NumModes]={"","energy","threshold","trimbits","position","custom script"}; -//------------------------------------------------------------------------------------------------------------------------------------------------- - -qScanWidget::qScanWidget(QWidget *parent,multiSlsDetector*& detector): - QWidget(parent),myDet(detector),actualNumSteps(0){ - setupUi(this); - positions.resize(0); - SetupWidgetWindow(); - Initialization(); - LoadPositions(); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -qScanWidget::~qScanWidget(){ - delete myDet; - delete stackedLayout; -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::SetupWidgetWindow(){ - id = NUM_SCAN_WIDGETS; - NUM_SCAN_WIDGETS++; - - setFixedHeight(125); - - btnGroup = new QButtonGroup(this); - btnGroup->addButton(radioRange,0); - btnGroup->addButton(radioCustom,1); - btnGroup->addButton(radioFile,2); - - - normal = radioCustom->palette(); - red = QPalette(); - red.setColor(QPalette::Active,QPalette::WindowText,Qt::red); - fileTip = radioFile->toolTip(); - customTip = radioCustom->toolTip(); - rangeTip = radioRange->toolTip(); - - //layout for the size widgets - stackedLayout = new QStackedLayout; - stackedLayout->setSpacing(0); - - - // Range Size Layout - QWidget *widgetRange = new QWidget; - QHBoxLayout *layoutRange = new QHBoxLayout(widgetRange); - layoutRange->setContentsMargins(0, 0, 0, 0); - lblFrom = new QLabel("from",widgetRange); - spinFrom = new QDoubleSpinBox(widgetRange); - lblTo = new QLabel("to",widgetRange); - spinTo = new QDoubleSpinBox(widgetRange); - lblSize = new QLabel("step size:",widgetRange); - spinSize = new QDoubleSpinBox(widgetRange); - lblFrom->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); - lblFrom->setToolTip(rangeTip); - spinFrom->setValue(0); - spinFrom->setToolTip(rangeTip); - spinFrom->setMaximum(1000000); - spinFrom->setMinimum(-1000000); - spinFrom->setKeyboardTracking(false); - spinFrom->setFixedWidth(80); - spinFrom->setDecimals(2); - lblTo->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); - lblTo->setToolTip(rangeTip); - lblTo->setFixedWidth(18); - spinTo->setValue(1); - spinTo->setToolTip(rangeTip); - spinTo->setMaximum(1000000); - spinTo->setMinimum(-1000000); - spinTo->setKeyboardTracking(false); - spinTo->setFixedWidth(80); - spinTo->setDecimals(2); - lblSize->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); - lblSize->setToolTip(rangeTip); - lblSize->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); - lblSize->setFixedWidth(67); - spinSize->setMaximum(1000000); - spinSize->setMinimum(-1000000); - spinSize->setValue(1); - spinSize->setSingleStep(0.1); - spinSize->setToolTip(rangeTip); - spinSize->setKeyboardTracking(false); - spinSize->setDecimals(2); - - //spinSize->setMinimum(0.0001); - layoutRange->addItem(new QSpacerItem(40,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - layoutRange->addWidget(lblFrom); - layoutRange->addItem(new QSpacerItem(5,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - layoutRange->addWidget(spinFrom); - layoutRange->addItem(new QSpacerItem(5,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - layoutRange->addWidget(lblTo); - layoutRange->addItem(new QSpacerItem(5,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - layoutRange->addWidget(spinTo); - layoutRange->addItem(new QSpacerItem(30,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - layoutRange->addWidget(lblSize); - layoutRange->addWidget(spinSize); - layoutRange->addItem(new QSpacerItem(40,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - - - // Custom Values Layout - QWidget *widgetCustom = new QWidget; - QHBoxLayout *layoutCustom = new QHBoxLayout(widgetCustom); - layoutCustom->setContentsMargins(0, 0, 0, 0); - comboCustom = new QComboBox(widgetCustom); - btnCustom = new QPushButton("Delete ",widgetCustom); - btnCustom->setIcon(QIcon( ":/icons/images/close.png" )); - comboCustom->setEditable(true); - comboCustom->setCompleter(NULL); - comboCustom->setValidator(new QDoubleValidator(comboCustom)); - comboCustom->setToolTip(customTip); - btnCustom->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); - btnCustom->setToolTip("Deletes current position from list and reduces Number of Positions by 1."); - layoutCustom->addItem(new QSpacerItem(160,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - layoutCustom->addWidget(comboCustom); - layoutCustom->addItem(new QSpacerItem(5,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - layoutCustom->addWidget(btnCustom); - layoutCustom->addItem(new QSpacerItem(160,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - - // File values From a File Layout - QWidget *widgetFile = new QWidget; - QHBoxLayout *layoutFile = new QHBoxLayout(widgetFile); - layoutFile->setContentsMargins(0, 0, 0, 0); - layoutFile->addItem(new QSpacerItem(50,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - dispFile = new QLineEdit(widgetFile); - dispFile->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed); - dispFile->setToolTip(fileTip); - layoutFile->addWidget(dispFile); - btnFile = new QPushButton("Browse",widgetFile); - btnFile->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); - btnFile->setToolTip(fileTip); - layoutFile->addWidget(btnFile); - layoutFile->addItem(new QSpacerItem(50,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - - - stackedLayout->addWidget(widgetRange); - stackedLayout->addWidget(widgetCustom); - stackedLayout->addWidget(widgetFile); - stackedWidget->setLayout(stackedLayout); - - radioCustom->setChecked(true); - stackedLayout->setCurrentIndex(CustomValues); - -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::Initialization(){ - //mode - connect(comboScript, SIGNAL(currentIndexChanged(int)), this,SLOT(SetMode(int))); - //file - connect(dispScript, SIGNAL(editingFinished()), this, SLOT(SetScriptFile())); - connect(btnBrowse, SIGNAL(clicked()), this, SLOT(BrowsePath())); - //parameter - connect(dispParameter, SIGNAL(editingFinished()), this, SLOT(SetParameter())); - //sizewidgets - connect(btnGroup, SIGNAL(buttonClicked(QAbstractButton*)),this,SLOT(EnableSizeWidgets())); - //numsteps - connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - //precision - connect(spinPrecision, SIGNAL(valueChanged(int)), this, SLOT(SetPrecision(int))); - //range values - connect(spinFrom, SIGNAL(valueChanged(double)), this, SLOT(RangeFromChanged())); - connect(spinTo, SIGNAL(valueChanged(double)), this, SLOT(RangeToChanged())); - connect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); - //custom values - connect(comboCustom, SIGNAL(currentIndexChanged(int)), this, SLOT(SetCustomSteps())); - connect(btnCustom, SIGNAL(clicked()), this, SLOT(DeleteCustomSteps())); - //file values - connect(dispFile, SIGNAL(editingFinished()), this, SLOT(SetFileSteps())); - connect(btnFile, SIGNAL(clicked()), this, SLOT(BrowseFileStepsPath())); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::EnableSizeWidgets(){ -#ifdef VERYVERBOSE - cout << "Entering EnableSizeWidgets()" << endl; -#endif - //setting to defaults is not done here as this is called even if mode changes - //so only if its to change the size widget type, its set to default for the others - - //scan is none - if(!comboScript->currentIndex()){ - radioCustom->setText("Specific Values"); - radioCustom->setPalette(normal); - radioCustom->setToolTip(customTip); - comboCustom->setToolTip(customTip); - - radioFile->setPalette(normal); - radioFile->setText("Values from File:"); - radioFile->setToolTip(fileTip); - dispFile->setToolTip(fileTip); - btnFile->setToolTip(fileTip); - - lblTo->setPalette(normal); - lblTo->setText("to"); - lblTo->setToolTip(rangeTip); - spinTo->setToolTip(rangeTip); - } - else{ - //range values - if(radioRange->isChecked()){ -#ifdef VERBOSE - cout << "Constant Range Values" << endl; -#endif - - radioCustom->setText("Specific Values"); - radioCustom->setPalette(normal); - radioCustom->setToolTip(customTip); - comboCustom->setToolTip(customTip); - - radioFile->setPalette(normal); - radioFile->setText("Values from File:"); - radioFile->setToolTip(fileTip); - dispFile->setToolTip(fileTip); - btnFile->setToolTip(fileTip); - - stackedLayout->setCurrentIndex(RangeValues); - - //recaluculate number of steps - disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - spinSteps->setValue(1+(int)(abs((spinTo->value() - spinFrom->value()) / spinSize->value()))); - connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - - spinSteps->setMinimum(2); - RangeCheckToValid(); - SetRangeSteps(); - } - //custom values - else if(radioCustom->isChecked()){ -#ifdef VERBOSE - cout << "Custom Values" << endl; -#endif - spinSteps->setMinimum(0); - //defaults for other mode - radioFile->setPalette(normal); - radioFile->setText("Values from File:"); - radioFile->setToolTip(fileTip); - dispFile->setToolTip(fileTip); - btnFile->setToolTip(fileTip); - - lblTo->setPalette(normal); - lblTo->setText("to"); - lblTo->setToolTip(rangeTip); - spinTo->setToolTip(rangeTip); - - //change it back as this list is what will be loaded. - //also numstpes could have been changed in other modes too - disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - spinSteps ->setValue(comboCustom->count()); - connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - - stackedLayout->setCurrentIndex(CustomValues); - //only for custom steps out here because many signals go through - //custom steps and we want to give the info msg only when changig range types - if(SetCustomSteps()==qDefs::OK){ -#ifdef VERYVERBOSE - char cNum[200];sprintf(cNum,"%d",actualNumSteps); - char cId[5];sprintf(cId,"%d",id); - qDefs::Message(qDefs::INFORMATION,string("Scan Level ")+string(cId)+ - string(": Specific Values

Number of positions added: ")+ - string(cNum)+string(""),"qScanWidget::EnableSizeWidgets"); -#endif - } - } - - //file values - else{ -#ifdef VERBOSE - cout << "File Values" << endl; -#endif - spinSteps->setMinimum(0); - //defaults for other mode - radioCustom->setText("Specific Values"); - radioCustom->setPalette(normal); - radioCustom->setToolTip(customTip); - comboCustom->setToolTip(customTip); - - lblTo->setPalette(normal); - lblTo->setText("to"); - lblTo->setToolTip(rangeTip); - spinTo->setToolTip(rangeTip); - - stackedLayout->setCurrentIndex(FileValues); - SetFileSteps(); - } - } - -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::SetMode(int mode){ -#ifdef VERYVERBOSE - cout << "Entering SetMode()" << endl; -#endif -#ifdef VERBOSE - cout << "Setting\tscan:" << id << "\tmode:" << mode << endl; -#endif - // defaults - dispScript->setEnabled(false); - btnBrowse->setEnabled(false); - lblParameter->setEnabled(false); - dispParameter->setEnabled(false); - group->setEnabled(false); - lblSteps->setEnabled(false); - spinSteps->setEnabled(false); - lblPrecision->setEnabled(false); - spinPrecision->setEnabled(false); - - // If anything other than None is selected - if(mode){ - lblSteps->setEnabled(true); - spinSteps->setEnabled(true); - // Custom Script only enables the first layout with addnl parameters etc - if(mode==CustomScript){ - dispScript->setEnabled(true); - btnBrowse->setEnabled(true); - lblParameter->setEnabled(true); - dispParameter->setEnabled(true); - } - group->setEnabled(true); - lblPrecision->setEnabled(true); - spinPrecision->setEnabled(true); - - } - - //set the group box widgets and also calls setscan - EnableSizeWidgets(); - - //set the mode if mode = none - if(!mode) SetScan(mode); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qScanWidget::SetScan(int mode){ -#ifdef VERYVERBOSE - cout << "Entering SetScan()" << endl; -#endif - string parameter = string(dispParameter->text().toAscii().constData()); - string script = string(dispScript->text().toAscii().constData()); -#ifdef VERBOSE - cout << "SETTING scan:" << id << "\tmode:" << comboScript->currentIndex() << - "\tnumSteps:" << actualNumSteps << - "\tscript:" << script << "\tparameter:" << parameter << endl; -#endif - double *values; - if(actualNumSteps) values = new double[actualNumSteps]; - else values = NULL; - for(int i=0;isetScan(id,script,actualNumSteps,values,parameter); - else - myDet->setScan(id,modeNames[mode],actualNumSteps,values,parameter); - - //custom script - int actualMode = myDet->getScanMode(id); - if((mode==CustomScript)&&((script=="")||(script=="none"))){ - return qDefs::OK; - }else{//mode NOT set - if((mode!=actualMode)&&(actualNumSteps)){ - qDefs::Message(qDefs::WARNING,"The mode could not be changed for an unknown reason.","qScanWidget::SetScan"); - comboScript->setCurrentIndex(actualMode); - return qDefs::FAIL; - } - } - - emit EnableScanBox(); - - qDefs::checkErrorMessage(myDet,"qScanWidget::SetScan"); - - return qDefs::OK; -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - -void qScanWidget::BrowsePath(){ -#ifdef VERYVERBOSE - cout << "Entering BrowsePath()" << endl; -#endif -#ifdef VERBOSE - cout << "Browsing Script File Path\tscan:" << id << endl; -#endif - QString fName = dispScript->text(); - QString dir = fName.section('/',0,-2,QString::SectionIncludeLeadingSep); - if(dir.isEmpty()) dir = "/home/"; - //dialog - fName = QFileDialog::getOpenFileName(this, - tr("Load Script File"),dir, - tr("Script Files(*.awk);;All Files(*)")); - //if empty, set the file name and it calls setscriptfile, else ignore - if (!fName.isEmpty()){ - dispScript->setText(fName); - SetScriptFile(); - } -} - -//------------------------------------------------------------------------------------------------------------------------------------------------- - -void qScanWidget::SetScriptFile(){ -#ifdef VERYVERBOSE - cout << "Entering SetScriptFile()" << endl; -#endif - QString fName = dispScript->text(); -#ifdef VERBOSE - cout << "Setting\tscan:" << id << "\tscript:" << fName.toAscii().constData() << endl; -#endif - bool set = false; - struct stat st_buf; - - //blank - if(fName.isEmpty()) - set = true; - //none isnt in the modeNames list, so check separately - else if(!fName.compare("none")) - set = true; - else{//if one of the other modes - for(int i=1;isetText(QString(myDet->getScanScript(id).c_str())); - } - //if its not a file - else if (!S_ISREG (st_buf.st_mode)) { - qDefs::Message(qDefs::WARNING,"The script file path entered is not a file","qScanWidget::SetScriptFile"); - dispScript->setText(QString(myDet->getScanScript(id).c_str())); - } - else - set=true; - } - - //if blank or valid file - if(set){ - myDet->setScanScript(id,fName.toAscii().constData()); - if(fName.compare(QString(myDet->getScanScript(id).c_str()))){ - //did not get set, write what is was before - if(!fName.isEmpty()) - qDefs::Message(qDefs::WARNING,"The script file could not be set. Reverting to previous file.","qScanWidget::SetScriptFile"); - dispScript->setText(QString(myDet->getScanScript(id).c_str())); - } - - } - - //dont display if theres a none - fName = dispScript->text(); - //none isnt in the modeNames list, so check separately - if(!fName.compare("none")) - dispScript->setText(""); - for(int i=1;isetText(""); - - qDefs::checkErrorMessage(myDet,"qScanWidget::SetScriptFile"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::SetParameter(){ -#ifdef VERYVERBOSE - cout << "Entering SetParameter()" << endl; -#endif - QString parameter = dispParameter->text(); -#ifdef VERBOSE - cout << "Setting\tscan:" << id << "\tparameter:" << parameter.toAscii().constData() << endl; -#endif - - myDet->setScanParameter(id,parameter.toAscii().constData()); - //dont display if theres a none - parameter = dispParameter->text(); - //none isnt in the modeNames list, so check separately - if(!parameter.compare("none")) - dispParameter->setText(""); - for(int i=1;isetText(""); - - qDefs::checkErrorMessage(myDet,"qScanWidget::SetParameter"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::SetPrecision(int value){ -#ifdef VERYVERBOSE - cout << "Entering SetPrecision()" << endl; -#endif -#ifdef VERBOSE - cout << "Setting\tscan:" << id << "\tprecision:" << value << endl; -#endif - myDet->setScanPrecision(id,value); - if(myDet->getScanPrecision(id)!=value) - qDefs::Message(qDefs::WARNING,"The precision was not set for an unknown reason.","qScanWidget::SetPrecision");; - - qDefs::checkErrorMessage(myDet,"qScanWidget::SetPrecision"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::SetNSteps(){ -#ifdef VERYVERBOSE - cout << "Entering SetNSteps()" << endl; -#endif -#ifdef VERBOSE - cout << "Setting number of steps" << endl; -#endif - - //check if its ok - if(radioRange->isChecked()){ - disconnect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); - spinSize->setValue( (spinTo->value()-spinFrom->value()) / (spinSteps->value()-1)); - connect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); - RangeCheckToValid(); - SetRangeSteps(); - }else if(radioCustom->isChecked()){ - comboCustom->setMaxCount(spinSteps->value()); - SetCustomSteps(); - }else if(radioFile->isChecked()){ - SetFileSteps(); - } - -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qScanWidget::RangeCheckSizeZero(){ -#ifdef VERYVERBOSE - cout << "Entering RangeCheckSizeZero()" << endl; -#endif - if((spinTo->value()-spinFrom->value())/(spinSteps->value()-1)) - return qDefs::OK; - - return qDefs::FAIL; -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qScanWidget::RangeCheckNumValid(int &num){ -#ifdef VERYVERBOSE - cout << "Entering RangeCheckNumValid()" << endl; -#endif - double div = abs(spinTo->value()-spinFrom->value())/(abs(spinSize->value())); - - //num = (to-from)/size +1 - num = (int)(div) + 1; - - if(num>=2) return qDefs::OK; - - return qDefs::FAIL; -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qScanWidget::RangeCheckToValid(){ -#ifdef VERYVERBOSE - cout << "Entering RangeCheckToValid()" << endl; -#endif - double to = (spinSize->value() * spinSteps->value()) - spinSize->value() + spinFrom->value(); - - //not exact value - if (abs(to-spinTo->value())>0.01){ - lblTo->setPalette(red); - lblTo->setText("to*"); - QString tip = rangeTip + QString("

" - "To is not exact. Entering Size should recalculate To."); - lblTo->setToolTip(tip); - spinTo->setToolTip(tip); - return qDefs::FAIL; - } - - lblTo->setPalette(normal); - lblTo->setText("to"); - lblTo->setToolTip(rangeTip); - spinTo->setToolTip(rangeTip); - return qDefs::OK; -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::RangeFromChanged(){ -#ifdef VERYVERBOSE - cout << "Entering RangeFromChanged()" << endl; -#endif - bool change = false; - int numSteps; - - disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - disconnect(spinFrom, SIGNAL(valueChanged(double)), this, SLOT(RangeFromChanged())); - disconnect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); - - - //check size validity - if(RangeCheckSizeZero()==qDefs::FAIL) - qDefs::Message(qDefs::WARNING,"From cannot be equal to To. Changing From back to previous value.","Scan"); - //check size validity - else if(RangeCheckNumValid(numSteps)==qDefs::FAIL) - qDefs::Message(qDefs::WARNING,"Number of Steps = 1 + ( To - From ) / Size.
" - "Number of Steps must be >= 2. Changing From back to previous value.","qScanWidget::RangeFromChanged"); - else change = true; - - //change it back from = to - size*num + size - if(!change) { - spinFrom->setValue(spinTo->value() - (spinSize->value() * spinSteps->value()) + spinSize->value()); -#ifdef VERBOSE - cout << "Changing From back:"<< spinFrom->value() << endl; -#endif - } - //change num steps - else{ - spinSteps->setValue(numSteps); - //size will lnever be zero here - //size should be positive - if(spinTo->value()>spinFrom->value()) - spinSize->setValue(abs(spinSize->value())); - //size should be negative - else if(spinSize->value()>0) - spinSize->setValue(-1*(spinSize->value())); - } - - RangeCheckToValid(); - SetRangeSteps(); - - connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - connect(spinFrom, SIGNAL(valueChanged(double)), this, SLOT(RangeFromChanged())); - connect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::RangeToChanged(){ -#ifdef VERYVERBOSE - cout << "Entering RangeToChanged()" << endl; -#endif - bool change = false; - int numSteps; - - disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - disconnect(spinTo, SIGNAL(valueChanged(double)), this, SLOT(RangeToChanged())); - disconnect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); - - //check size validity - if(RangeCheckSizeZero()==qDefs::FAIL) - qDefs::Message(qDefs::WARNING,"From cannot be equal to To. Changing To back to previous value.","qScanWidget::RangeToChanged"); - //check size validity - else if(RangeCheckNumValid(numSteps)==qDefs::FAIL) - qDefs::Message(qDefs::WARNING,"Number of Steps = 1 + ( To - From ) / Size.
" - "Number of Steps must be >= 2. Changing To back to previous value.","qScanWidget::RangeToChanged"); - else change = true; - - //change it back to = size*num - size + from - if(!change) { - spinTo->setValue((spinSize->value() * spinSteps->value()) - spinSize->value() + spinFrom->value()); -#ifdef VERBOSE - cout << "Changing To back:"<< spinTo->value() << endl; -#endif - } - //change num steps - else{ - spinSteps->setValue(numSteps); - //size will lnever be zero here - //size should be positive - if(spinTo->value()>spinFrom->value()) - spinSize->setValue(abs(spinSize->value())); - //size should be negative - else if(spinSize->value()>0) - spinSize->setValue(-1*(spinSize->value())); - - } - - RangeCheckToValid(); - SetRangeSteps(); - - connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - connect(spinTo, SIGNAL(valueChanged(double)), this, SLOT(RangeToChanged())); - connect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::RangeSizeChanged(){ -#ifdef VERYVERBOSE - cout << "Entering RangeSizeChanged()" << endl; -#endif - bool change = false; - int numSteps; - - disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - disconnect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); - disconnect(spinTo, SIGNAL(valueChanged(double)), this, SLOT(RangeToChanged())); - - //check size validity - if(!spinSize->value()) - qDefs::Message(qDefs::WARNING,"Size cannot be 0. Changing Size back to previous value.","qScanWidget::RangeSizeChanged"); - //check size validity - else if(RangeCheckNumValid(numSteps)==qDefs::FAIL) - qDefs::Message(qDefs::WARNING,"Number of Steps = 1 + ( To - From ) / Size.
" - "Number of Steps must be >= 2. Changing Size back to previous value.","qScanWidget::RangeSizeChanged"); - else change = true; - - //change it back size = (to-from)/(num-1) - if(!change) { - spinSize->setValue((spinTo->value()-spinFrom->value())/(spinSteps->value()-1)); -#ifdef VERBOSE - cout << "Changing Size back:"<< spinSize->value() << endl; -#endif - } - //change num steps - else{ - spinSteps->setValue(numSteps); - //in case size changed to negative - spinTo->setValue((spinSize->value() * spinSteps->value()) - spinSize->value() + spinFrom->value()); - lblTo->setPalette(normal); - lblTo->setText("to"); - lblTo->setToolTip(rangeTip); - spinTo->setToolTip(rangeTip); - } - - RangeCheckToValid(); - SetRangeSteps(); - - connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - connect(spinSize, SIGNAL(valueChanged(double)), this, SLOT(RangeSizeChanged())); - connect(spinTo, SIGNAL(valueChanged(double)), this, SLOT(RangeToChanged())); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::SetRangeSteps(){ -#ifdef VERYVERBOSE - cout << "Entering SetRangeSteps()" << endl; -#endif -#ifdef VERBOSE - cout << "Setting\tscan:" << id << "\trange\t"; -#endif - double fromVal = spinFrom->value(); - double sizeVal = spinSize->value(); - actualNumSteps = spinSteps->value(); - - -#ifdef VERBOSE - cout << "num pos:" << actualNumSteps << endl; -#endif - - //set the vector positions - positions.resize(actualNumSteps); - for(int i=0;icurrentIndex())==qDefs::OK){ - char cId[5];sprintf(cId,"%d",id); - QString script = dispScript->text(); - - - //positions wont be loaded if its custom script - if((comboScript->currentIndex()==CustomScript)&&((script=="")||(script=="none"))){ - qDefs::Message(qDefs::INFORMATION,string("Scan Level ")+string(cId)+ - string(": Constant Step Size

" - "Positions could not be loaded as the script file path is empty."),"qScanWidget::SetRangeSteps"); - }else{ - //error loading positions - if(myDet->getScanSteps(id)!=actualNumSteps){ - qDefs::Message(qDefs::WARNING,string("Scan Level ")+string(cId)+ - string(": Values From File

" - "The positions list was not set for an unknown reason."),"qScanWidget::SetRangeSteps"); - /*LoadPositions(); - comboScript->setCurrentIndex(myDet->getScanMode(id))*/ - } -#ifdef VERYVERBOSE - else{//SUCCESS - char cNum[200];sprintf(cNum,"%d",actualNumSteps); - qDefs::Message(qDefs::INFORMATION,string("Scan Level ")+string(cId)+ - string(": Constant Step Size

Number of positions added: ")+ - string(cNum)+string(""),"qScanWidget::SetRangeSteps"); - } -#endif - } - } - - qDefs::checkErrorMessage(myDet,"qScanWidget::SetRangeSteps"); -} -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qScanWidget::SetCustomSteps(){ -#ifdef VERYVERBOSE - cout << "Entering SetCustomSteps()" << endl; -#endif -#ifdef VERBOSE - cout << "Setting\tscan:" << id << "\tcustom\tnum pos:" << comboCustom->count() << endl; -#endif - disconnect(comboCustom, SIGNAL(currentIndexChanged(int)), this, SLOT(SetCustomSteps())); - - //get number of positions - int numSteps = spinSteps->value(); - comboCustom->setMaxCount(numSteps); - comboCustom->setEnabled(numSteps); - btnCustom->setEnabled(numSteps); - - //deleting too many or not entering enough - if(numSteps>comboCustom->count()){ -#ifdef VERBOSE - cout << "Too few entries" << endl; -#endif - int diff = numSteps - (comboCustom->count()); - radioCustom->setPalette(red); - radioCustom->setText("Specific Values*"); - QString tip = customTip + QString("

Add ")+ - (QString("%1").arg(diff))+ - QString(" more positions to the list to match Number of Steps.
" - "
Or reduce Number of Steps.
"); - radioCustom->setToolTip(tip); - comboCustom->setToolTip(tip); - }else{ - radioCustom->setText("Specific Values"); - radioCustom->setPalette(normal); - radioCustom->setToolTip(customTip); - comboCustom->setToolTip(customTip); - } - - actualNumSteps = comboCustom->count(); - //delete existing positions - positions.resize(actualNumSteps); - //copying the list - for(int i=0;iitemText(i).toDouble(); -#ifdef VERBOSE - cout << "positions[" << i << "]:" << positions[i] << endl; -#endif - } - - //sets the scan - if(SetScan(comboScript->currentIndex())==qDefs::OK){ - char cId[5];sprintf(cId,"%d",id); - QString script = dispScript->text(); - //positions wont be loaded if its custom script - if((comboScript->currentIndex()==CustomScript)&&((script=="")||(script=="none"))){ - qDefs::Message(qDefs::INFORMATION,string("Scan Level ")+string(cId)+ - string(": Values From File

" - "Positions could not be loaded as the script file path is empty."),"qScanWidget::SetCustomSteps"); - return qDefs::FAIL; - }else{ - if(myDet->getScanSteps(id)!=actualNumSteps){ - qDefs::Message(qDefs::WARNING,"The positions list was not set for an unknown reason.","qScanWidget::SetCustomSteps"); - LoadPositions(); - comboScript->setCurrentIndex(myDet->getScanMode(id)); - qDefs::checkErrorMessage(myDet,"qScanWidget::qScanWidget::SetCustomSteps"); - return qDefs::FAIL; - } - //else success is checked in enabledsizewidgets , else it does this for every add, delete etc - } - } - - //if num of steps = 0 - if(!spinSteps->value()){ - comboCustom->setEnabled(false); - btnCustom->setEnabled(false); - radioCustom->setPalette(red); - radioCustom->setText("Specific Values*"); - QString tip = customTip + QString("

First, increase Number of Steps. " - "Then, enter values here."); - radioCustom->setToolTip(tip); - comboCustom->setToolTip(tip); - } - connect(comboCustom, SIGNAL(currentIndexChanged(int)), this, SLOT(SetCustomSteps())); - - return qDefs::OK; -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::DeleteCustomSteps(){ -#ifdef VERYVERBOSE - cout << "Entering DeleteCustomSteps()" << endl; -#endif - QString pos = comboCustom->currentText(); - bool found = false; - //loops through to find the index and to make sure its in the list - for(int i=0;icount();i++){ - if(!comboCustom->itemText(i).compare(pos)){ - found = true; - comboCustom->removeItem(i); - break; - } - } - if(found){ -#ifdef VERBOSE - cout << "Deleting Position " << endl; -#endif - } -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::SetFileSteps(){ -#ifdef VERYVERBOSE - cout << "Entering SetFileSteps()" << endl; -#endif - QString fName = dispFile->text(); -#ifdef VERBOSE - cout << "Setting\tscan:" << id << "\tfile\t:" << fName.toAscii().constData() << endl; -#endif - bool set = false; - struct stat st_buf; - - //blank - if(fName.isEmpty()){ -#ifdef VERBOSE - cout << "Empty file" << endl; -#endif - radioFile->setPalette(red); - radioFile->setText("Values from File:*"); - QString errTip = fileTip + QString("

The file path is empty.");; - radioFile->setToolTip(errTip);dispFile->setToolTip(errTip);btnFile->setToolTip(errTip); - } - //not a blank - else{ - QString file = dispFile->text().section('/',-1); - - //path doesnt exist - if(stat(file.toAscii().constData(),&st_buf)){ -#ifdef VERBOSE - cout << "The file entered does not exist." << endl; -#endif - radioFile->setPalette(red); - radioFile->setText("Values from File:*"); - QString errTip = fileTip + QString("

The file entered does not exist."); - radioFile->setToolTip(errTip);dispFile->setToolTip(errTip);btnFile->setToolTip(errTip); - } - //if its not a file - else if (!S_ISREG (st_buf.st_mode)) { -#ifdef VERBOSE - cout << "The file path entered is not a file." << endl; -#endif - radioFile->setPalette(red); - radioFile->setText("Values from File:*"); - QString errTip = fileTip + QString("

The file path entered is not a file."); - radioFile->setToolTip(errTip); dispFile->setToolTip(errTip);btnFile->setToolTip(errTip); - } - else - set = true; - } - - //if valid file - if(set){ - ifstream inFile;string sLine;char sArg[200]=""; - //open file - inFile.open(fName.toAscii().constData(), ifstream::in); - if(inFile.is_open()){ - //delete existing positions - positions.resize(0); - actualNumSteps = 0; -#ifdef VERBOSE - cout << "Opening file "<< fName.toAscii().constData() << endl; -#endif - while(inFile.good()) { - getline(inFile,sLine); - if(sLine.find('#')!=string::npos) continue;//commented out - else if(sLine.length()<2) continue;// empty line - else { - istringstream sstr(sLine); - if(sstr.good()){ - actualNumSteps++; - positions.resize(actualNumSteps); - sstr>>sArg; - if(!sscanf(sArg,"%lf",&positions[actualNumSteps-1])){ - actualNumSteps--; - positions.resize(actualNumSteps); - } - else cout << "value[" << actualNumSteps-1 << "]:" << positions[actualNumSteps-1] << endl; - } - } - } - disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - spinSteps->setValue(actualNumSteps); - connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - inFile.close(); - }else {//could not open file -#ifdef VERBOSE - cout << "Could not open file" << endl; -#endif - set = false; - radioFile->setPalette(red); - radioFile->setText("Values from File:*"); - QString errTip = fileTip + QString("

Could not read file."); - radioFile->setToolTip(errTip);dispFile->setToolTip(errTip); btnFile->setToolTip(errTip); - } - } - if(set){//no error while reading file - //sets the scan and positions - if(SetScan(comboScript->currentIndex())==qDefs::OK){ - char cId[5];sprintf(cId,"%d",id); - QString script = dispScript->text(); - radioFile->setPalette(normal); - radioFile->setText("Values from File:"); - radioFile->setToolTip(fileTip);dispFile->setToolTip(fileTip);btnFile->setToolTip(fileTip); - //positions wont be loaded if its custom script - if((comboScript->currentIndex()==CustomScript)&&((script=="")||(script=="none"))){ - qDefs::Message(qDefs::INFORMATION,string("Scan Level ")+string(cId)+ - string(": Values From File

" - "Positions could not be loaded as the script file path is empty."),"qScanWidget::SetFileSteps"); - }else{ - //error loading positions - if(myDet->getScanSteps(id)!=actualNumSteps){ - qDefs::Message(qDefs::WARNING,string("Scan Level ")+string(cId)+ - string(": Values From File

" - "The positions list was not set for an unknown reason."),"qScanWidget::SetFileSteps"); - } -#ifdef VERYVERBOSE - else{//SUCCESS - char cNum[200];sprintf(cNum,"%d",actualNumSteps); - qDefs::Message(qDefs::INFORMATION,string("Scan Level ")+string(cId)+ - string(": Values From File

Number of positions added: ")+ - string(cNum)+string(""),"qScanWidget::SetFileSteps"); - } -#endif - } - } - } - //ERROR IN WRITING FILENAME OR READING FILE - else{ - actualNumSteps=0; - positions.resize(0); - SetScan(comboScript->currentIndex()); - disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - spinSteps->setValue(actualNumSteps); - connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - } - - qDefs::checkErrorMessage(myDet,"qScanWidget::SetFileSteps"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::BrowseFileStepsPath(){ -#ifdef VERYVERBOSE - cout << "Entering BrowseFileStepsPath()" << endl; -#endif -#ifdef VERBOSE - cout << "Browsing Steps File Path\tscan:" << id << endl; -#endif - QString fName = dispFile->text(); - QString dir = fName.section('/',0,-2,QString::SectionIncludeLeadingSep); - if(dir.isEmpty()) dir = "/home/"; - //dialog - fName = QFileDialog::getOpenFileName(this, - tr("Load Scan Steps Script File"),dir, - tr("Scan Steps Script Files(*.awk);;All Files(*)")); - //if empty, set the file name and it calls SetFileSteps, else ignore - if (!fName.isEmpty()){ - dispFile->setText(fName); - SetFileSteps(); - } - -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::LoadPositions(){ -#ifdef VERYVERBOSE - cout << "Entering LoadPositions()" << endl; -#endif - disconnect(comboCustom, SIGNAL(currentIndexChanged(int)), this, SLOT(SetCustomSteps())); - disconnect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - disconnect(btnGroup, SIGNAL(buttonClicked(QAbstractButton*)),this,SLOT(EnableSizeWidgets())); - - - int mode = myDet->getScanMode(id); - radioCustom->setChecked(true); - - int numSteps = myDet->getScanSteps(id); - actualNumSteps = numSteps; - comboCustom->setMaxCount(numSteps); - positions.resize(actualNumSteps); - - //set the number of steps in the gui - spinSteps->setValue(numSteps); - - //load the positions - double *values = NULL; - if(actualNumSteps){ - values = new double[actualNumSteps]; - myDet->getScanSteps(id,values); - } - for(int i=0;isetText("Specific Values"); - radioCustom->setPalette(normal); - radioCustom->setToolTip(customTip); - comboCustom->setToolTip(customTip); - }//no positions and has a mode - else if(mode){ - radioCustom->setPalette(red); - radioCustom->setText("Specific Values*"); - QString tip = customTip + QString("

First, increase Number of Steps. " - "Then, enter values here."); - radioCustom->setToolTip(tip); - comboCustom->setToolTip(tip); - } - for(int i=0;icount();i++) - comboCustom->removeItem(i); - for(int i=0;iinsertItem(i,QString("%1").arg(positions[i])); - - //delete the combolist and reload it - comboCustom->setEnabled(numSteps&&mode); - btnCustom->setEnabled(numSteps&&mode); - - connect(comboCustom, SIGNAL(currentIndexChanged(int)), this, SLOT(SetCustomSteps())); - connect(spinSteps, SIGNAL(valueChanged(int)), this, SLOT(SetNSteps())); - connect(btnGroup, SIGNAL(buttonClicked(QAbstractButton*)),this,SLOT(EnableSizeWidgets())); - - qDefs::checkErrorMessage(myDet,"qScanWidget::LoadPositions"); - //do not set the range variables because if the stepsize is by any chance 0.. - //then the number of steps should change to 1. so only set custom steps -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qScanWidget::Refresh(){ -#ifdef VERYVERBOSE - cout << "Entering Refresh()" << endl; -#endif - int mode = (myDet->getScanMode(id)); - string script = myDet->getScanScript(id); - string parameter = myDet->getScanParameter(id); - int precision = myDet->getScanPrecision(id); - - - //settings values and checking for none - if(QString(script.c_str()).compare("none")) - dispScript->setText(QString(script.c_str())); - if(mode) SetScriptFile(); - dispParameter->setText(QString(parameter.c_str())); - SetParameter(); - spinPrecision->setValue(precision); - - //set mode which also checks number of steps - //and enable size widgets and set the positions from combolist to server - comboScript->setCurrentIndex(mode); - - -#ifdef VERBOSE - cout << "Updated\tscan:" << id << "\t" - "mode:" << mode << "\t" - "script:" << script << "\t" - "numSteps:" << actualNumSteps << "\t" - //"values:" << arrSteps << "\t" - "parameter:" << parameter << "\t" - "precision:" << precision << "\t***" << endl; -#endif - - qDefs::checkErrorMessage(myDet,"qScanWidget::Refresh"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/slsDetectorGui/src/qServer.cpp b/slsDetectorGui/src/qServer.cpp old mode 100644 new mode 100755 index 9b83a8d9c..e8ae77581 --- a/slsDetectorGui/src/qServer.cpp +++ b/slsDetectorGui/src/qServer.cpp @@ -1,431 +1,171 @@ -/* - * qServer.cpp - * - * Created on: Feb 27, 2013 - * Author: Dhanya Maliakal - */ -// Qt Project Class Headers #include "qServer.h" #include "qDetectorMain.h" -// Project Class Headers -#include "slsDetector.h" + +#include "ServerSocket.h" #include "multiSlsDetector.h" -#include "MySocketTCP.h" -// C++ Include Headers +#include "string_utils.h" + #include #include -using namespace std; - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qServer::gui_server_thread_running(0); - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -qServer::qServer(qDetectorMain *t): - myMainTab(t), mySocket(0),myStopSocket(0),port_no(DEFAULT_GUI_PORTNO),lockStatus(0),checkStarted(0),checkStopStarted(0){ - strcpy(mess,""); - FunctionTable(); +#include +qServer::qServer(qDetectorMain *t) + : threadRunning(false), threadStarted(false), mainTab(t), + controlPort(DEFAULT_GUI_PORTNO), stopPort(DEFAULT_GUI_PORTNO + 1), + controlSocket(nullptr), stopSocket(nullptr) { + FILE_LOG(logDEBUG) << "Client Server ready"; } +qServer::~qServer() {} -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -qServer::~qServer(){ - delete myMainTab; - if(mySocket) delete mySocket; - if(myStopSocket) delete myStopSocket; +void qServer::FunctionTable() { + flist.push_back(qServer::GetStatus); + flist.push_back(qServer::StartAcquisition); + flist.push_back(qServer::StopsAcquisition); + flist.push_back(qServer::Acquire); + flist.push_back(qServer::ExitServer); } +int qServer::DecodeFunction(ServerSocket *sock) { + int ret = qDefs::FAIL; + int fnum = 0; + int n = sock->ReceiveDataOnly(&fnum, sizeof(fnum)); + if (n <= 0) { + FILE_LOG(logDEBUG3) << "Received " << n << " bytes"; + throw sls::RuntimeError("Could not read socket"); + } -//------------------------------------------------------------------------------------------------------------------------------------------------- + // unrecognized function + if (fnum < 0 && fnum >= qDefs::NUM_GUI_FUNCS) { + ret = qDefs::FAIL; + char mess[MAX_STR_LENGTH] = {}; + sls::strcpy_safe(mess, "Unrecognized function"); + // will throw an exception + sock->SendResult(ret, nullptr, 0, mess); + } + // calling function + FILE_LOG(logDEBUG1) << "calling function fnum: " << fnum; + ret = (this->*flist[fnum])(); -int qServer::FunctionTable(){ - - flist[F_GET_RUN_STATUS] = &qServer::GetStatus; - flist[F_START_ACQUISITION] = &qServer::StartAcquisition; - flist[F_STOP_ACQUISITION] = &qServer::StopsAcquisition; - flist[F_START_AND_READ_ALL] = &qServer::Acquire; - flist[F_EXIT_SERVER] = &qServer::ExitServer; - - return qDefs::OK; + return ret; } - -//------------------------------------------------------------------------------------------------------------------------------------------ - - -int qServer::DecodeFunction(MySocketTCP* sock){ - int ret = qDefs::FAIL; - int n,fnum; -#ifdef VERYVERBOSE - cout << "receive data" << endl; -#endif - n = sock->ReceiveDataOnly(&fnum,sizeof(fnum)); - if (n <= 0) { -#ifdef VERYVERBOSE - cout << "ERROR reading from socket " << n << ", " << fnum << endl; -#endif - return qDefs::FAIL; - } -#ifdef VERYVERBOSE - else - cout << "size of data received " << n <ShutDownSocket(); - - myStopSocket->SendDataOnly(&ret,sizeof(ret)); - myStopSocket->SendDataOnly(mess,sizeof(mess)); - return GOODBYE; - } - - - //calling function - ret = (this->*flist[fnum])(); - if (ret==qDefs::FAIL) - cout << "Error executing the function = " << fnum << endl; - - return ret; +void qServer::ShutDownSockets() { + threadRunning = false; + if (controlSocket) { + controlSocket->shutDownSocket(); + delete controlSocket; + controlSocket = nullptr; + } + if (stopSocket) { + stopSocket->shutDownSocket(); + delete stopSocket; + stopSocket = nullptr; + } } - -//------------------------------------------------------------------------------------------------------------------------------------------ - - -int qServer::ExitServer(){ - - int ret = OK; - strcpy(mess," Gui Server closed successfully\n"); - - if(mySocket) - mySocket->ShutDownSocket(); - - myStopSocket->SendDataOnly(&ret,sizeof(ret)); - myStopSocket->SendDataOnly(mess,sizeof(mess)); - cout << mess << endl; - - return GOODBYE; +void qServer::CreateServers() { + if (!threadRunning) { + FILE_LOG(logINFO) << "Starting Gui Servers"; + threadRunning = true; + + try { + // start control server + controlSocket = new ServerSocket(controlPort); + std::async(std::launch::async, ServerThread, controlSocket); + FILE_LOG(logDEBUG) + << "Gui control server thread created successfully."; + // start stop server + stopSocket = new ServerSocket(stopPort); + std::async(std::launch::async, ServerThread, stopSocket); + FILE_LOG(logDEBUG) + << "Gui stop server thread created successfully."; + } catch (...) { + ShutDownSockets(); + std::string message = "Can't create gui control server thread"; + FILE_LOG(logERROR) << message; + qDefs::Message(qDefs::WARNING, message, "qServer::CreateServers"); + } + } } - -//------------------------------------------------------------------------------------------------------------------------------------------ - - - -int qServer::StartStopServer(int start){ - - //start server - if(start){ -#ifdef VERBOSE - cout << endl << "Starting Gui Server" << endl; -#endif - - if(!gui_server_thread_running){ - gui_server_thread_running=1; - - - //error creating thread - checkStarted=1; - if (pthread_create(&gui_server_thread, NULL,StartServerThread, (void*) this)){ - gui_server_thread_running=0; - qDefs::Message(qDefs::WARNING,"Can't create gui server thread", "qServer::StartStopServer"); - cout << "ERROR: Can't create gui server thread" << endl; - return FAIL; - } - while(checkStarted); - checkStarted = 0; -#ifdef VERBOSE - if(gui_server_thread_running) - cout << "Server thread created successfully." << endl; -#endif - - - //error creating thread - checkStopStarted=1; - if (pthread_create(&gui_stop_server_thread, NULL,StopServerThread, (void*) this)){ - gui_server_thread_running=0; - qDefs::Message(qDefs::WARNING,"Can't create gui stop server thread", "qServer::StartStopServer"); - cout << "ERROR: Can't create gui stop server thread" << endl; - return FAIL; - } - while(checkStopStarted); - checkStopStarted=0; -#ifdef VERBOSE - if(gui_server_thread_running) - cout << "Server Stop thread created successfully." << endl; -#endif - } - } - - - //stop server - else{ -#ifdef VERBOSE - cout << "Stopping Gui Server" << endl; -#endif - - if(gui_server_thread_running){ - gui_server_thread_running=0; - - if(mySocket) - mySocket->ShutDownSocket(); - pthread_join(gui_server_thread,NULL); - if(mySocket){ - delete mySocket; - mySocket = 0; - } - - if(myStopSocket) - myStopSocket->ShutDownSocket(); - pthread_join(gui_stop_server_thread,NULL); - if(myStopSocket){ - delete myStopSocket; - myStopSocket = 0; - } - } -#ifdef VERBOSE - cout << "Server threads stopped successfully." << endl; -#endif - } - - return gui_server_thread_running; +void qServer::DestroyServers() { + if (threadRunning) { + FILE_LOG(logINFO) << "Stopping Gui Servers"; + ShutDownSockets(); + FILE_LOG(logDEBUG) << "Server threads stopped successfully."; + } } +void qServer::ServerThread(ServerSocket* sock) { + FILE_LOG(logDEBUG) << "Starting Gui Server at port " << sock->getPort(); -//------------------------------------------------------------------------------------------------------------------------------------------------- + while (threadRunning)) { + try{ + sock->accept(); + if (DecodeFunction(sock) == GOODBYE) { + threadRunning = false; + } + sock->close(); + } + // any fails will throw an exception, which will be displayed at client side. Ignore here + catch (...) {} + } + FILE_LOG(logDEBUG) << "Stopped gui server thread"; - -void* qServer::StopServerThread(void* this_pointer){ - ((qServer*)this_pointer)->StopServer(); - return this_pointer; + // stop port is closed last + if (sock->getPort() == stopPort) + emit ServerStoppedSignal(); } +int qServer::GetStatus(ServerSock* sock) { + slsDetectorDefs::runStatus status = slsDetectorDefs::ERROR; + int progress = 0; + if (myMainTab->isPlotRunning()) + status = slsDetectorDefs::RUNNING; + else + status = slsDetectorDefs::IDLE; -//------------------------------------------------------------------------------------------------------------------------------------------------- + progress = myMainTab->GetProgress(); - - -int qServer::StopServer(){ -#ifdef VERYVERBOSE - cout << "In StopServer()" << endl; -#endif - int ret = qDefs::OK; - - try { - MySocketTCP* s = new MySocketTCP(port_no+1); - myStopSocket = s; - } catch(...) { - gui_server_thread_running = 0; - qDefs::Message(qDefs::WARNING,"Could not start gui stop server socket","qServer::StopServer"); - } - checkStopStarted = 0; - - while ((gui_server_thread_running) && (ret!=GOODBYE)) { -#ifdef VERBOSE - cout<< endl; -#endif -#ifdef VERYVERBOSE - cout << "Waiting for client call" << endl; -#endif - if(myStopSocket->Connect()>=0){ -#ifdef VERYVERBOSE - cout << "Conenction accepted" << endl; -#endif - ret = DecodeFunction(myStopSocket); -#ifdef VERYVERBOSE - cout << "function executed" << endl; -#endif - myStopSocket->Disconnect(); -#ifdef VERYVERBOSE - cout << "connection closed" << endl; -#endif - } - } -#ifdef VERBOSE - cout << "Stopped gui stop server thread" << endl; -#endif - gui_server_thread_running = 0; - //delete socket(via exit server) - if(myStopSocket){ - delete myStopSocket; - myStopSocket = 0; - } - - if(!gui_server_thread_running) - emit ServerStoppedSignal(); - - return qDefs::OK; + int ret = qDefs::OK + int retvals[2] = {static_cast(retval), progress}; + sock->SendResult(ret, retvals, sizeof(retvals), nullptr); + return ret; } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - - -void* qServer::StartServerThread(void* this_pointer){ - ((qServer*)this_pointer)->StartServer(); - return this_pointer; +int qServer::StartAcquisition(ServerSock* sock) { + char mess[MAX_STR_LENGTH] = {}; + sls::strcpy_safe(mess, "Could not start acquistion in Gui"); + int ret = myMainTab->StartStopAcquisitionFromClient(true); + sock->SendResult(ret, nullptr, 0, mess); + return ret; } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - - -int qServer::StartServer(){ -#ifdef VERYVERBOSE - cout << "In StartServer()" << endl; -#endif - int ret = qDefs::OK; - - try { - MySocketTCP* s = new MySocketTCP(port_no); - mySocket = s; - } catch(...) { - gui_server_thread_running = 0; - qDefs::Message(qDefs::WARNING,"Could not start gui server socket","qServer::StartServer"); - } - checkStarted = 0; - - while ((gui_server_thread_running) && (ret!=GOODBYE)) { -#ifdef VERBOSE - cout<< endl; -#endif -#ifdef VERYVERBOSE - cout << "Waiting for client call" << endl; -#endif - if(mySocket->Connect()>=0){ -#ifdef VERYVERBOSE - cout << "Conenction accepted" << endl; -#endif - ret = DecodeFunction(mySocket); -#ifdef VERYVERBOSE - cout << "function executed" << endl; -#endif - mySocket->Disconnect(); -#ifdef VERYVERBOSE - cout << "connection closed" << endl; -#endif - } - } -#ifdef VERBOSE - cout << "Stopped gui server thread" << endl; -#endif - gui_server_thread_running = 0; - //delete socket(via exit server) - if(mySocket){ - delete mySocket; - mySocket = 0; - } - - if(!gui_server_thread_running) - emit ServerStoppedSignal(); - - return qDefs::OK; +int qServer::StopsAcquisition(ServerSock* sock) { + char mess[MAX_STR_LENGTH] = {}; + sls::strcpy_safe(mess, "Could not stop acquistion in Gui"); + int ret = myMainTab->StartStopAcquisitionFromClient(false); + sock->SendResult(ret, nullptr, 0, mess); + return ret; } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qServer::GetStatus(){ - - int ret = qDefs::OK; - enum slsDetectorDefs::runStatus retval; - int progress = 0; - - // execute action if the arguments correctly arrived - if(myMainTab->isPlotRunning()) - retval = slsDetectorDefs::RUNNING; - else - retval = slsDetectorDefs::IDLE; - - progress = myMainTab->GetProgress(); - - // send answer - myStopSocket->SendDataOnly(&ret,sizeof(ret)); - myStopSocket->SendDataOnly(&retval,sizeof(retval)); - myStopSocket->SendDataOnly(&progress,sizeof(progress)); - //return ok/fail - return ret; +int qServer::Acquire(ServerSock* sock) { + char mess[MAX_STR_LENGTH] = {}; + sls::strcpy_safe(mess, "Could not start blocking acquistion in Gui"); + int ret = myMainTab->StartStopAcquisitionFromClient(true); + // blocking + usleep(5000); + while (myMainTab->isPlotRunning()) + ; + sock->SendResult(ret, nullptr, 0, mess); + return ret; } - -//------------------------------------------------------------------------------------------------------------------------------------------ - - -int qServer::StartAcquisition(){ - - strcpy(mess,"Could not start acquisition in gui. \n"); - - int ret = myMainTab->StartStopAcquisitionFromClient(true); - mySocket->SendDataOnly(&ret,sizeof(ret)); - if(ret==FAIL) - mySocket->SendDataOnly(mess,sizeof(mess)); - - return ret; -} - - -//------------------------------------------------------------------------------------------------------------------------------------------ - - -int qServer::StopsAcquisition(){ - - strcpy(mess,"Could not stop acquisition in gui. \n"); - - int ret = myMainTab->StartStopAcquisitionFromClient(false); - myStopSocket->SendDataOnly(&ret,sizeof(ret)); - if(ret==FAIL) - myStopSocket->SendDataOnly(mess,sizeof(mess)); - - return ret; -} - - -//------------------------------------------------------------------------------------------------------------------------------------------ - - -int qServer::Acquire(){ - - strcpy(mess,"Could not start blocking acquisition in gui. \n"); - - int ret = myMainTab->StartStopAcquisitionFromClient(true); - - usleep(5000); - while(myMainTab->isPlotRunning()); - - mySocket->SendDataOnly(&ret,sizeof(ret)); - if(ret==FAIL) - mySocket->SendDataOnly(mess,sizeof(mess)); - - return ret; -} - - -//------------------------------------------------------------------------------------------------------------------------------------------ - +int qServer::ExitServer(ServerSock* sock) { + DestroyServers(); + int ret = qDefs::OK; + sock->SendResult(ret, nullptr, 0, mess); + return GOODBYE; +} \ No newline at end of file diff --git a/slsDetectorGui/src/qTabActions.cpp b/slsDetectorGui/src/qTabActions.cpp deleted file mode 100644 index 37a8f7693..000000000 --- a/slsDetectorGui/src/qTabActions.cpp +++ /dev/null @@ -1,585 +0,0 @@ -/* - * qTabActions.cpp - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ -// Qt Project Class Headers -#include "qTabActions.h" -// Project Class Headers -#include "slsDetector.h" -#include "multiSlsDetector.h" -// Qt Include Headers -#include -// C++ Include Headers -#include -using namespace std; - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -qTabActions::qTabActions(QWidget *parent,multiSlsDetector*& detector): - QWidget(parent),myDet(detector), - positionWidget(0), - lblNumPos(0), - lblPosList(0), - spinNumPos(0), - comboPos(0), - btnDelete(0), - chkInvert(0), - chkSeparate(0), - chkReturn(0), - positions(0), - iconPlus(0), - iconMinus(0){ - for(int i=0;i<6;i++) - actionWidget[i]=0; - for(int i=0;i<2;i++) - scanWidget[i]=0; - for(int i=0;isetWidget(this); - scroll->setWidgetResizable(true); - - // Layout Settings - gridLayout = new QGridLayout(scroll); - setLayout(gridLayout); - gridLayout->setContentsMargins(10,5,0,0); - gridLayout->setVerticalSpacing(2); - - // Buttongroup to know which +/- button was clicked - group = new QButtonGroup(this); - group->setExclusive(false); - palette = new QPalette(); - - QPalette p; - p.setColor(QPalette::Shadow,QColor(0,0,0,0)); - p.setColor(QPalette::Button,QColor(0,0,0,0)); -/*get rid of this vector*/ - char names[NumTotalActions][200] = { - "Action at Start", - "Scan Level 0", - "Scan Level 1", - "Action before each Frame", - "Positions", - "Header before Frame", - "Header after Frame", - "Action after each Frame", - "Action at Stop" - }; - - //creating the icons for the buttons - iconPlus = new QIcon(":/icons/images/add.png"); - iconMinus = new QIcon(":/icons/images/remove.png"); - - QString tip = "Click on the \"+\" to Expand or \"-\" to Collapse."; - - - - int hIndent=0, vIndent=0, colspan=6, posVal=0; - QLabel *lblReal; - // For each level of Actions - for(int i=0;isetToolTip(tip); - btnExpand[i]->setCheckable(true); - btnExpand[i]->setChecked(false); - btnExpand[i]->setFixedSize(16,16); - btnExpand[i]->setToolTip(tip); - btnExpand[i]->setIcon(*iconPlus); - btnExpand[i]->setFocusPolicy(Qt::NoFocus); - btnExpand[i]->setFlat(true); - btnExpand[i]->setIconSize(QSize(16,16)); - btnExpand[i]->setPalette(p); - group->addButton(btnExpand[i],i); - - - //add label and button to expand or collapse - gridLayout->addWidget(btnExpand[i],vIndent,hIndent,1,1); - gridLayout->addWidget(lblName[i],vIndent,hIndent+1,1,colspan); - - //creating the action/scan/position widgets and adding them - switch(i){ - case NumPositions: - CreatePositionsWidget(); - gridLayout->addWidget(positionWidget,vIndent+1,hIndent+1,1,colspan); - positionWidget->hide(); - break; - case Scan0: - case Scan1: - posVal = qScanWidget::NUM_SCAN_WIDGETS; - scanWidget[posVal] = new qScanWidget(this,myDet); - gridLayout->addWidget(scanWidget[posVal],vIndent+1,hIndent+1,1,colspan); - scanWidget[posVal]->hide(); - break; - default: - posVal = qActionsWidget::NUM_ACTION_WIDGETS; - actionWidget[posVal] = new qActionsWidget(this,myDet); - gridLayout->addWidget(actionWidget[posVal],vIndent+1,hIndent+1,1,colspan); - actionWidget[posVal]->hide(); - break; - } - - //incrementing the vertical and horizontal indent - vIndent+=2; - switch(i){ - case HeaderBefore: - //real time acquisition - palette->setColor(QPalette::Active,QPalette::WindowText,QColor(0,0,200,255)); - lblReal = new QLabel(" Real Time Acquisition"); - lblReal->setFixedHeight(25); - //lblReal->setPalette(*palette); - gridLayout->addWidget(lblReal,vIndent,hIndent+1,1,colspan); - vIndent++; - break; - case HeaderAfter: - hIndent-=2; - colspan+=2; - break; - case ActionAfter: - hIndent=0; - colspan=6; - break; - default: - hIndent++; - colspan--; - break; - } - - } - - - //Number of positions is only for mythen or gotthard - detType = myDet->getDetectorsType(); - if((detType == slsDetectorDefs::EIGER) || - (detType == slsDetectorDefs::AGIPD) || - (detType == slsDetectorDefs::PROPIX) || - (detType == slsDetectorDefs::JUNGFRAU) || - (detType == slsDetectorDefs::JUNGFRAUCTB) || - (detType == slsDetectorDefs::MOENCH)) { - lblName[NumPositions]->setEnabled(false); - btnExpand[NumPositions]->setEnabled(false); - }else{ - //disable positions if angular conversion is enabled - int ang; - if(!myDet->getAngularConversion(ang)){ - lblName[NumPositions]->setEnabled(false); - btnExpand[NumPositions]->setEnabled(false); - } - - } - - //load positions - if(lblName[NumPositions]->isEnabled()){ - //delete existing positions - if (positions) {delete [] positions; positions = NULL;} - //get number of positions - int numPos=myDet->getPositions(); - comboPos->setMaxCount(numPos); - - //set the number of positions in the gui - spinNumPos->setValue(numPos); - - positions=new double[numPos]; - //load the positions - myDet->getPositions(positions); - - //delete the combolist and reload it - comboPos->setEnabled(numPos); - lblPosList->setEnabled(numPos); - btnDelete->setEnabled(numPos); - lblPosList->setText("List of Positions: "); - lblPosList->setPalette(normal); - for(int i=0;icount();i++) comboPos->removeItem(i); - for(int i=0;iinsertItem(i,QString("%1").arg(positions[i])); - } - - - qDefs::checkErrorMessage(myDet,"qTabActions::SetupWidgetWindow"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabActions::CreatePositionsWidget(){ - positionWidget = new QWidget; - positionWidget->setFixedHeight(25); - positionWidget->setFixedWidth(680); - - QGridLayout *layout = new QGridLayout(positionWidget); - layout->setContentsMargins(0,0,0,0); - layout->setHorizontalSpacing(0); - layout->setVerticalSpacing(5); - - lblNumPos = new QLabel("Number of Positions: "); - lblNumPos->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); - layout->addWidget(lblNumPos,0,0); - layout->addItem(new QSpacerItem(5,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,1); - spinNumPos = new QSpinBox(this); - layout->addWidget(spinNumPos,0,2); - layout->addItem(new QSpacerItem(80,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,3); - lblPosList = new QLabel("List of Positions: "); - lblPosList->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); - lblPosList->setFixedWidth(108); - lblPosList->setEnabled(false); - lblPosList->setToolTip("Enter the positions at which the detector should be moved.
" - "Number of entries is restricted to Number of Positions field."); - layout->addWidget(lblPosList,0,4); - comboPos = new QComboBox(this); - comboPos->setEditable(true); -// comboPos->setCompleter(false); - comboPos->setCompleter(NULL); - normal = comboPos->palette(); - comboPos->setEnabled(false); - QDoubleValidator *validate = new QDoubleValidator(comboPos); - comboPos->setValidator(validate); - layout->addWidget(comboPos,0,5); - layout->addItem(new QSpacerItem(5,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,6); - btnDelete = new QPushButton("Delete "); - btnDelete->setEnabled(false); - btnDelete->setIcon(QIcon( ":/icons/images/close.png" )); - btnDelete->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); - layout->addWidget(btnDelete,0,7); - - //might be included at some point -/* QGroupBox *w = new QGroupBox; - layout->addWidget(w,1,0,1,9); - QHBoxLayout *l1 = new QHBoxLayout(w); - l1->setContentsMargins(0,0,0,0); - l1->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - chkInvert = new QCheckBox("Invert Angles"); - l1->addWidget(chkInvert); - chkSeparate = new QCheckBox("Separate Two Halves"); - l1->addWidget(chkSeparate); - chkReturn = new QCheckBox("Return to Start Position"); - chkReturn->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); - l1->addWidget(chkReturn); - l1->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed)); - w->setLayout(l1);*/ - - positionWidget->setLayout(layout); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabActions::Initialization(){ - //expand - connect(group, SIGNAL(buttonClicked(QAbstractButton*)), this,SLOT(Expand(QAbstractButton*))); - //enable scan box in plot tab - for(int i=0;iid(button); - - // Collapse - if(!button->isChecked()){ - palette->setColor(QPalette::Active,QPalette::WindowText,Qt::black); - - - lblName[index]->setPalette(*palette); - button->setIcon(*iconPlus); - - if(index==NumPositions) { - positionWidget->hide(); - setFixedHeight(height()-30);//-80 if the checkboxes are included - if(myDet->getPositions()) { - palette->setColor(QPalette::Active,QPalette::WindowText,Qt::darkGreen); - lblName[index]->setPalette(*palette); - } - } - else if((index==Scan0)||(index==Scan1)) { - scanWidget[GetActualIndex(index)]->hide(); - setFixedHeight(height()-130); - if(myDet->getScanMode(GetActualIndex(index))){ - palette->setColor(QPalette::Active,QPalette::WindowText,Qt::darkGreen); - lblName[index]->setPalette(*palette); - } - } - else { - actionWidget[GetActualIndex(index)]->hide(); - setFixedHeight(height()-30); - if(myDet->getActionMode(GetActualIndex(index))){ - palette->setColor(QPalette::Active,QPalette::WindowText,Qt::darkGreen); - lblName[index]->setPalette(*palette); - } - } - }else{ - // Expand - //always set title color to blue for expan\d - - palette->setColor(QPalette::Active,QPalette::WindowText,QColor(0,0,200,255)); - - - lblName[index]->setPalette(*palette); - button->setIcon(*iconMinus); - - if(index==NumPositions){ - positionWidget->show(); - setFixedHeight(height()+30);//+80 if the checkboxes are included - } - else if((index==Scan0)||(index==Scan1)){ - scanWidget[GetActualIndex(index)]->show(); - setFixedHeight(height()+130); - } - else{ - actionWidget[GetActualIndex(index)]->show(); - setFixedHeight(height()+30); - } - } - - qDefs::checkErrorMessage(myDet,"qTabActions::Expand"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabActions::SetPosition(){ -#ifdef VERBOSE - cout << "Entering SetPosition\tnum Pos:" << spinNumPos->value() << "\tlist count:" << comboPos->count() << endl; -#endif - //get number of positions - int numPos = spinNumPos->value(); - comboPos->setMaxCount(numPos); - comboPos->setEnabled(numPos); - lblPosList->setEnabled(numPos); - btnDelete->setEnabled(numPos); - - //deleting too many or not entering enough - if(numPos>comboPos->count()){ - - QPalette red = QPalette(); - red.setColor(QPalette::Active,QPalette::WindowText,Qt::red); - lblPosList->setPalette(red); - QString tip = QString("Enter the positions at which the detector should be moved.
" - "Number of entries is restricted to Number of Positions field.

")+ - QString("Add ")+ - (QString("%1").arg(((numPos)-(comboPos->count()))))+ - QString(" more positions to the list to match Number of Positions.
" - "Or reduce Number of Positions.
"); - lblPosList->setToolTip(tip); - lblPosList->setText("List of Positions:*"); - }else{ - lblPosList->setText("List of Positions: "); - lblPosList->setPalette(normal); - lblPosList->setToolTip("Enter the positions at which the detector should be moved.
" - "Number of entries is restricted to Number of Positions field."); - } - - //delete existing positions - if (positions) {delete [] positions; positions = NULL;} - positions=new double[comboPos->count()]; - //copying the list - for(int i=0;icount();i++) - positions[i] = comboPos->itemText(i).toDouble(); - //setting the list and catching error - if(myDet->setPositions(comboPos->count(),positions)!=comboPos->count()) - qDefs::Message(qDefs::WARNING,"The positions list was not set for some reason.","qTabActions::SetPosition"); - - - qDefs::checkErrorMessage(myDet,"qTabActions::SetPosition"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabActions::DeletePosition(){ - QString pos = comboPos->currentText(); - bool found = false; - //loops through to find the index and to make sure its in the list - for(int i=0;icount();i++){ - if(!comboPos->itemText(i).compare(pos)){ - found = true; - comboPos->removeItem(i); - break; - } - } - if(found){ -#ifdef VERBOSE - cout << "Deleting Position " << endl; -#endif - } -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabActions::EnablePositions(bool enable){ -#ifdef VERBOSE - cout << "Enable Positions: " << enable << endl; -#endif - if(enable){ - lblName[NumPositions]->setEnabled(true); - btnExpand[NumPositions]->setEnabled(true); - }else{ - //deletes all positions - for(int i=0;icount();i++) - comboPos->removeItem(i); - cout<<"Number of Positions set to :"<getPositions()<isChecked()){ - disconnect(group, SIGNAL(buttonClicked(QAbstractButton*)), this,SLOT(Expand(QAbstractButton*))); - btnExpand[NumPositions]->setChecked(false); - connect(group, SIGNAL(buttonClicked(QAbstractButton*)), this,SLOT(Expand(QAbstractButton*))); - Expand(group->button(NumPositions)); - } - lblName[NumPositions]->setEnabled(false); - btnExpand[NumPositions]->setEnabled(false); - } - - qDefs::checkErrorMessage(myDet,"qTabActions::EnablePositions"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabActions::Refresh(){ -#ifdef VERBOSE - cout << endl <<"**Updating all action widgets: " << endl; -#endif - if((detType == slsDetectorDefs::MYTHEN) || (detType == slsDetectorDefs::GOTTHARD)){ - //positions is enabled only if angular conversion is enabled - int ang; if(!myDet->getAngularConversion(ang)) EnablePositions(false); - - if(lblName[NumPositions]->isEnabled()){ - //delete existing positions - if (positions) {delete [] positions; positions = NULL;} - //get number of positions - int numPos=myDet->getPositions(); - comboPos->setMaxCount(numPos); - - //set the number of positions in the gui - disconnect(spinNumPos, SIGNAL(valueChanged(int)), this, SLOT(SetPosition())); - spinNumPos->setValue(numPos); - connect(spinNumPos, SIGNAL(valueChanged(int)), this, SLOT(SetPosition())); - - positions=new double[numPos]; - //load the positions - myDet->getPositions(positions); - - //delete the combolist and reload it - disconnect(comboPos,SIGNAL(currentIndexChanged(int)), this, SLOT(SetPosition())); - comboPos->setEnabled(numPos); - lblPosList->setEnabled(numPos); - btnDelete->setEnabled(numPos); - lblPosList->setText("List of Positions: "); - lblPosList->setPalette(normal); - for(int i=0;icount();i++) - comboPos->removeItem(i); - for(int i=0;iinsertItem(i,QString("%1").arg(positions[i])); - connect(comboPos, SIGNAL(currentIndexChanged(int)), this, SLOT(SetPosition())); - - -#ifdef VERBOSE - cout << "Updated position widget\tnum:" << numPos << "\t***" << endl; -#endif - } - } - for(int i=0;iRefresh(); - for(int i=0;iRefresh(); - UpdateCollapseColors(); -#ifdef VERBOSE - cout << "**Updated all action widgets: " << endl << endl; -#endif - - qDefs::checkErrorMessage(myDet,"qTabActions::Refresh"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qTabActions::GetActualIndex(int index){ - switch(index){ - case 0: return slsDetectorDefs::startScript; - case Scan0: return 0; - case Scan1: return 1; - case 3: return slsDetectorDefs::scriptBefore; - case 5: return slsDetectorDefs::headerBefore; - case 6: return slsDetectorDefs::headerAfter; - case 7: return slsDetectorDefs::scriptAfter; - case 8: return slsDetectorDefs::stopScript; - default: return -1; - } -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabActions::UpdateCollapseColors(){ -#ifdef VERYVERBOSE - cout << "Updating Collapse Colors" << endl; -#endif - for(int i=0;igetPositions()) palette->setColor(QPalette::Active,QPalette::WindowText,Qt::darkGreen); - else palette->setColor(QPalette::Active,QPalette::WindowText,Qt::black); - lblName[i]->setPalette(*palette); - } - //scans - else if((i==Scan0)||(i==Scan1)){ - if(myDet->getScanMode(GetActualIndex(i))) palette->setColor(QPalette::Active,QPalette::WindowText,Qt::darkGreen); - else palette->setColor(QPalette::Active,QPalette::WindowText,Qt::black); - lblName[i]->setPalette(*palette); - } - //actions - else{ - if(myDet->getActionMode(GetActualIndex(i))) palette->setColor(QPalette::Active,QPalette::WindowText,Qt::darkGreen); - else palette->setColor(QPalette::Active,QPalette::WindowText,Qt::black); - lblName[i]->setPalette(*palette); - } - } - -} -//------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/slsDetectorGui/src/qTabAdvanced.cpp b/slsDetectorGui/src/qTabAdvanced.cpp old mode 100644 new mode 100755 index 616d2ed4d..d808196e0 --- a/slsDetectorGui/src/qTabAdvanced.cpp +++ b/slsDetectorGui/src/qTabAdvanced.cpp @@ -1,200 +1,88 @@ -/* - * qTabAdvanced.cpp - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ #include "qTabAdvanced.h" #include "qDrawPlot.h" -/** Project Class Headers */ -#include "slsDetector.h" + #include "multiSlsDetector.h" -/** Qt Include Headers */ -#include -/** C++ Include Headers */ + #include -using namespace std; -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -qTabAdvanced::qTabAdvanced(QWidget *parent,multiSlsDetector*& detector, qDrawPlot*& plot): - QWidget(parent),myDet(detector),det(0),myPlot(plot),btnGroup(NULL),isEnergy(false),isAngular(false), - lblFromX(0), - spinFromX(0), - lblFromY(0), - spinFromY(0), - lblToX(0), - spinToX(0), - lblToY(0), - spinToY(0), - numRois(0){ +qTabAdvanced::qTabAdvanced(QWidget *parent, multiSlsDetector* detector): +QWidget(parent), myDet(detector),detType(slsDetectorDefs::GENERIC), +lblFromX(0), +spinFromX(0), +lblFromY(0), +spinFromY(0), +lblToX(0), +spinToX(0), +lblToY(0), +spinToY(0), +numRois(0){ setupUi(this); SetupWidgetWindow(); + FILE_LOG(logDEBUG) << "Advanced ready"; } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - - qTabAdvanced::~qTabAdvanced(){ delete myDet; - if(det) delete det; } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetupWidgetWindow(){ -//executed even for non digital, so make sure its necessary - - //Network - lblIP->setEnabled(false); - lblMAC->setEnabled(false); - dispIP->setEnabled(false); - dispMAC->setEnabled(false); - boxRxr->setEnabled(false); - boxSetAllTrimbits->setEnabled(false); - - red = QPalette(); red.setColor(QPalette::Active,QPalette::WindowText,Qt::red); - outputDirTip = dispFile->toolTip(); - errOutputTip = QString("

" - "Output Trim File should contain both existing directory and a file name.
" - "The extensions are automatically added.

" - "Enter valid Output Trim File to enable Start Trimming button.
"); detOnlineTip = comboOnline->toolTip(); rxrOnlineTip = comboRxrOnline->toolTip(); errOnlineTip = QString("

It is offline!"); - acqSubPeriodTip = spinSubPeriod->toolTip(); - errSubPeriodTip = acqSubPeriodTip + - QString("

Sub Frame Period " - "should be greater than or equal to " - "Sub Frame Exposure Time.
"); - - - - detType = myDet->getDetectorsType(); - switch(detType){ - case slsDetectorDefs::MYTHEN: - isEnergy = true; - isAngular = true; - spinZmqPort->setEnabled(false); - spinZmqPort2->setEnabled(false); - dispZMQIP->setEnabled(false); - dispZMQIP2->setEnabled(false); - break; - case slsDetectorDefs::EIGER: - isEnergy = true; - isAngular = false; - lblIP->setEnabled(true); - lblMAC->setEnabled(true); - dispIP->setEnabled(true); - dispMAC->setEnabled(true); - boxRxr->setEnabled(true); + detType = myDet->getDetectorTypeAsEnum(); + if (detType == slsDetectorDefs::EIGER ) { boxSetAllTrimbits->setEnabled(true); lblSubExpTime->setEnabled(true); spinSubExpTime->setEnabled(true); comboSubExpTimeUnit->setEnabled(true); - lblSubPeriod->setEnabled(true); - spinSubPeriod->setEnabled(true); - comboSubPeriodUnit->setEnabled(true); - break; - case slsDetectorDefs::MOENCH: - isEnergy = false; - isAngular = false; - lblIP->setEnabled(true); - lblMAC->setEnabled(true); - dispIP->setEnabled(true); - dispMAC->setEnabled(true); - boxRxr->setEnabled(true); - break; - case slsDetectorDefs::GOTTHARD: - isEnergy = false; - isAngular = true; - lblIP->setEnabled(true); - lblMAC->setEnabled(true); - dispIP->setEnabled(true); - dispMAC->setEnabled(true); - boxRxr->setEnabled(true); - break; - case slsDetectorDefs::JUNGFRAU: - case slsDetectorDefs::JUNGFRAUCTB: - isEnergy = false; - isAngular = false; - lblIP->setEnabled(true); - lblMAC->setEnabled(true); - dispIP->setEnabled(true); - dispMAC->setEnabled(true); - boxRxr->setEnabled(true); - break; - default: break; + lblSubDeadTime->setEnabled(true); + spinSubDeadTime->setEnabled(true); + comboSubDeadTimeUnit->setEnabled(true); } - //logs and trimming - if(!isAngular && !isEnergy) boxLogs->setEnabled(false); - else{ - if(!isAngular) chkAngularLog->setEnabled(false); - if(!isEnergy){ - chkEnergyLog->setEnabled(false); - boxPlot->setEnabled(false); - boxTrimming->setEnabled(false); - }else{ - boxTrimming->setChecked(false); - SetOptimize(false); - - btnGroup = new QButtonGroup(this); - btnGroup->addButton(btnRefresh,0); - btnGroup->addButton(btnGetTrimbits,1); - } - } - trimmingMode = slsDetectorDefs::NOISE_TRIMMING; - //network //add detectors - for(int i=0;igetNumberOfDetectors();i++) + for(int i=0;igetNumberOfDetectors(); ++i) comboDetector->addItem(QString(myDet->getHostname(i).c_str())); comboDetector->setCurrentIndex(0); - - det = myDet->getSlsDetector(comboDetector->currentIndex()); + int moduleId = comboDetector->currentIndex(); qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetupWidgetWindow"); - cout << "Getting ports" << endl; - spinControlPort->setValue(det->getControlPort()); - spinStopPort->setValue(det->getStopPort()); - spinTCPPort->setValue(det->getReceiverPort()); - spinUDPPort->setValue(atoi(det->getReceiverUDPPort().c_str())); - spinZmqPort->setValue(atoi(det->getClientStreamingPort().c_str())); - spinZmqPort2->setValue(atoi(det->getReceiverStreamingPort().c_str())); + FILE_LOG(logDEBUG) << "Getting ports"; + spinControlPort->setValue(myDet->setControlPort(-1, moduleId)); + spinStopPort->setValue(myDet->setStopPort(-1, moduleId)); + spinTCPPort->setValue(myDet->setReceiverPort(-1, moduleId)); + spinUDPPort->setValue(myDet->getReceiverUDPPort(moduleId)); + spinZmqPort->setValue(myDet->getClientStreamingPort(moduleId)); + spinZmqPort2->setValue(myDet->getReceiverStreamingPort(moduleId)); - cout << "Getting network information" << endl; - dispIP->setText(det->getDetectorIP().c_str()); - dispMAC->setText(det->getDetectorMAC().c_str()); - dispRxrHostname->setText(det->getReceiver().c_str()); - dispUDPIP->setText(det->getReceiverUDPIP().c_str()); - dispUDPMAC->setText(det->getReceiverUDPMAC().c_str()); - dispZMQIP->setText(det->getClientStreamingIP().c_str()); - dispZMQIP2->setText(det->getReceiverStreamingIP().c_str()); + FILE_LOG(logDEBUG) << "Getting network information"; + dispIP->setText(myDet->getDetectorIP(moduleId).c_str()); + dispMAC->setText(myDet->getDetectorMAC(moduleId).c_str()); + dispRxrHostname->setText(myDet->getReceiverHostname(moduleId).c_str()); + dispUDPIP->setText(myDet->getReceiverUDPIP(moduleId).c_str()); + dispUDPMAC->setText(myDet->getReceiverUDPMAC(moduleId).c_str()); + dispZMQIP->setText(myDet->getClientStreamingIP(moduleId).c_str()); + dispZMQIP2->setText(myDet->getReceiverStreamingIP(moduleId).c_str()); //check if its online and set it to red if offline -#ifdef VERYVERBOSE - cout << "online" << endl; -#endif - if(det->setOnline()==slsDetectorDefs::ONLINE_FLAG) - det->checkOnline(); - if(det->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG) - det->checkReceiverOnline(); - comboOnline->setCurrentIndex(det->setOnline()); - comboRxrOnline->setCurrentIndex(det->setReceiverOnline()); + FILE_LOG(logDEBUG) << "Getting online status"; + if(myDet->setOnline(moduleId)==slsDetectorDefs::ONLINE_FLAG) + myDet->checkOnline(moduleId); + if(myDet->setReceiverOnline(moduleId)==slsDetectorDefs::ONLINE_FLAG) + myDet->checkReceiverOnline(moduleId); + comboOnline->setCurrentIndex(myDet->setOnline(moduleId)); + comboRxrOnline->setCurrentIndex(myDet->setReceiverOnline(moduleId)); if(!comboOnline->currentIndex()){ comboOnline->setToolTip(detOnlineTip + errOnlineTip); lblOnline->setToolTip(detOnlineTip + errOnlineTip); @@ -210,22 +98,16 @@ void qTabAdvanced::SetupWidgetWindow(){ //updates roi - cout << "Getting ROI" << endl; + FILE_LOG(logDEBUG) << "Getting ROI"; if (detType == slsDetectorDefs::GOTTHARD) updateROIList(); -#ifdef VERYVERBOSE - // print receiver configurations - if(detType != slsDetectorDefs::MYTHEN){ - cout << endl; - myDet->printReceiverConfiguration(); - } -#endif + myDet->printReceiverConfiguration(logDEBUG); // jungfrau - if (detType == slsReceiverDefs::JUNGFRAU) { - lblNumStoragecells->setEnabled(true); - spinNumStoragecells->setEnabled(true); - spinNumStoragecells->setValue((int)myDet->setTimer(slsDetectorDefs::STORAGE_CELL_NUMBER,-1)); + if (detType == slsDetectorDefs::JUNGFRAU) { + lblNumStoragecells->setEnabled(true); + spinNumStoragecells->setEnabled(true); + spinNumStoragecells->setValue((int)myDet->setTimer(slsDetectorDefs::STORAGE_CELL_NUMBER,-1)); } else if (detType == slsDetectorDefs::EIGER) { //subexptime qDefs::timeUnit unit; @@ -234,555 +116,119 @@ void qTabAdvanced::SetupWidgetWindow(){ comboSubExpTimeUnit->setCurrentIndex((int)unit); //period time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::SUBFRAME_DEADTIME,-1)*(1E-9)))); - spinSubPeriod->setValue(time); - comboSubPeriodUnit->setCurrentIndex((int)unit); + spinSubDeadTime->setValue(time); + comboSubDeadTimeUnit->setCurrentIndex((int)unit); - CheckAcqPeriodGreaterThanExp(); } Initialization(); - qDefs::checkErrorMessage(det,"qTabAdvanced::SetupWidgetWindow"); + qDefs::checkErrorMessage(myDet, moduleId,"qTabAdvanced::SetupWidgetWindow"); } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::Initialization(){ connect(tabAdvancedSettings,SIGNAL(currentChanged(int)), this, SLOT(Refresh())); - //energy/angular logs - if(isAngular) - connect(chkEnergyLog, SIGNAL(toggled(bool)), this, SLOT(SetLogs())); - - if(isEnergy){ - connect(chkAngularLog, SIGNAL(toggled(bool)), this, SLOT(SetLogs())); - - //exptime - connect(spinExpTime, SIGNAL(valueChanged(double)), this, SLOT(SetExposureTime())); - connect(comboExpUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(SetExposureTime())); - - //threshold dac - connect(spinThreshold, SIGNAL(valueChanged(double)), this, SLOT(SetThreshold())); - - //output directory - connect(dispFile, SIGNAL(editingFinished()), this, SLOT(SetOutputFile())); - connect(btnFile, SIGNAL(clicked()), this, SLOT(BrowseOutputFile())); - - //setalltrimbits - if(boxSetAllTrimbits->isEnabled()) - connect(spinSetAllTrimbits, SIGNAL(editingFinished()), this, SLOT(SetAllTrimbits())); - - //enable trimming method group box - connect(boxTrimming, SIGNAL(toggled(bool)), this, SLOT(EnableTrimming(bool))); - - //trimming method combo - connect(comboMethod, SIGNAL(currentIndexChanged(int)), this, SLOT(SetTrimmingMethod(int))); - - //method options - connect(chkOptimize, SIGNAL(toggled(bool)), this, SLOT(SetOptimize(bool))); - - //start Trimming - connect(btnStart, SIGNAL(clicked()), this, SLOT(StartTrimming())); - - //refresh - connect(btnGroup, SIGNAL(buttonClicked(int)), this, SLOT(UpdateTrimbitPlot(int))); - } - //network connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(SetDetector(int))); connect(spinControlPort, SIGNAL(valueChanged(int)), this, SLOT(SetControlPort(int))); connect(spinStopPort, SIGNAL(valueChanged(int)), this, SLOT(SetStopPort(int))); connect(comboOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetOnline(int))); - if(detType!=slsDetectorDefs::MYTHEN){ + //network + connect(spinTCPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrTCPPort(int))); + connect(spinUDPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrUDPPort(int))); + connect(spinZmqPort, SIGNAL(valueChanged(int)), this, SLOT(SetCltZmqPort(int))); + connect(spinZmqPort2, SIGNAL(valueChanged(int)), this, SLOT(SetRxrZmqPort(int))); + connect(comboRxrOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetReceiverOnline(int))); - //network - connect(spinTCPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrTCPPort(int))); - connect(spinUDPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrUDPPort(int))); - connect(spinZmqPort, SIGNAL(valueChanged(int)), this, SLOT(SetCltZmqPort(int))); - connect(spinZmqPort2, SIGNAL(valueChanged(int)), this, SLOT(SetRxrZmqPort(int))); - connect(comboRxrOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetReceiverOnline(int))); + connect(dispIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispUDPIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispUDPMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); - connect(dispIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); - connect(dispMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); - connect(dispUDPIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); - connect(dispUDPMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispZMQIP, SIGNAL(editingFinished()), this, SLOT(SetClientZMQIP())); + connect(dispZMQIP2, SIGNAL(editingFinished()), this, SLOT(SetReceiverZMQIP())); - connect(dispZMQIP, SIGNAL(editingFinished()), this, SLOT(SetClientZMQIP())); - connect(dispZMQIP2, SIGNAL(editingFinished()), this, SLOT(SetReceiverZMQIP())); + connect(btnRxr, SIGNAL(clicked()), this, SLOT(SetReceiver())); - connect(btnRxr, SIGNAL(clicked()), this, SLOT(SetReceiver())); - } - - - //roi if (detType == slsDetectorDefs::GOTTHARD) { + // roi connect(btnClearRoi, SIGNAL(clicked()), this, SLOT(clearROIinDetector())); connect(btnGetRoi, SIGNAL(clicked()), this, SLOT(updateROIList())); connect(btnSetRoi, SIGNAL(clicked()), this, SLOT(setROI())); } - if(detType == slsReceiverDefs::JUNGFRAU) { - connect(spinNumStoragecells, SIGNAL(valueChanged(int)), this, SLOT(SetNumStoragecells(int))); - } else if (detType == slsDetectorDefs::EIGER) { + else if(detType == slsDetectorDefs::JUNGFRAU) { + // storage cells + connect(spinNumStoragecells, SIGNAL(valueChanged(int)), this, SLOT(SetNumStoragecells(int))); + } + + else if (detType == slsDetectorDefs::EIGER) { + // all trimbits + connect(spinSetAllTrimbits, SIGNAL(editingFinished()), this, SLOT(SetAllTrimbits())); + //Exposure Time connect(spinSubExpTime,SIGNAL(valueChanged(double)), this, SLOT(SetSubExposureTime())); connect(comboSubExpTimeUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(SetSubExposureTime())); + //Frame Period between exposures - connect(spinSubPeriod,SIGNAL(valueChanged(double)), this, SLOT(SetSubPeriod())); - connect(comboSubPeriodUnit,SIGNAL(currentIndexChanged(int)),this, SLOT(SetSubPeriod())); + connect(spinSubDeadTime,SIGNAL(valueChanged(double)), this, SLOT(SetSubDeadTime())); + connect(comboSubDeadTimeUnit,SIGNAL(currentIndexChanged(int)),this, SLOT(SetSubDeadTime())); } } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabAdvanced::SetLogs(){ - QCheckBox *checkedBox = qobject_cast(sender()); - int index = ((!checkedBox->text().compare("Energy Calibration"))?slsDetectorDefs::enCalLog:slsDetectorDefs::angCalLog); - bool enable = checkedBox->isChecked(); -#ifdef VERBOSE - if(index==slsDetectorDefs::enCalLog) - cout << "Setting Energy Calibration Logs to " << enable << endl; - else - cout << "Setting Angular Calibration Logs to " << enable << endl; -#endif - //set/unset the log - myDet->setAction(index,(enable?"set":"none")); - //verify - if(myDet->getActionMode(index)!=(enable)){ -#ifdef VERBOSE - cout << "Could not set/reset Log." << endl; -#endif - qDefs::Message(qDefs::WARNING,"Could not set/reset Log.","qTabAdvanced::SetLogs"); - checkedBox->setChecked(!enable); - } - - qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetLogs"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabAdvanced::SetExposureTime(){ - //Get the value of timer in ns - double exptimeNS = qDefs::getNSTime((qDefs::timeUnit)comboExpUnit->currentIndex(),spinExpTime->value()); -#ifdef VERBOSE - cout << "Setting Exposure Time to " << exptimeNS << " clocks" << "/" << spinExpTime->value() << qDefs::getUnitString((qDefs::timeUnit)comboExpUnit->currentIndex()) << endl; -#endif - myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME,(int64_t)exptimeNS); - - qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetExposureTime"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabAdvanced::SetThreshold(){ -#ifdef VERBOSE - cout << "Setting Threshold DACu:" << spinThreshold->value() << endl; -#endif - spinThreshold->setValue((double)myDet->setDAC((dacs_t)spinThreshold->value(),slsDetectorDefs::THRESHOLD,0)); - qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetThreshold"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabAdvanced::SetOutputFile(){ -#ifdef VERBOSE - cout << "Setting Output File for Trimming:" << endl; -#endif - QString dirPath = dispFile->text().section('/',0,-2,QString::SectionIncludeLeadingSep); - cout << "Directory:" << dirPath.toAscii().constData() << "." << endl; - QString fName = dispFile->text().section('/',-1); - cout << "File Name:" << fName.toAscii().constData() << "." << endl; - //checks if directory exists and file name is not empty - if((QFile::exists(dirPath))&&(!fName.isEmpty())){ - - dispFile->setToolTip(outputDirTip); - lblFile->setToolTip(outputDirTip); - lblFile->setPalette(lblExpTime->palette()); - lblFile->setText("Output Trim File: "); - btnStart->setEnabled(true); - - - //check if you're overwriting original trimsettings - QDir dir; - //gets the clean absolute path - dirPath = dir.absoluteFilePath(dirPath); - dirPath = dir.cleanPath(dirPath); - QString trimdir = QString::fromStdString(myDet->getSettingsFile()).section('/',0,-2,QString::SectionIncludeLeadingSep); - trimdir = dir.absoluteFilePath(trimdir); - trimdir = dir.cleanPath(trimdir); - if(!dirPath.compare(trimdir)){ - int ret = qDefs::Message(qDefs::QUESTION,string("This will possibly overwrite your original trimbits.
" - "Proposed file path:") + string(dirPath.toAscii().constData())+ - string("
Do you still want to continue?"),"qTabAdvanced::SetOutputFile"); - if(ret==qDefs::FAIL){ - dispFile->setText(""); - dispFile->setToolTip(outputDirTip + errOutputTip); - lblFile->setToolTip(outputDirTip + errOutputTip); - lblFile->setPalette(red); - lblFile->setText("Output Trim File:*"); - btnStart->setEnabled(false); - } - } - - }//if the directory doesnt exist or if file name is empty - else{ - cout<<"Invalid Trimming output File"<setToolTip(outputDirTip + errOutputTip); - lblFile->setToolTip(outputDirTip + errOutputTip); - lblFile->setPalette(red); - lblFile->setText("Output Trim File:*"); - btnStart->setEnabled(false); - } - - qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetOutputFile"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabAdvanced::BrowseOutputFile(){ -#ifdef VERBOSE - cout << "Browsing Output Dir for Trimming" << endl; -#endif - QString fName = dispFile->text(); - //dialog - QFileDialog *fileDialog = new QFileDialog(this, - tr("Save Trimbits"),fName, - tr("Trimbit files (*.trim noise.sn*);;All Files(*) ")); - fileDialog->setFileMode(QFileDialog::AnyFile ); - if ( fileDialog->exec() == QDialog::Accepted ) - fName = fileDialog->selectedFiles()[0]; - - //if empty, set the file name and it calls SetFileSteps, else ignore - if (!fName.isEmpty()){ - dispFile->setText(fName); - SetOutputFile(); - } -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabAdvanced::EnableTrimming(bool enable){ -#ifdef VERBOSE - cout << "Enable Trimming set to:" << enable << endl; -#endif - if(enable){ - //show error label if invalid output dir - SetOutputFile(); - SetTrimmingMethod(comboMethod->currentIndex()); - }else{ - //error label shouldnt show when disabled - dispFile->setToolTip(outputDirTip); - lblFile->setToolTip(outputDirTip); - lblFile->setPalette(lblExpTime->palette()); - lblFile->setText("Output Trim File: "); - } -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- -void qTabAdvanced::SetOptimize(bool enable){ -#ifdef VERBOSE - cout << "Setting Optimize to:" << enable << endl; -#endif - //trimming method is adjust to count - if(!comboMethod->currentIndex()){ - lblCounts->setEnabled(true); - spinCounts->setEnabled(true); - lblResolution->setEnabled(enable); - spinResolution->setEnabled(enable); - }//trimming method is equalize to median - else{ - lblCounts->setEnabled(false); - spinCounts->setEnabled(false); - lblResolution->setEnabled(true); - spinResolution->setEnabled(true); - } -} - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabAdvanced::SetTrimmingMethod(int mode){ -#ifdef VERBOSE - cout << "Setting Trimming method to :" << mode << endl; -#endif - //make sure the right resolution/Counts is enabled - SetOptimize(chkOptimize->isChecked()); - - //set mode - switch(mode){ - case 0: trimmingMode = slsDetectorDefs::NOISE_TRIMMING; break; - case 1: trimmingMode = slsDetectorDefs::IMPROVE_TRIMMING; break; - } -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qTabAdvanced::validateBeforeTrimming(){ -#ifdef VERBOSE - cout << "Validating conditions before Trimming" << endl; -#endif - char temp[100]; - string message = "All conditions satisfied for Trimming.
"; - switch(detType){ - case slsDetectorDefs::MYTHEN: - - //dynamic range - if(myDet->setDynamicRange(-1) != TRIMMING_DYNAMIC_RANGE){ - sprintf(temp,"%d",TRIMMING_DYNAMIC_RANGE); - if(myDet->setDynamicRange(TRIMMING_DYNAMIC_RANGE) != TRIMMING_DYNAMIC_RANGE){ - qDefs::Message(qDefs::WARNING, - string("Trimming Pre-condition not satisfied:
" - "Could not set dynamic range to ") + string(temp)+string(".
" - "Trimming Aborted."),"qTabAdvanced::validateBeforeTrimming"); - return slsDetectorDefs::FAIL; - }else - message.append(string("Dynamic Range has been changed to ") + string(temp) + string(".
")); - } - //frames - if((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,-1) != TRIMMING_FRAME_NUMBER){ - sprintf(temp,"%d",TRIMMING_FRAME_NUMBER); - if((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,TRIMMING_FRAME_NUMBER) != TRIMMING_FRAME_NUMBER){ - qDefs::Message(qDefs::WARNING, - string("
Trimming Pre-condition not satisfied:
" - "Could not set Number of Frames to ") + string(temp)+string(".
" - "Trimming Aborted."),"qTabAdvanced::validateBeforeTrimming"); - return slsDetectorDefs::FAIL; - }else - message.append(string("Number of Frames has been changed to ") + string(temp) + string(".
")); - } - //trigger - if((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,-1) != TRIMMING_TRIGGER_NUMBER){ - sprintf(temp,"%d",TRIMMING_TRIGGER_NUMBER); - if((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,TRIMMING_TRIGGER_NUMBER) != TRIMMING_TRIGGER_NUMBER){ - qDefs::Message(qDefs::WARNING, - string("
Trimming Pre-condition not satisfied:
" - "Could not set Number of Triggers to ") + string(temp)+string(".
" - "Trimming Aborted."),"qTabAdvanced::validateBeforeTrimming"); - return slsDetectorDefs::FAIL; - }else - message.append(string("Number of Triggers has been changed to ") + string(temp) + string(".
")); - } - //probes - if((int)myDet->setTimer(slsDetectorDefs::PROBES_NUMBER,-1) != TRIMMING_PROBE_NUMBER){ - sprintf(temp,"%d",TRIMMING_PROBE_NUMBER); - if((int)myDet->setTimer(slsDetectorDefs::PROBES_NUMBER,TRIMMING_PROBE_NUMBER) != TRIMMING_PROBE_NUMBER){ - qDefs::Message(qDefs::WARNING, - string("
Trimming Pre-condition not satisfied:
" - "Could not set Number of Probes to ") + string(temp)+string(".
" - "Trimming Aborted."),"qTabAdvanced::validateBeforeTrimming"); - return slsDetectorDefs::FAIL; - }else - message.append(string("Number of Probes has been changed to ") + string(temp) + string(".
")); - } - //Setting - if(myDet->getSettings() == slsDetectorDefs::UNINITIALIZED){ - if(qDefs::Message(qDefs::QUESTION, - string("
Trimming Pre-condition not satisfied:
")+ - string("Settings cannot be Uninitialized to start Trimming.
" - "Change it to Standard and proceed?"),"qTabAdvanced::validateBeforeTrimming") == slsDetectorDefs::FAIL){ - qDefs::Message(qDefs::INFORMATION, - "Please change the Settings in the Settings tab to your choice.
" - "Aborting Trimming.","qTabAdvanced::validateBeforeTrimming"); - return slsDetectorDefs::FAIL; - } - //user asked to change settings to standard - else{ - if((int)myDet->setSettings(slsDetectorDefs::STANDARD) != slsDetectorDefs::STANDARD){ - qDefs::Message(qDefs::WARNING, - string("Trimming Pre-condition not satisfied:
" - "Could not change Settings to Standard
" - "Trimming Aborted."),"qTabAdvanced::validateBeforeTrimming"); - return slsDetectorDefs::FAIL; - }else - message.append(string("Settings has been changed to Standard.
")); - } - } - break; - default: - return slsDetectorDefs::FAIL; - - } - - message.append("
Initiating Trimming..."); - qDefs::Message(qDefs::INFORMATION,message,"qTabAdvanced::validateBeforeTrimming"); - return slsDetectorDefs::OK; - -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabAdvanced::StartTrimming(){ - //check a few conditions before trimming - if(validateBeforeTrimming() == slsDetectorDefs::FAIL) - return; - -#ifdef VERBOSE - cout << "Starting Trimming" << endl; -#endif - int parameter1=0, parameter2=0; - //optimize - bool optimize = chkOptimize->isChecked(); - - //set the mode again and also set resolution, counts - switch(trimmingMode){ - - case slsDetectorDefs::NOISE_TRIMMING: - //define parameters - parameter1 = spinCounts->value(); - parameter2 = spinResolution->value(); - if(!optimize){ - parameter2 = -1; - trimmingMode = slsDetectorDefs::FIXEDSETTINGS_TRIMMING; -#ifdef VERBOSE - cout << "Trimming Mode: FIXEDSETTINGS_TRIMMING" << endl; -#endif - }else{ -#ifdef VERBOSE - cout << "Trimming Mode: NOISE_TRIMMING" << endl; -#endif - } - break; - - case slsDetectorDefs::IMPROVE_TRIMMING: -#ifdef VERBOSE - cout << "Trimming Mode: IMPROVE_TRIMMING" << endl; -#endif - //define parameters - parameter1 = spinResolution->value(); - parameter2 = 1; - if(!optimize) parameter2 = 0; - break; - default: - cout << "Should never come here. Start Trimming will have only 2 methods. Trimming Method:" << trimmingMode << endl; - return; - } - - //execute - int ret = myDet->executeTrimming(trimmingMode,parameter1,parameter2,-1); - - if((ret!=slsDetectorDefs::FAIL)&&(ret!=-1)); - else - qDefs::Message(qDefs::WARNING,"Atleast 1 channel could not be trimmed.","qTabAdvanced::StartTrimming"); - //save trim file - ret = myDet->saveSettingsFile(string(dispFile->text().toAscii().constData()),-1); - if((ret!=slsDetectorDefs::FAIL)&&(ret!=-1)){ - qDefs::Message(qDefs::INFORMATION,"The Trimbits have been saved successfully.","qTabAdvanced::StartTrimming"); - //updates plots - myPlot->UpdateTrimbitPlot(false,radioHistogram->isChecked()); - } - else qDefs::Message(qDefs::WARNING,string("Could not Save the Trimbits to file:\n")+dispFile->text().toAscii().constData(),"qTabAdvanced::StartTrimming"); - - qDefs::checkErrorMessage(myDet,"qTabAdvanced::StartTrimming"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabAdvanced::UpdateTrimbitPlot(int id){ - if(boxPlot->isChecked()){ - //refresh - if(!id) myPlot->UpdateTrimbitPlot(false,radioHistogram->isChecked()); - //from detector - else myPlot->UpdateTrimbitPlot(true,radioHistogram->isChecked()); - } -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetControlPort(int port){ -#ifdef VERBOSE - cout << "Setting Control Port:" << port << endl; -#endif + FILE_LOG(logINFO) << "Setting Control Port:" << port; disconnect(spinControlPort, SIGNAL(valueChanged(int)), this, SLOT(SetControlPort(int))); - spinControlPort->setValue(det->setPort(slsDetectorDefs::CONTROL_PORT,port)); - qDefs::checkErrorMessage(det,"qTabAdvanced::SetControlPort"); + spinControlPort->setValue(myDet->setControlPort(port, comboDetector->currentIndex())); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabAdvanced::SetControlPort"); connect(spinControlPort, SIGNAL(valueChanged(int)), this, SLOT(SetControlPort(int))); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetStopPort(int port){ -#ifdef VERBOSE - cout << "Setting Stop Port:" << port << endl; -#endif + FILE_LOG(logINFO) << "Setting Stop Port:" << port; disconnect(spinStopPort, SIGNAL(valueChanged(int)), this, SLOT(SetStopPort(int))); - spinStopPort->setValue(det->setPort(slsDetectorDefs::STOP_PORT,port)); - qDefs::checkErrorMessage(det,"qTabAdvanced::SetStopPort"); + spinStopPort->setValue(myDet->setStopPort(port, comboDetector->currentIndex())); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabAdvanced::SetStopPort"); connect(spinStopPort, SIGNAL(valueChanged(int)), this, SLOT(SetStopPort(int))); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetRxrTCPPort(int port){ -#ifdef VERBOSE - cout << "Setting Receiver TCP Port:" << port << endl; -#endif + FILE_LOG(logINFO) << "Setting Receiver TCP Port:" << port; disconnect(spinTCPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrTCPPort(int))); - spinTCPPort->setValue(det->setPort(slsDetectorDefs::DATA_PORT,port)); - qDefs::checkErrorMessage(det,"qTabAdvanced::SetRxrTCPPort"); + spinTCPPort->setValue(myDet->setReceiverPort(port, comboDetector->currentIndex())); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabAdvanced::SetRxrTCPPort"); connect(spinTCPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrTCPPort(int))); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetRxrUDPPort(int port){ -#ifdef VERBOSE - cout << "Setting Receiver UDP Port:" << port << endl; -#endif + FILE_LOG(logINFO) << "Setting Receiver UDP Port:" << port; disconnect(spinUDPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrUDPPort(int))); - spinUDPPort->setValue(det->setReceiverUDPPort(port)); - qDefs::checkErrorMessage(det,"qTabAdvanced::SetRxrUDPPort"); + spinUDPPort->setValue(myDet->setReceiverUDPPort(port, comboDetector->currentIndex())); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabAdvanced::SetRxrUDPPort"); connect(spinUDPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrUDPPort(int))); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetCltZmqPort(int port){ -#ifdef VERBOSE - cout << "Setting Client UDP Port:" << port << endl; -#endif - ostringstream ss; ss << port; string sport = ss.str(); + FILE_LOG(logINFO) << "Setting Client UDP Port:" << port; + std::ostringstream ss; ss << port; std::string sport = ss.str(); disconnect(spinZmqPort, SIGNAL(valueChanged(int)), this, SLOT(SetCltZmqPort(int))); - spinZmqPort->setValue(atoi(det->setClientStreamingPort(sport).c_str())); - qDefs::checkErrorMessage(det,"qTabAdvanced::SetCltZmqPort"); + myDet->setClientDataStreamingInPort(port, comboDetector->currentIndex()); + spinZmqPort->setValue(myDet->getClientStreamingPort(comboDetector->currentIndex())); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabAdvanced::SetCltZmqPort"); myDet->enableDataStreamingToClient(false); myDet->enableDataStreamingToClient(true); qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetCltZmqPort"); @@ -790,18 +236,14 @@ void qTabAdvanced::SetCltZmqPort(int port){ } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetRxrZmqPort(int port){ -#ifdef VERBOSE - cout << "Setting Receiver UDP Port:" << port << endl; -#endif - ostringstream ss; ss << port; string sport = ss.str(); + FILE_LOG(logINFO) << "Setting Receiver UDP Port:" << port; + std::ostringstream ss; ss << port; std::string sport = ss.str(); disconnect(spinZmqPort2, SIGNAL(valueChanged(int)), this, SLOT(SetRxrZmqPort(int))); - spinZmqPort2->setValue(atoi(det->setReceiverStreamingPort(sport).c_str())); - qDefs::checkErrorMessage(det,"qTabAdvanced::SetRxrZmqPort"); + myDet->setReceiverDataStreamingOutPort(port, comboDetector->currentIndex()); + spinZmqPort2->setValue(myDet->getReceiverStreamingPort(comboDetector->currentIndex())); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabAdvanced::SetRxrZmqPort"); myDet->enableDataStreamingFromReceiver(false); myDet->enableDataStreamingFromReceiver(true); qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetRxrZmqPort"); @@ -809,19 +251,15 @@ void qTabAdvanced::SetRxrZmqPort(int port){ } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetReceiverOnline(int index){ -#ifdef VERBOSE - cout << "Setting Reciever Online to :" << index << endl; -#endif + FILE_LOG(logINFO) << "Setting Reciever Online to :" << index; disconnect(comboRxrOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetReceiverOnline(int))); - if(index) + if(index){ SetReceiver(); - else - comboRxrOnline->setCurrentIndex(det->setReceiverOnline(index)); - qDefs::checkErrorMessage(det,"qTabAdvanced::SetReceiverOnline"); + }else{ + comboRxrOnline->setCurrentIndex(myDet->setReceiverOnline(index, comboDetector->currentIndex())); + } + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabAdvanced::SetReceiverOnline"); connect(comboRxrOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetReceiverOnline(int))); //highlight in red if offline if(!comboRxrOnline->currentIndex()){ @@ -838,16 +276,11 @@ void qTabAdvanced::SetReceiverOnline(int index){ } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetOnline(int index){ -#ifdef VERBOSE - cout << "Setting Detector Online to " << index << endl; -#endif + FILE_LOG(logINFO) << "Setting Detector Online to " << index; disconnect(comboOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetOnline(int))); - comboOnline->setCurrentIndex(det->setOnline(index)); - qDefs::checkErrorMessage(det,"qTabAdvanced::SetOnline"); + comboOnline->setCurrentIndex(myDet->setOnline(index, comboDetector->currentIndex())); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabAdvanced::SetOnline"); connect(comboOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetOnline(int))); //highlight in red if offline if(!comboOnline->currentIndex()){ @@ -865,23 +298,19 @@ void qTabAdvanced::SetOnline(int index){ } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetNetworkParameters(){ -#ifdef VERBOSE - cout << "Setting Network Parametrs" << endl; -#endif + FILE_LOG(logINFO) << "Setting Network Parametrs"; disconnect(dispIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); disconnect(dispMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); disconnect(dispUDPIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); disconnect(dispUDPMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); - dispIP->setText(QString(det->setDetectorIP(dispIP->text().toAscii().constData()).c_str())); - dispMAC->setText(QString(det->setDetectorMAC(dispMAC->text().toAscii().constData()).c_str())); - dispUDPIP->setText(QString(det->setReceiverUDPIP(dispUDPIP->text().toAscii().constData()).c_str())); - dispUDPMAC->setText(QString(det->setReceiverUDPMAC(dispUDPMAC->text().toAscii().constData()).c_str())); - qDefs::checkErrorMessage(det,"qTabAdvanced::SetNetworkParameters"); + auto moduleId = comboDetector->currentIndex(); + dispIP->setText(QString(myDet->setDetectorIP(dispIP->text().toAscii().constData(), moduleId).c_str())); + dispMAC->setText(QString(myDet->setDetectorMAC(dispMAC->text().toAscii().constData(), moduleId).c_str())); + dispUDPIP->setText(QString(myDet->setReceiverUDPIP(dispUDPIP->text().toAscii().constData(), moduleId).c_str())); + dispUDPMAC->setText(QString(myDet->setReceiverUDPMAC(dispUDPMAC->text().toAscii().constData(), moduleId).c_str())); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabAdvanced::SetNetworkParameters"); connect(dispIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); connect(dispMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); @@ -890,65 +319,55 @@ void qTabAdvanced::SetNetworkParameters(){ } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetClientZMQIP(){ -#ifdef VERBOSE - cout << "Setting Client ZMQ IP" << endl; -#endif + FILE_LOG(logINFO) << "Setting Client ZMQ IP"; disconnect(dispZMQIP, SIGNAL(editingFinished()), this, SLOT(SetClientZMQIP())); - dispZMQIP->setText(QString(det->setClientStreamingIP(dispZMQIP->text().toAscii().constData()).c_str())); + auto moduleId = comboDetector->currentIndex(); + myDet->setClientDataStreamingInIP(dispZMQIP->text().toAscii().constData(), moduleId); + dispZMQIP->setText(QString(myDet->getClientStreamingIP(moduleId).c_str())); myDet->enableDataStreamingToClient(false); myDet->enableDataStreamingToClient(true); - qDefs::checkErrorMessage(det,"qTabAdvanced::SetClientZMQIP"); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabAdvanced::SetClientZMQIP"); connect(dispZMQIP, SIGNAL(editingFinished()), this, SLOT(SetClientZMQIP())); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetReceiverZMQIP(){ -#ifdef VERBOSE - cout << "Setting Receiver ZMQ IP" << endl; -#endif + FILE_LOG(logINFO) << "Setting Receiver ZMQ IP"; disconnect(dispZMQIP2, SIGNAL(editingFinished()), this, SLOT(SetReceiverZMQIP())); - dispZMQIP2->setText(QString(det->setReceiverStreamingIP(dispZMQIP2->text().toAscii().constData()).c_str())); + auto moduleId = comboDetector->currentIndex(); + myDet->setReceiverDataStreamingOutIP(dispZMQIP2->text().toAscii().constData(), moduleId); + dispZMQIP2->setText(QString(myDet->getReceiverStreamingIP(moduleId).c_str())); myDet->enableDataStreamingFromReceiver(false); myDet->enableDataStreamingFromReceiver(true); - qDefs::checkErrorMessage(det,"qTabAdvanced::SetReceiverZMQIP"); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(),"qTabAdvanced::SetReceiverZMQIP"); connect(dispZMQIP2, SIGNAL(editingFinished()), this, SLOT(SetReceiverZMQIP())); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetReceiver(){ -#ifdef VERBOSE - cout << "Setting Receiver" << endl; -#endif - string outdir = myDet->getFilePath(); - dispRxrHostname->setText(QString(det->setReceiver(dispRxrHostname->text().toAscii().constData()).c_str())); - qDefs::checkErrorMessage(det,"qTabAdvanced::SetReceiver"); - det->setFilePath(outdir); - qDefs::checkErrorMessage(det,"qTabAdvanced::SetReceiver"); + FILE_LOG(logINFO) << "Setting Receiver"; + auto outdir = myDet->getFilePath(); + auto moduleId = comboDetector->currentIndex(); + dispRxrHostname->setText(QString(myDet->setReceiverHostname(dispRxrHostname->text().toAscii().constData(), moduleId).c_str())); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabAdvanced::SetReceiver"); + myDet->setFilePath(outdir, moduleId); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabAdvanced::SetReceiver"); Refresh(); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabAdvanced::AddROIInputSlot(){ + AddROIInput(1); +} void qTabAdvanced::updateROIList(){ -#ifdef VERYVERBOSE - cout<<"in updateROIList() " << endl; -#endif + FILE_LOG(logDEBUG) << "Updating ROIList"; clearROI(); int n,i; @@ -970,20 +389,15 @@ void qTabAdvanced::updateROIList(){ spinToX[i]->setValue(allroi[i].xmax); spinToY[i]->setValue(allroi[i].ymax); } - cout << "ROIs populated: " << n << endl; + FILE_LOG(logDEBUG) << "ROIs populated: " << n; } } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::AddROIInput(int num){ -#ifdef VERVERBOSE - cout<<"in AddROIInput() " << num << endl; -#endif + FILE_LOG(logDEBUG) << "Add ROI Input " << num; if((int)lblFromX.size()){ disconnect(spinFromX[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); disconnect(spinFromY[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); @@ -1032,10 +446,10 @@ void qTabAdvanced::AddROIInput(int num){ spinToX[i]->setFixedHeight(19); spinToY[i]->setFixedHeight(19); - spinFromX[i]->setMaximum(myDet->getMaxNumberOfChannels(slsDetectorDefs::X)-1); - spinToX[i]->setMaximum(myDet->getMaxNumberOfChannels(slsDetectorDefs::X)-1); - spinFromY[i]->setMaximum(myDet->getMaxNumberOfChannels(slsDetectorDefs::Y)-1); - spinToY[i]->setMaximum(myDet->getMaxNumberOfChannels(slsDetectorDefs::Y)-1); + spinFromX[i]->setMaximum(myDet->getTotalNumberOfChannels(slsDetectorDefs::X)-1); + spinToX[i]->setMaximum(myDet->getTotalNumberOfChannels(slsDetectorDefs::X)-1); + spinFromY[i]->setMaximum(myDet->getTotalNumberOfChannels(slsDetectorDefs::Y)-1); + spinToY[i]->setMaximum(myDet->getTotalNumberOfChannels(slsDetectorDefs::Y)-1); spinFromX[i]->setMinimum(-1); spinToX[i]->setMinimum(-1); spinFromY[i]->setMinimum(-1); @@ -1075,30 +489,21 @@ void qTabAdvanced::AddROIInput(int num){ connect(spinToX[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); connect(spinToY[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); -#ifdef VERYVERBOSE - cout<<"ROI Inputs added " << num << endl; -#endif + FILE_LOG(logDEBUG) << "ROI Inputs added " << num; qDefs::checkErrorMessage(myDet,"qTabAdvanced::AddROIInput"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::clearROI(){ -#ifdef VERYVERBOSE - cout<<"in clearROI() " << endl; -#endif + FILE_LOG(logDEBUG) << "in clearROI() "; if((int)lblFromX.size()){ disconnect(spinFromX[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); disconnect(spinFromY[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); disconnect(spinToX[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); disconnect(spinToY[numRois], SIGNAL(valueChanged(int)), this, SLOT(AddROIInputSlot())); - } - for (int i=0;isetValue(-1); spinFromY[i]->setValue(-1); @@ -1123,13 +528,8 @@ void qTabAdvanced::clearROI(){ } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::setROI(){ -#ifdef VERYVERBOSE - cout<<"in setROI() " << endl; -#endif + FILE_LOG(logINFO) << "Setting ROI"; slsDetectorDefs::ROI allroi[MAX_ROIS]; @@ -1142,7 +542,7 @@ void qTabAdvanced::setROI(){ myDet->setROI(numRois,allroi); //qDefs::checkErrorMessage(myDet); - cout<<"ROIs set" << endl; + FILE_LOG(logDEBUG) << "ROIs set"; //get the correct list back updateROIList(); //configuremac @@ -1152,13 +552,8 @@ void qTabAdvanced::setROI(){ } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::clearROIinDetector(){ -#ifdef VERYVERBOSE - cout<<"in clearROIinDetector() " << endl; -#endif + FILE_LOG(logINFO) << "Clearing ROI"; if (QMessageBox::warning(this, "Clear ROI", "Are you sure you want to clear all the ROI in detector?", @@ -1166,46 +561,39 @@ void qTabAdvanced::clearROIinDetector(){ clearROI(); setROI(); -#ifdef VERBOSE - cout << "ROIs cleared" << endl; -#endif + FILE_LOG(logDEBUG) << "ROIs cleared"; } } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetDetector(int index){ -#ifdef VERYVERBOSE - cout<<"in SetDetector: " << index << endl; -#endif - det = myDet->getSlsDetector(comboDetector->currentIndex()); + FILE_LOG(logINFO) << "in SetDetector: " << index; + // det = myDet->getSlsDetector(comboDetector->currentIndex()); + auto moduleId = comboDetector->currentIndex(); + spinControlPort->setValue(myDet->setControlPort(-1, moduleId)); + spinStopPort->setValue(myDet->setStopPort(-1, moduleId)); + spinTCPPort->setValue(myDet->setReceiverPort(-1, moduleId)); + spinUDPPort->setValue(myDet->getReceiverUDPPort(moduleId)); + spinZmqPort->setValue(myDet->getClientStreamingPort(moduleId)); + spinZmqPort2->setValue(myDet->getReceiverStreamingPort(moduleId)); - spinControlPort->setValue(det->getControlPort()); - spinStopPort->setValue(det->getStopPort()); - spinTCPPort->setValue(det->getReceiverPort()); - spinUDPPort->setValue(atoi(det->getReceiverUDPPort().c_str())); - spinZmqPort->setValue(atoi(det->getClientStreamingPort().c_str())); - spinZmqPort2->setValue(atoi(det->getReceiverStreamingPort().c_str())); - - dispIP->setText(det->getDetectorIP().c_str()); - dispMAC->setText(det->getDetectorMAC().c_str()); - dispRxrHostname->setText(det->getReceiver().c_str()); - dispUDPIP->setText(det->getReceiverUDPIP().c_str()); - dispUDPMAC->setText(det->getReceiverUDPMAC().c_str()); - dispZMQIP->setText(det->getClientStreamingIP().c_str()); - dispZMQIP2->setText(det->getReceiverStreamingIP().c_str()); + dispIP->setText(myDet->getDetectorIP(moduleId).c_str()); + dispMAC->setText(myDet->getDetectorMAC(moduleId).c_str()); + dispRxrHostname->setText(myDet->getReceiverHostname(moduleId).c_str()); + dispUDPIP->setText(myDet->getReceiverUDPIP(moduleId).c_str()); + dispUDPMAC->setText(myDet->getReceiverUDPMAC(moduleId).c_str()); + dispZMQIP->setText(myDet->getClientStreamingIP(moduleId).c_str()); + dispZMQIP2->setText(myDet->getReceiverStreamingIP(moduleId).c_str()); //check if its online and set it to red if offline - if(det->setOnline()==slsDetectorDefs::ONLINE_FLAG) - det->checkOnline(); - if(det->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG) - det->checkReceiverOnline(); - comboOnline->setCurrentIndex(det->setOnline()); - comboRxrOnline->setCurrentIndex(det->setReceiverOnline()); + if(myDet->getOnline(moduleId) == slsDetectorDefs::ONLINE_FLAG) + myDet->checkOnline(moduleId); + if(myDet->getReceiverOnline(moduleId)==slsDetectorDefs::ONLINE_FLAG) + myDet->checkReceiverOnline(moduleId); + comboOnline->setCurrentIndex(myDet->getOnline(moduleId)); + comboRxrOnline->setCurrentIndex(myDet->getReceiverOnline(moduleId)); //highlight in red if detector or receiver is offline if(!comboOnline->currentIndex()){ comboOnline->setToolTip(detOnlineTip + errOnlineTip); @@ -1232,31 +620,21 @@ void qTabAdvanced::SetDetector(int index){ } } - qDefs::checkErrorMessage(det,"qTabAdvanced::SetDetector"); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabAdvanced::SetDetector"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetAllTrimbits(){ -#ifdef VERBOSE - cout<<"Set all trimbits to " << spinSetAllTrimbits->value() << endl; -#endif + FILE_LOG(logINFO) << "Set all trimbits to " << spinSetAllTrimbits->value(); myDet->setAllTrimbits(spinSetAllTrimbits->value()); - qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetAllTrimbits"); - updateAllTrimbitsFromServer(); + qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetAllTrimbits"); + updateAllTrimbitsFromServer(); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::updateAllTrimbitsFromServer(){ -#ifdef VERBOSE - cout<<"Getting all trimbits value" << endl; -#endif + FILE_LOG(logDEBUG) << "Getting all trimbits value"; disconnect(spinSetAllTrimbits, SIGNAL(editingFinished()), this, SLOT(SetAllTrimbits())); int ret = myDet->setAllTrimbits(-1); @@ -1267,26 +645,18 @@ void qTabAdvanced::updateAllTrimbitsFromServer(){ } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetNumStoragecells(int value) { -#ifdef VERBOSE - cout << "Setting number of stoarge cells to " << value << endl; -#endif - myDet->setTimer(slsDetectorDefs::STORAGE_CELL_NUMBER,value); + FILE_LOG(logINFO) << "Setting number of stoarge cells to " << value; + myDet->setTimer(slsDetectorDefs::STORAGE_CELL_NUMBER,value); - disconnect(spinNumStoragecells,SIGNAL(valueChanged(int)),this, SLOT(SetNumStoragecells(int))); - spinNumStoragecells->setValue((int)myDet->setTimer(slsDetectorDefs::STORAGE_CELL_NUMBER,-1)); - connect(spinNumStoragecells,SIGNAL(valueChanged(int)), this, SLOT(SetNumStoragecells(int))); + disconnect(spinNumStoragecells,SIGNAL(valueChanged(int)),this, SLOT(SetNumStoragecells(int))); + spinNumStoragecells->setValue((int)myDet->setTimer(slsDetectorDefs::STORAGE_CELL_NUMBER,-1)); + connect(spinNumStoragecells,SIGNAL(valueChanged(int)), this, SLOT(SetNumStoragecells(int))); - qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetNumStoragecells"); + qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetNumStoragecells"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::SetSubExposureTime() { disconnect(spinSubExpTime,SIGNAL(valueChanged(double)), this, SLOT(SetSubExposureTime())); disconnect(comboSubExpTimeUnit,SIGNAL(currentIndexChanged(int)),this, SLOT(SetSubExposureTime())); @@ -1297,11 +667,9 @@ void qTabAdvanced::SetSubExposureTime() { spinSubExpTime->value()); // set value -#ifdef VERBOSE - cout << "Setting sub frame acquisition time to " << timeNS << " clocks" << + FILE_LOG(logINFO) << "Setting sub frame acquisition time to " << timeNS << " clocks" << "/" << spinSubExpTime->value() << - qDefs::getUnitString((qDefs::timeUnit)comboSubExpTimeUnit->currentIndex()) << endl; -#endif + qDefs::getUnitString((qDefs::timeUnit)comboSubExpTimeUnit->currentIndex()); myDet->setTimer(slsDetectorDefs::SUBFRAME_ACQUISITION_TIME,(int64_t)timeNS); qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetSubExposureTime"); @@ -1313,9 +681,6 @@ void qTabAdvanced::SetSubExposureTime() { comboSubExpTimeUnit->setCurrentIndex((int)unit); - // highlight if period < exptime - CheckAcqPeriodGreaterThanExp(); - connect(spinSubExpTime,SIGNAL(valueChanged(double)), this, SLOT(SetSubExposureTime())); connect(comboSubExpTimeUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(SetSubExposureTime())); @@ -1324,163 +689,59 @@ void qTabAdvanced::SetSubExposureTime() { } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabAdvanced::SetSubPeriod() { - disconnect(spinSubPeriod,SIGNAL(valueChanged(double)), this, SLOT(SetSubPeriod())); - disconnect(comboSubPeriodUnit,SIGNAL(currentIndexChanged(int)),this, SLOT(SetSubPeriod())); +void qTabAdvanced::SetSubDeadTime() { + disconnect(spinSubDeadTime,SIGNAL(valueChanged(double)), this, SLOT(SetSubDeadTime())); + disconnect(comboSubDeadTimeUnit,SIGNAL(currentIndexChanged(int)),this, SLOT(SetSubDeadTime())); //Get the value of timer in ns double timeNS = qDefs::getNSTime( - (qDefs::timeUnit)comboSubPeriodUnit->currentIndex(), - spinSubPeriod->value()); + (qDefs::timeUnit)comboSubDeadTimeUnit->currentIndex(), + spinSubDeadTime->value()); // set value -#ifdef VERBOSE - cout << "Setting sub frame period to " << timeNS << " clocks" << - "/" << spinSubPeriod->value() << - qDefs::getUnitString((qDefs::timeUnit)comboSubPeriodUnit->currentIndex()) << endl; -#endif + FILE_LOG(logINFO) << "Setting sub dead time to " << timeNS << " clocks" << + "/" << spinSubDeadTime->value() << + qDefs::getUnitString((qDefs::timeUnit)comboSubDeadTimeUnit->currentIndex()); myDet->setTimer(slsDetectorDefs::SUBFRAME_DEADTIME,(int64_t)timeNS); - qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetSubPeriod"); + qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetSubDeadTime"); // update value in gui qDefs::timeUnit unit; double time = qDefs::getCorrectTime(unit,((double)( myDet->setTimer(slsDetectorDefs::SUBFRAME_DEADTIME,-1)*(1E-9)))); - spinSubPeriod->setValue(time); - comboSubPeriodUnit->setCurrentIndex((int)unit); + spinSubDeadTime->setValue(time); + comboSubDeadTimeUnit->setCurrentIndex((int)unit); - // highlight if period < exptime - CheckAcqPeriodGreaterThanExp(); + connect(spinSubDeadTime,SIGNAL(valueChanged(double)), this, SLOT(SetSubDeadTime())); + connect(comboSubDeadTimeUnit,SIGNAL(currentIndexChanged(int)),this, SLOT(SetSubDeadTime())); - connect(spinSubPeriod,SIGNAL(valueChanged(double)), this, SLOT(SetSubPeriod())); - connect(comboSubPeriodUnit,SIGNAL(currentIndexChanged(int)),this, SLOT(SetSubPeriod())); - - - qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetSubPeriod"); + qDefs::checkErrorMessage(myDet,"qTabAdvanced::SetSubDeadTime"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabAdvanced::CheckAcqPeriodGreaterThanExp(){ - double exptimeNS = qDefs::getNSTime( - (qDefs::timeUnit)comboSubExpTimeUnit->currentIndex(), - spinSubExpTime->value()); - double acqtimeNS = qDefs::getNSTime( - (qDefs::timeUnit)comboSubPeriodUnit->currentIndex(), - spinSubPeriod->value()); - if(exptimeNS>acqtimeNS && acqtimeNS > 0) { - spinSubPeriod->setToolTip(errSubPeriodTip); - lblSubPeriod->setToolTip(errSubPeriodTip); - lblSubPeriod->setPalette(red); - lblSubPeriod->setText("Sub Frame Period:*"); - } - else { - spinSubPeriod->setToolTip(acqSubPeriodTip); - lblSubPeriod->setToolTip(acqSubPeriodTip); - lblSubPeriod->setPalette(lblExpTime->palette()); - lblSubPeriod->setText("Sub Frame Period:"); - } -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabAdvanced::Refresh(){ -#ifdef VERBOSE - cout << endl << "**Updating Advanced Tab" << endl; -#endif - //setting color of tab - //void setTabBar ( QTabBar * tb ) - //QTabBar * tabBar () const - /* - for(int i=0;itabBar()->setTabTextColor(i,defaultTabColor); - tabAdvancedSettings->tabBar()->setTabTextColor(index,QColor(0,0,200,255)); - */ - - if(isAngular){ -#ifdef VERBOSE - cout << "Angular Calibration Log set to " << chkAngularLog->isChecked() << endl; -#endif - - disconnect(chkAngularLog, SIGNAL(toggled(bool)), this, SLOT(SetLogs())); - - chkAngularLog->setChecked(myDet->getActionMode(slsDetectorDefs::angCalLog)); - - connect(chkAngularLog, SIGNAL(toggled(bool)), this, SLOT(SetLogs())); - } - - - if(isEnergy){ - //disconnect - disconnect(chkEnergyLog, SIGNAL(toggled(bool)), this, SLOT(SetLogs())); - disconnect(spinExpTime, SIGNAL(valueChanged(double)), this, SLOT(SetExposureTime())); - disconnect(comboExpUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(SetExposureTime())); - disconnect(spinThreshold, SIGNAL(valueChanged(double)), this, SLOT(SetThreshold())); - - - //energy/angular logs - chkEnergyLog->setChecked(myDet->getActionMode(slsDetectorDefs::enCalLog)); -#ifdef VERBOSE - cout << "Energy Calibration Log set to " << chkEnergyLog->isChecked() << endl; -#endif - - - //exptime - qDefs::timeUnit unit; - double time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME,-1)*(1E-9)))); -#ifdef VERBOSE - cout << "Getting acquisition time : " << time << qDefs::getUnitString(unit) << endl; -#endif - spinExpTime->setValue(time); - comboExpUnit->setCurrentIndex((int)unit); - - - //threshold - double threshold = (double)myDet->setDAC(-1,slsDetectorDefs::THRESHOLD,0); -#ifdef VERBOSE - cout << "Getting Threshold DACu : " << threshold << endl; -#endif - spinThreshold->setValue(threshold); - - - //connect - connect(chkEnergyLog, SIGNAL(toggled(bool)), this, SLOT(SetLogs())); - connect(spinExpTime, SIGNAL(valueChanged(double)), this, SLOT(SetExposureTime())); - connect(comboExpUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(SetExposureTime())); - connect(spinThreshold, SIGNAL(valueChanged(double)), this, SLOT(SetThreshold())); - } - + FILE_LOG(logDEBUG) << endl << "**Updating Advanced Tab"; //network - det = myDet->getSlsDetector(comboDetector->currentIndex()); - + auto moduleId = comboDetector->currentIndex(); qDefs::checkErrorMessage(myDet,"qTabAdvanced::Refresh"); -#ifdef VERBOSE - cout << "Getting Detector Ports" << endl; -#endif + FILE_LOG(logDEBUG) << "Getting Detector Ports"; //disconnect disconnect(spinControlPort, SIGNAL(valueChanged(int)), this, SLOT(SetControlPort(int))); disconnect(spinStopPort, SIGNAL(valueChanged(int)), this, SLOT(SetStopPort(int))); disconnect(comboOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetOnline(int))); //so that updated status - if(det->setOnline()==slsDetectorDefs::ONLINE_FLAG) - det->checkOnline(); - comboOnline->setCurrentIndex(det->setOnline()); - spinControlPort->setValue(det->getControlPort()); - spinStopPort->setValue(det->getStopPort()); + if(myDet->getOnline(moduleId)==slsDetectorDefs::ONLINE_FLAG) + myDet->checkOnline(moduleId); + comboOnline->setCurrentIndex(myDet->getOnline(moduleId)); + spinControlPort->setValue(myDet->setControlPort(-1, moduleId)); + spinStopPort->setValue(myDet->setStopPort(-1, moduleId)); //connect connect(spinControlPort, SIGNAL(valueChanged(int)), this, SLOT(SetControlPort(int))); @@ -1488,60 +749,56 @@ void qTabAdvanced::Refresh(){ connect(comboOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetOnline(int))); -#ifdef VERBOSE - cout << "Getting Receiver Network Information" << endl; -#endif - if (detType!=slsDetectorDefs::MYTHEN){ - //disconnect - disconnect(spinTCPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrTCPPort(int))); - disconnect(spinUDPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrUDPPort(int))); - disconnect(spinZmqPort, SIGNAL(valueChanged(int)), this, SLOT(SetCltZmqPort(int))); - disconnect(spinZmqPort2, SIGNAL(valueChanged(int)), this, SLOT(SetRxrZmqPort(int))); - disconnect(comboRxrOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetReceiverOnline(int))); - disconnect(dispIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); - disconnect(dispMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); - disconnect(dispUDPIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); - disconnect(dispUDPMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); - disconnect(btnRxr, SIGNAL(clicked()), this, SLOT(SetReceiver())); + FILE_LOG(logDEBUG) << "Getting Receiver Network Information"; + //disconnect + disconnect(spinTCPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrTCPPort(int))); + disconnect(spinUDPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrUDPPort(int))); + disconnect(spinZmqPort, SIGNAL(valueChanged(int)), this, SLOT(SetCltZmqPort(int))); + disconnect(spinZmqPort2, SIGNAL(valueChanged(int)), this, SLOT(SetRxrZmqPort(int))); + disconnect(comboRxrOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetReceiverOnline(int))); + disconnect(dispIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + disconnect(dispMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + disconnect(dispUDPIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + disconnect(dispUDPMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + disconnect(btnRxr, SIGNAL(clicked()), this, SLOT(SetReceiver())); - dispIP->setText(det->getDetectorIP().c_str()); - dispMAC->setText(det->getDetectorMAC().c_str()); + dispIP->setText(myDet->getDetectorIP(moduleId).c_str()); + dispMAC->setText(myDet->getDetectorMAC(moduleId).c_str()); - //so that updated status - if(det->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG) - det->checkReceiverOnline(); - comboRxrOnline->setCurrentIndex(det->setReceiverOnline()); + //so that updated status + if(myDet->setReceiverOnline(slsDetectorDefs::GET_ONLINE_FLAG, moduleId)==slsDetectorDefs::ONLINE_FLAG) + myDet->checkReceiverOnline(moduleId); + comboRxrOnline->setCurrentIndex(myDet->setReceiverOnline(slsDetectorDefs::GET_ONLINE_FLAG, moduleId)); - dispRxrHostname->setText(det->getReceiver().c_str()); - spinTCPPort->setValue(det->getReceiverPort()); - spinUDPPort->setValue(atoi(det->getReceiverUDPPort().c_str())); - spinZmqPort->setValue(atoi(det->getClientStreamingPort().c_str())); - spinZmqPort2->setValue(atoi(det->getReceiverStreamingPort().c_str())); + dispRxrHostname->setText(myDet->getReceiverHostname(moduleId).c_str()); + spinTCPPort->setValue(myDet->setReceiverPort(-1, moduleId)); + spinUDPPort->setValue(myDet->getReceiverUDPPort(moduleId)); + spinZmqPort->setValue(myDet->getClientStreamingPort(moduleId)); + spinZmqPort2->setValue(myDet->getReceiverStreamingPort(moduleId)); - dispUDPIP->setText(det->getReceiverUDPIP().c_str()); - dispUDPMAC->setText(det->getReceiverUDPMAC().c_str()); + dispUDPIP->setText(myDet->getReceiverUDPIP(moduleId).c_str()); + dispUDPMAC->setText(myDet->getReceiverUDPMAC(moduleId).c_str()); - //connect - connect(spinTCPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrTCPPort(int))); - connect(spinUDPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrUDPPort(int))); - connect(spinZmqPort, SIGNAL(valueChanged(int)), this, SLOT(SetCltZmqPort(int))); - connect(spinZmqPort2, SIGNAL(valueChanged(int)), this, SLOT(SetRxrZmqPort(int))); - connect(comboRxrOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetReceiverOnline(int))); - connect(dispIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); - connect(dispMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); - connect(dispUDPIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); - connect(dispUDPMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); - connect(btnRxr, SIGNAL(clicked()), this, SLOT(SetReceiver())); + //connect + connect(spinTCPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrTCPPort(int))); + connect(spinUDPPort, SIGNAL(valueChanged(int)), this, SLOT(SetRxrUDPPort(int))); + connect(spinZmqPort, SIGNAL(valueChanged(int)), this, SLOT(SetCltZmqPort(int))); + connect(spinZmqPort2, SIGNAL(valueChanged(int)), this, SLOT(SetRxrZmqPort(int))); + connect(comboRxrOnline, SIGNAL(currentIndexChanged(int)), this, SLOT(SetReceiverOnline(int))); + connect(dispIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispUDPIP, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(dispUDPMAC, SIGNAL(editingFinished()), this, SLOT(SetNetworkParameters())); + connect(btnRxr, SIGNAL(clicked()), this, SLOT(SetReceiver())); - // zmq parameters - disconnect(dispZMQIP, SIGNAL(editingFinished()), this, SLOT(SetClientZMQIP())); - dispZMQIP->setText(det->getClientStreamingIP().c_str()); - connect(dispZMQIP, SIGNAL(editingFinished()), this, SLOT(SetClientZMQIP())); + // zmq parameters + disconnect(dispZMQIP, SIGNAL(editingFinished()), this, SLOT(SetClientZMQIP())); + dispZMQIP->setText(myDet->getClientStreamingIP(moduleId).c_str()); + connect(dispZMQIP, SIGNAL(editingFinished()), this, SLOT(SetClientZMQIP())); - disconnect(dispZMQIP2, SIGNAL(editingFinished()), this, SLOT(SetReceiverZMQIP())); - dispZMQIP2->setText(det->getReceiverStreamingIP().c_str()); - connect(dispZMQIP2, SIGNAL(editingFinished()), this, SLOT(SetReceiverZMQIP())); - } + disconnect(dispZMQIP2, SIGNAL(editingFinished()), this, SLOT(SetReceiverZMQIP())); + dispZMQIP2->setText(myDet->getReceiverStreamingIP(moduleId).c_str()); + connect(dispZMQIP2, SIGNAL(editingFinished()), this, SLOT(SetReceiverZMQIP())); //highlight in red if detector or receiver is offline if(!comboOnline->currentIndex()){ @@ -1570,33 +827,29 @@ void qTabAdvanced::Refresh(){ } //roi -#ifdef VERBOSE - cout << "Getting ROI" << endl; -#endif - if (detType == slsDetectorDefs::GOTTHARD) - updateROIList(); + FILE_LOG(logDEBUG) << "Getting ROI"; + if (detType == slsDetectorDefs::GOTTHARD) + updateROIList(); //update alltirmbits from server if(boxSetAllTrimbits->isEnabled()) updateAllTrimbitsFromServer(); // storage cells - if (detType == slsReceiverDefs::JUNGFRAU) { - disconnect(spinNumStoragecells,SIGNAL(valueChanged(int)),this, SLOT(SetNumStoragecells(int))); - spinNumStoragecells->setValue((int)myDet->setTimer(slsDetectorDefs::STORAGE_CELL_NUMBER,-1)); - connect(spinNumStoragecells,SIGNAL(valueChanged(int)), this, SLOT(SetNumStoragecells(int))); + if (detType == slsDetectorDefs::JUNGFRAU) { + disconnect(spinNumStoragecells,SIGNAL(valueChanged(int)),this, SLOT(SetNumStoragecells(int))); + spinNumStoragecells->setValue((int)myDet->setTimer(slsDetectorDefs::STORAGE_CELL_NUMBER,-1)); + connect(spinNumStoragecells,SIGNAL(valueChanged(int)), this, SLOT(SetNumStoragecells(int))); } - // sub exptime and sub period - else if (detType == slsReceiverDefs::EIGER) { + // sub exptime and sub dead time + else if (detType == slsDetectorDefs::EIGER) { disconnect(spinSubExpTime,SIGNAL(valueChanged(double)), this, SLOT(SetSubExposureTime())); disconnect(comboSubExpTimeUnit,SIGNAL(currentIndexChanged(int)),this, SLOT(SetSubExposureTime())); - disconnect(spinSubPeriod,SIGNAL(valueChanged(double)), this, SLOT(SetSubPeriod())); - disconnect(comboSubPeriodUnit,SIGNAL(currentIndexChanged(int)),this, SLOT(SetSubPeriod())); + disconnect(spinSubDeadTime,SIGNAL(valueChanged(double)), this, SLOT(SetSubDeadTime())); + disconnect(comboSubDeadTimeUnit,SIGNAL(currentIndexChanged(int)),this, SLOT(SetSubDeadTime())); -#ifdef VERBOSE - cout << "Getting Sub Exposure time and Sub Period" << endl; -#endif + FILE_LOG(logDEBUG) << "Getting Sub Exposure time and Sub Dead Time"; // subexptime qDefs::timeUnit unit; double time = qDefs::getCorrectTime(unit,((double)( @@ -1604,28 +857,20 @@ void qTabAdvanced::Refresh(){ spinSubExpTime->setValue(time); comboSubExpTimeUnit->setCurrentIndex((int)unit); - // subperiod + // subdeadtime time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::SUBFRAME_DEADTIME,-1)*(1E-9)))); - spinSubPeriod->setValue(time); - comboSubPeriodUnit->setCurrentIndex((int)unit); + spinSubDeadTime->setValue(time); + comboSubDeadTimeUnit->setCurrentIndex((int)unit); - // highlight if period < exptime - CheckAcqPeriodGreaterThanExp(); - connect(spinSubExpTime,SIGNAL(valueChanged(double)), this, SLOT(SetSubExposureTime())); connect(comboSubExpTimeUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(SetSubExposureTime())); - connect(spinSubPeriod,SIGNAL(valueChanged(double)), this, SLOT(SetSubPeriod())); - connect(comboSubPeriodUnit,SIGNAL(currentIndexChanged(int)),this, SLOT(SetSubPeriod())); + connect(spinSubDeadTime,SIGNAL(valueChanged(double)), this, SLOT(SetSubDeadTime())); + connect(comboSubDeadTimeUnit,SIGNAL(currentIndexChanged(int)),this, SLOT(SetSubDeadTime())); } -#ifdef VERBOSE - cout << "**Updated Advanced Tab" << endl << endl; -#endif + FILE_LOG(logDEBUG) << "**Updated Advanced Tab"; - qDefs::checkErrorMessage(det,"qTabAdvanced::Refresh"); + qDefs::checkErrorMessage(myDet, moduleId, "qTabAdvanced::Refresh"); } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - diff --git a/slsDetectorGui/src/qTabDataOutput.cpp b/slsDetectorGui/src/qTabDataOutput.cpp old mode 100644 new mode 100755 index 1f38edb5e..6256b0363 --- a/slsDetectorGui/src/qTabDataOutput.cpp +++ b/slsDetectorGui/src/qTabDataOutput.cpp @@ -1,556 +1,149 @@ -/* - * qTabDataOutput.cpp - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ -/********************************************************************** - * ********************************************************************/ - #include "qTabDataOutput.h" -// Project Class Headers -#include "slsDetector.h" + #include "multiSlsDetector.h" -// Qt Include Headers -#include + #include -// C++ Include Headers +#include + #include #include -using namespace std; -//------------------------------------------------------------------------------------------------------------------------------------------------- - - - -qTabDataOutput::qTabDataOutput(QWidget *parent,multiSlsDetector*& detector): - QWidget(parent),myDet(detector){ +qTabDataOutput::qTabDataOutput(QWidget *parent, multiSlsDetector *detector) : QWidget(parent), myDet(detector) { setupUi(this); SetupWidgetWindow(); Refresh(); + FILE_LOG(logDEBUG) << "DataOutput ready"; } -//------------------------------------------------------------------------------------------------------------------------------------------------- +qTabDataOutput::~qTabDataOutput() {} -qTabDataOutput::~qTabDataOutput(){ - delete myDet; -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::SetupWidgetWindow(){ - // Detector Type - detType=myDet->getDetectorsType(); - widgetEiger->setVisible(false); - - //rate correction - not for charge integrating detectors - if((detType == slsDetectorDefs::MYTHEN)||(detType == slsDetectorDefs::EIGER)) - chkRate->setEnabled(true); - - if((detType == slsDetectorDefs::MYTHEN)||(detType == slsDetectorDefs::GOTTHARD)) - chkAngular->setEnabled(true); - - if(detType == slsDetectorDefs::EIGER){ - chkRate->setEnabled(true); - chkTenGiga->setEnabled(true); - widgetEiger->setVisible(true); - } - - /** error message **/ +void qTabDataOutput::SetupWidgetWindow() { red = QPalette(); - red.setColor(QPalette::Active,QPalette::WindowText,Qt::red); + red.setColor(QPalette::Active, QPalette::WindowText, Qt::red); black = QPalette(); - black.setColor(QPalette::Active,QPalette::WindowText,Qt::black); + black.setColor(QPalette::Active, QPalette::WindowText, Qt::black); red1 = new QPalette(); - red1->setColor(QPalette::Text,Qt::red); + red1->setColor(QPalette::Text, Qt::red); black1 = new QPalette(); - black1->setColor(QPalette::Text,Qt::black); + black1->setColor(QPalette::Text, Qt::black); - flatFieldTip = dispFlatField->toolTip(); - errFlatFieldTip = QString("Flat field corrections.
" - " #flatfield# filename

")+ - QString("" - "Enter a valid file to enable Flat Field."); outDirTip = lblOutputDir->toolTip(); + // Detector Type + detType = myDet->getDetectorTypeAsEnum(); - //not used at all, later used for gappixels - chkUnused->setEnabled(false); - - //enabling file format depending on detector type - SetupFileFormat(); + // disabling depening on detector type + chkRate->setEnabled(false); + widgetEiger->setVisible(false); + if (detType == slsDetectorDefs::EIGER) { + chkRate->setEnabled(true); + widgetEiger->setVisible(true); + } + chkTenGiga->setEnabled(false); + if (detType == slsDetectorDefs::EIGER || detType == slsDetectorDefs::MOENCH) { + chkTenGiga->setEnabled(true); + } Initialization(); - disconnect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(GetOutputDir())); + // populate detectors, get output dir PopulateDetectors(); - connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(GetOutputDir())); - //flat field correction from server -#ifdef VERBOSE - cout << "Getting flat field" << endl; -#endif - UpdateFlatFieldFromServer(); + VerifyOutputDirectory(); + // over write + UpdateFileOverwriteFromServer(); - //rate correction - not for charge integrating detectors - if((detType == slsDetectorDefs::MYTHEN)||(detType == slsDetectorDefs::EIGER)){ -#ifdef VERBOSE - cout << "Getting rate correction" << endl; -#endif + // file format + UpdateFileFormatFromServer(); + + // rate correction + if (chkRate->isEnabled()) { UpdateRateCorrectionFromServer(); } - - //update angular conversion from server - if((detType == slsDetectorDefs::MYTHEN)||(detType == slsDetectorDefs::GOTTHARD)){ -#ifdef VERBOSE - cout << "Getting angular conversion" << endl; -#endif - int ang; - if(myDet->getAngularConversion(ang)) - chkAngular->setChecked(true); - emit AngularConversionSignal(chkAngular->isChecked()); + // 10 gbe + if (chkTenGiga->isEnabled()) { + EnableTenGigabitEthernet(-1, 1); } - - //discard bad channels from server -#ifdef VERBOSE - cout << "Getting bad channel correction:" << myDet->getBadChannelCorrection() << endl; -#endif - disconnect(chkDiscardBad, SIGNAL(toggled(bool))); - if(myDet->getBadChannelCorrection()) - chkDiscardBad->setChecked(true); - else - chkDiscardBad->setChecked(false); - connect(chkDiscardBad, SIGNAL(toggled(bool)), this, SLOT(DiscardBadChannels())); - -/* - if(detType == slsDetectorDefs::MYTHEN){ - comboDetector->hide(); + //Eiger specific + if (widgetEiger->isVisible()) { + //speed + UpdateSpeedFromServer(); + //flags + UpdateFlagsFromServer(); } -*/ - qDefs::checkErrorMessage(myDet,"qTabDataOutput::SetupWidgetWindow"); + + qDefs::checkErrorMessage(myDet, "qTabDataOutput::SetupWidgetWindow"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::Initialization(){ +void qTabDataOutput::Initialization() { //output dir - connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(GetOutputDir())); - connect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); + connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(GetOutputDir())); + connect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); + connect(btnOutputBrowse, SIGNAL(clicked()), this, SLOT(BrowseOutputDir())); //overwrite enable - connect(chkOverwriteEnable, SIGNAL(toggled(bool)), this, SLOT(SetOverwriteEnable(bool))); + connect(chkOverwriteEnable, SIGNAL(toggled(bool)), this, SLOT(SetOverwriteEnable(bool))); //file format - connect(comboFileFormat, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFileFormat(int))); + connect(comboFileFormat, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFileFormat(int))); - connect(btnOutputBrowse, SIGNAL(clicked()), this, SLOT(BrowseOutputDir())); - //flat field correction - connect(chkFlatField, SIGNAL(toggled(bool)), this, SLOT(SetFlatField())); - connect(btnFlatField, SIGNAL(clicked()), this, SLOT(BrowseFlatFieldPath())); //rate correction - connect(chkRate, SIGNAL(toggled(bool)), this, SLOT(SetRateCorrection())); - connect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); - connect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); + connect(chkRate, SIGNAL(toggled(bool)), this, SLOT(SetRateCorrection())); + connect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); + connect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); - //angular correction - connect(chkAngular, SIGNAL(toggled(bool)), this, SLOT(SetAngularCorrection())); - //discard bad channels - connect(chkDiscardBad, SIGNAL(toggled(bool)), this, SLOT(DiscardBadChannels())); //10GbE - connect(chkTenGiga, SIGNAL(toggled(bool)), this, SLOT(EnableTenGigabitEthernet(bool))); + connect(chkTenGiga, SIGNAL(toggled(bool)), this, SLOT(EnableTenGigabitEthernet(bool))); //eiger - if(widgetEiger->isVisible()){ + if (widgetEiger->isVisible()) { //speed - connect(comboEigerClkDivider,SIGNAL(currentIndexChanged(int)), this, SLOT(SetSpeed())); + connect(comboEigerClkDivider, SIGNAL(currentIndexChanged(int)), this, SLOT(SetSpeed())); //flags - connect(comboEigerFlags1, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFlags())); - connect(comboEigerFlags2, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFlags())); + connect(comboEigerFlags1, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFlags())); + connect(comboEigerFlags2, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFlags())); } } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::BrowseOutputDir() -{ - QString directory = QFileDialog::getExistingDirectory(this,tr("Choose Output Directory "),dispOutputDir->text()); +void qTabDataOutput::BrowseOutputDir() { + QString directory = QFileDialog::getExistingDirectory(this, tr("Choose Output Directory "), dispOutputDir->text()); if (!directory.isEmpty()) dispOutputDir->setText(directory); SetOutputDir(); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabDataOutput::GetOutputDir() { + FILE_LOG(logDEBUG) << "Getting output directory"; - -void qTabDataOutput::SetFlatField(){ -#ifdef VERYVERBOSE - cout << "Entering Set Flat Field Correction Function" << endl; -#endif - // so that it doesnt call it twice - disconnect(dispFlatField, SIGNAL(editingFinished()), this, SLOT(SetFlatField())); - - //enable/disable - dispFlatField->setEnabled(chkFlatField->isChecked()); - btnFlatField->setEnabled(chkFlatField->isChecked()); - - if(chkFlatField->isChecked()){ - if(dispFlatField->text().isEmpty()){ - chkFlatField->setToolTip(errFlatFieldTip); - dispFlatField->setToolTip(errFlatFieldTip); - chkFlatField->setPalette(red); - chkFlatField->setText("Flat Field File:*"); -#ifdef VERBOSE - cout << "Flat Field File is not set." << endl; -#endif - }else{ - QString fName = dispFlatField->text(); - QString file = fName.section('/',-1); - QString dir = fName.section('/',0,-2,QString::SectionIncludeLeadingSep); - - chkFlatField->setToolTip(flatFieldTip); - dispFlatField->setToolTip(flatFieldTip); - chkFlatField->setPalette(chkDiscardBad->palette()); - chkFlatField->setText("Flat Field File:"); - //set ff dir - myDet->setFlatFieldCorrectionDir(dir.toAscii().constData()); - //set ff file and catch error if -1 - if(myDet->setFlatFieldCorrectionFile(file.toAscii().constData())<0){ - string sDir = dir.toAscii().constData(),sFile = file.toAscii().constData(); - if(sDir.length()<1) {sDir = string(QDir::current().absolutePath().toAscii().constData()); /*"/home/";*/} - qDefs::Message(qDefs::WARNING,"Invalid Flat Field file: "+sDir+"/"+sFile+ - ".\nUnsetting Flat Field.","qTabDataOutput::SetFlatField"); - - //Unsetting flat field - myDet->setFlatFieldCorrectionFile(""); - dispFlatField->setText(""); - chkFlatField->setToolTip(errFlatFieldTip); - dispFlatField->setToolTip(errFlatFieldTip); - chkFlatField->setPalette(red); - chkFlatField->setText("Flat Field File:*"); -#ifdef VERBOSE - cout << "Invalid Flat Field File - "<< sDir << sFile << ". Unsetting Flat Field." << endl; -#endif - } - else{ -#ifdef VERBOSE - cout << "Setting flat field file to "<< dispFlatField->text().toAscii().constData() << endl; -#endif - } - } - }else{ - chkFlatField->setToolTip(flatFieldTip); - dispFlatField->setToolTip(flatFieldTip); - chkFlatField->setPalette(chkDiscardBad->palette()); - chkFlatField->setText("Flat Field File:"); - //Unsetting flat field - myDet->setFlatFieldCorrectionFile(""); - dispFlatField->setText(""); -#ifdef VERBOSE - cout << "Unsetting flat field correction file" << endl; -#endif - } - - connect(dispFlatField,SIGNAL(editingFinished()),this,SLOT(SetFlatField())); - - qDefs::checkErrorMessage(myDet,"qTabDataOutput::SetFlatField"); -} - -//------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabDataOutput::UpdateFlatFieldFromServer(){ - disconnect(dispFlatField, SIGNAL(editingFinished()), this, SLOT(SetFlatField())); - - dispFlatField->setText(QString(myDet->getFlatFieldCorrectionDir().c_str())+"/"+QString(myDet->getFlatFieldCorrectionFile().c_str())); -#ifdef VERBOSE - cout << "Getting flat field correction file" << dispFlatField->text().toAscii().constData() << endl; -#endif - //calls setflatfield to ensure the file still exists or disable it - if(!QString(myDet->getFlatFieldCorrectionFile().c_str()).compare("none")){ - dispFlatField->setText(""); - chkFlatField->setChecked(false); -#ifdef VERBOSE - cout << "Flat Field is not set." << endl; -#endif - } - else - chkFlatField->setChecked(true); - - chkFlatField->setToolTip(flatFieldTip); - dispFlatField->setToolTip(flatFieldTip); - chkFlatField->setPalette(chkDiscardBad->palette()); - chkFlatField->setText("Flat Field File:"); - - connect(dispFlatField, SIGNAL(editingFinished()), this, SLOT(SetFlatField())); - - qDefs::checkErrorMessage(myDet,"qTabDataOutput::UpdateFlatFieldFromServer"); -} - -//------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabDataOutput::BrowseFlatFieldPath(){ - QString fName = dispFlatField->text(); - QString dir = fName.section('/',0,-2,QString::SectionIncludeLeadingSep); - if(dir.isEmpty()) dir = QString(myDet->getFlatFieldCorrectionDir().c_str());/*"/home/";*/ - fName = QFileDialog::getOpenFileName(this, - tr("Load Flat Field Correction File"),dir, - tr("Data Files(*.raw *.dat);; All Files (*.*)"),0,QFileDialog::ShowDirsOnly); - if (!fName.isEmpty()){ - dispFlatField->setText(fName); - SetFlatField(); - } - - qDefs::checkErrorMessage(myDet,"qTabDataOutput::BrowseFlatFieldPath"); - -} - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::SetRateCorrection(int deadtime){ - disconnect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); - disconnect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); - -#ifdef VERBOSE - cout << "Entering Set Rate Correction function" << endl; -#endif - - if(chkRate->isChecked()){ - if(!btnDefaultRate->isEnabled()){ - btnDefaultRate->setEnabled(true); - lblDeadTime->setEnabled(true); - spinDeadTime->setEnabled(true); - } - - if(deadtime!=-1){ - deadtime = (double)spinDeadTime->value(); -#ifdef VERBOSE - cout << "Setting rate corrections with custom dead time: " << deadtime << endl; -#endif - }else{; -#ifdef VERBOSE - cout << "Setting rate corrections with default dead time" << endl; -#endif - } - myDet->setRateCorrection(deadtime); - - }//unsetting rate correction - else{ - btnDefaultRate->setEnabled(false); - lblDeadTime->setEnabled(false); - spinDeadTime->setEnabled(false); - myDet->setRateCorrection(0); -#ifdef VERBOSE - cout << "Unsetting rate correction" << endl; -#endif - } - qDefs::checkErrorMessage(myDet,"qTabDataOutput::SetRateCorrection"); - - //update just the value - double rate = (double)myDet->getRateCorrectionTau(); - spinDeadTime->setValue((double)rate); - if(rate == -1){ - qDefs::Message(qDefs::WARNING,"Dead time is inconsistent for all detectors. Returned Value: -1.","qTabDataOutput::UpdateRateCorrectionFromServer"); - QString errorTip = QString("Rate Corrections.
" - " #ratecorr# tau in seconds

")+ - QString("" - "Dead time is inconsistent for all detectors."); - chkRate->setToolTip(errorTip); - spinDeadTime->setToolTip(errorTip); - chkRate->setPalette(red); - chkRate->setText("Rate:*"); - }else{ - QString normalTip = QString("Rate Corrections.
" - " #ratecorr# tau in seconds

"); - chkRate->setToolTip(normalTip); - spinDeadTime->setToolTip(normalTip); - chkRate->setPalette(chkDiscardBad->palette()); - chkRate->setText("Rate:"); - } - - connect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); - connect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); - -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::SetDefaultRateCorrection(){ - SetRateCorrection(-1); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::UpdateRateCorrectionFromServer(){ - disconnect(chkRate, SIGNAL(toggled(bool)), this, SLOT(SetRateCorrection())); - disconnect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); - disconnect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); - - double rate; - rate = (double)myDet->getRateCorrectionTau(); - qDefs::checkErrorMessage(myDet,"qTabDataOutput::UpdateRateCorrectionFromServer"); -#ifdef VERBOSE - cout << "Getting rate correction from server: " << rate << endl; -#endif - if(rate==0){ - chkRate->setChecked(false); - btnDefaultRate->setEnabled(false); - lblDeadTime->setEnabled(false); - spinDeadTime->setEnabled(false); - } - - else{ - chkRate->setChecked(true); - btnDefaultRate->setEnabled(true); - lblDeadTime->setEnabled(true); - spinDeadTime->setEnabled(true); - spinDeadTime->setValue((double)rate); - } - - if(rate == -1){ - qDefs::Message(qDefs::WARNING,"Dead time is inconsistent for all detectors. Returned Value: -1.","qTabDataOutput::UpdateRateCorrectionFromServer"); - QString errorTip = QString("Rate Corrections.
" - " #ratecorr# tau in seconds

")+ - QString("" - "Dead time is inconsistent for all detectors."); - chkRate->setToolTip(errorTip); - spinDeadTime->setToolTip(errorTip); - chkRate->setPalette(red); - chkRate->setText("Rate:*"); - }else{ - QString normalTip = QString("Rate Corrections.
" - " #ratecorr# tau in seconds

"); - chkRate->setToolTip(normalTip); - spinDeadTime->setToolTip(normalTip); - chkRate->setPalette(chkDiscardBad->palette()); - chkRate->setText("Rate:"); - } - - connect(chkRate, SIGNAL(toggled(bool)), this, SLOT(SetRateCorrection())); - connect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); - connect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::SetAngularCorrection(){ - disconnect(chkAngular, SIGNAL(toggled(bool)), this, SLOT(SetAngularCorrection())); -#ifdef VERYVERBOSE - cout << "Entering Set Angular Correction function" << endl; -#endif - bool enabled = chkAngular->isChecked(); - //set - if(myDet->setAngularCorrectionMask(enabled) == enabled){ -#ifdef VERBOSE - cout << "Angular Conversion mask:" << enabled << endl; -#endif - } - //error - else{ -#ifdef VERBOSE - cout << "Could not set angular conversion to default" << endl; -#endif - qDefs::Message(qDefs::WARNING,"Angular Conversion could not be set/reset. Please set the default file name using the command line, if you want to set it.","qTabDataOutput::SetAngularCorrection"); - chkAngular->setChecked(!enabled); - } - - emit AngularConversionSignal(chkAngular->isChecked()); - connect(chkAngular, SIGNAL(toggled(bool)), this, SLOT(SetAngularCorrection())); - qDefs::checkErrorMessage(myDet,"qTabDataOutput::SetAngularCorrection"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::DiscardBadChannels(){ -#ifdef VERBOSE - cout << "Entering Discard bad channels function" << endl; -#endif - if(chkDiscardBad->isChecked()){ -#ifdef VERBOSE - cout << "Setting bad channel correction to default" << endl; -#endif - myDet->setBadChannelCorrection("default"); - }else{ -#ifdef VERBOSE - cout << "Unsetting bad channel correction" << endl; -#endif - myDet->setBadChannelCorrection(""); - } - - qDefs::checkErrorMessage(myDet,"qTabDataOutput::DiscardBadChannels"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::PopulateDetectors(){ -#ifdef VERBOSE - cout << "Populating detectors" << endl; -#endif - comboDetector->clear(); - comboDetector->addItem("All"); - lblOutputDir->setText("Path:"); - //add specific detector options only if more than 1 detector - if(myDet->getNumberOfDetectors()>1){ - for(int i=0;igetNumberOfDetectors();i++) - comboDetector->addItem(QString(myDet->getHostname(i).c_str())); - } - GetOutputDir(); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::GetOutputDir(){ -#ifdef VERBOSE - cout << "Getting output directory" << endl; -#endif - - disconnect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); + disconnect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); //all - if(!comboDetector->currentIndex()) { + if (!comboDetector->currentIndex()) { dispOutputDir->setText(QString(myDet->getFilePath().c_str())); + qDefs::checkErrorMessage(myDet, "qTabDataOutput::GetOutputDir"); + //multi file path blank means sls file paths are different if (dispOutputDir->text().isEmpty()) { -#ifdef VERYVERBOSE - qDefs::Message(qDefs::INFORMATION,"The file path for individual units are different.\n" - "Hence, leaving the common field blank.","qTabDataOutput::GetOutputDir"); -#endif -#ifdef VERBOSE - cout << "The file path for individual units are different.\n" - "Hence, leaving the common field blank." << endl; -#endif - QString errTip = QString("
" - "Output Directory Information only: The file path for individual units are different.
" - "Hence, leaving the common field blank.
"); - lblOutputDir->setText("Path*:"); - lblOutputDir->setPalette(red); - lblOutputDir->setToolTip(errTip); - btnOutputBrowse->setToolTip(errTip); - dispOutputDir->setToolTip(errTip); + qDefs::Message(qDefs::INFORMATION, "The file path for individual readouts are different.\n" + "Hence, leaving the common field blank.", "qTabDataOutput::GetOutputDir"); + FILE_LOG(logWARNING) << "The file path for individual units are different."; + QString errTip = QString("
" + "Output Directory Information only: The file path for individual readouts are different.
" + "Hence, leaving the common field blank.
"); + lblOutputDir->setText("Path*:"); + lblOutputDir->setPalette(red); + lblOutputDir->setToolTip(errTip); + btnOutputBrowse->setToolTip(errTip); + dispOutputDir->setToolTip(errTip); } else { lblOutputDir->setText("Path:"); lblOutputDir->setPalette(*black1); @@ -561,64 +154,57 @@ void qTabDataOutput::GetOutputDir(){ } //specific - else{ - slsDetector *det = myDet->getSlsDetector(comboDetector->currentIndex()-1); - qDefs::checkErrorMessage(myDet,"qTabDataOutput::GetOutputDir"); - dispOutputDir->setText(QString(det->getFilePath().c_str())); + else { + dispOutputDir->setText(QString(myDet->getFilePath(comboDetector->currentIndex() - 1).c_str())); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex() - 1, "qTabDataOutput::GetOutputDir"); } - connect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); + connect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -int qTabDataOutput::VerifyOutputDirectory(){ -#ifdef VERBOSE - cout << "Verifying output directory" << endl; -#endif +int qTabDataOutput::VerifyOutputDirectory() { + FILE_LOG(logDEBUG) << "Verifying output directory"; GetOutputDir(); bool error = false; - string detName = ""; - string mess = ""; + std::string detName = ""; + std::string mess = ""; - //common - myDet->setFilePath(myDet->getFilePath()); - if(!qDefs::checkErrorMessage(myDet,"qTabDataOutput::VerifyOutputDirectory").empty()) - error = true; + //common (check only if no +, different values) + std::string fpath = myDet->getFilePath(); + if (fpath.find('+') == std::string::npos) { + myDet->setFilePath(myDet->getFilePath()); + if (!qDefs::checkErrorMessage(myDet, "qTabDataOutput::VerifyOutputDirectory").empty()) + error = true; + } //for each detector - for(int i=0;igetNumberOfDetectors();i++){ - slsDetector *det = myDet->getSlsDetector(i); - qDefs::checkErrorMessage(myDet,"qTabDataOutput::VerifyOutputDirectory"); - detName = string("\n - ") + string(comboDetector->itemText(i+1).toAscii().constData()); - det->setFilePath(det->getFilePath()); - if(!qDefs::checkErrorMessage(det,"qTabDataOutput::VerifyOutputDirectory").empty()) { - mess. append(detName); - error = true; - } + for (int i = 0; i < myDet->getNumberOfDetectors(); ++i) { + detName = std::string("\n - ") + std::string(comboDetector->itemText(i+1).toAscii().constData()); + myDet->setFilePath(myDet->getFilePath(i), i); + if(!qDefs::checkErrorMessage(myDet, i, "qTabDataOutput::VerifyOutputDirectory").empty()) { + mess. append(detName); + error = true; + } } //invalid - if(error){ - qDefs::Message(qDefs::WARNING,string("Invalid Output Directory ")+ mess ,"qTabDataOutput::VerifyOutputDirectory"); -#ifdef VERBOSE - cout << "The output path doesnt exist anymore" << endl; -#endif + if (error) { + qDefs::Message(qDefs::WARNING, std::string("Invalid Output Directory ") + mess, "qTabDataOutput::VerifyOutputDirectory"); + FILE_LOG(logWARNING) << "The output path doesnt exist anymore"; //replace all \n with
size_t pos = 0; - while((pos = mess.find("\n", pos)) != string::npos){ + while ((pos = mess.find("\n", pos)) != std::string::npos) { mess.replace(pos, 1, "
"); pos += 1; } QString errTip = outDirTip + QString("
" - "Invalid Output Directory") + - QString(mess.c_str()) + - QString( "."); + "Invalid Output Directory") + + QString(mess.c_str()) + + QString("."); lblOutputDir->setText("Path*:"); lblOutputDir->setPalette(red); lblOutputDir->setToolTip(errTip); @@ -629,10 +215,8 @@ int qTabDataOutput::VerifyOutputDirectory(){ } //valid - else{ -#ifdef VERBOSE - cout << "The output pathid valid" << endl; -#endif + else { + FILE_LOG(logDEBUG) << "The output path is valid"; lblOutputDir->setText("Path:"); lblOutputDir->setPalette(*black1); lblOutputDir->setToolTip(outDirTip); @@ -644,351 +228,390 @@ int qTabDataOutput::VerifyOutputDirectory(){ } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabDataOutput::SetOutputDir() { + FILE_LOG(logDEBUG) << "Setting output directory"; -void qTabDataOutput::SetOutputDir(){ - -#ifdef VERBOSE - cout << "Setting output directory" << endl; -#endif - - disconnect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); - + disconnect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); bool error = false; QString path = dispOutputDir->text(); //empty - if(path.isEmpty()) { - qDefs::Message(qDefs::WARNING,"Invalid Output Path. Must not be empty.","qTabDataOutput::SetOutputDir"); -#ifdef VERBOSE - cout << "Invalid Output Path. Must not be empty." << endl; -#endif + if (path.isEmpty()) { + qDefs::Message(qDefs::WARNING, "Invalid Output Path. Must not be empty.", "qTabDataOutput::SetOutputDir"); + FILE_LOG(logWARNING) << "Invalid Output Path. Must not be empty."; error = true; } //gets rid of the end '/'s - else if (path.endsWith('/')){ - while(path.endsWith('/')) + else if (path.endsWith('/')) { + while (path.endsWith('/')) path.chop(1); dispOutputDir->setText(path); } //specific - if(comboDetector->currentIndex()){ - slsDetector *det = myDet->getSlsDetector(comboDetector->currentIndex()-1); - qDefs::checkErrorMessage(myDet,"qTabDataOutput::SetOutputDir"); - det->setFilePath(string(dispOutputDir->text().toAscii().constData())); - if(!qDefs::checkErrorMessage(det,"qTabDataOutput::SetOutputDir").empty()) + if (comboDetector->currentIndex()) { + myDet->setFilePath(std::string(dispOutputDir->text().toAscii().constData()), comboDetector->currentIndex() - 1); + if (!qDefs::checkErrorMessage(myDet, comboDetector->currentIndex() - 1, "qTabDataOutput::SetOutputDir").empty()) error = true; } //multi - else{ - myDet->setFilePath(string(path.toAscii().constData())); - if(!qDefs::checkErrorMessage(myDet,"qTabDataOutput::SetOutputDir").empty()) + else { + myDet->setFilePath(std::string(path.toAscii().constData())); + if (!qDefs::checkErrorMessage(myDet, "qTabDataOutput::SetOutputDir").empty()) error = true; } - - if(error){ -#ifdef VERBOSE - cout << "The output path could not be set" << endl; -#endif + if (error) { + FILE_LOG(logWARNING) << "The output path could not be set"; QString errTip = outDirTip + QString("
" - "Invalid File Path"); + "Invalid File Path"); lblOutputDir->setText("Path*:"); lblOutputDir->setPalette(red); lblOutputDir->setToolTip(errTip); btnOutputBrowse->setToolTip(errTip); dispOutputDir->setToolTip(errTip); - } - else{ -#ifdef VERBOSE - cout << "The output path has been modified" << endl; -#endif + } else { + FILE_LOG(logINFO) << "Output dir set to " << path.toAscii().constData(); lblOutputDir->setText("Path:"); lblOutputDir->setPalette(*black1); lblOutputDir->setToolTip(outDirTip); btnOutputBrowse->setToolTip(outDirTip); dispOutputDir->setToolTip(outDirTip); - } - - connect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); - + connect(dispOutputDir, SIGNAL(editingFinished()), this, SLOT(SetOutputDir())); } -//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabDataOutput::SetRateCorrection(int deadtime) { + disconnect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); + disconnect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); + + FILE_LOG(logDEBUG) << "Entering Set Rate Correction function"; + + if (chkRate->isChecked()) { + if (!btnDefaultRate->isEnabled()) { + btnDefaultRate->setEnabled(true); + lblDeadTime->setEnabled(true); + spinDeadTime->setEnabled(true); + } + + if (deadtime != -1) { + deadtime = (double)spinDeadTime->value(); + FILE_LOG(logINFO) << "Setting rate corrections with custom dead time: " << deadtime << '\n'; + } else { + FILE_LOG(logINFO) << "Setting rate corrections with default dead time" << '\n'; + } + myDet->setRateCorrection(deadtime); + + } //unsetting rate correction + else { + btnDefaultRate->setEnabled(false); + lblDeadTime->setEnabled(false); + spinDeadTime->setEnabled(false); + myDet->setRateCorrection(0); + FILE_LOG(logINFO) << "Unsetting rate correction"; + } + qDefs::checkErrorMessage(myDet, "qTabDataOutput::SetRateCorrection"); + + //update just the value + double rate = (double)myDet->getRateCorrection(); + spinDeadTime->setValue((double)rate); + if (rate == -1) { + qDefs::Message(qDefs::WARNING, "Dead time is inconsistent for all detectors. Returned Value: -1.", "qTabDataOutput::UpdateRateCorrectionFromServer"); + QString errorTip = QString("Rate Corrections.
" + " #ratecorr# tau in seconds

") + + QString("" + "Dead time is inconsistent for all detectors."); + chkRate->setToolTip(errorTip); + spinDeadTime->setToolTip(errorTip); + chkRate->setPalette(red); + chkRate->setText("Rate:*"); + } else { + QString normalTip = QString("Rate Corrections.
" + " #ratecorr# tau in seconds

"); + chkRate->setToolTip(normalTip); + spinDeadTime->setToolTip(normalTip); + chkRate->setPalette(chkDiscardBad->palette()); + chkRate->setText("Rate:"); + } + + connect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); + connect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); +} -void qTabDataOutput::EnableTenGigabitEthernet(bool enable,int get){ -#ifdef VERBOSE - cout << endl << "Enabling/Disabling 10GbE" << endl; -#endif - disconnect(chkTenGiga, SIGNAL(toggled(bool)), this, SLOT(EnableTenGigabitEthernet(bool))); +void qTabDataOutput::SetDefaultRateCorrection() { + SetRateCorrection(-1); +} + + +void qTabDataOutput::UpdateRateCorrectionFromServer() { + disconnect(chkRate, SIGNAL(toggled(bool)), this, SLOT(SetRateCorrection())); + disconnect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); + disconnect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); + + double rate; + rate = (double)myDet->getRateCorrection(); + qDefs::checkErrorMessage(myDet, "qTabDataOutput::UpdateRateCorrectionFromServer"); + FILE_LOG(logDEBUG) << "Getting rate correction from server: " << rate << '\n'; + if (rate == 0) { + chkRate->setChecked(false); + btnDefaultRate->setEnabled(false); + lblDeadTime->setEnabled(false); + spinDeadTime->setEnabled(false); + } + + else { + chkRate->setChecked(true); + btnDefaultRate->setEnabled(true); + lblDeadTime->setEnabled(true); + spinDeadTime->setEnabled(true); + spinDeadTime->setValue((double)rate); + } + + if (rate == -1) { + qDefs::Message(qDefs::WARNING, "Dead time is inconsistent for all detectors. Returned Value: -1.", "qTabDataOutput::UpdateRateCorrectionFromServer"); + FILE_LOG(logWARNING) << "Dead time is inconsistent for all detectors."; + QString errorTip = QString("Rate Corrections.
" + " #ratecorr# tau in seconds

") + + QString("" + "Dead time is inconsistent for all detectors."); + chkRate->setToolTip(errorTip); + spinDeadTime->setToolTip(errorTip); + chkRate->setPalette(red); + chkRate->setText("Rate:*"); + } else { + QString normalTip = QString("Rate Corrections.
" + " #ratecorr# tau in seconds

"); + chkRate->setToolTip(normalTip); + spinDeadTime->setToolTip(normalTip); + chkRate->setPalette(chkDiscardBad->palette()); + chkRate->setText("Rate:"); + } + + connect(chkRate, SIGNAL(toggled(bool)), this, SLOT(SetRateCorrection())); + connect(btnDefaultRate, SIGNAL(clicked()), this, SLOT(SetDefaultRateCorrection())); + connect(spinDeadTime, SIGNAL(editingFinished()), this, SLOT(SetRateCorrection())); +} + + +void qTabDataOutput::PopulateDetectors() { + disconnect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(GetOutputDir())); + + FILE_LOG(logDEBUG) << "Populating detectors"; + comboDetector->clear(); + comboDetector->addItem("All"); + lblOutputDir->setText("Path:"); + //add specific detector options only if more than 1 detector + if (myDet->getNumberOfDetectors() > 1) { + for (int i = 0; i < myDet->getNumberOfDetectors(); i++) + comboDetector->addItem(QString(myDet->getHostname(i).c_str())); + } + GetOutputDir(); + connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(GetOutputDir())); +} + + + + +void qTabDataOutput::EnableTenGigabitEthernet(bool enable, int get) { + if (get || enable == -1) { + FILE_LOG(logDEBUG) << "Getting 10Gbe enable"; + } else { + FILE_LOG(logINFO) << (enable == 0 ? "Disabling" : "Enabling") << "10GbE"; + } + disconnect(chkTenGiga, SIGNAL(toggled(bool)), this, SLOT(EnableTenGigabitEthernet(bool))); int ret; - if(get) + if (get) ret = myDet->enableTenGigabitEthernet(-1); else ret = myDet->enableTenGigabitEthernet(enable); - if(ret > 0) chkTenGiga->setChecked(true); - else chkTenGiga->setChecked(false); - connect(chkTenGiga, SIGNAL(toggled(bool)), this, SLOT(EnableTenGigabitEthernet(bool))); + if (ret > 0) + chkTenGiga->setChecked(true); + else + chkTenGiga->setChecked(false); + connect(chkTenGiga, SIGNAL(toggled(bool)), this, SLOT(EnableTenGigabitEthernet(bool))); - qDefs::checkErrorMessage(myDet,"qTabDataOutput::EnableTenGigabitEthernet"); + qDefs::checkErrorMessage(myDet, "qTabDataOutput::EnableTenGigabitEthernet"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::SetSpeed(){ -#ifdef VERBOSE - cout << endl << "Setting Speed" << endl; -#endif - if(widgetEiger->isVisible()){ - myDet->setSpeed(slsDetectorDefs::CLOCK_DIVIDER,comboEigerClkDivider->currentIndex()); - qDefs::checkErrorMessage(myDet,"qTabDataOutput::SetSpeed"); - UpdateSpeedFromServer(); - } - -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::SetFlags(){ -#ifdef VERBOSE - cout << endl << "Setting Readout Flags" << endl; -#endif - slsDetectorDefs::readOutFlags val = slsDetectorDefs::GET_READOUT_FLAGS; - if(widgetEiger->isVisible()){ - - //set to continous or storeinram - switch(comboEigerFlags1->currentIndex()){ - case Storeinram: val = slsDetectorDefs::STORE_IN_RAM; break; - default: val = slsDetectorDefs::CONTINOUS_RO; break; - } - myDet->setReadOutFlags(val); - qDefs::checkErrorMessage(myDet,"qTabDataOutput::setFlags"); - - //set to parallel, nonparallel or safe - switch(comboEigerFlags2->currentIndex()){ - case Parallel: val = slsDetectorDefs::PARALLEL; break; - case Safe: val = slsDetectorDefs::SAFE; break; - default: val = slsDetectorDefs::NONPARALLEL; break; - } - myDet->setReadOutFlags(val); - qDefs::checkErrorMessage(myDet,"qTabDataOutput::setFlags"); - - //update flags - UpdateFlagsFromServer(); - } - -} - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::UpdateSpeedFromServer(){ +void qTabDataOutput::UpdateSpeedFromServer() { int ret; - if(widgetEiger->isVisible()){ - disconnect(comboEigerClkDivider, SIGNAL(currentIndexChanged(int)), this, SLOT(SetSpeed())); + if (widgetEiger->isVisible()) { + disconnect(comboEigerClkDivider, SIGNAL(currentIndexChanged(int)), this, SLOT(SetSpeed())); //get speed ret = myDet->setSpeed(slsDetectorDefs::CLOCK_DIVIDER, -1); - qDefs::checkErrorMessage(myDet,"qTabDataOutput::updateSpeedFromServer"); + qDefs::checkErrorMessage(myDet, "qTabDataOutput::updateSpeedFromServer"); //valid speed - if(ret >= 0 && ret < NumberofSpeeds) + if (ret >= 0 && ret < NUMBEROFSPEEDS) comboEigerClkDivider->setCurrentIndex(ret); //invalid speed - else{ - qDefs::Message(qDefs::WARNING,"Inconsistent value from clock divider.\n" - "Setting it for all detectors involved to half speed.","qTabDataOutput::updateSpeedFromServer"); + else { + qDefs::Message(qDefs::WARNING, "Inconsistent value from clock divider.\n" + "Setting it for all detectors involved to half speed.", + "qTabDataOutput::updateSpeedFromServer"); + FILE_LOG(logWARNING) << "Inconsistent value from clock divider."; //set to default - comboEigerClkDivider->setCurrentIndex(HalfSpeed); - myDet->setSpeed(slsDetectorDefs::CLOCK_DIVIDER,HalfSpeed); - qDefs::checkErrorMessage(myDet,"qTabDataOutput::updateSpeedFromServer"); - + comboEigerClkDivider->setCurrentIndex(HALFSPEED); + myDet->setSpeed(slsDetectorDefs::CLOCK_DIVIDER, HALFSPEED); + qDefs::checkErrorMessage(myDet, "qTabDataOutput::updateSpeedFromServer"); } - connect(comboEigerClkDivider, SIGNAL(currentIndexChanged(int)), this, SLOT(SetSpeed())); + connect(comboEigerClkDivider, SIGNAL(currentIndexChanged(int)), this, SLOT(SetSpeed())); } } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabDataOutput::SetSpeed() { + FILE_LOG(logINFO) << "Setting Speed"; + myDet->setSpeed(slsDetectorDefs::CLOCK_DIVIDER, comboEigerClkDivider->currentIndex()); + qDefs::checkErrorMessage(myDet, "qTabDataOutput::SetSpeed"); + UpdateSpeedFromServer(); +} -void qTabDataOutput::UpdateFlagsFromServer(){ + +void qTabDataOutput::UpdateFlagsFromServer() { int ret; - if(widgetEiger->isVisible()){ - disconnect(comboEigerFlags1, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFlags())); - disconnect(comboEigerFlags2, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFlags())); + if (widgetEiger->isVisible()) { + disconnect(comboEigerFlags1, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFlags())); + disconnect(comboEigerFlags2, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFlags())); //get speed ret = myDet->setReadOutFlags(slsDetectorDefs::GET_READOUT_FLAGS); - qDefs::checkErrorMessage(myDet,"qTabDataOutput::updateFlagsFromServer"); + qDefs::checkErrorMessage(myDet, "qTabDataOutput::updateFlagsFromServer"); //invalid flags - if(ret==-1){ - qDefs::Message(qDefs::WARNING,"Inconsistent value for readout flags.\n" - "Setting it for all detectors involved to continous nonparallel mode.", - "qTabDataOutput::updateFlagsFromServer"); + if (ret == -1) { + qDefs::Message(qDefs::WARNING, "Inconsistent value for readout flags.\n" + "Setting it for all detectors involved to continous nonparallel mode.", + "qTabDataOutput::updateFlagsFromServer"); + FILE_LOG(logWARNING) << "Inconsistent value for readout flags."; //set to default - comboEigerFlags1->setCurrentIndex(Continous); - myDet->setReadOutFlags(slsDetectorDefs::CONTINOUS_RO); - qDefs::checkErrorMessage(myDet,"qTabDataOutput::updateFlagsFromServer"); - comboEigerFlags2->setCurrentIndex(NonParallel); - myDet->setReadOutFlags(slsDetectorDefs::NONPARALLEL); - qDefs::checkErrorMessage(myDet,"qTabDataOutput::updateFlagsFromServer"); + comboEigerFlags1->setCurrentIndex(CONTINUOUS); + myDet->setReadOutFlags(slsDetectorDefs::CONTINOUS_RO); + qDefs::checkErrorMessage(myDet, "qTabDataOutput::updateFlagsFromServer"); + comboEigerFlags2->setCurrentIndex(NONPARALLEL); + myDet->setReadOutFlags(slsDetectorDefs::NONPARALLEL); + qDefs::checkErrorMessage(myDet, "qTabDataOutput::updateFlagsFromServer"); } //valid flags - else{ - if(ret & slsDetectorDefs::STORE_IN_RAM) - comboEigerFlags1->setCurrentIndex(Storeinram); - else if(ret & slsDetectorDefs::CONTINOUS_RO) - comboEigerFlags1->setCurrentIndex(Continous); - if(ret & slsDetectorDefs::PARALLEL) - comboEigerFlags2->setCurrentIndex(Parallel); - else if(ret & slsDetectorDefs::NONPARALLEL) - comboEigerFlags2->setCurrentIndex(NonParallel); - else if(ret & slsDetectorDefs::SAFE) - comboEigerFlags2->setCurrentIndex(Safe); + else { + if (ret & slsDetectorDefs::STORE_IN_RAM) + comboEigerFlags1->setCurrentIndex(STOREINRAM); + else if (ret & slsDetectorDefs::CONTINOUS_RO) + comboEigerFlags1->setCurrentIndex(CONTINUOUS); + if (ret & slsDetectorDefs::PARALLEL) + comboEigerFlags2->setCurrentIndex(PARALLEL); + else if (ret & slsDetectorDefs::NONPARALLEL) + comboEigerFlags2->setCurrentIndex(NONPARALLEL); + else if (ret & slsDetectorDefs::SAFE) + comboEigerFlags2->setCurrentIndex(SAFE); } - connect(comboEigerFlags1, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFlags())); - connect(comboEigerFlags2, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFlags())); + connect(comboEigerFlags1, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFlags())); + connect(comboEigerFlags2, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFlags())); } } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabDataOutput::SetFlags() { + FILE_LOG(logINFO) << "Setting Readout Flags"; + slsDetectorDefs::readOutFlags val = slsDetectorDefs::GET_READOUT_FLAGS; - -void qTabDataOutput::SetupFileFormat(){ - - - //To be able to index items on a combo box - QStandardItemModel* model = qobject_cast(comboFileFormat->model()); - QModelIndex index[slsReceiverDefs::NUM_FILE_FORMATS]; - QStandardItem* item[slsReceiverDefs::NUM_FILE_FORMATS]; - if (model) { - for(int i=0;iindex(i, comboFileFormat->modelColumn(), comboFileFormat->rootModelIndex()); - item[i] = model->itemFromIndex(index[i]); - } - //Enabling/Disabling depending on the detector type - switch(detType){ - case slsDetectorDefs::MYTHEN: - item[(int)slsReceiverDefs::BINARY]->setEnabled(false); - item[(int)slsReceiverDefs::ASCII]->setEnabled(true); - item[(int)slsReceiverDefs::HDF5]->setEnabled(false); - break; - case slsDetectorDefs::EIGER: - case slsDetectorDefs::MOENCH: - case slsDetectorDefs::PROPIX: - case slsDetectorDefs::GOTTHARD: - case slsDetectorDefs::JUNGFRAU: - case slsDetectorDefs::JUNGFRAUCTB: - item[(int)slsReceiverDefs::BINARY]->setEnabled(true); - item[(int)slsReceiverDefs::ASCII]->setEnabled(false); - item[(int)slsReceiverDefs::HDF5]->setEnabled(true); - break; - default: - cout << "Unknown detector type " << endl; - qDefs::Message(qDefs::CRITICAL,"Unknown detector type.","qTabDataOutput::SetupFileFormat"); - exit(-1); - break; - } + //set to continous or storeinram + switch (comboEigerFlags1->currentIndex()) { + case STOREINRAM: + val = slsDetectorDefs::STORE_IN_RAM; + break; + default: + val = slsDetectorDefs::CONTINOUS_RO; + break; } + myDet->setReadOutFlags(val); + qDefs::checkErrorMessage(myDet, "qTabDataOutput::setFlags"); + + //set to parallel, nonparallel or safe + switch (comboEigerFlags2->currentIndex()) { + case PARALLEL: + val = slsDetectorDefs::PARALLEL; + break; + case SAFE: + val = slsDetectorDefs::SAFE; + break; + default: + val = slsDetectorDefs::NONPARALLEL; + break; + } + myDet->setReadOutFlags(val); + qDefs::checkErrorMessage(myDet, "qTabDataOutput::setFlags"); + + //update flags + UpdateFlagsFromServer(); - comboFileFormat->setCurrentIndex((int)myDet->getFileFormat()); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::UpdateFileFormatFromServer(){ -#ifdef VERBOSE - cout << endl << "Getting File Format" << endl; -#endif - disconnect(comboFileFormat, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFileFormat(int))); +void qTabDataOutput::UpdateFileFormatFromServer() { + FILE_LOG(logDEBUG) << "Getting File Format"; + disconnect(comboFileFormat, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFileFormat(int))); comboFileFormat->setCurrentIndex((int)myDet->getFileFormat()); - connect(comboFileFormat, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFileFormat(int))); + connect(comboFileFormat, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFileFormat(int))); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabDataOutput::SetFileFormat(int format) { + FILE_LOG(logINFO) << "Setting File Format"; + disconnect(comboFileFormat, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFileFormat(int))); - -void qTabDataOutput::SetFileFormat(int format){ -#ifdef VERBOSE - cout << endl << "Setting File Format" << endl; -#endif - disconnect(comboFileFormat, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFileFormat(int))); - - int ret = (int)myDet->setFileFormat((slsReceiverDefs::fileFormat)comboFileFormat->currentIndex()); + int ret = (int)myDet->setFileFormat((slsDetectorDefs::fileFormat)comboFileFormat->currentIndex()); if (ret != comboFileFormat->currentIndex()) { - qDefs::Message(qDefs::WARNING,"Could not set file format.","qTabDataOutput::SetFileFormat"); + qDefs::Message(qDefs::WARNING, "Could not set file format.", "qTabDataOutput::SetFileFormat"); comboFileFormat->setCurrentIndex((int)ret); } - connect(comboFileFormat, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFileFormat(int))); + connect(comboFileFormat, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFileFormat(int))); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::UpdateFileOverwriteFromServer(){ -#ifdef VERBOSE - cout << endl << "Getting File Over Write Enable" << endl; -#endif - disconnect(chkOverwriteEnable, SIGNAL(toggled(bool)), this, SLOT(SetOverwriteEnable(bool))); +void qTabDataOutput::UpdateFileOverwriteFromServer() { + FILE_LOG(logDEBUG) << "Getting File Over Write Enable"; + disconnect(chkOverwriteEnable, SIGNAL(toggled(bool)), this, SLOT(SetOverwriteEnable(bool))); chkOverwriteEnable->setChecked(myDet->overwriteFile()); - connect(chkOverwriteEnable, SIGNAL(toggled(bool)), this, SLOT(SetOverwriteEnable(bool))); + connect(chkOverwriteEnable, SIGNAL(toggled(bool)), this, SLOT(SetOverwriteEnable(bool))); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabDataOutput::SetOverwriteEnable(bool enable) { + FILE_LOG(logINFO) << "Setting File Over Write Enable"; + disconnect(chkOverwriteEnable, SIGNAL(toggled(bool)), this, SLOT(SetOverwriteEnable(bool))); - -void qTabDataOutput::SetOverwriteEnable(bool enable){ -#ifdef VERBOSE - cout << endl << "Setting File Over Write Enable" << endl; -#endif - disconnect(chkOverwriteEnable, SIGNAL(toggled(bool)), this, SLOT(SetOverwriteEnable(bool))); - - int valid = (enable?1:0); + int valid = (enable ? 1 : 0); if (myDet->overwriteFile(enable) != valid) - qDefs::Message(qDefs::WARNING,"Could not over write enable.","qTabDataOutput::SetOverwriteEnable"); + qDefs::Message(qDefs::WARNING, "Could not over write enable.", "qTabDataOutput::SetOverwriteEnable"); - connect(chkOverwriteEnable, SIGNAL(toggled(bool)), this, SLOT(SetOverwriteEnable(bool))); + connect(chkOverwriteEnable, SIGNAL(toggled(bool)), this, SLOT(SetOverwriteEnable(bool))); UpdateFileOverwriteFromServer(); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDataOutput::Refresh(){ -#ifdef VERBOSE - cout << endl << "**Updating DataOutput Tab" << endl; -#endif +void qTabDataOutput::Refresh() { + FILE_LOG(logDEBUG) << "**Updating DataOutput Tab"; if (!myDet->enableWriteToFile()) boxFileWriteEnabled->setEnabled(false); @@ -996,107 +619,46 @@ void qTabDataOutput::Refresh(){ boxFileWriteEnabled->setEnabled(true); // output dir -#ifdef VERBOSE - cout << "Getting output directory" << endl; -#endif - - disconnect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(GetOutputDir())); PopulateDetectors(); - connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(GetOutputDir())); - - //file format - UpdateFileFormatFromServer(); //overwrite UpdateFileOverwriteFromServer(); + //file format + UpdateFileFormatFromServer(); + //file name dispFileName->setText(QString(myDet->getFileName().c_str())); - //flat field correction from server -#ifdef VERBOSE - cout << "Getting flat field" << endl; -#endif - UpdateFlatFieldFromServer(); - - - //rate correction - not for charge integrating detectors - if((detType == slsDetectorDefs::MYTHEN)||(detType == slsDetectorDefs::EIGER)){ -#ifdef VERBOSE - cout << "Getting rate correction" << endl; -#endif + // rate correction + if (chkRate->isEnabled()) { UpdateRateCorrectionFromServer(); } - - //update angular conversion from server - if((detType == slsDetectorDefs::MYTHEN)||(detType == slsDetectorDefs::GOTTHARD)){ -#ifdef VERBOSE - cout << "Getting angular conversion" << endl; -#endif - int ang; - if(myDet->getAngularConversion(ang)) - chkAngular->setChecked(true); - emit AngularConversionSignal(chkAngular->isChecked()); - } - - - //discard bad channels from server -#ifdef VERBOSE - cout << "Getting bad channel correction" << endl;//cout << "ff " << myDet->getBadChannelCorrection() << endl; -#endif - - - disconnect(chkDiscardBad, SIGNAL(toggled(bool))); - if(myDet->getBadChannelCorrection()) - chkDiscardBad->setChecked(true); - else - chkDiscardBad->setChecked(false); - connect(chkDiscardBad, SIGNAL(toggled(bool)), this, SLOT(DiscardBadChannels())); - - if(myDet->setReceiverOnline()==slsDetectorDefs::ONLINE_FLAG){ + if (myDet->setReceiverOnline() == slsDetectorDefs::ONLINE_FLAG) { btnOutputBrowse->setEnabled(false); btnOutputBrowse->setToolTip("This button is disabled as receiver PC is different from " - "client PC and hence different directory structures.

" + dispOutputDir->toolTip()); - }else{ + "client PC and hence different directory structures.

" + + dispOutputDir->toolTip()); + } else { btnOutputBrowse->setEnabled(true); btnOutputBrowse->setToolTip(dispOutputDir->toolTip()); } - //getting 10GbE - if(chkTenGiga->isEnabled()){ -#ifdef VERBOSE - cout << "Getting 10GbE enable" << endl; -#endif - EnableTenGigabitEthernet(-1,1); + // 10GbE + if (chkTenGiga->isEnabled()) { + EnableTenGigabitEthernet(-1, 1); } //Eiger specific - if(widgetEiger->isVisible()){ + if (widgetEiger->isVisible()) { //speed -#ifdef VERBOSE - cout << "Getting Speed" << endl; -#endif UpdateSpeedFromServer(); //flags -#ifdef VERBOSE - cout << "Getting Readout Flags" << endl; -#endif UpdateFlagsFromServer(); - - - } + FILE_LOG(logDEBUG) << "**Updated DataOutput Tab"; -#ifdef VERBOSE - cout << "**Updated DataOutput Tab" << endl << endl; -#endif - - qDefs::checkErrorMessage(myDet,"qTabDataOutput::Refresh"); + qDefs::checkErrorMessage(myDet, "qTabDataOutput::Refresh"); } - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - diff --git a/slsDetectorGui/src/qTabDebugging.cpp b/slsDetectorGui/src/qTabDebugging.cpp old mode 100644 new mode 100755 index 46b861052..f0cc36e14 --- a/slsDetectorGui/src/qTabDebugging.cpp +++ b/slsDetectorGui/src/qTabDebugging.cpp @@ -1,619 +1,272 @@ -/* - * qTabDebugging.cpp - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ #include "qTabDebugging.h" -// Project Class Headers -#include "slsDetector.h" + #include "multiSlsDetector.h" -// Qt Include Headers + #include #include -// C++ Include Headers -#include -using namespace std; - +#include //------------------------------------------------------------------------------------------------------------------------------------------------- +qTabDebugging::qTabDebugging(QWidget *parent, multiSlsDetector *detector) : QWidget(parent), + myDet(detector), + detType(slsDetectorDefs::GENERIC), + treeDet(0), + lblDetectorId(0), + lblDetectorFirmware(0), + lblDetectorSoftware(0) { + setupUi(this); + SetupWidgetWindow(); + Initialization(); + FILE_LOG(logDEBUG) << "Debugging ready"; +} -qTabDebugging::qTabDebugging(QWidget *parent,multiSlsDetector*& detector): - QWidget(parent), - myDet(detector), - det(0), - treeDet(0), - dispFrame(0), - lblDetectorId(0), - lblDetectorSerial(0), - lblDetectorFirmware(0), - lblDetectorSoftware(0), - lblModuleId(0), - lblModuleFirmware(0), - lblModuleSerial(0){ - setupUi(this); - SetupWidgetWindow(); - Initialization(); +qTabDebugging::~qTabDebugging() { + delete myDet; } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabDebugging::SetupWidgetWindow() { + blue = new QPalette(); + blue->setColor(QPalette::Active, QPalette::WindowText, Qt::darkBlue); -qTabDebugging::~qTabDebugging(){ - delete myDet; - if(det) delete det; + // Detector Type + detType = myDet->getDetectorTypeAsEnum(); + + // rename label and disable tests + if (detType == slsDetectorDefs::EIGER) { + lblDetector->setText("Half Module:"); + chkDetectorFirmware->setEnabled(false); + chkDetectorBus->setEnabled(false); + btnTest->setEnabled(false); + } + + //add detectors + for (int i = 0; i < myDet->getNumberOfDetectors(); ++i) { + comboDetector->addItem(QString(myDet->getHostname(i).c_str())); + } + + UpdateStatus(); + + qDefs::checkErrorMessage(myDet, "qTabDebugging::SetupWidgetWindow"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabDebugging::Initialization() { - -void qTabDebugging::SetupWidgetWindow(){ - - blue = new QPalette(); - blue->setColor(QPalette::Active,QPalette::WindowText,Qt::darkBlue); - - - // Detector Type - detType=myDet->getDetectorsType(); - ///change module label - switch(detType){ - case slsDetectorDefs::EIGER: - lblDetector->setText("Half Module:"); - chkDetectorFirmware->setText("Half Module Firmware:"); - chkDetectorSoftware->setText("Half Module Software:"); - chkDetectorMemory->setText("Half Module Memory:"); - chkDetectorBus->setText("Half Module Bus:"); - lblModule->hide(); - comboModule->hide(); - chkModuleFirmware->hide(); - chkChip->setEnabled(false); - chkModuleFirmware->setEnabled(false); - break; - case slsDetectorDefs::JUNGFRAU: - case slsDetectorDefs::JUNGFRAUCTB: - case slsDetectorDefs::PROPIX: - case slsDetectorDefs::GOTTHARD: - lblDetector->setText("Module:"); - chkDetectorFirmware->setText("Module Firmware:"); - chkDetectorSoftware->setText("Module Software:"); - chkDetectorMemory->setText("Module Memory:"); - chkDetectorBus->setText("Module Bus:"); - lblModule->hide(); - comboModule->hide(); - chkModuleFirmware->hide(); - chkChip->setEnabled(false); - chkModuleFirmware->setEnabled(false); - break; - case slsDetectorDefs::MOENCH: - lblDetector->setText("Module:"); - chkDetectorFirmware->setText("Module Firmware:"); - chkDetectorSoftware->setText("Module Software:"); - chkDetectorMemory->setText("Module Memory:"); - chkDetectorBus->setText("Module Bus:"); - lblModule->hide(); - comboModule->hide(); - chkModuleFirmware->hide(); - chkChip->setEnabled(false); - chkModuleFirmware->setEnabled(false); - break; - case slsDetectorDefs::MYTHEN: - break; - default: - //leave everything as it is(mythen is default) - break; - } - - - //add detectors - for(int i=0;igetNumberOfDetectors();i++){ - comboDetector->addItem(QString(myDet->getHostname(i).c_str())); - } - - - //add modules and status for current detector - if(detType==slsDetectorDefs::MYTHEN) UpdateModuleList(); - UpdateStatus(); - - qDefs::checkErrorMessage(myDet,"qTabDebugging::SetupWidgetWindow"); -} - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDebugging::Initialization(){ - if(detType==slsDetectorDefs::MYTHEN) - connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(UpdateModuleList())); - - connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(UpdateStatus())); - connect(btnGetInfo, SIGNAL(clicked()), this, SLOT(GetInfo())); - connect(btnTest, SIGNAL(clicked()), this, SLOT(TestDetector())); + connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(UpdateStatus())); + connect(btnGetInfo, SIGNAL(clicked()), this, SLOT(GetInfo())); + if (btnTest ->isEnabled()) + connect(btnTest, SIGNAL(clicked()), this, SLOT(TestDetector())); } +void qTabDebugging::UpdateStatus() { + FILE_LOG(logDEBUG) << "Getting Status"; -//------------------------------------------------------------------------------------------------------------------------------------------------- + auto moduleId = comboDetector->currentIndex(); + int detStatus = (int)myDet->getRunStatus(moduleId); + std::string status = slsDetectorDefs::runStatusType(slsDetectorDefs::runStatus(detStatus)); + lblStatus->setText(QString(status.c_str()).toUpper()); - -void qTabDebugging::UpdateModuleList(){ -#ifdef VERBOSE - cout << "Getting Module List" << endl; -#endif - det = myDet->getSlsDetector(comboDetector->currentIndex()); - qDefs::checkErrorMessage(myDet,"qTabDebugging::UpdateModuleList"); - //deletes all modules except "all modules" - for(int i=0;icount()-1;i++) - comboModule->removeItem(i); - for(int i=0;igetNMods();i++){ - comboModule->addItem(QString("Module %1").arg(i)); - } - - qDefs::checkErrorMessage(det,"qTabDebugging::UpdateModuleList"); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabDebugging::UpdateStatus"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabDebugging::GetInfo() { + FILE_LOG(logDEBUG) << "Getting Readout Info"; + + //window + QFrame *popup1 = new QFrame(this, Qt::Popup | Qt::SubWindow); + QList items; + + //layout + QGridLayout *layout = new QGridLayout(popup1); + //treewidget + treeDet = new QTreeWidget(popup1); + layout->addWidget(treeDet, 0, 0); + //display the details + QFrame *dispFrame = new QFrame(popup1); + QGridLayout *formLayout = new QGridLayout(dispFrame); + // hostname + lblDetectorId = new QLabel(""); + lblDetectorId->setPalette(*blue); + // firmware version + lblDetectorFirmware = new QLabel(""); + lblDetectorFirmware->setPalette(*blue); + // software version + lblDetectorSoftware = new QLabel(""); + lblDetectorSoftware->setPalette(*blue); + //to make sure the size is constant + lblDetectorFirmware->setFixedWidth(100); + layout->addWidget(dispFrame, 0, 1); + + QString detName = QString(myDet->getDetectorTypeAsString().c_str()); + + switch (detType) { -void qTabDebugging::UpdateStatus(){ -#ifdef VERBOSE - cout << "Getting Status" << endl; -#endif - det = myDet->getSlsDetector(comboDetector->currentIndex()); - qDefs::checkErrorMessage(myDet,"qTabDebugging::UpdateStatus"); - int detStatus = (int)det->getRunStatus(); - string status = slsDetectorBase::runStatusType(slsDetectorDefs::runStatus(detStatus)); - lblStatus->setText(QString(status.c_str()).toUpper()); + case slsDetectorDefs::EIGER: + //display widget + formLayout->addWidget(new QLabel("Half Module:"), 0, 0); + formLayout->addItem(new QSpacerItem(15, 20, QSizePolicy::Fixed, QSizePolicy::Fixed), 0, 1); + formLayout->addWidget(lblDetectorId, 0, 2); + formLayout->addWidget(new QLabel("Half Module Firmware Version:"), 1, 0); + formLayout->addWidget(lblDetectorFirmware, 1, 2); + formLayout->addWidget(new QLabel("Half Module Software Version:"), 2, 0); + formLayout->addWidget(lblDetectorSoftware, 2, 2); - qDefs::checkErrorMessage(det,"qTabDebugging::UpdateStatus"); + //tree widget + treeDet->setHeaderLabel("Eiger Detector"); + //get num modules + for (int i = 0; i < comboDetector->count() / 2; ++i) + items.append(new QTreeWidgetItem((QTreeWidget *)0, QStringList(QString("Module %1").arg(i)))); + treeDet->insertTopLevelItems(0, items); + //gets det names + for (int i = 0; i < comboDetector->count(); ++i) { + QList childItems; + childItems.append(new QTreeWidgetItem((QTreeWidget *)0, QStringList(QString("Half Module (%1)").arg(comboDetector->itemText(i))))); + treeDet->topLevelItem(i * 2)->insertChildren(0, childItems); + } + break; + + default: + + //display widget + formLayout->addWidget(new QLabel("Module:"), 0, 0); + formLayout->addItem(new QSpacerItem(15, 20, QSizePolicy::Fixed, QSizePolicy::Fixed), 0, 1); + formLayout->addWidget(lblDetectorId, 0, 2); + formLayout->addWidget(new QLabel("Module Firmware Version:"), 1, 0); + formLayout->addWidget(lblDetectorFirmware, 1, 2); + formLayout->addWidget(new QLabel("Module Software Version:"), 2, 0); + formLayout->addWidget(lblDetectorSoftware, 2, 2); + //tree widget + treeDet->setHeaderLabel(QString(detName + " Detector")); + //gets det names + for (int i = 0; i < comboDetector->count(); ++i) + items.append(new QTreeWidgetItem((QTreeWidget *)0, QStringList(QString("Module (%1)").arg(comboDetector->itemText(i))))); + treeDet->insertTopLevelItems(0, items); + + break; + } + + //show and center widget + int x = ((parentWidget()->width()) - (popup1->frameGeometry().width())) / 2; + int y = ((parentWidget()->height()) - (popup1->frameGeometry().height())) / 2; + QDesktopWidget *desktop = QApplication::desktop(); + int screen = desktop->screenNumber(this); + popup1->setWindowModality(Qt::WindowModal); + popup1->move((desktop->screenGeometry(screen).x()) + x, (desktop->screenGeometry(screen).y()) + y); + popup1->show(); + + //put the first parameters + SetParameters(treeDet->topLevelItem(0)); + + //initializations + connect(treeDet, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(SetParameters(QTreeWidgetItem *))); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabDebugging::SetParameters(QTreeWidgetItem *item) { + char value[200]; + int i; + + auto moduleId = comboDetector->currentIndex(); + switch (detType) { -void qTabDebugging::GetInfo(){ -#ifdef VERBOSE - cout << "Getting Info" << endl; -#endif - //window - QFrame* popup1 = new QFrame(this, Qt::Popup | Qt::SubWindow ); - QList items; + case slsDetectorDefs::EIGER: + //only if half module clicked + if (item->text(0).contains("Half Module")) { + //find index + for (i = 0; i < comboDetector->count(); ++i) + if (item == treeDet->topLevelItem(i)) + break; + sprintf(value, "%lx", (long long unsigned int)myDet->getId(slsDetectorDefs::DETECTOR_FIRMWARE_VERSION, moduleId)); + lblDetectorFirmware->setText(QString(value)); + sprintf(value, "%lx", (long long unsigned int)myDet->getId(slsDetectorDefs::DETECTOR_SOFTWARE_VERSION, moduleId)); + lblDetectorSoftware->setText(QString(value)); + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabDebugging::SetParameters"); + } + break; - //layout - QGridLayout *layout = new QGridLayout(popup1); - //treewidget - treeDet = new QTreeWidget(popup1); - layout->addWidget(treeDet,0,0); - //display the details - dispFrame = new QFrame(popup1); - QGridLayout *formLayout = new QGridLayout(dispFrame); - lblDetectorId = new QLabel(""); lblDetectorId->setPalette(*blue); - lblDetectorSerial = new QLabel(""); lblDetectorSerial->setPalette(*blue); - lblDetectorFirmware = new QLabel(""); lblDetectorFirmware->setPalette(*blue); - lblDetectorSoftware = new QLabel(""); lblDetectorSoftware->setPalette(*blue); - lblModuleId = new QLabel(""); lblModuleId->setPalette(*blue); - lblModuleSerial = new QLabel(""); lblModuleSerial->setPalette(*blue); - lblModuleFirmware = new QLabel(""); lblModuleFirmware->setPalette(*blue); - //to make sure the size is constant - lblDetectorFirmware->setFixedWidth(100); - layout->addWidget(dispFrame,0,1); + default: + //find index + for (i = 0; i < comboDetector->count(); ++i) + if (item == treeDet->topLevelItem(i)) + break; - switch(detType){ + sprintf(value, "%lx", (long long unsigned int)myDet->getId(slsDetectorDefs::DETECTOR_FIRMWARE_VERSION, moduleId)); + lblDetectorFirmware->setText(QString(value)); + sprintf(value, "%lx", (long long unsigned int)myDet->getId(slsDetectorDefs::DETECTOR_SOFTWARE_VERSION, moduleId)); + lblDetectorSoftware->setText(QString(value)); - case slsDetectorDefs::MYTHEN: - //display widget - formLayout->addWidget(new QLabel("Readout:"),0,0); - formLayout->addItem(new QSpacerItem(15,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,1); - formLayout->addWidget(lblDetectorId,0,2); - formLayout->addWidget(new QLabel("Readout MAC Address:"),1,0); - formLayout->addWidget(lblDetectorSerial,1,2); - formLayout->addWidget(new QLabel("Readout Firmware Version:"),2,0); - formLayout->addWidget(lblDetectorFirmware,2,2); - formLayout->addWidget(new QLabel("Readout Software Version:"),3,0); - formLayout->addWidget(lblDetectorSoftware,3,2); - formLayout->addWidget(new QLabel("Module:"),4,0); - formLayout->addWidget(lblModuleId,4,2); - formLayout->addWidget(new QLabel("Module Serial Number:"),5,0); - formLayout->addWidget(lblModuleSerial,5,2); - formLayout->addWidget(new QLabel("Module Firmware Version:"),6,0); - formLayout->addWidget(lblModuleFirmware,6,2); - - - //tree widget - treeDet->setHeaderLabel("Mythen Detector"); - //gets det names - for (int i=0;icount();i++) - items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Readout (%1)").arg(comboDetector->itemText(i))))); - treeDet->insertTopLevelItems(0, items); - //gets module names - for (int i=0;icount();i++){ - QList childItems; - det = myDet->getSlsDetector(i); - qDefs::checkErrorMessage(myDet,"qTabDebugging::GetInfo"); - for(int j=0;jgetNMods();j++) - childItems.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Module %1").arg(j)))); - treeDet->topLevelItem(i)->insertChildren(0,childItems); - qDefs::checkErrorMessage(det,"qTabDebugging::GetInfo"); - } - - break; - - - - - case slsDetectorDefs::EIGER: - //display widget - formLayout->addWidget(new QLabel("Half Module:"),0,0); - formLayout->addItem(new QSpacerItem(15,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,1); - formLayout->addWidget(lblDetectorId,0,2); - formLayout->addWidget(new QLabel("Half Module MAC Address:"),1,0); - formLayout->addWidget(lblDetectorSerial,1,2); - formLayout->addWidget(new QLabel("Half Module Firmware Version:"),2,0); - formLayout->addWidget(lblDetectorFirmware,2,2); - formLayout->addWidget(new QLabel("Half Module Software Version:"),3,0); - formLayout->addWidget(lblDetectorSoftware,3,2); - - //tree widget - treeDet->setHeaderLabel("Eiger Detector"); - //get num modules - for (int i=0;icount()/2;i++) - items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Module %1").arg(i)))); - treeDet->insertTopLevelItems(0, items); - //gets det names - for (int i=0;icount();i++){ - QList childItems; - childItems.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Half Module (%1)").arg(comboDetector->itemText(i))))); - treeDet->topLevelItem(i*2)->insertChildren(0,childItems); - } - break; - - - - case slsDetectorDefs::MOENCH: - - //display widget - formLayout->addWidget(new QLabel("Module:"),0,0); - formLayout->addItem(new QSpacerItem(15,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,1); - formLayout->addWidget(lblDetectorId,0,2); - formLayout->addWidget(new QLabel("Module MAC Address:"),1,0); - formLayout->addWidget(lblDetectorSerial,1,2); - formLayout->addWidget(new QLabel("Module Firmware Version:"),2,0); - formLayout->addWidget(lblDetectorFirmware,2,2); - formLayout->addWidget(new QLabel("Module Software Version:"),3,0); - formLayout->addWidget(lblDetectorSoftware,3,2); - //tree widget - treeDet->setHeaderLabel("Moench Detector"); - //gets det names - for (int i=0;icount();i++) - items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Module (%1)").arg(comboDetector->itemText(i))))); - treeDet->insertTopLevelItems(0, items); - - break; - - - - case slsDetectorDefs::PROPIX: - - //display widget - formLayout->addWidget(new QLabel("Module:"),0,0); - formLayout->addItem(new QSpacerItem(15,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,1); - formLayout->addWidget(lblDetectorId,0,2); - formLayout->addWidget(new QLabel("Module MAC Address:"),1,0); - formLayout->addWidget(lblDetectorSerial,1,2); - formLayout->addWidget(new QLabel("Module Firmware Version:"),2,0); - formLayout->addWidget(lblDetectorFirmware,2,2); - formLayout->addWidget(new QLabel("Module Software Version:"),3,0); - formLayout->addWidget(lblDetectorSoftware,3,2); - //tree widget - treeDet->setHeaderLabel("Propix Detector"); - //gets det names - for (int i=0;icount();i++) - items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Module (%1)").arg(comboDetector->itemText(i))))); - treeDet->insertTopLevelItems(0, items); - - break; - - - - case slsDetectorDefs::GOTTHARD: - - //display widget - formLayout->addWidget(new QLabel("Module:"),0,0); - formLayout->addItem(new QSpacerItem(15,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,1); - formLayout->addWidget(lblDetectorId,0,2); - formLayout->addWidget(new QLabel("Module MAC Address:"),1,0); - formLayout->addWidget(lblDetectorSerial,1,2); - formLayout->addWidget(new QLabel("Module Firmware Version:"),2,0); - formLayout->addWidget(lblDetectorFirmware,2,2); - formLayout->addWidget(new QLabel("Module Software Version:"),3,0); - formLayout->addWidget(lblDetectorSoftware,3,2); - //tree widget - treeDet->setHeaderLabel("Gotthard Detector"); - //gets det names - for (int i=0;icount();i++) - items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Module (%1)").arg(comboDetector->itemText(i))))); - treeDet->insertTopLevelItems(0, items); - - break; - - - case slsDetectorDefs::JUNGFRAU: - case slsDetectorDefs::JUNGFRAUCTB: - //display widget - formLayout->addWidget(new QLabel("Module:"),0,0); - formLayout->addItem(new QSpacerItem(15,20,QSizePolicy::Fixed,QSizePolicy::Fixed),0,1); - formLayout->addWidget(lblDetectorId,0,2); - formLayout->addWidget(new QLabel("Module MAC Address:"),1,0); - formLayout->addWidget(lblDetectorSerial,1,2); - formLayout->addWidget(new QLabel("Module Firmware Version:"),2,0); - formLayout->addWidget(lblDetectorFirmware,2,2); - formLayout->addWidget(new QLabel("Module Software Version:"),3,0); - formLayout->addWidget(lblDetectorSoftware,3,2); - //tree widget - if (detType == slsDetectorDefs::JUNGFRAU) - treeDet->setHeaderLabel("JungFrau Detector"); - else - treeDet->setHeaderLabel("JungFrauCTB Detector"); - //gets det names - for (int i=0;icount();i++) - items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString("Module (%1)").arg(comboDetector->itemText(i))))); - treeDet->insertTopLevelItems(0, items); - - break; - - - default: - break; - } - - //show and center widget - - int x = ((parentWidget()->width()) - (popup1->frameGeometry().width())) / 2; - int y = ((parentWidget()->height()) - (popup1->frameGeometry().height())) / 2; - QDesktopWidget *desktop = QApplication::desktop(); - int screen = desktop->screenNumber(this); - popup1->setWindowModality(Qt::WindowModal); - popup1->move( (desktop->screenGeometry(screen).x())+x, (desktop->screenGeometry(screen).y())+y ); - popup1->show(); - - //put the first parameters - SetParameters(treeDet->topLevelItem(0)); - - //initializations - connect(treeDet, SIGNAL(itemDoubleClicked(QTreeWidgetItem *,int)) , this, SLOT(SetParameters(QTreeWidgetItem *))); - -} -//------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabDebugging::SetParameters(QTreeWidgetItem *item){ - char value[200]; - int i; - - - switch(detType){ - - case slsDetectorDefs::MYTHEN: - if(item->text(0).contains("Readout")){ - //find index - for(i=0;icount();i++) - if(item== treeDet->topLevelItem(i)) - break; - - det = myDet->getSlsDetector(i); - qDefs::checkErrorMessage(myDet,"qTabDebugging::SetParameters"); - lblDetectorId->setText(comboDetector->itemText(i)); - sprintf(value,"%llx",(long long unsigned int)det->getId(slsDetectorDefs::DETECTOR_SERIAL_NUMBER)); - lblDetectorSerial->setText(QString(value)); - sprintf(value,"%llx",(long long unsigned int)det->getId(slsDetectorDefs::DETECTOR_FIRMWARE_VERSION)); - lblDetectorFirmware ->setText(QString(value)); - sprintf(value,"%llx",(long long unsigned int)det->getId(slsDetectorDefs::DETECTOR_SOFTWARE_VERSION)); - lblDetectorSoftware->setText(QString(value)); - qDefs::checkErrorMessage(det,"qTabDebugging::SetParameters"); - - lblModuleId->setText(""); - lblModuleSerial->setText(""); - lblModuleFirmware->setText(""); - }else{ - //find index - for(i=0;icount();i++) - if(item->parent() == treeDet->topLevelItem(i)) - break; - int im = item->parent()->indexOfChild(item); - - det = myDet->getSlsDetector(i); - qDefs::checkErrorMessage(myDet,"qTabDebugging::SetParameters"); - lblDetectorId->setText(comboDetector->itemText(i)); - sprintf(value,"%llx",(long long unsigned int)det->getId(slsDetectorDefs::DETECTOR_SERIAL_NUMBER)); - lblDetectorSerial->setText(QString(value)); - sprintf(value,"%llx",(long long unsigned int)det->getId(slsDetectorDefs::DETECTOR_FIRMWARE_VERSION)); - lblDetectorFirmware ->setText(QString(value)); - sprintf(value,"%llx",(long long unsigned int)det->getId(slsDetectorDefs::DETECTOR_SOFTWARE_VERSION)); - lblDetectorSoftware->setText(QString(value)); - - lblModuleId->setText(QString("%1").arg(im)); - sprintf(value,"%llx",(long long unsigned int)det->getId(slsDetectorDefs::MODULE_SERIAL_NUMBER,im)); - lblModuleSerial->setText(QString(value)); - sprintf(value,"%llx",(long long unsigned int)det->getId(slsDetectorDefs::MODULE_FIRMWARE_VERSION,im)); - lblModuleFirmware->setText(QString(value)); - - qDefs::checkErrorMessage(det,"qTabDebugging::SetParameters"); - } - break; - - - - - - case slsDetectorDefs::EIGER: - //only if half module clicked - if(item->text(0).contains("Half Module")){ - //find index - for(i=0;icount();i++) - if(item== treeDet->topLevelItem(i)) - break; - - det = myDet->getSlsDetector(i); - qDefs::checkErrorMessage(myDet,"qTabDebugging::SetParameters"); - lblDetectorId->setText(comboDetector->itemText(i)); - sprintf(value,"%llx",(long long unsigned int)det->getId(slsDetectorDefs::DETECTOR_SERIAL_NUMBER)); - lblDetectorSerial->setText(QString(value)); - sprintf(value,"%llx",(long long unsigned int)det->getId(slsDetectorDefs::DETECTOR_FIRMWARE_VERSION)); - lblDetectorFirmware ->setText(QString(value)); - sprintf(value,"%llx",(long long unsigned int)det->getId(slsDetectorDefs::DETECTOR_SOFTWARE_VERSION)); - lblDetectorSoftware->setText(QString(value)); - - qDefs::checkErrorMessage(det,"qTabDebugging::SetParameters"); - } - break; - - - case slsDetectorDefs::JUNGFRAU: - case slsDetectorDefs::JUNGFRAUCTB: - case slsDetectorDefs::PROPIX: - case slsDetectorDefs::MOENCH: - case slsDetectorDefs::GOTTHARD: - //find index - for(i=0;icount();i++) - if(item== treeDet->topLevelItem(i)) - break; - - det = myDet->getSlsDetector(i); - qDefs::checkErrorMessage(myDet,"qTabDebugging::SetParameters"); - lblDetectorId->setText(comboDetector->itemText(i)); - sprintf(value,"%llx",(long long unsigned int)det->getId(slsDetectorDefs::DETECTOR_SERIAL_NUMBER)); - lblDetectorSerial->setText(QString(value)); - sprintf(value,"%llx",(long long unsigned int)det->getId(slsDetectorDefs::DETECTOR_FIRMWARE_VERSION)); - lblDetectorFirmware ->setText(QString(value)); - sprintf(value,"%llx",(long long unsigned int)det->getId(slsDetectorDefs::DETECTOR_SOFTWARE_VERSION)); - lblDetectorSoftware->setText(QString(value)); - - qDefs::checkErrorMessage(det,"qTabDebugging::SetParameters"); - break; - - - - - default: - break; - } + qDefs::checkErrorMessage(myDet, comboDetector->currentIndex(), "qTabDebugging::SetParameters"); + break; + } } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabDebugging::TestDetector() { + FILE_LOG(logINFO) << "Testing Readout"; -void qTabDebugging::TestDetector(){ -#ifdef VERBOSE - cout << "Testing" << endl; -#endif + int retval = slsDetectorDefs::FAIL; + QString message; + QString Detector = "Detector"; - int retval=slsDetectorDefs::FAIL; - QString message; - QString Detector = "Detector"; + //main messagebox title + switch (detType) { + case slsDetectorDefs::EIGER: + Detector = "Half Module"; + break; + default: + Detector = "Module"; + break; + } - //main messagebox title - switch(detType){ - case slsDetectorDefs::MYTHEN: - message = QString("Test Results for %1 and %2:

").arg(comboDetector->currentText(),comboModule->currentText()); - break; - case slsDetectorDefs::EIGER: Detector = "Half Module"; break; - case slsDetectorDefs::JUNGFRAU: - case slsDetectorDefs::JUNGFRAUCTB: - case slsDetectorDefs::MOENCH: - case slsDetectorDefs::PROPIX: - case slsDetectorDefs::GOTTHARD: Detector = "Module"; break; - default: break; - } + // construct message + message = QString("Test Results for %1:

").arg(comboDetector->currentText()); + auto moduleId = comboDetector->currentIndex(); - if(detType==slsDetectorDefs::MYTHEN) - message = QString("Test Results for %1 and %2:

").arg(comboDetector->currentText(),comboModule->currentText()); - else message = QString("Test Results for %1:

").arg(comboDetector->currentText()); + //detector firmware + if (chkDetectorFirmware->isChecked()) { + retval = myDet->digitalTest(slsDetectorDefs::DETECTOR_FIRMWARE_TEST, moduleId); + if (retval == slsDetectorDefs::FAIL) { + message.append(QString("%1 Firmware: FAIL
").arg(Detector)); + FILE_LOG(logERROR) << "Firmware fail"; + } + else + message.append(QString("%1 Firmware: %2
").arg(Detector, QString::number(retval))); + FILE_LOG(logINFO) << "Detector Firmware Test: " << retval; + } - //get sls det object - det = myDet->getSlsDetector(comboDetector->currentIndex()); - qDefs::checkErrorMessage(myDet,"qTabDebugging::TestDetector"); + //detector CPU-FPGA bus + if (chkDetectorBus->isChecked()) { + retval = myDet->digitalTest(slsDetectorDefs::DETECTOR_BUS_TEST, moduleId); + if (retval == slsDetectorDefs::FAIL) { + message.append(QString("%1 Bus:     FAIL
").arg(Detector)); + FILE_LOG(logERROR) << "Bus Test fail"; + } else + message.append(QString("%1 Bus:     %2
").arg(Detector, QString::number(retval))); + FILE_LOG(logINFO) << "Detector Bus Test: " << retval; + } - //detector firmware - if(chkDetectorFirmware->isChecked()){ - retval = det->digitalTest(slsDetectorDefs::DETECTOR_FIRMWARE_TEST); - if(retval== slsDetectorDefs::FAIL) message.append(QString("%1 Firmware: FAIL
").arg(Detector)); - else message.append(QString("%1 Firmware: %2
").arg(Detector,QString::number(retval))); -#ifdef VERBOSE - cout<<"Detector Firmware: "<isChecked()){ - retval = det->digitalTest(slsDetectorDefs::DETECTOR_SOFTWARE_TEST); - if(retval== slsDetectorDefs::FAIL) message.append(QString("%1 Software: FAIL
").arg(Detector)); - else message.append(QString("%1 Software: %2
").arg(Detector,QString::number(retval))); -#ifdef VERBOSE - cout<<"Detector Software: "<isChecked()){ - retval = det->digitalTest(slsDetectorDefs::DETECTOR_BUS_TEST); - if(retval== slsDetectorDefs::FAIL) message.append(QString("%1 Bus:     FAIL
").arg(Detector)); - else message.append(QString("%1 Bus:     %2
").arg(Detector,QString::number(retval))); -#ifdef VERBOSE - cout<<"Detector Bus: "<isChecked()){ - retval = det->digitalTest(slsDetectorDefs::DETECTOR_MEMORY_TEST); - if(retval== slsDetectorDefs::FAIL) message.append(QString("%1 Memory:  FAIL
").arg(Detector)); - else message.append(QString("%1 Memory:  %2
").arg(Detector,QString::number(retval))); -#ifdef VERBOSE - cout<<"Detector Memory: "<isChecked()){ - retval = det->digitalTest(slsDetectorDefs::CHIP_TEST,comboModule->currentIndex()); - if(retval== slsDetectorDefs::FAIL) message.append("
Chip: FAIL
"); - else message.append(QString("Chip: %1
").arg(retval)); -#ifdef VERBOSE - cout<<"Chip: "<isChecked()){ - retval = det->digitalTest(slsDetectorDefs::MODULE_FIRMWARE_TEST,comboModule->currentIndex()); - if(retval== slsDetectorDefs::FAIL) message.append("Module Firmware: FAIL
"); - else message.append(QString("Module Firmware: %1
").arg(retval)); -#ifdef VERBOSE - cout<<"Module Firmware: "<currentIndex(), "qTabDebugging::TestDetector"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDebugging::Refresh(){ -#ifdef VERBOSE - cout << endl << "**Updating Debugging Tab" << endl; -#endif - UpdateStatus(); -#ifdef VERBOSE - cout << "**Updated Debugging Tab" << endl << endl; -#endif +void qTabDebugging::Refresh() { + FILE_LOG(logDEBUG) << "\n**Updating Debugging Tab"; + UpdateStatus(); + FILE_LOG(logDEBUG) << "**Updated Debugging Tab"; } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - diff --git a/slsDetectorGui/src/qTabDeveloper.cpp b/slsDetectorGui/src/qTabDeveloper.cpp old mode 100644 new mode 100755 index 8f60f659b..291625c36 --- a/slsDetectorGui/src/qTabDeveloper.cpp +++ b/slsDetectorGui/src/qTabDeveloper.cpp @@ -1,90 +1,58 @@ -/* - * qTabDeveloper.cpp - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ #include "qTabDeveloper.h" #include "qDetectorMain.h" -//Project Class Headers -#include "slsDetector.h" + #include "multiSlsDetector.h" -//Qt Include Headers + +#include #include #include -#include -//C++ Include Headers -#include -using namespace std; - -//------------------------------------------------------------------------------------------------------------------------------------------------- - -int qTabDeveloper::NUM_DAC_WIDGETS(0); -int qTabDeveloper::NUM_ADC_WIDGETS(0); - -//------------------------------------------------------------------------------------------------------------------------------------------------- +#include -qTabDeveloper::qTabDeveloper(qDetectorMain *parent,multiSlsDetector*& detector): - thisParent(parent), - myDet(detector), - det(0), - boxDacs(0), - boxAdcs(0), - lblHV(0), - comboHV(0), - adcTimer(0), - dacLayout(0){ - for(int i=0;i<20;i++) { - lblDacs[i]=0; - lblAdcs[i]=0; - spinDacs[i]=0; - spinAdcs[i]=0; - lblDacsmV[i]=0; - } +qTabDeveloper::qTabDeveloper(QWidget *parent, multiSlsDetector *detector) : QWidget(parent), + myDet(detector), + detType(slsDetectorDefs::GENERIC), + numDACWidgets(0), + numADCWidgets(0), + boxDacs(0), + boxAdcs(0), + lblHV(0), + comboHV(0), + dacLayout(0), + comboDetector(0) { + + + lblDacs.clear(); + lblAdcs.clear(); + spinDacs.clear(); + spinAdcs.clear(); + lblDacsmV.clear(); + SetupWidgetWindow(); Initialization(); + FILE_LOG(logDEBUG) << "Developer ready"; } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - qTabDeveloper::~qTabDeveloper() { - delete myDet; - if(det) delete det; - if(thisParent) delete thisParent; + if (myDet) + delete myDet; } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - void qTabDeveloper::SetupWidgetWindow() { //Detector Type - detType=myDet->getDetectorsType(); + detType = myDet->getDetectorTypeAsEnum(); //palette red = QPalette(); - red.setColor(QPalette::Active,QPalette::WindowText,Qt::red); - + red.setColor(QPalette::Active, QPalette::WindowText, Qt::red); //the number of dacs and adcs - switch(detType){ - case slsDetectorDefs::MYTHEN: - NUM_DAC_WIDGETS = 6; - NUM_ADC_WIDGETS = 0; - dacNames.push_back("v Trimbit:"); - dacNames.push_back("v Threshold:"); - dacNames.push_back("v Shaper1:"); - dacNames.push_back("v Shaper2:"); - dacNames.push_back("v Calibration:"); - dacNames.push_back("v Preamp:"); - break; + switch (detType) { case slsDetectorDefs::EIGER: - NUM_DAC_WIDGETS = 17; - NUM_ADC_WIDGETS = 6; + numDACWidgets = 17; + numADCWidgets = 6; dacNames.push_back("v SvP:"); dacNames.push_back("v SvN"); @@ -112,10 +80,10 @@ void qTabDeveloper::SetupWidgetWindow() { adcNames.push_back("Temperature FPGA:"); break; - case slsDetectorDefs::PROPIX: + case slsDetectorDefs::GOTTHARD: - NUM_DAC_WIDGETS = 8; - NUM_ADC_WIDGETS = 2; + numDACWidgets = 8; + numADCWidgets = 2; dacNames.push_back("v Reference:"); dacNames.push_back("v Cascode n:"); dacNames.push_back("v Cascode p:"); @@ -129,28 +97,10 @@ void qTabDeveloper::SetupWidgetWindow() { adcNames.push_back("Temperature FPGA:"); break; - case slsDetectorDefs::MOENCH: - NUM_DAC_WIDGETS = 8; - NUM_ADC_WIDGETS = 2; - dacNames.push_back("v Dac 0:"); - dacNames.push_back("v Dac 1:"); - dacNames.push_back("v Dac 2:"); - dacNames.push_back("v Dac 3:"); - dacNames.push_back("v Dac 4:"); - dacNames.push_back("v Dac 5:"); - dacNames.push_back("v Dac 6:"); - dacNames.push_back("i Dac 7:"); - - adcNames.push_back("Temperature ADC:"); - adcNames.push_back("Temperature FPGA:"); - - break; - case slsDetectorDefs::JUNGFRAU: - case slsDetectorDefs::JUNGFRAUCTB: - NUM_DAC_WIDGETS = 8; - NUM_ADC_WIDGETS = 1; + numDACWidgets = 8; + numADCWidgets = 1; dacNames.push_back("v vb comp:"); dacNames.push_back("v vdd prot:"); dacNames.push_back("v vin com:"); @@ -164,51 +114,154 @@ void qTabDeveloper::SetupWidgetWindow() { break; + case slsDetectorDefs::MOENCH: + + numDACWidgets = 8; + numADCWidgets = 0; + dacNames.push_back("v Dac 0:"); + dacNames.push_back("v Dac 1:"); + dacNames.push_back("v Dac 2:"); + dacNames.push_back("v Dac 3:"); + dacNames.push_back("v Dac 4:"); + dacNames.push_back("v Dac 5:"); + dacNames.push_back("v Dac 6:"); + dacNames.push_back("i Dac 7:"); + + break; + default: - cout << "ERROR: Unknown detector type: " + myDet->slsDetectorBase::getDetectorType(detType) << endl; - qDefs::Message(qDefs::CRITICAL,string("Unknown detector type:")+myDet->slsDetectorBase::getDetectorType(detType),"qTabDeveloper::SetupWidgetWindow"); + FILE_LOG(logERROR) << "Unknown detector type: " + myDet->getDetectorTypeAsString(); + qDefs::Message(qDefs::CRITICAL, std::string("Unknown detector type:") + myDet->getDetectorTypeAsString(), "qTabDeveloper::SetupWidgetWindow"); exit(-1); break; } - //layout setFixedWidth(765); - setFixedHeight(20+50+(NUM_DAC_WIDGETS/2)*35); - //setHeight(340); + setFixedHeight(20 + 50 + (numDACWidgets / 2) * 35); - scroll = new QScrollArea; - //scroll->setFrameShape(QFrame::NoFrame); + QScrollArea* scroll = new QScrollArea; scroll->setWidget(this); scroll->setWidgetResizable(true); - layout = new QGridLayout(scroll); - layout->setContentsMargins(20,10,10,5); + QGridLayout *layout = new QGridLayout(scroll); + layout->setContentsMargins(20, 10, 10, 5); setLayout(layout); //readout comboDetector = new QComboBox(this); - //comboDetector->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); comboDetector->addItem("All"); //add detectors - for(int i=1;igetNumberOfDetectors()+1;i++) - comboDetector->addItem(QString(myDet->getHostname(i-1).c_str())); + for (int i = 1; i < myDet->getNumberOfDetectors() + 1; ++i) + comboDetector->addItem(QString(myDet->getHostname(i - 1).c_str())); comboDetector->setCurrentIndex(0); - //dacs - boxDacs = new QGroupBox("Dacs",this); - boxDacs->setFixedHeight(25+(NUM_DAC_WIDGETS/2)*35); CreateDACWidgets(); - //HV for gotthard - if ((detType==slsDetectorDefs::GOTTHARD) || - (detType==slsDetectorDefs::PROPIX) || - (detType==slsDetectorDefs::MOENCH)){ - boxDacs->setFixedHeight(boxDacs->height()+35); + // hv for gotthard, jungfrau, moench + if ((detType == slsDetectorDefs::GOTTHARD) || + (detType == slsDetectorDefs::JUNGFRAU) || + (detType == slsDetectorDefs::MOENCH)) { + CreateHVWidget(); - lblHV = new QLabel("High Voltage",boxDacs); - comboHV = new QComboBox(boxDacs); + } + layout->addWidget(comboDetector, 0, 0); + layout->addWidget(boxDacs, 1, 0); + + //adcs + if (numADCWidgets) { + CreateADCWidgets(); + layout->addWidget(boxAdcs, 2, 0); + } + + qDefs::checkErrorMessage(myDet, "qTabDeveloper::SetupWidgetWindow"); +} + + +void qTabDeveloper::Initialization() { + connect(comboDetector, SIGNAL(currentIndexChanged(int)), this, SLOT(Refresh())); + + // dacs + for (int i = 0; i < numDACWidgets; ++i) + connect(spinDacs[i], SIGNAL(editingFinished(int)), this, SLOT(SetDacValues(int))); + + // hv + if (comboHV) { + connect(comboHV, SIGNAL(currentIndexChanged(int)), this, SLOT(SetHighVoltage())); + } else { + connect(spinHV, SIGNAL(valueChanged(int)), this, SLOT(SetHighVoltage())); + } +} + + +void qTabDeveloper::CreateDACWidgets() { + boxDacs = new QGroupBox("Dacs", this); + boxDacs->setFixedHeight(25 + (numDACWidgets / 2) * 35); + dacLayout = new QGridLayout(boxDacs); + + for (int i = 0; i < numDACWidgets; ++i) { + lblDacs[i] = new QLabel(QString(dacNames[i].c_str()), boxDacs); + spinDacs[i] = new MyDoubleSpinBox(i, boxDacs); + spinDacs[i]->setMinimum(-1); + spinDacs[i]->setMaximum(10000); + lblDacsmV[i] = new QLabel("", boxDacs); + + dacLayout->addWidget(lblDacs[i], (int)(i / 2), ((i % 2) == 0) ? 1 : 5); + dacLayout->addWidget(spinDacs[i], (int)(i / 2), ((i % 2) == 0) ? 2 : 6); + dacLayout->addWidget(lblDacsmV[i], (int)(i / 2), ((i % 2) == 0) ? 3 : 7); + if (!(i % 2)) { + dacLayout->addItem(new QSpacerItem(20, 20, QSizePolicy::Fixed, QSizePolicy::Fixed), (int)(i / 2), 0); + dacLayout->addItem(new QSpacerItem(60, 20, QSizePolicy::Fixed, QSizePolicy::Fixed), (int)(i / 2), 4); + dacLayout->addItem(new QSpacerItem(20, 20, QSizePolicy::Fixed, QSizePolicy::Fixed), (int)(i / 2), 8); + } + } +} + + +void qTabDeveloper::CreateADCWidgets() { + int rows = numADCWidgets / 2; + if (numADCWidgets % 2) + rows++; + setFixedHeight(20 + (50 + (numDACWidgets / 2) * 35) + (50 + rows * 35)); + boxAdcs = new QGroupBox("ADCs", this); + boxAdcs->setFixedHeight(25 + rows * 35); + + QGridLayout *adcLayout = new QGridLayout(boxAdcs); + + for (int i = 0; i < numADCWidgets; ++i) { + lblAdcs[i] = new QLabel(QString(adcNames[i].c_str()), boxAdcs); + spinAdcs[i] = new QLineEdit(boxAdcs); + spinAdcs[i]->setReadOnly(true); + + adcLayout->addWidget(lblAdcs[i], (int)(i / 2), ((i % 2) == 0) ? 1 : 4); + adcLayout->addWidget(spinAdcs[i], (int)(i / 2), ((i % 2) == 0) ? 2 : 5); + if (!(i % 2)) { + adcLayout->addItem(new QSpacerItem(20, 20, QSizePolicy::Fixed, QSizePolicy::Fixed), (int)(i / 2), 0); + adcLayout->addItem(new QSpacerItem(60, 20, QSizePolicy::Fixed, QSizePolicy::Fixed), (int)(i / 2), 3); + adcLayout->addItem(new QSpacerItem(20, 20, QSizePolicy::Fixed, QSizePolicy::Fixed), (int)(i / 2), 6); + } + } + + //to make the adcs at the bottom most + if (detType != slsDetectorDefs::EIGER) { + int diff = 340 - height(); + setFixedHeight(340); + layout->setVerticalSpacing(diff / 2); + } +} + +void qTabDeveloper::CreateHVWidget() { + boxDacs->setFixedHeight(boxDacs->height() + 35); + lblHV = new QLabel("High Voltage", boxDacs); + dacLayout->addWidget(lblHV, (int)(numDACWidgets / 2), 1); + + comboHV = nullptr; + spinHV = nullptr; + + // drop down with specific values + if (detType == slsDetectorDefs::GOTTHARD) { + comboHV = new QComboBox(boxDacs); comboHV->addItem("0"); comboHV->addItem("90"); comboHV->addItem("110"); @@ -217,415 +270,306 @@ void qTabDeveloper::SetupWidgetWindow() { comboHV->addItem("180"); comboHV->addItem("200"); tipHV = "Set high voltage to 0, 90, 110, 120, 150 or 200V."; - lblHV->setToolTip(tipHV); comboHV->setToolTip(tipHV); - dacLayout->addWidget(lblHV,(int)(NUM_DAC_WIDGETS/2),1); - dacLayout->addWidget(comboHV,(int)(NUM_DAC_WIDGETS/2),2); - connect(comboHV, SIGNAL(currentIndexChanged(int)), this, SLOT(SetHighVoltage())); - } - layout->addWidget(comboDetector,0,0); - layout->addWidget(boxDacs,1,0); - - //adcs - if(NUM_ADC_WIDGETS) { - int rows = NUM_ADC_WIDGETS/2; - if (NUM_ADC_WIDGETS%2)rows++; - setFixedHeight(20+(50+(NUM_DAC_WIDGETS/2)*35)+(50+rows*35)); - boxAdcs = new QGroupBox("ADCs",this); - boxAdcs->setFixedHeight(25+rows*35); - layout->addWidget(boxAdcs,2,0); - CreateADCWidgets(); - //to make the adcs at the bottom most - if (detType!=slsDetectorDefs::EIGER) { - int diff = 340-height(); - setFixedHeight(340); - layout->setVerticalSpacing(diff/2); - } - //timer to check adcs - /*adcTimer = new QTimer(this); adc timer disabled, display adcs only when refreshing developer tab */ + dacLayout->addWidget(comboHV, (int)(numDACWidgets / 2), 2); } - qDefs::checkErrorMessage(myDet,"qTabDeveloper::SetupWidgetWindow"); -} - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDeveloper::Initialization(){ - /*if(NUM_ADC_WIDGETS) connect(adcTimer, SIGNAL(timeout()), this, SLOT(RefreshAdcs()));*/ - - for(int i=0;isetMinimum(-1); - spinDacs[i]->setMaximum(10000); - lblDacsmV[i]= new QLabel("",boxDacs); - - - dacLayout->addWidget(lblDacs[i],(int)(i/2),((i%2)==0)?1:5); - dacLayout->addWidget(spinDacs[i],(int)(i/2),((i%2)==0)?2:6); - dacLayout->addWidget(lblDacsmV[i],(int)(i/2),((i%2)==0)?3:7); - if(!(i%2)){ - dacLayout->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed),(int)(i/2),0); - dacLayout->addItem(new QSpacerItem(60,20,QSizePolicy::Fixed,QSizePolicy::Fixed),(int)(i/2),4); - dacLayout->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed),(int)(i/2),8); - } + spinDacs[i]->setMaximum(200); + tipHV = "Set high voltage to 0 or 60 - 200V"; + spinHV->setToolTip(tipHV); + dacLayout->addWidget(spinHV, (int)(numDACWidgets / 2), 2); } + lblHV->setToolTip(tipHV); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabDeveloper::SetDacValues(int id) { + FILE_LOG(logINFO) << "Setting dac:" << dacNames[id] << " : " << spinDacs[id]->value(); + int moduleId = comboDetector->currentIndex() - 1; -void qTabDeveloper::CreateADCWidgets(){ - QGridLayout *adcLayout = new QGridLayout(boxAdcs); - - for(int i=0;isetReadOnly(true); - - adcLayout->addWidget(lblAdcs[i],(int)(i/2),((i%2)==0)?1:4); - adcLayout->addWidget(spinAdcs[i],(int)(i/2),((i%2)==0)?2:5); - if(!(i%2)){ - adcLayout->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed),(int)(i/2),0); - adcLayout->addItem(new QSpacerItem(60,20,QSizePolicy::Fixed,QSizePolicy::Fixed),(int)(i/2),3); - adcLayout->addItem(new QSpacerItem(20,20,QSizePolicy::Fixed,QSizePolicy::Fixed),(int)(i/2),6); - } - } + myDet->setDAC(spinDacs[id]->value(),getSLSIndex(id), 0, moduleId); + lblDacsmV[id]->setText(QString("%1mV").arg(myDet->setDAC(-1, getSLSIndex(id), 1, moduleId),-10)); + qDefs::checkErrorMessage(myDet, moduleId, "qTabDeveloper::SetDacValues"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDeveloper::SetDacValues(int id){ -#ifdef VERBOSE - cout << "Setting dac:" << dacNames[id] << " : " << spinDacs[id]->value() << endl; -#endif - - int detid = comboDetector->currentIndex(); - if(detid) - det = myDet->getSlsDetector(detid-1); - - //all detectors - if(!detid){ - myDet->setDAC((dacs_t)spinDacs[id]->value(),getSLSIndex(id),0); - lblDacsmV[id]->setText(QString("%1mV").arg(myDet->setDAC(-1,getSLSIndex(id),1),-10)); - qDefs::checkErrorMessage(myDet,"qTabDeveloper::SetDacValues"); - } - //specific detector - else{ - det->setDAC((dacs_t)spinDacs[id]->value(),getSLSIndex(id),0); - lblDacsmV[id]->setText(QString("%1mV").arg(det->setDAC(-1,getSLSIndex(id),1),-10)); - qDefs::checkErrorMessage(det,"qTabDeveloper::SetDacValues"); - } - -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabDeveloper::SetHighVoltage(){ -#ifdef VERBOSE - cout << "Setting high voltage:" << comboHV->currentText().toAscii().constData() << endl; -#endif - - int detid = comboDetector->currentIndex(); - if(detid) - det = myDet->getSlsDetector(detid-1); - - int highvoltage = comboHV->currentText().toInt(); - int ret; - - //all detectors - if(!detid){ - ret = myDet->setDAC(highvoltage,slsDetectorDefs::HV_POT,0); - qDefs::checkErrorMessage(myDet,"qTabDeveloper::SetHighVoltage"); - } - //specific detector - else{ - ret = det->setDAC(highvoltage,slsDetectorDefs::HV_POT,0); - qDefs::checkErrorMessage(det,"qTabDeveloper::SetHighVoltage"); - } +void qTabDeveloper::SetHighVoltage() { + int highvoltage = (comboHV ? comboHV->currentText().toInt() : spinHV->value()); + FILE_LOG(logINFO) << "Setting high voltage:" << highvoltage; + auto moduleId = comboDetector->currentIndex() - 1; + int ret = det->setDAC(highvoltage,slsDetectorDefs::HIGH_VOLTAGE, 0, moduleId); + qDefs::checkErrorMessage(myDet, moduleId, "qTabDeveloper::SetHighVoltage"); //error - if(ret != highvoltage){ - qDefs::Message(qDefs::CRITICAL,"High Voltage could not be set to this value.","qTabDeveloper::SetHighVoltage"); + if (ret != highvoltage && highvoltage != -1) { + qDefs::Message(qDefs::CRITICAL, "High Voltage could not be set to this value.", "qTabDeveloper::SetHighVoltage"); + FILE_LOG(logERROR) << "Could not set High voltage"; lblHV->setPalette(red); lblHV->setText("High Voltage:*"); - QString errTip = tipHV+QString("

High Voltage could not be set. The return value is ")+ - QString::number(ret)+ QString(""); + QString errTip = tipHV + QString("

High Voltage could not be set. The return value is ") + + QString::number(ret) + QString(""); lblHV->setToolTip(errTip); - comboHV->setToolTip(errTip); - }else{ + if (comboHV) + comboHV->setToolTip(errTip); + else + spinHV->setToolTip(errTip); + } else { lblHV->setPalette(lblDacs[0]->palette()); lblHV->setText("High Voltage:"); lblHV->setToolTip(tipHV); - comboHV->setToolTip(tipHV); + if (comboHV) + comboHV->setToolTip(tipHV); + else + spinHV->setToolTip(errTip); } } -//------------------------------------------------------------------------------------------------------------------------------------------------- +slsDetectorDefs::dacIndex qTabDeveloper::getSLSIndex(int index) { + switch (detType) { - -slsDetectorDefs::dacIndex qTabDeveloper::getSLSIndex(int index){ - switch(detType){ - case slsDetectorDefs::MYTHEN: - switch(index){ - case 0: return slsDetectorDefs::TRIMBIT_SIZE; - case 1: return slsDetectorDefs::THRESHOLD; - case 2: return slsDetectorDefs::SHAPER1; - case 3: return slsDetectorDefs::SHAPER2; - case 4: return slsDetectorDefs::CALIBRATION_PULSE; - case 5: return slsDetectorDefs::PREAMP; + case slsDetectorDefs::EIGER: + switch (index) { + case 0: + return slsDetectorDefs::E_SvP; + case 1: + return slsDetectorDefs::E_SvN; + case 2: + return slsDetectorDefs::E_Vrf; + case 3: + return slsDetectorDefs::E_Vrs; + case 4: + return slsDetectorDefs::E_Vtr; + case 5: + return slsDetectorDefs::E_Vtgstv; + case 6: + return slsDetectorDefs::E_cal; + case 7: + return slsDetectorDefs::E_Vcp; + case 8: + return slsDetectorDefs::E_Vcn; + case 9: + return slsDetectorDefs::E_Vis; + case 10: + return slsDetectorDefs::E_rxb_lb; + case 11: + return slsDetectorDefs::E_rxb_rb; + case 12: + return slsDetectorDefs::E_Vcmp_ll; + case 13: + return slsDetectorDefs::E_Vcmp_lr; + case 14: + return slsDetectorDefs::E_Vcmp_rl; + case 15: + return slsDetectorDefs::E_Vcmp_rr; + case 16: + return slsDetectorDefs::THRESHOLD; + case 17: + return slsDetectorDefs::TEMPERATURE_FPGAEXT; + case 18: + return slsDetectorDefs::TEMPERATURE_10GE; + case 19: + return slsDetectorDefs::TEMPERATURE_DCDC; + case 20: + return slsDetectorDefs::TEMPERATURE_SODL; + case 21: + return slsDetectorDefs::TEMPERATURE_SODR; + case 22: + return slsDetectorDefs::TEMPERATURE_FPGA; default: - qDefs::Message(qDefs::CRITICAL,"Unknown DAC/ADC Index. Weird Error Index:"+ index,"qTabDeveloper::getSLSIndex"); + qDefs::Message(qDefs::CRITICAL, "Unknown DAC/ADC Index. Weird Error Index:" + index, "qTabDeveloper::getSLSIndex"); Refresh(); break; } break; - case slsDetectorDefs::EIGER: - switch(index){ - case 0: return slsDetectorDefs::E_SvP; - case 1: return slsDetectorDefs::E_SvN; - case 2: return slsDetectorDefs::E_Vrf; - case 3: return slsDetectorDefs::E_Vrs; - case 4: return slsDetectorDefs::E_Vtr; - case 5: return slsDetectorDefs::E_Vtgstv; - case 6: return slsDetectorDefs::E_cal; - case 7: return slsDetectorDefs::E_Vcp; - case 8: return slsDetectorDefs::E_Vcn; - case 9: return slsDetectorDefs::E_Vis; - case 10:return slsDetectorDefs::E_rxb_lb; - case 11:return slsDetectorDefs::E_rxb_rb; - case 12:return slsDetectorDefs::E_Vcmp_ll; - case 13:return slsDetectorDefs::E_Vcmp_lr; - case 14:return slsDetectorDefs::E_Vcmp_rl; - case 15:return slsDetectorDefs::E_Vcmp_rr; - case 16:return slsDetectorDefs::THRESHOLD; - case 17:return slsDetectorDefs::TEMPERATURE_FPGAEXT; - case 18:return slsDetectorDefs::TEMPERATURE_10GE; - case 19:return slsDetectorDefs::TEMPERATURE_DCDC; - case 20:return slsDetectorDefs::TEMPERATURE_SODL; - case 21:return slsDetectorDefs::TEMPERATURE_SODR; - case 22:return slsDetectorDefs::TEMPERATURE_FPGA; - default: - qDefs::Message(qDefs::CRITICAL,"Unknown DAC/ADC Index. Weird Error Index:"+ index,"qTabDeveloper::getSLSIndex"); - Refresh(); - break; - } + case slsDetectorDefs::GOTTHARD: + switch (index) { + case 0: + return slsDetectorDefs::G_VREF_DS; + case 1: + return slsDetectorDefs::G_VCASCN_PB; + case 2: + return slsDetectorDefs::G_VCASCP_PB; + case 3: + return slsDetectorDefs::G_VOUT_CM; + case 4: + return slsDetectorDefs::G_VCASC_OUT; + case 5: + return slsDetectorDefs::G_VIN_CM; + case 6: + return slsDetectorDefs::G_VREF_COMP; + case 7: + return slsDetectorDefs::G_IB_TESTC; + case 8: + return slsDetectorDefs::TEMPERATURE_ADC; + case 9: + return slsDetectorDefs::TEMPERATURE_FPGA; + default: + qDefs::Message(qDefs::CRITICAL, "Unknown DAC/ADC Index. Weird Error Index:" + index, "qTabDeveloper::getSLSIndex"); + Refresh(); break; - case slsDetectorDefs::MOENCH: - switch(index){ - case 0: return slsDetectorDefs::V_DAC0; - case 1: return slsDetectorDefs::V_DAC1; - case 2: return slsDetectorDefs::V_DAC2; - case 3: return slsDetectorDefs::V_DAC3; - case 4: return slsDetectorDefs::V_DAC4; - case 5: return slsDetectorDefs::V_DAC5; - case 6: return slsDetectorDefs::V_DAC6; - case 7: return slsDetectorDefs::V_DAC7; - case 8: return slsDetectorDefs::TEMPERATURE_ADC; - case 9:return slsDetectorDefs::TEMPERATURE_FPGA; + } + break; - default: - qDefs::Message(qDefs::CRITICAL,"Unknown DAC/ADC Index. Weird Error. Index:"+ index,"qTabDeveloper::getSLSIndex"); - Refresh(); - break; - } - break; - case slsDetectorDefs::PROPIX: - case slsDetectorDefs::GOTTHARD: - switch(index){ - case 0: return slsDetectorDefs::G_VREF_DS; - case 1: return slsDetectorDefs::G_VCASCN_PB; - case 2: return slsDetectorDefs::G_VCASCP_PB; - case 3: return slsDetectorDefs::G_VOUT_CM; - case 4: return slsDetectorDefs::G_VCASC_OUT; - case 5: return slsDetectorDefs::G_VIN_CM; - case 6: return slsDetectorDefs::G_VREF_COMP; - case 7: return slsDetectorDefs::G_IB_TESTC; - case 8: return slsDetectorDefs::TEMPERATURE_ADC; - case 9:return slsDetectorDefs::TEMPERATURE_FPGA; - default: - qDefs::Message(qDefs::CRITICAL,"Unknown DAC/ADC Index. Weird Error Index:"+ index,"qTabDeveloper::getSLSIndex"); - Refresh(); - break; - } - break; - case slsDetectorDefs::JUNGFRAU: - case slsDetectorDefs::JUNGFRAUCTB: + case slsDetectorDefs::JUNGFRAU: + if (index >= 0 && index <= 7) { + return (slsDetectorDefs::dacIndex)index; + } + if (index == 8) { + return slsDetectorDefs::TEMPERATURE_ADC; + } else { + qDefs::Message(qDefs::CRITICAL, "Unknown DAC/ADC Index. Weird Error Index:" + index, "qTabDeveloper::getSLSIndex"); + Refresh(); + } + break; + case slsDetectorDefs::MOENCH: + if (index >= 0 && index <= 7) { + return (slsDetectorDefs::dacIndex)index; + } else { + qDefs::Message(qDefs::CRITICAL, "Unknown DAC/ADC Index. Weird Error Index:" + index, "qTabDeveloper::getSLSIndex"); + Refresh(); + } + break; - switch(index){ - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - return (slsDetectorDefs::dacIndex)index; - break; - case 8: return slsDetectorDefs::TEMPERATURE_ADC; - default: - qDefs::Message(qDefs::CRITICAL,"Unknown DAC/ADC Index. Weird Error Index:"+ index,"qTabDeveloper::getSLSIndex"); - Refresh(); - break; - } - break; - default: - cout << "Unknown detector type:" + myDet->slsDetectorBase::getDetectorType(detType) << endl; - qDefs::Message(qDefs::CRITICAL,string("Unknown detector type:")+myDet->slsDetectorBase::getDetectorType(detType),"qTabDeveloper::getSLSIndex"); - qDefs::checkErrorMessage(myDet,"qTabDeveloper::getSLSIndex"); - exit(-1); - break; + default: + FILE_LOG(logERROR) << "Unknown detector type:" + myDet->getDetectorTypeAsString(); + qDefs::Message(qDefs::CRITICAL, std::string("Unknown detector type:") + myDet->getDetectorTypeAsString(), "qTabDeveloper::getSLSIndex"); + qDefs::checkErrorMessage(myDet, "qTabDeveloper::getSLSIndex"); + exit(-1); + break; } - return slsDetectorDefs::HUMIDITY; + return (slsDetectorDefs::dacIndex)0; } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabDeveloper::RefreshAdcs() { + FILE_LOG(logDEBUG) << "Updating ADCs"; + auto moduleId = comboDetector->currentIndex() - 1; -void qTabDeveloper::RefreshAdcs(){ - if(!thisParent->isCurrentlyTabDeveloper()) - return; + for (int i = 0; i < numADCWidgets; ++i) { -#ifdef VERYVERBOSE - cout << "Updating ADCs" <stop();*/ - - int detid = comboDetector->currentIndex(); - if(detid) - det = myDet->getSlsDetector(detid-1); - - for(int i=0;igetADC(getSLSIndex(i+NUM_DAC_WIDGETS),-1); - - if(value == -1) - spinAdcs[i]->setText(QString("Different values")); - else { - if(detType == slsDetectorDefs::EIGER || detType == slsDetectorDefs::JUNGFRAU || detType == slsDetectorDefs::JUNGFRAUCTB) - value/=1000.00; - spinAdcs[i]->setText(QString::number(value,'f',2)+0x00b0+QString("C")); - } - } - //specific detector - else{ - double value = (double)det->getADC(getSLSIndex(i+NUM_DAC_WIDGETS)); - - if(detType == slsDetectorDefs::EIGER || detType == slsDetectorDefs::JUNGFRAU || detType == slsDetectorDefs::JUNGFRAUCTB) - value/=1000.00; - spinAdcs[i]->setText(QString::number(value,'f',2)+0x00b0+QString("C")); + double value = (double)myDet->getADC(getSLSIndex(i + numDACWidgets), moduleId); + if (value == -1 && moduleId == -1) { + spinAdcs[i]->setText(QString("Different values")); + } else { + if (detType == slsDetectorDefs::EIGER || detType == slsDetectorDefs::JUNGFRAU) + value /= 1000.00; + spinAdcs[i]->setText(QString::number(value, 'f', 2) + 0x00b0 + QString("C")); } } - - /*adcTimer->start(ADC_TIMEOUT);*/ - qDefs::checkErrorMessage(myDet,"qTabDeveloper::RefreshAdcs"); + qDefs::checkErrorMessage(myDet, "qTabDeveloper::RefreshAdcs"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabDeveloper::Refresh() { + FILE_LOG(logDEBUG) << "**Updating Developer Tab\n"; + auto moduleId = comboDetector->currentIndex() - 1; -void qTabDeveloper::Refresh(){ -#ifdef VERBOSE - cout << endl << "**Updating Developer Tab" << endl; -#endif - - - int detid = comboDetector->currentIndex(); - if(detid) - det = myDet->getSlsDetector(detid-1); - - - //dacs -#ifdef VERBOSE - cout << "Getting DACs" << NUM_DAC_WIDGETS <setValue((double)myDet->setDAC(-1,getSLSIndex(i),0)); - lblDacsmV[i]->setText(QString("%1mV").arg(myDet->setDAC(-1,getSLSIndex(i),1),-10)); - } - //specific detector - else{ - spinDacs[i]->setValue((double)det->setDAC(-1,getSLSIndex(i),0)); - lblDacsmV[i]->setText(QString("%1mV").arg(det->setDAC(-1,getSLSIndex(i),1),-10)); - } + // dacs + FILE_LOG(logDEBUG) << "Getting DACs"; + for (int i = 0; i < numDACWidgets; ++i) { + spinDacs[i]->setValue(myDet->setDAC(-1, getSLSIndex(i), 0, moduleId)); + lblDacsmV[i]->setText(QString("%1mV").arg(myDet->setDAC(-1, getSLSIndex(i), 1, moduleId), -10)); } - //adcs - if(NUM_ADC_WIDGETS) RefreshAdcs(); + if (numADCWidgets) + RefreshAdcs(); //gotthard -high voltage - if((detType == slsDetectorDefs::GOTTHARD) || - (detType == slsDetectorDefs::PROPIX) || - (detType == slsDetectorDefs::MOENCH)){ - disconnect(comboHV, SIGNAL(currentIndexChanged(int)), this, SLOT(SetHighVoltage())); + if ((detType == slsDetectorDefs::GOTTHARD) || + (detType == slsDetectorDefs::JUNGFRAU) || + (detType == slsDetectorDefs::MOENCH)) { + + if (comboHV) + disconnect(comboHV, SIGNAL(currentIndexChanged(int)), this, SLOT(SetHighVoltage())); + else + disconnect(spinHV, SIGNAL(valueChanged(int)), this, SLOT(SetHighVoltage())); //default should be correct lblHV->setPalette(lblDacs[0]->palette()); lblHV->setText("High Voltage:"); lblHV->setToolTip(tipHV); - comboHV->setToolTip(tipHV); - //getting hv value - int ret; - if(!detid) ret = (int)myDet->setDAC(-1,slsDetectorDefs::HV_POT,0); - else ret = (int)det->setDAC(-1,slsDetectorDefs::HV_POT,0); + if (comboHV) + comboHV->setToolTip(tipHV); + else + spinHV->setToolTip(tipHV); - switch(ret){ - case 0: comboHV->setCurrentIndex(0);break; - case 90: comboHV->setCurrentIndex(1);break; - case 110: comboHV->setCurrentIndex(2);break; - case 120: comboHV->setCurrentIndex(3);break; - case 150: comboHV->setCurrentIndex(4);break; - case 180: comboHV->setCurrentIndex(5);break; - case 200: comboHV->setCurrentIndex(6);break; - default: comboHV->setCurrentIndex(0);//error - lblHV->setPalette(red); - lblHV->setText("High Voltage:*"); - QString errTip = tipHV+QString("

High Voltage could not be set. The return value is ")+ - QString::number(ret)+ QString(""); - lblHV->setToolTip(errTip); - comboHV->setToolTip(errTip); - break; + //getting hv value + int ret = myDet->setDAC(-1, slsDetectorDefs::HIGH_VOLTAGE, 0, moduleId); + + bool error = false; + if (spinHV) { + if (ret != 0 && ret < 60 && ret > 200) + error = true; + else + spinHV->setValue(ret); + } else { + switch (ret) { + case 0: + comboHV->setCurrentIndex(0); + break; + case 90: + comboHV->setCurrentIndex(1); + break; + case 110: + comboHV->setCurrentIndex(2); + break; + case 120: + comboHV->setCurrentIndex(3); + break; + case 150: + comboHV->setCurrentIndex(4); + break; + case 180: + comboHV->setCurrentIndex(5); + break; + case 200: + comboHV->setCurrentIndex(6); + break; + default: + comboHV->setCurrentIndex(0); //error + error = true; + break; + } } - connect(comboHV, SIGNAL(currentIndexChanged(int)), this, SLOT(SetHighVoltage())); + if (error) { + lblHV->setPalette(red); + lblHV->setText("High Voltage:*"); + QString errTip = tipHV + QString("

High Voltage could not be set. The return value is ") + + QString::number(ret) + QString(""); + lblHV->setToolTip(errTip); + if (comboHV) + comboHV->setToolTip(errTip); + else + spinHV->setToolTip(errTip); + } else { + lblHV->setPalette(lblDacs[0]->palette()); + lblHV->setText("High Voltage:"); + lblHV->setToolTip(tipHV); + if (comboHV) + comboHV->setToolTip(tipHV); + else + spinHV->setToolTip(errTip); + } + if (comboHV) + connect(comboHV, SIGNAL(currentIndexChanged(int)), this, SLOT(SetHighVoltage())); + else + connect(spinHV, SIGNAL(valueChanged(int)), this, SLOT(SetHighVoltage())); } -#ifdef VERBOSE - cout << "**Updated Developer Tab" << endl << endl; -#endif + FILE_LOG(logDEBUG) << "**Updated Developer Tab"; - qDefs::checkErrorMessage(myDet,"qTabDeveloper::Refresh"); + qDefs::checkErrorMessage(myDet, "qTabDeveloper::Refresh"); } - -//------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/slsDetectorGui/src/qTabMeasurement.cpp b/slsDetectorGui/src/qTabMeasurement.cpp old mode 100644 new mode 100755 index caa3995c9..fab4ab919 --- a/slsDetectorGui/src/qTabMeasurement.cpp +++ b/slsDetectorGui/src/qTabMeasurement.cpp @@ -1,517 +1,265 @@ -/* - * qTabMeasurement.cpp - * - * Created on: May 2, 2012 - * Author: l_maliakal_d - */ - -//Qt Project Class Headers #include "qTabMeasurement.h" #include "qDetectorMain.h" -//Project Class Headers -#include "slsDetector.h" + #include "multiSlsDetector.h" -//C++ Include Headers -#include -using namespace std; + +#include - - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -qTabMeasurement::qTabMeasurement(qDetectorMain *parent,multiSlsDetector*& detector, qDrawPlot*& plot): - thisParent(parent),myDet(detector),myPlot(plot),expertMode(false){ +qTabMeasurement::qTabMeasurement(QWidget *parent, multiSlsDetector *detector, qDrawPlot *plot) : QWidget(parent), myDet(detector), myPlot(plot) { setupUi(this); SetupWidgetWindow(); Initialization(); - SetupTimingMode(); + + // updated after slots to enable/disable widgets + GetTimingModeFromDetector(true); + + FILE_LOG(logDEBUG) << "Measurement ready"; } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -qTabMeasurement::~qTabMeasurement(){ +qTabMeasurement::~qTabMeasurement() { delete myDet; - delete myPlot; - delete thisParent; } -//------------------------------------------------------------------------------------------------------------------------------------------------- +bool qTabMeasurement::GetStartStatus(){ + return (!btnStart->isEnabled()); +} -void qTabMeasurement::SetupWidgetWindow(){ +void qTabMeasurement::ClickStartStop(){ + startAcquisition(); + myPlot->SetClientInitiated(); +} - detType = myDet->getDetectorsType(); - //Number of measurements - spinNumMeasurements->setValue((int)myDet->setTimer(slsDetectorDefs::MEASUREMENTS_NUMBER,-1)); - //Number of frames - spinNumFrames->setValue((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,-1)); +int qTabMeasurement::GetProgress(){ + return progressBar->value(); +} + + +void qTabMeasurement::SetupWidgetWindow() { + + detType = myDet->getDetectorTypeAsEnum(); + + //measurements + spinNumMeasurements->setValue((int)myDet->setTimer(slsDetectorDefs::MEASUREMENTS_NUMBER, -1)); + //frames + spinNumFrames->setValue((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER, -1)); //Exp Time qDefs::timeUnit unit; - double time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME,-1)*(1E-9)))); + double time = qDefs::getCorrectTime(unit, ((double)(myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME, -1) * (1E-9)))); spinExpTime->setValue(time); comboExpUnit->setCurrentIndex((int)unit); //period - time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::FRAME_PERIOD,-1)*(1E-9)))); + time = qDefs::getCorrectTime(unit, ((double)(myDet->setTimer(slsDetectorDefs::FRAME_PERIOD, -1) * (1E-9)))); spinPeriod->setValue(time); comboPeriodUnit->setCurrentIndex((int)unit); - //Number of Triggers - spinNumTriggers->setValue((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,-1)); + //triggers + spinNumTriggers->setValue((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER, -1)); //delay if (detType == slsDetectorDefs::EIGER) { lblDelay->setEnabled(false); spinDelay->setEnabled(false); comboDelayUnit->setEnabled(false); } else { - time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::DELAY_AFTER_TRIGGER,-1)*(1E-9)))); + time = qDefs::getCorrectTime(unit, ((double)(myDet->setTimer(slsDetectorDefs::DELAY_AFTER_TRIGGER, -1) * (1E-9)))); spinDelay->setValue(time); comboDelayUnit->setCurrentIndex((int)unit); } - //gates - if ((detType == slsDetectorDefs::EIGER) || (detType == slsDetectorDefs::JUNGFRAU) || (detType == slsDetectorDefs::JUNGFRAUCTB)) { - lblNumGates->setEnabled(false); - spinNumGates->setEnabled(false); - } else - spinNumGates->setValue((int)myDet->setTimer(slsDetectorDefs::GATES_NUMBER,-1)); - //probes - if(detType == slsDetectorDefs::MYTHEN) - spinNumProbes->setValue((int)myDet->setTimer(slsDetectorDefs::PROBES_NUMBER,-1)); - //File Name + //samples + if (detType != slsDetectorDefs::MOENCH) { + lblNumSamples->setEnabled(false); + spinNumSamples->setEnabled(false); + } else { + spinNumSamples->setValue((int)myDet->setTimer(slsDetectorDefs::SAMPLES, -1)); + } + //file name dispFileName->setText(QString(myDet->getFileName().c_str())); - //File Index + //file write enable + chkFile->setChecked(myDet->enableWriteToFile()); + dispFileName->setEnabled(chkFile->isChecked()); + //file index spinIndex->setValue(myDet->getFileIndex()); //only initially lblProgressIndex->setText(QString::number(0)); - //ly initially progressBar->setValue(0); - //file write enabled/disabled - chkFile->setChecked(myDet->enableWriteToFile()); - dispFileName->setEnabled(myDet->enableWriteToFile()); //Timer to update the progress bar progressTimer = new QTimer(this); //Hide the error message red = QPalette(); - red.setColor(QPalette::Active,QPalette::WindowText,Qt::red); + red.setColor(QPalette::Active, QPalette::WindowText, Qt::red); acqPeriodTip = spinPeriod->toolTip(); errPeriodTip = QString("Frame period between exposures.
" - " #period#

")+ - QString("Acquisition Period should be" - " greater than or equal to Exposure Time."); + " #period#

") + + QString("Acquisition Period should be" + " greater than or equal to Exposure Time."); - qDefs::checkErrorMessage(myDet,"qTabMeasurement::SetupWidgetWindow"); + SetupTimingMode(); + // update timing mode after enabling slots to enable/disable widgets + + qDefs::checkErrorMessage(myDet, "qTabMeasurement::SetupWidgetWindow"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::SetExpertMode(bool enable){ - expertMode = enable; - qDefs::checkErrorMessage(myDet,"qTabMeasurement::SetExpertMode"); - - EnableProbes(); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::SetupTimingMode(){ +void qTabMeasurement::SetupTimingMode() { //To be able to index items on a combo box - model = qobject_cast(comboTimingMode->model()); - QModelIndex index[NumTimingModes]; - QStandardItem* item[NumTimingModes]; + model = qobject_cast(comboTimingMode->model()); + QModelIndex index[NUM_TIMING_MODES]; + QStandardItem *item[NUM_TIMING_MODES]; if (model) { - for(int i=0;iindex(i, comboTimingMode->modelColumn(), comboTimingMode->rootModelIndex()); + for (int i = 0; i < NUM_TIMING_MODES; i++) { + index[i] = model->index(i, comboTimingMode->modelColumn(), comboTimingMode->rootModelIndex()); item[i] = model->itemFromIndex(index[i]); } - //Enabling/Disabling depending on the detector type - switch(detType){ - case slsDetectorDefs::MYTHEN: - item[(int)Trigger_Exp_Series]->setEnabled(true); - item[(int)Trigger_Readout]->setEnabled(true); - item[(int)Gated]->setEnabled(true); - item[(int)Gated_Start]->setEnabled(true); - item[(int)Burst_Trigger]->setEnabled(false); - break; - case slsDetectorDefs::EIGER: - item[(int)Trigger_Exp_Series]->setEnabled(true); - item[(int)Trigger_Readout]->setEnabled(false); - item[(int)Gated]->setEnabled(true); - item[(int)Gated_Start]->setEnabled(false); - item[(int)Burst_Trigger]->setEnabled(true); - break; - case slsDetectorDefs::MOENCH: - case slsDetectorDefs::PROPIX: - case slsDetectorDefs::GOTTHARD: - case slsDetectorDefs::JUNGFRAU: - case slsDetectorDefs::JUNGFRAUCTB: - item[(int)Trigger_Exp_Series]->setEnabled(true); - item[(int)Trigger_Readout]->setEnabled(false); - item[(int)Gated]->setEnabled(false); - item[(int)Gated_Start]->setEnabled(false); - item[(int)Burst_Trigger]->setEnabled(false); - break; - default: - cout << "Unknown detector type." << endl; - qDefs::Message(qDefs::CRITICAL,"Unknown detector type.","qTabMeasurement::SetupTimingMode"); - exit(-1); - break; + + if (detType != slsDetectorDefs::EIGER) { + item[(int)GATED]->setEnabled(false); + item[(int)BURST_TRIGGER]->setEnabled(false); } } - - GetModeFromDetector(true); } -//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabMeasurement::Initialization() { + //measurements + connect(spinNumMeasurements, SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); + //frames + connect(spinNumFrames, SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); + //exposure time + connect(spinExpTime, SIGNAL(valueChanged(double)), this, SLOT(setExposureTime())); + connect(comboExpUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setExposureTime())); + //frame period between exposures + connect(spinPeriod, SIGNAL(valueChanged(double)), this, SLOT(setAcquisitionPeriod())); + connect(comboPeriodUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setAcquisitionPeriod())); + //triggers + connect(spinNumTriggers, SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); + //Delay After Trigger + if (spinDelay->isEnabled()) { + connect(spinDelay, SIGNAL(valueChanged(double)), this, SLOT(setDelay())); + connect(comboDelayUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setDelay())); + } + //samples + if (spinSamples->isEnabled()) + connect(spinNumSamples, SIGNAL(valueChanged(int)), this, SLOT(setNumSamples(int))); + //file name + connect(dispFileName, SIGNAL(editingFinished()), this, SLOT(setFileName())); + //file write enable + connect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); + //file index + connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + //progress bar + connect(progressTimer, SIGNAL(timeout()), this, SLOT(UpdateProgress())); + //start acquisition + connect(btnStart, SIGNAL(clicked()), this, SLOT(startAcquisition())); + //stop acquisition + connect(btnStop, SIGNAL(clicked()), this, SLOT(stopAcquisition())); + //timing mode + connect(comboTimingMode, SIGNAL(currentIndexChanged(int)), this, SLOT(SetTimingMode(int))); +} -void qTabMeasurement::GetModeFromDetector(bool startup){ -#ifdef VERBOSE - cout << "Getting timing mode" << endl; -#endif + +void qTabMeasurement::GetTimingModeFromDetector(bool startup) { + FILE_LOG(logDEBUG) << "Getting timing mode"; + //Get timing mode from detector slsDetectorDefs::externalCommunicationMode mode = myDet->setExternalCommunicationMode(); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::GetTimingModeFromDetector"); - //Setting the timing mode in gui - if(model && model->itemFromIndex(model->index(mode+1,comboTimingMode->modelColumn(), comboTimingMode->rootModelIndex()))->isEnabled()){ + //if the mode is enabled + if (model && model->itemFromIndex(model->index(mode, comboTimingMode->modelColumn(), comboTimingMode->rootModelIndex()))->isEnabled()) { - //these are things checked in setuptimingmode - - // to let qdrawplot know that triggers or frames are used - myPlot->setFrameEnabled(lblNumFrames->isEnabled()); - myPlot->setTriggerEnabled(lblNumTriggers->isEnabled()); - if((!startup) && (comboTimingMode->currentIndex() == (mode+1))){ - if(lblPeriod->isEnabled()) - CheckAcqPeriodGreaterThanExp(); - else{ - spinPeriod->setToolTip(acqPeriodTip); - lblPeriod->setToolTip(acqPeriodTip); - lblPeriod->setPalette(lblTimingMode->palette()); - lblPeriod->setText("Acquisition Period:"); - } - EnableProbes(); - emit CheckPlotIntervalSignal(); + // first time + if (startup) { + // explicitly call SetTimingMode first time + disconnect(comboTimingMode, SIGNAL(currentIndexChanged(int)), this, SLOT(SetTimingMode(int))); + comboTimingMode->setCurrentIndex((int)mode); + SetTimingMode((int)mode); + connect(comboTimingMode, SIGNAL(currentIndexChanged(int)), this, SLOT(SetTimingMode(int))); return; } - //if the timing mode is Auto and - // number of Frames and number of triggers is 1, - // then the timing mode is 'None'. - // This is for the inexperienced user - if(mode==slsDetectorDefs::AUTO_TIMING){ - int frames = spinNumFrames->value(); - int triggers = spinNumTriggers->value(); - int storagecells = 0; - if (detType == slsDetectorDefs::JUNGFRAU) - storagecells = myDet->setTimer(slsDetectorDefs::STORAGE_CELL_NUMBER, -1); - if((frames==1)&&(triggers==1)&&(storagecells==0)){ - comboTimingMode->setCurrentIndex((int)None); - SetTimingMode((int)None); - }else{ - comboTimingMode->setCurrentIndex((int)Auto); - SetTimingMode((int)Auto); - } - }else{ - //mode +1 since the detector class has no timingmode as "None" - comboTimingMode->setCurrentIndex((int)mode+1); - SetTimingMode((int)mode+1); + // mode is the different from current (from refresh), + if (comboTimingMode->currentIndex() != mode) { + comboTimingMode->setCurrentIndex((int)mode); } - } - // Mode NOT ENABLED. - // This should not happen -only if the server and gui has a mismatch - // on which all modes are allowed in detectors - else{ - //check if the detector is not even connected - string offline = myDet->checkOnline(); - qDefs::checkErrorMessage(myDet,"qTabMeasurement::GetModeFromDetector"); - if(!offline.empty()){ - qDefs::Message(qDefs::CRITICAL,string("The detector(s) ")+offline+string(" is/are not connected. Exiting GUI."),"Main"); - cout << "The detector(s) " << offline << " is/are not connected. Exiting GUI." << endl; + } + // Mode not enabled + else { + //check if the detector is not even connected + std::string offline = myDet->checkOnline(); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::GetTimingModeFromDetector"); + if (!offline.empty()) { + qDefs::Message(qDefs::CRITICAL, std::string("The detector(s) ") + offline + std::string(" is/are not connected. Exiting GUI."), "Main"); + FILE_LOG(logERROR) << "The detector(s) " << offline << " is/are not connected. Exiting GUI."; exit(-1); } - cout << "Unknown Timing Mode " << mode << " detected from detector" << endl; - qDefs::Message(qDefs::WARNING,"Unknown Timing Mode detected from detector." - "\n\nSetting the following defaults:\nTiming Mode \t: None\n" - "Number of Frames \t: 1\nNumber of Triggers \t: 1","qTabMeasurement::GetModeFromDetector"); - comboTimingMode->setCurrentIndex((int)None); - SetTimingMode((int)None); - } - qDefs::checkErrorMessage(myDet,"qTabMeasurement::GetModeFromDetector"); - -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - - -void qTabMeasurement::Initialization(){ - //Number of Measurements - connect(spinNumMeasurements,SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); - //File Name - connect(dispFileName, SIGNAL(editingFinished()),this, SLOT(setFileName())); - //File Index - connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); - //Start Acquisition - connect(btnStart, SIGNAL(clicked()), this, SLOT(startAcquisition())); - //Stop Acquisition - connect(btnStop, SIGNAL(clicked()), this, SLOT(stopAcquisition())); - //Timing Mode - connect(comboTimingMode, SIGNAL(currentIndexChanged(int)), this, SLOT(SetTimingMode(int)));// - //progress bar - connect(progressTimer, SIGNAL(timeout()), this, SLOT(UpdateProgress())); - //enable write to file - connect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); - //Number of Frames - connect(spinNumFrames,SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); - //Exposure Time - connect(spinExpTime,SIGNAL(valueChanged(double)), this, SLOT(setExposureTime())); - connect(comboExpUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(setExposureTime())); - //Frame Period between exposures - connect(spinPeriod,SIGNAL(valueChanged(double)), this, SLOT(setAcquisitionPeriod())); - connect(comboPeriodUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(setAcquisitionPeriod())); - //Number of Triggers - connect(spinNumTriggers,SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); - - //Delay After Trigger - if (detType != slsDetectorDefs::EIGER) { - connect(spinDelay,SIGNAL(valueChanged(double)), this, SLOT(setDelay())); - connect(comboDelayUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(setDelay())); - } - - //Number of Gates - if ((detType != slsDetectorDefs::EIGER) && (detType != slsDetectorDefs::JUNGFRAU) && (detType != slsDetectorDefs::JUNGFRAUCTB)) - connect(spinNumGates,SIGNAL(valueChanged(int)), this, SLOT(setNumGates(int))); - - //Number of Probes - connect(spinNumProbes,SIGNAL(valueChanged(int)), this, SLOT(setNumProbes(int))); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::Enable(bool enable){ - frameTimeResolved->setEnabled(enable); - frameNotTimeResolved->setEnabled(enable); - - //shortcut each time, else it doesnt work a second time - btnStart->setShortcut(QApplication::translate("TabMeasurementObject", "Shift+Space", 0, QApplication::UnicodeUTF8)); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::startAcquisition(){ - btnStart->setEnabled(false); - //if file write enabled and output dir doesnt exist - if((chkFile->isChecked())&&(thisParent->DoesOutputDirExist() == slsDetectorDefs::FAIL)){ - if(qDefs::Message(qDefs::QUESTION, - "Your data will not be saved.
Disable File write and Proceed with acquisition anyway?", - "qTabMeasurement::startAcquisition") == slsDetectorDefs::FAIL){ - btnStart->setEnabled(true); - return; - }else{ - //done because for receiver it cant save a file with blank file path and returns without acquiring even to the gui - disconnect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); - chkFile->setChecked(false); - EnableFileWrite(false); - connect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); - } - } - -#ifdef VERBOSE - cout << endl << endl << "Starting Acquisition" << endl; -#endif - lblProgressIndex->setText(QString::number(0)); - Enable(0); - progressBar->setValue(0); - progressTimer->start(100); - - emit StartSignal(); - qDefs::checkErrorMessage(myDet,"qTabMeasurement::startAcquisition"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::stopAcquisition(){ -#ifdef VERBOSE - cout << "Stopping Acquisition" << endl<< endl; -#endif - myDet->stopAcquisition(); - qDefs::checkErrorMessage(myDet,"qTabMeasurement::stopAcquisition"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::UpdateFinished(){ - UpdateProgress(); - disconnect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); - spinIndex->setValue(myDet->getFileIndex()); - connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); - progressTimer->stop(); - - Enable(1); - btnStart->setEnabled(true); - qDefs::checkErrorMessage(myDet,"qTabMeasurement::UpdateFinished"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::SetCurrentMeasurement(int val){ - if((val)value()) - lblCurrentMeasurement->setText(QString::number(val)); - -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::UpdateProgress(){ - progressBar->setValue((int)myPlot->GetProgress()); - lblProgressIndex->setText(QString::number(myPlot->GetFrameIndex())); - qDefs::checkErrorMessage(myDet,"qTabMeasurement::UpdateProgress"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::setFileName(){ - QString fName = dispFileName->text(); -#ifdef VERBOSE - cout << "Setting File name to " << fName.toAscii().constData() << endl; -#endif - myDet->setFileName(fName.toAscii().data()); - - disconnect(dispFileName, SIGNAL(editingFinished()),this, SLOT(setFileName())); - dispFileName->setText(QString(myDet->getFileName().c_str())); - connect(dispFileName, SIGNAL(editingFinished()),this, SLOT(setFileName())); - - qDefs::checkErrorMessage(myDet,"qTabMeasurement::setFileName"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabMeasurement::setRunIndex(int index){ -#ifdef VERBOSE - cout << "Setting File Index to " << index << endl; -#endif - myDet->setFileIndex(index); - - disconnect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); - spinIndex->setValue(myDet->getFileIndex()); - connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); - - qDefs::checkErrorMessage(myDet,"qTabMeasurement::setRunIndex"); -} - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::setNumMeasurements(int val){ -#ifdef VERBOSE - cout << "Setting Number of Measurements to " << val << endl; -#endif - myDet->setTimer(slsDetectorDefs::MEASUREMENTS_NUMBER,val); - - disconnect(spinNumMeasurements,SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); - spinNumMeasurements->setValue((int)myDet->setTimer(slsDetectorDefs::MEASUREMENTS_NUMBER,-1)); - connect(spinNumMeasurements,SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); - - qDefs::checkErrorMessage(myDet,"qTabMeasurement::setNumMeasurements"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::setNumFrames(int val){ -#ifdef VERBOSE - cout << "Setting number of frames to " << val << endl; -#endif - myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,val); - - disconnect(spinNumFrames,SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); - spinNumFrames->setValue((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,-1)); - connect(spinNumFrames,SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); - - qDefs::checkErrorMessage(myDet,"qTabMeasurement::setNumFrames"); - - EnableProbes(); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::CheckAcqPeriodGreaterThanExp(){ - double exptimeNS = qDefs::getNSTime((qDefs::timeUnit)comboExpUnit->currentIndex(),spinExpTime->value()); - double acqtimeNS = qDefs::getNSTime((qDefs::timeUnit)comboPeriodUnit->currentIndex(),spinPeriod->value()); - if(exptimeNS>acqtimeNS) { - spinPeriod->setToolTip(errPeriodTip); - lblPeriod->setToolTip(errPeriodTip); - lblPeriod->setPalette(red); - lblPeriod->setText("Acquisition Period:*"); - } - else { - spinPeriod->setToolTip(acqPeriodTip); - lblPeriod->setToolTip(acqPeriodTip); - lblPeriod->setPalette(lblTimingMode->palette()); - lblPeriod->setText("Acquisition Period:"); + // onlne but mismatch in timing mode + FILE_LOG(logWARNING) << "Unknown Timing Mode " << mode << " from detector"; + qDefs::Message(qDefs::WARNING, "Unknown Timing Mode from detector.\n\nSetting timing mode to Auto.", + "qTabMeasurement::GetTimingModeFromDetector"); + comboTimingMode->setCurrentIndex((int)AUTO); + SetTimingMode((int)AUTO); } } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabMeasurement::setNumMeasurements(int val) { + FILE_LOG(logINFO) << "Setting Number of Measurements to " << val; + + myDet->setTimer(slsDetectorDefs::MEASUREMENTS_NUMBER, val); + + disconnect(spinNumMeasurements, SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); + spinNumMeasurements->setValue((int)myDet->setTimer(slsDetectorDefs::MEASUREMENTS_NUMBER, -1)); + connect(spinNumMeasurements, SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); + + qDefs::checkErrorMessage(myDet, "qTabMeasurement::setNumMeasurements"); +} -void qTabMeasurement::setExposureTime(){ +void qTabMeasurement::setNumFrames(int val) { + FILE_LOG(logINFO) << "Setting number of frames to " << val; + + myDet->setTimer(slsDetectorDefs::FRAME_NUMBER, val); + + disconnect(spinNumFrames, SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); + spinNumFrames->setValue((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER, -1)); + connect(spinNumFrames, SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); + + qDefs::checkErrorMessage(myDet, "qTabMeasurement::setNumFrames"); +} + + +void qTabMeasurement::setExposureTime() { //Get the value of timer in ns - double exptimeNS = qDefs::getNSTime((qDefs::timeUnit)comboExpUnit->currentIndex(),spinExpTime->value()); -#ifdef VERBOSE - cout << "Setting acquisition time to " << exptimeNS << " clocks" << "/" << spinExpTime->value() << qDefs::getUnitString((qDefs::timeUnit)comboExpUnit->currentIndex()) << endl; -#endif - myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME,(int64_t)exptimeNS); - qDefs::checkErrorMessage(myDet,"qTabMeasurement::setExposureTime"); + double exptimeNS = qDefs::getNSTime((qDefs::timeUnit)comboExpUnit->currentIndex(), spinExpTime->value()); + FILE_LOG(logINFO) << "Setting acquisition time to " << exptimeNS << " ns" + << "/" << spinExpTime->value() << qDefs::getUnitString((qDefs::timeUnit)comboExpUnit->currentIndex()); - if(lblPeriod->isEnabled()) - CheckAcqPeriodGreaterThanExp(); + myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME, (int64_t)exptimeNS); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::setExposureTime"); + + CheckAcqPeriodGreaterThanExp(); + + //Check if the interval between plots is ok + emit CheckPlotIntervalSignal(); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::setAcquisitionPeriod(){ +void qTabMeasurement::setAcquisitionPeriod() { //Get the value of timer in ns - double acqtimeNS = qDefs::getNSTime((qDefs::timeUnit)comboPeriodUnit->currentIndex(),spinPeriod->value()); -#ifdef VERBOSE - cout << "Setting frame period between exposures to " << acqtimeNS << " clocks"<< "/" << spinPeriod->value() << qDefs::getUnitString((qDefs::timeUnit)comboPeriodUnit->currentIndex()) << endl; -#endif - myDet->setTimer(slsDetectorDefs::FRAME_PERIOD,(int64_t)acqtimeNS); - qDefs::checkErrorMessage(myDet,"qTabMeasurement::setAcquisitionPeriod"); + double acqtimeNS = qDefs::getNSTime((qDefs::timeUnit)comboPeriodUnit->currentIndex(), spinPeriod->value()); + FILE_LOG(logINFO) << "Setting frame period between exposures to " << acqtimeNS << " ns" + << "/" << spinPeriod->value() << qDefs::getUnitString((qDefs::timeUnit)comboPeriodUnit->currentIndex()); + + myDet->setTimer(slsDetectorDefs::FRAME_PERIOD, (int64_t)acqtimeNS); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::setAcquisitionPeriod"); CheckAcqPeriodGreaterThanExp(); //Check if the interval between plots is ok @@ -519,408 +267,407 @@ void qTabMeasurement::setAcquisitionPeriod(){ } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabMeasurement::setNumTriggers(int val) { + FILE_LOG(logINFO) << "Setting number of triggers to " << val; + myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER, val); -void qTabMeasurement::setNumTriggers(int val){ -#ifdef VERBOSE - cout << "Setting number of triggers to " << val << endl; -#endif - myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,val); + disconnect(spinNumTriggers, SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); + spinNumTriggers->setValue((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER, -1)); + connect(spinNumTriggers, SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); - disconnect(spinNumTriggers,SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); - spinNumTriggers->setValue((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,-1)); - connect(spinNumTriggers,SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); - - qDefs::checkErrorMessage(myDet,"qTabMeasurement::setNumTriggers"); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::setNumTriggers"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::setDelay(){ +void qTabMeasurement::setDelay() { //Get the value of timer in ns - double exptimeNS = qDefs::getNSTime((qDefs::timeUnit)comboDelayUnit->currentIndex(),spinDelay->value()); -#ifdef VERBOSE - cout << "Setting delay after trigger to " << exptimeNS << " clocks" << "/" << spinDelay->value() << qDefs::getUnitString((qDefs::timeUnit)comboDelayUnit->currentIndex()) << endl; -#endif - myDet->setTimer(slsDetectorDefs::DELAY_AFTER_TRIGGER,(int64_t)exptimeNS); -/* - //updating value set - disconnect(spinDelay,SIGNAL(valueChanged(double)), this, SLOT(setDelay())); - disconnect(comboDelayUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(setDelay())); - qDefs::timeUnit unit; - double time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::DELAY_AFTER_TRIGGER,-1)*(1E-9)))); - spinDelay->setValue(time); - comboDelayUnit->setCurrentIndex((int)unit); - connect(spinDelay,SIGNAL(valueChanged(double)), this, SLOT(setDelay())); - connect(comboDelayUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(setDelay())); -*/ + double exptimeNS = qDefs::getNSTime((qDefs::timeUnit)comboDelayUnit->currentIndex(), spinDelay->value()); + FILE_LOG(logINFO) << "Setting delay after trigger to " << exptimeNS << " ns" + << "/" << spinDelay->value() << qDefs::getUnitString((qDefs::timeUnit)comboDelayUnit->currentIndex()); - qDefs::checkErrorMessage(myDet,"qTabMeasurement::setDelay"); + myDet->setTimer(slsDetectorDefs::DELAY_AFTER_TRIGGER, (int64_t)exptimeNS); + + qDefs::checkErrorMessage(myDet, "qTabMeasurement::setDelay"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabMeasurement::setNumSamples(int val) { + FILE_LOG(logINFO) << "Setting number of samples to " << val; + myDet->setTimer(slsDetectorDefs::SAMPLES, val); -void qTabMeasurement::setNumGates(int val){ -#ifdef VERBOSE - cout << "Setting number of gates to " << val << endl; -#endif - myDet->setTimer(slsDetectorDefs::GATES_NUMBER,val); + disconnect(spinNumSamples, SIGNAL(valueChanged(int)), this, SLOT(setNumSamples(int))); + spinNumSamples->setValue((int)myDet->setTimer(slsDetectorDefs::SAMPLES, -1)); + connect(spinNumSamples, SIGNAL(valueChanged(int)), this, SLOT(setNumSamples(int))); - disconnect(spinNumGates,SIGNAL(valueChanged(int)), this, SLOT(setNumGates(int))); - spinNumGates->setValue((int)myDet->setTimer(slsDetectorDefs::GATES_NUMBER,-1)); - connect(spinNumGates,SIGNAL(valueChanged(int)), this, SLOT(setNumGates(int))); - - qDefs::checkErrorMessage(myDet,"qTabMeasurement::setNumGates"); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::setNumSamples"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabMeasurement::setFileName() { + QString fName = dispFileName->text(); + FILE_LOG(logINFO) << "Setting File name to " << fName.toAscii().constData(); + myDet->setFileName(fName.toAscii().data()); -void qTabMeasurement::setNumProbes(int val){ -#ifdef VERBOSE - cout << "Setting number of probes to " << val << endl; -#endif - disconnect(spinNumTriggers,SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); - disconnect(spinNumProbes,SIGNAL(valueChanged(int)), this, SLOT(setNumProbes(int))); + disconnect(dispFileName, SIGNAL(editingFinished()), this, SLOT(setFileName())); + dispFileName->setText(QString(myDet->getFileName().c_str())); + connect(dispFileName, SIGNAL(editingFinished()), this, SLOT(setFileName())); - //set probes - int ret = myDet->setTimer(slsDetectorDefs::PROBES_NUMBER,val); - if(ret != val) - ret = myDet->setTimer(slsDetectorDefs::PROBES_NUMBER,-1); - spinNumProbes->setValue(ret); - qDefs::checkErrorMessage(myDet,"qTabMeasurement::setNumProbes"); - - - //Setting number of probes should reset number of triggers to 1, need to check if enabled, cuz its updated when refresh - if((spinNumProbes->isEnabled()) && (ret > 0) && (spinNumTriggers->value() != 1)){ - qDefs::Message(qDefs::INFORMATION,"Number of Triggers has been reset to 1.
" - "This is mandatory to use probes.","qTabMeasurement::setNumProbes"); - cout << "Resetting Number of triggers to 1" << endl; - spinNumTriggers->setValue(1); - } - qDefs::checkErrorMessage(myDet,"qTabMeasurement::setNumProbes"); - - connect(spinNumTriggers,SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); - connect(spinNumProbes,SIGNAL(valueChanged(int)), this, SLOT(setNumProbes(int))); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::setFileName"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabMeasurement::EnableFileWrite(bool enable) { + FILE_LOG(logINFO) << "Enable File Write:" << enable; + + myDet->enableWriteToFile(enable); + disconnect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); + chkFile->setChecked(myDet->enableWriteToFile()); + connect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); + + bool ret = chkFile->isChecked(); + dispFileName->setEnabled(ret); + if (ret) + setFileName(); + myPlot->SetEnableFileWrite(ret); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::EnableFileWrite"); +} -void qTabMeasurement::SetTimingMode(int mode){ -#ifdef VERBOSE - cout << "Setting Timing mode to " << comboTimingMode->currentText().toAscii().data() << endl; -#endif - //Default settings - lblNumFrames->setEnabled(false); spinNumFrames->setEnabled(false); - lblExpTime->setEnabled(false); spinExpTime->setEnabled(false); comboExpUnit->setEnabled(false); - lblPeriod->setEnabled(false); spinPeriod->setEnabled(false); comboPeriodUnit->setEnabled(false); - lblNumTriggers->setEnabled(false); spinNumTriggers->setEnabled(false); - lblDelay->setEnabled(false); spinDelay->setEnabled(false); comboDelayUnit->setEnabled(false); - lblNumGates->setEnabled(false); spinNumGates->setEnabled(false); - lblNumProbes->setEnabled(false); spinNumProbes->setEnabled(false); +void qTabMeasurement::setRunIndex(int index) { + FILE_LOG(logINFO) << "Setting File Index to " << index; - bool success = false; - switch(mode){ - case None://Exposure Time - lblExpTime->setEnabled(true); spinExpTime->setEnabled(true); comboExpUnit->setEnabled(true); - spinNumTriggers->setValue(1); - spinNumFrames->setValue(1); - if (detType == slsDetectorDefs::JUNGFRAU) - myDet->setTimer(slsReceiverDefs::STORAGE_CELL_NUMBER, 0); - if(myDet->setExternalCommunicationMode(slsDetectorDefs::AUTO_TIMING)==slsDetectorDefs::AUTO_TIMING) - success = true; - break; - case Auto://#Frames, ExpTime, Period - spinNumTriggers->setValue(1); - lblNumFrames->setEnabled(true); spinNumFrames->setEnabled(true); - lblExpTime->setEnabled(true); spinExpTime->setEnabled(true); comboExpUnit->setEnabled(true); - lblPeriod->setEnabled(true); spinPeriod->setEnabled(true); comboPeriodUnit->setEnabled(true); - if(myDet->setExternalCommunicationMode(slsDetectorDefs::AUTO_TIMING)==slsDetectorDefs::AUTO_TIMING) - success = true; - break; - case Trigger_Exp_Series://#(Frames), #Triggers, ExpTime, Period, (Delay) - if(detType == slsDetectorDefs::EIGER) //only 1 frame for each trigger for eiger - spinNumFrames->setValue(1); - else{ - lblNumFrames->setEnabled(true); spinNumFrames->setEnabled(true); - lblDelay->setEnabled(true); spinDelay->setEnabled(true); comboDelayUnit->setEnabled(true); - lblPeriod->setEnabled(true); spinPeriod->setEnabled(true); comboPeriodUnit->setEnabled(true); + myDet->setFileIndex(index); + + disconnect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + spinIndex->setValue(myDet->getFileIndex()); + connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + + qDefs::checkErrorMessage(myDet, "qTabMeasurement::setRunIndex"); +} + + +void qTabMeasurement::UpdateProgress() { + progressBar->setValue((int)myPlot->GetProgress()); + lblProgressIndex->setText(QString::number(myPlot->GetFrameIndex())); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::UpdateProgress"); +} + + +void qTabMeasurement::startAcquisition() { + btnStart->setEnabled(false); + //if file write enabled and output dir doesnt exist + if ((chkFile->isChecked()) && (VerifyOutputDirectoryError() == slsDetectorDefs::FAIL)) { + if (qDefs::Message(qDefs::QUESTION, + "Your data will not be saved.
Disable File write and Proceed with acquisition anyway?", + "qTabMeasurement::startAcquisition") == slsDetectorDefs::FAIL) { + btnStart->setEnabled(true); + return; + } else { + //done because for receiver it cant save a file with blank file path and returns without acquiring even to the gui + disconnect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); + EnableFileWrite(false); + connect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); } - lblExpTime->setEnabled(true); spinExpTime->setEnabled(true); comboExpUnit->setEnabled(true); - lblNumTriggers->setEnabled(true); spinNumTriggers->setEnabled(true); - if(myDet->setExternalCommunicationMode(slsDetectorDefs::TRIGGER_EXPOSURE)==slsDetectorDefs::TRIGGER_EXPOSURE) - success = true; - break; - case Trigger_Readout://#Frames, ExpTime, Period, (Delay) - spinNumTriggers->setValue(1); - lblNumFrames->setEnabled(true); spinNumFrames->setEnabled(true); - lblExpTime->setEnabled(true); spinExpTime->setEnabled(true); comboExpUnit->setEnabled(true); - lblPeriod->setEnabled(true); spinPeriod->setEnabled(true); comboPeriodUnit->setEnabled(true); - if(myDet->setExternalCommunicationMode(slsDetectorDefs::TRIGGER_READOUT)==slsDetectorDefs::TRIGGER_READOUT) - success = true; - break; - case Gated://#Frames, #(Gates) - if(detType != slsDetectorDefs::EIGER){ - lblNumGates->setEnabled(true); spinNumGates->setEnabled(true); - } - spinNumTriggers->setValue(1); - lblNumFrames->setEnabled(true); spinNumFrames->setEnabled(true); - - - if(myDet->setExternalCommunicationMode(slsDetectorDefs::GATE_FIX_NUMBER)==slsDetectorDefs::GATE_FIX_NUMBER) - success = true; - break; - case Gated_Start://#Frames, #Triggers, #Gates, ExpTime, Period - lblNumFrames->setEnabled(true); spinNumFrames->setEnabled(true); - lblExpTime->setEnabled(true); spinExpTime->setEnabled(true); comboExpUnit->setEnabled(true); - lblPeriod->setEnabled(true); spinPeriod->setEnabled(true); comboPeriodUnit->setEnabled(true); - lblNumTriggers->setEnabled(true); spinNumTriggers->setEnabled(true); - lblNumGates->setEnabled(true); spinNumGates->setEnabled(true); - if(myDet->setExternalCommunicationMode(slsDetectorDefs::GATE_WITH_START_TRIGGER)==slsDetectorDefs::GATE_WITH_START_TRIGGER) - success = true; - break; - case Burst_Trigger://#Frames, ExpTime, Period, (Delay) - spinNumTriggers->setValue(1); - if(detType != slsDetectorDefs::EIGER){ - lblDelay->setEnabled(true); spinDelay->setEnabled(true); comboDelayUnit->setEnabled(true); - } - lblNumFrames->setEnabled(true); spinNumFrames->setEnabled(true); - lblExpTime->setEnabled(true); spinExpTime->setEnabled(true); comboExpUnit->setEnabled(true); - lblPeriod->setEnabled(true); spinPeriod->setEnabled(true); comboPeriodUnit->setEnabled(true); - if(myDet->setExternalCommunicationMode(slsDetectorDefs::BURST_TRIGGER)==slsDetectorDefs::BURST_TRIGGER) - success = true; - break; - default: - cout << "Timing mode unknown to GUI" << endl; - //This should never happen - qDefs::Message(qDefs::CRITICAL,"Timing mode unknown to GUI","qTabMeasurement::SetTimingMode"); - qDefs::checkErrorMessage(myDet,"qTabMeasurement::SetTimingMode"); - exit(-1); - } - qDefs::checkErrorMessage(myDet,"qTabMeasurement::SetTimingMode"); - if(!success){ - qDefs::Message(qDefs::WARNING,"The detector timing mode could not be set.\n" - "Please check the external flags." - "\n\nSetting the following defaults:\nTiming Mode \t: None\n" - "Number of Frames \t: 1\nNumber of Triggers \t: 1","qTabMeasurement::SetTimingMode"); - spinNumFrames->setValue(1); - spinNumTriggers->setValue(1); - if (detType == slsReceiverDefs::JUNGFRAU) - myDet->setTimer(slsDetectorDefs::STORAGE_CELL_NUMBER, 0); - comboTimingMode->setCurrentIndex((int)None); - return; } + FILE_LOG(logINFOBLUE) << "Starting Acquisition"; + lblProgressIndex->setText(QString::number(0)); + Enable(0); + progressBar->setValue(0); + progressTimer->start(100); - //Frame Period between exposures - if(lblPeriod->isEnabled()) - CheckAcqPeriodGreaterThanExp(); - else{ + emit StartSignal(); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::startAcquisition"); +} + + +void qTabMeasurement::stopAcquisition() { + FILE_LOG(logINFORED) << "Stopping Acquisition"; + myDet->stopAcquisition(); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::stopAcquisition"); +} + + +void qTabMeasurement::Enable(bool enable) { + frameTimeResolved->setEnabled(enable); + frameNotTimeResolved->setEnabled(enable); + + //shortcut each time, else it doesnt work a second time + btnStart->setShortcut(QApplication::translate("TabMeasurementObject", "Shift+Space", 0, QApplication::UnicodeUTF8)); +} + +int qTabMeasurement::VerifyOutputDirectoryError() { + for (int i = 0; i < myDet->getNumberOfDetectors(); i++) { + if (getModuleErrorMask(i) == FILE_PATH_DOES_NOT_EXIST) { + return slsDetectorDefs:: FAIL; + } + return slsDetectorDefs:: OK; + } +} + + +void qTabMeasurement::UpdateFinished() { + UpdateProgress(); + disconnect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + spinIndex->setValue(myDet->getFileIndex()); + connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + progressTimer->stop(); + + Enable(1); + btnStart->setEnabled(true); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::UpdateFinished"); +} + + +void qTabMeasurement::SetCurrentMeasurement(int val) { + if ((val) < spinNumMeasurements->value()) + lblCurrentMeasurement->setText(QString::number(val)); +} + + +void qTabMeasurement::CheckAcqPeriodGreaterThanExp() { + bool error = false; + if (lblPeriod->isEnabled()) { + double exptimeNS = qDefs::getNSTime((qDefs::timeUnit)comboExpUnit->currentIndex(), spinExpTime->value()); + double acqtimeNS = qDefs::getNSTime((qDefs::timeUnit)comboPeriodUnit->currentIndex(), spinPeriod->value()); + if (exptimeNS > acqtimeNS) { + error = true; + spinPeriod->setToolTip(errPeriodTip); + lblPeriod->setToolTip(errPeriodTip); + lblPeriod->setPalette(red); + lblPeriod->setText("Acquisition Period:*"); + } + } + + // no error or period disabled + if (!error) { spinPeriod->setToolTip(acqPeriodTip); lblPeriod->setToolTip(acqPeriodTip); lblPeriod->setPalette(lblTimingMode->palette()); lblPeriod->setText("Acquisition Period:"); } +} - //Check if Number of Probes should be enabled - EnableProbes(); +void qTabMeasurement::SetTimingMode(int mode) { + FILE_LOG(logINFO) << "Setting Timing mode to " << comboTimingMode->currentText().toAscii().data(); + + //Default settings + lblNumFrames->setEnabled(false); + spinNumFrames->setEnabled(false); + lblExpTime->setEnabled(false); + spinExpTime->setEnabled(false); + comboExpUnit->setEnabled(false); + lblPeriod->setEnabled(false); + spinPeriod->setEnabled(false); + comboPeriodUnit->setEnabled(false); + lblNumTriggers->setEnabled(false); + spinNumTriggers->setEnabled(false); + lblDelay->setEnabled(false); + spinDelay->setEnabled(false); + comboDelayUnit->setEnabled(false); + + bool success = false; + switch (mode) { + case AUTO: //#Frames, ExpTime, Period + spinNumTriggers->setValue(1); + lblNumFrames->setEnabled(true); + spinNumFrames->setEnabled(true); + lblExpTime->setEnabled(true); + spinExpTime->setEnabled(true); + comboExpUnit->setEnabled(true); + lblPeriod->setEnabled(true); + spinPeriod->setEnabled(true); + comboPeriodUnit->setEnabled(true); + if (myDet->setExternalCommunicationMode(slsDetectorDefs::AUTO_TIMING) == slsDetectorDefs::AUTO_TIMING) + success = true; + break; + case TRIGGER: // #Triggers, ExpTime, (#Frames, Period, Delay) + if (detType == slsDetectorDefs::EIGER) //only 1 frame for each trigger for eiger + spinNumFrames->setValue(1); + else { + lblNumFrames->setEnabled(true); + spinNumFrames->setEnabled(true); + lblDelay->setEnabled(true); + spinDelay->setEnabled(true); + comboDelayUnit->setEnabled(true); + lblPeriod->setEnabled(true); + spinPeriod->setEnabled(true); + comboPeriodUnit->setEnabled(true); + } + lblExpTime->setEnabled(true); + spinExpTime->setEnabled(true); + comboExpUnit->setEnabled(true); + lblNumTriggers->setEnabled(true); + spinNumTriggers->setEnabled(true); + if (myDet->setExternalCommunicationMode(slsDetectorDefs::TRIGGER_EXPOSURE) == slsDetectorDefs::TRIGGER_EXPOSURE) + success = true; + break; + + case GATED: //#Frames (Only Eiger) + + spinNumTriggers->setValue(1); + lblNumFrames->setEnabled(true); + spinNumFrames->setEnabled(true); + + if (myDet->setExternalCommunicationMode(slsDetectorDefs::GATED) == slsDetectorDefs::GATED) + success = true; + break; + + case BURST_TRIGGER: //#Frames, ExpTime, Period (Only Eiger) + spinNumTriggers->setValue(1); + + lblNumFrames->setEnabled(true); + spinNumFrames->setEnabled(true); + lblExpTime->setEnabled(true); + spinExpTime->setEnabled(true); + comboExpUnit->setEnabled(true); + lblPeriod->setEnabled(true); + spinPeriod->setEnabled(true); + comboPeriodUnit->setEnabled(true); + if (myDet->setExternalCommunicationMode(slsDetectorDefs::BURST_TRIGGER) == slsDetectorDefs::BURST_TRIGGER) + success = true; + break; + default: + FILE_LOG(logERROR) << "Timing mode unknown to GUI"; + //This should never happen + qDefs::Message(qDefs::CRITICAL, "Timing mode unknown to GUI", "qTabMeasurement::SetTimingMode"); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::SetTimingMode"); + exit(-1); + } + qDefs::checkErrorMessage(myDet, "qTabMeasurement::SetTimingMode"); + if (!success) { + + if (mode != AUTO) { + qDefs::Message(qDefs::WARNING, "The detector timing mode could not be set.\n\nSetting timing mode to Auto", + "qTabMeasurement::SetTimingMode"); + comboTimingMode->setCurrentIndex((int)AUTO); + return; + } else { + // can't do anything. just ignore + qDefs::Message(qDefs::ERROR, "The detector timing mode could not be set.", "qTabMeasurement::SetTimingMode"); + } + } + + //Frame Period between exposures + CheckAcqPeriodGreaterThanExp(); // to let qdrawplot know that triggers or frames are used myPlot->setFrameEnabled(lblNumFrames->isEnabled()); myPlot->setTriggerEnabled(lblNumTriggers->isEnabled()); - qDefs::checkErrorMessage(myDet,"qTabMeasurement::SetTimingMode"); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::SetTimingMode"); emit CheckPlotIntervalSignal(); - - return; } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabMeasurement::Refresh() { + FILE_LOG(logDEBUG) << "**Updating Measurement Tab"; + if (!myPlot->isRunning()) { -void qTabMeasurement::EnableFileWrite(bool enable){ -#ifdef VERBOSE - cout << "Enable File Write:" << enable << endl; -#endif - myDet->enableWriteToFile(enable); - dispFileName->setEnabled(enable); - if(enable) setFileName(); - myPlot->SetEnableFileWrite(enable); + //timing mode - will also check if exptime>acq period + GetTimingModeFromDetector(); - disconnect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); - chkFile->setChecked(myDet->enableWriteToFile()); - connect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); - - qDefs::checkErrorMessage(myDet,"qTabMeasurement::EnableFileWrite"); -}; - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::Refresh(){ -#ifdef VERBOSE - cout << endl << "**Updating Measurement Tab" << endl; -#endif - - if(!myPlot->isRunning()){ //to prevent it from recalculating forever - disconnect(spinNumMeasurements, SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); - disconnect(dispFileName, SIGNAL(editingFinished()), this, SLOT(setFileName())); - disconnect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); - disconnect(progressTimer, SIGNAL(timeout()), this, SLOT(UpdateProgress())); - disconnect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); - disconnect(spinNumFrames, SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); - disconnect(spinExpTime, SIGNAL(valueChanged(double)), this, SLOT(setExposureTime())); - disconnect(comboExpUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setExposureTime())); - disconnect(spinPeriod, SIGNAL(valueChanged(double)), this, SLOT(setAcquisitionPeriod())); - disconnect(comboPeriodUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setAcquisitionPeriod())); - disconnect(spinNumTriggers, SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); - if (detType != slsDetectorDefs::EIGER) { - disconnect(spinDelay, SIGNAL(valueChanged(double)), this, SLOT(setDelay())); - disconnect(comboDelayUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setDelay())); + disconnect(spinNumMeasurements, SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); + disconnect(spinNumFrames, SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); + disconnect(spinExpTime, SIGNAL(valueChanged(double)), this, SLOT(setExposureTime())); + disconnect(comboExpUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setExposureTime())); + disconnect(spinPeriod, SIGNAL(valueChanged(double)), this, SLOT(setAcquisitionPeriod())); + disconnect(comboPeriodUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setAcquisitionPeriod())); + disconnect(spinNumTriggers, SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); + if (spinDelay->isEnabled()) { + disconnect(spinDelay, SIGNAL(valueChanged(double)), this, SLOT(setDelay())); + disconnect(comboDelayUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setDelay())); } - if ((detType != slsDetectorDefs::EIGER) && (detType != slsDetectorDefs::JUNGFRAU) && (detType != slsDetectorDefs::JUNGFRAUCTB)) - disconnect(spinNumGates, SIGNAL(valueChanged(int)), this, SLOT(setNumGates(int))); - -#ifdef VERBOSE - cout << "Getting number of measurements & frames" << endl; -#endif - //Number of measurements - spinNumMeasurements->setValue((int)myDet->setTimer(slsDetectorDefs::MEASUREMENTS_NUMBER,-1)); - //Number of frames - spinNumFrames->setValue((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER,-1)); + if (spinSamples->isEnabled()) + disconnect(spinNumSamples, SIGNAL(valueChanged(int)), this, SLOT(setNumSamples(int))); + disconnect(dispFileName, SIGNAL(editingFinished()), this, SLOT(setFileName())); + disconnect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); + disconnect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + disconnect(progressTimer, SIGNAL(timeout()), this, SLOT(UpdateProgress())); -#ifdef VERBOSE - cout << "Getting Exposure time and Acquisition Period" << endl; -#endif - //Exp Time + FILE_LOG(logDEBUG) << "Getting number of measurements & frames"; + //measurements + spinNumMeasurements->setValue((int)myDet->setTimer(slsDetectorDefs::MEASUREMENTS_NUMBER, -1)); + //frames + spinNumFrames->setValue((int)myDet->setTimer(slsDetectorDefs::FRAME_NUMBER, -1)); + + FILE_LOG(logDEBUG) << "Getting Exposure time"; qDefs::timeUnit unit; - double time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME,-1)*(1E-9)))); + //Exp Time + double oldExptimeNs = qDefs::getNSTime((qDefs::timeUnit)comboExpUnit->currentIndex(), spinExpTime->value()); + double time = qDefs::getCorrectTime(unit, ((double)(myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME, -1) * (1E-9)))); spinExpTime->setValue(time); comboExpUnit->setCurrentIndex((int)unit); + double newExptimeNs = qDefs::getNSTime((qDefs::timeUnit)comboExpUnit->currentIndex(), spinExpTime->value()); + //period - time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::FRAME_PERIOD,-1)*(1E-9)))); + FILE_LOG(logDEBUG) << "Getting Acquisition Period"; + double oldAcqtimeNS = qDefs::getNSTime((qDefs::timeUnit)comboPeriodUnit->currentIndex(), spinPeriod->value()); + time = qDefs::getCorrectTime(unit, ((double)(myDet->setTimer(slsDetectorDefs::FRAME_PERIOD, -1) * (1E-9)))); spinPeriod->setValue(time); comboPeriodUnit->setCurrentIndex((int)unit); + double newAcqtimeNS = qDefs::getNSTime((qDefs::timeUnit)comboPeriodUnit->currentIndex(), spinPeriod->value()); + // change in period or exptime + if (newExptimeNs != oldExptimeNs || newAcqtimeNS != oldAcqtimeNS) { + //Frame Period between exposures + CheckAcqPeriodGreaterThanExp(); + + emit CheckPlotIntervalSignal(); + } + + FILE_LOG(logDEBUG) << "Getting #triggers and delay"; + //triggers + spinNumTriggers->setValue((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER, -1)); -#ifdef VERBOSE - cout << "Getting delay after trigger, number of triggers and number of gates" << endl; -#endif //delay - if (detType != slsDetectorDefs::EIGER) - time = qDefs::getCorrectTime(unit,((double)(myDet->setTimer(slsDetectorDefs::DELAY_AFTER_TRIGGER,-1)*(1E-9)))); + if (spinDelay->isEnabled()) + time = qDefs::getCorrectTime(unit, ((double)(myDet->setTimer(slsDetectorDefs::DELAY_AFTER_TRIGGER, -1) * (1E-9)))); - //gates - if ((detType != slsDetectorDefs::EIGER) && (detType != slsDetectorDefs::JUNGFRAU) && (detType != slsDetectorDefs::JUNGFRAUCTB) ) - spinNumGates->setValue((int)myDet->setTimer(slsDetectorDefs::GATES_NUMBER,-1)); + // samples + if (spinSamples->isEnabled()) { + spinNumSamples->setValue((int)myDet->setTimer(slsDetectorDefs::SAMPLES, -1)); + } - - //Number of Triggers - spinNumTriggers->setValue((int)myDet->setTimer(slsDetectorDefs::CYCLES_NUMBER,-1)); - -#ifdef VERBOSE - cout << "Getting file name prefix, file index, file write enable and progress index" << endl; -#endif - //File Name + FILE_LOG(logDEBUG) << "Getting file name prefix, file index, file write enable and progress index"; + //file name dispFileName->setText(QString(myDet->getFileName().c_str())); - //File Index - spinIndex->setValue(myDet->getFileIndex()); - //file write enabled/disabled + //file write enable chkFile->setChecked(myDet->enableWriteToFile()); + //file index + spinIndex->setValue(myDet->getFileIndex()); //progress label index - if(myDet->getFrameIndex()==-1) - lblProgressIndex->setText("0"); - else - lblProgressIndex->setText(QString::number(myDet->getFrameIndex())); + lblProgressIndex->setText("0"); - connect(spinNumMeasurements,SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); - connect(dispFileName, SIGNAL(editingFinished()), this, SLOT(setFileName())); - connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); - connect(progressTimer, SIGNAL(timeout()), this, SLOT(UpdateProgress())); - connect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); - connect(spinNumFrames, SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); - connect(spinExpTime, SIGNAL(valueChanged(double)), this, SLOT(setExposureTime())); - connect(comboExpUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setExposureTime())); - connect(spinPeriod, SIGNAL(valueChanged(double)), this, SLOT(setAcquisitionPeriod())); - connect(comboPeriodUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setAcquisitionPeriod())); - connect(spinNumTriggers, SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); - if (detType != slsDetectorDefs::EIGER) { - connect(spinDelay, SIGNAL(valueChanged(double)), this, SLOT(setDelay())); - connect(comboDelayUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setDelay())); + connect(spinNumMeasurements, SIGNAL(valueChanged(int)), this, SLOT(setNumMeasurements(int))); + connect(spinNumFrames, SIGNAL(valueChanged(int)), this, SLOT(setNumFrames(int))); + connect(spinExpTime, SIGNAL(valueChanged(double)), this, SLOT(setExposureTime())); + connect(comboExpUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setExposureTime())); + connect(spinPeriod, SIGNAL(valueChanged(double)), this, SLOT(setAcquisitionPeriod())); + connect(comboPeriodUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setAcquisitionPeriod())); + connect(spinNumTriggers, SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); + if (spinDelay->isEnabled()) { + connect(spinDelay, SIGNAL(valueChanged(double)), this, SLOT(setDelay())); + connect(comboDelayUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(setDelay())); } - if ((detType != slsDetectorDefs::EIGER) && (detType != slsDetectorDefs::JUNGFRAU) && (detType != slsDetectorDefs::JUNGFRAUCTB)) - connect(spinNumGates, SIGNAL(valueChanged(int)), this, SLOT(setNumGates(int))); + if (spinSamples->isEnabled()) + connect(spinNumSamples, SIGNAL(valueChanged(int)), this, SLOT(setNumSamples(int))); + disconnect(dispFileName, SIGNAL(editingFinished()), this, SLOT(setFileName())); + connect(chkFile, SIGNAL(toggled(bool)), this, SLOT(EnableFileWrite(bool))); + connect(spinIndex, SIGNAL(valueChanged(int)), this, SLOT(setRunIndex(int))); + connect(progressTimer, SIGNAL(timeout()), this, SLOT(UpdateProgress())); - //timing mode - will also check if exptime>acq period and also enableprobes() - GetModeFromDetector(); - - // to let qdrawplot know that triggers or frames are used - myPlot->setFrameEnabled(lblNumFrames->isEnabled()); - myPlot->setTriggerEnabled(lblNumTriggers->isEnabled()); - - qDefs::checkErrorMessage(myDet,"qTabMeasurement::Refresh"); + qDefs::checkErrorMessage(myDet, "qTabMeasurement::Refresh"); } -#ifdef VERBOSE - cout << "**Updated Measurement Tab" << endl << endl; -#endif + FILE_LOG(logDEBUG) << "**Updated Measurement Tab"; } - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabMeasurement::EnableProbes(){ - - //disconnect(spinNumProbes,SIGNAL(valueChanged(int)), this, SLOT(setNumProbes(int))); - disconnect(spinNumTriggers,SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); - - - //enabled only in expert mode and if #Frames > 1 - if((expertMode)&&(detType==slsDetectorDefs::MYTHEN)&&(spinNumFrames->value()>1)){ - lblNumProbes->setEnabled(true); - spinNumProbes->setEnabled(true); - spinNumProbes->setValue((int)myDet->setTimer(slsDetectorDefs::PROBES_NUMBER,-1)); -#ifdef VERBOSE - cout << "Getting number of probes : " << spinNumProbes->value() << endl; -#endif - - //Setting number of probes should reset number of triggers to 1, need to check if enabled, cuz its updated when refresh - if((spinNumProbes->isEnabled()) && (spinNumProbes->value() > 0) && (spinNumTriggers->value() != 1)){ - qDefs::Message(qDefs::INFORMATION,"Number of Triggers has been reset to 1.
" - "This is mandatory to use probes.","qTabMeasurement::EnableProbes"); - cout << "Resetting Number of triggers to 1" << endl; - spinNumTriggers->setValue(1); - } - qDefs::checkErrorMessage(myDet,"qTabMeasurement::EnableProbes"); - - connect(spinNumProbes, SIGNAL(valueChanged(int)), this, SLOT(setNumProbes(int))); - connect(spinNumTriggers, SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); - return; - } - cout << "Probes not enabled" << endl; - if(detType==slsDetectorDefs::MYTHEN) - spinNumProbes->setValue(0); - lblNumProbes->setEnabled(false); - spinNumProbes->setEnabled(false); - - //connect(spinNumProbes,SIGNAL(valueChanged(int)), this, SLOT(setNumProbes(int))); - connect(spinNumTriggers,SIGNAL(valueChanged(int)), this, SLOT(setNumTriggers(int))); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/slsDetectorGui/src/qTabMessages.cpp b/slsDetectorGui/src/qTabMessages.cpp old mode 100644 new mode 100755 index 460351164..c350c1e37 --- a/slsDetectorGui/src/qTabMessages.cpp +++ b/slsDetectorGui/src/qTabMessages.cpp @@ -1,122 +1,95 @@ -/* - * qTabMessages.cpp - * - * Created on: Jun 26, 2012 - * Author: l_maliakal_d - */ - -/** Qt Project Class Headers */ #include "qTabMessages.h" #include "qDetectorMain.h" -/** Project Class Headers */ -/** Qt Include Headers */ -#include + #include -#include #include +#include +#include - -/** C++ Include Headers */ #include #include -using namespace std; -//------------------------------------------------------------------------------------------------------------------------------------------------- -qTabMessages::qTabMessages(qDetectorMain* m):myMainTab(m),qout(0),qerr(0){ - SetupWidgetWindow(); - Initialization(); +qTabMessages::qTabMessages(QWidget *parent) : QWidget(parent) { + SetupWidgetWindow(); + Initialization(); + FILE_LOG(logDEBUG) << "Messages ready"; } -//------------------------------------------------------------------------------------------------------------------------------------------------- -qTabMessages::~qTabMessages(){ - delete myMainTab; - delete dispLog; - delete qout; - delete qerr; +qTabMessages::~qTabMessages() { + delete dispLog; } -//------------------------------------------------------------------------------------------------------------------------------------------------- -void qTabMessages::SetupWidgetWindow(){ - /** Layout */ - QGridLayout *gridLayout = new QGridLayout(this); +void qTabMessages::SetupWidgetWindow() { + /** Layout */ + QGridLayout *gridLayout = new QGridLayout(this); - dispLog = new QTextEdit(this); - dispLog->setReadOnly(true); - dispLog->setFocusPolicy(Qt::NoFocus); - dispLog->setTextColor(Qt::darkBlue); + dispLog = new QTextEdit(this); + dispLog->setReadOnly(true); + dispLog->setFocusPolicy(Qt::NoFocus); + dispLog->setTextColor(Qt::darkBlue); + btnSave = new QPushButton("Save Log ", this); + btnSave->setFocusPolicy(Qt::NoFocus); + btnSave->setFixedWidth(100); + btnSave->setIcon(QIcon(":/icons/images/save.png")); - btnSave = new QPushButton("Save Log ",this); - btnSave->setFocusPolicy(Qt::NoFocus); - btnSave->setFixedWidth(100); - btnSave->setIcon(QIcon( ":/icons/images/save.png" )); + btnClear = new QPushButton("Clear ", this); + btnClear->setFocusPolicy(Qt::NoFocus); + btnClear->setFixedWidth(100); + btnClear->setIcon(QIcon(":/icons/images/erase.png")); - btnClear = new QPushButton("Clear ",this); - btnClear->setFocusPolicy(Qt::NoFocus); - btnClear->setFixedWidth(100); - btnClear->setIcon(QIcon( ":/icons/images/erase.png" )); - - gridLayout->addItem(new QSpacerItem(15,10,QSizePolicy::Fixed,QSizePolicy::Fixed),0,0); - gridLayout->addWidget(btnSave,1,0,1,1); - gridLayout->addWidget(btnClear,1,4,1,1); - gridLayout->addItem(new QSpacerItem(15,10,QSizePolicy::Fixed,QSizePolicy::Fixed),2,0); - gridLayout->addWidget(dispLog,3,0,1,5); - - errMsg = " Please check Messages Tab. Following message was caught:

"; - qout=new qDebugStream(std::cout,this); - qerr=new qDebugStream(std::cerr,this); + gridLayout->addItem(new QSpacerItem(15, 10, QSizePolicy::Fixed, QSizePolicy::Fixed), 0, 0); + gridLayout->addWidget(btnSave, 1, 0, 1, 1); + gridLayout->addWidget(btnClear, 1, 4, 1, 1); + gridLayout->addItem(new QSpacerItem(15, 10, QSizePolicy::Fixed, QSizePolicy::Fixed), 2, 0); + gridLayout->addWidget(dispLog, 3, 0, 1, 5); + qDebugStream *qout = new qDebugStream(std::cout, this); + qDebugStream *qerr = new qDebugStream(std::cerr, this); } -//------------------------------------------------------------------------------------------------------------------------------------------------- -void qTabMessages::Initialization(){ - connect(btnSave,SIGNAL(clicked()),this,SLOT(SaveLog())); - connect(btnClear,SIGNAL(clicked()),this,SLOT(ClearLog())); +void qTabMessages::Initialization() { + connect(btnSave, SIGNAL(clicked()), this, SLOT(SaveLog())); + connect(btnClear, SIGNAL(clicked()), this, SLOT(ClearLog())); } -//------------------------------------------------------------------------------------------------------------------------------------------------- void qTabMessages::customEvent(QEvent *e) { - if (e->type() == (STREAMEVENT)){ - QString temp = ((qStreamEvent*)e)->getString(); - dispLog->append(temp); - } - + if (e->type() == (STREAMEVENT)) { + QString temp = ((qStreamEvent *)e)->getString(); + dispLog->append(temp); + } } -//------------------------------------------------------------------------------------------------------------------------------------------------- void qTabMessages::SaveLog() { - QString fName = QString(myMainTab->GetFilePath()); - fName = fName+"/LogFile.txt"; - fName = QFileDialog::getSaveFileName(this,tr("Save Snapshot "), - fName,tr("Text files (*.txt);;All Files(*)")); - if (!fName.isEmpty()){ - QFile outfile; - outfile.setFileName(fName); - if(outfile.open(QIODevice::WriteOnly | QIODevice::Text)){//Append - QTextStream out(&outfile); - out<toPlainText() << endl; - qDefs::Message(qDefs::INFORMATION,string("The Log has been successfully saved to " - "")+fName.toAscii().constData(),"qTabMessages::SaveLog"); - } - else qDefs::Message(qDefs::WARNING,"Attempt to save log file failed.","qTabMessages::SaveLog"); - } + QString fName = QString(""); //FIXME:current directory? + fName = fName + "/LogFile.txt"; + fName = QFileDialog::getSaveFileName(this, tr("Save Snapshot "), + fName, tr("Text files (*.txt);;All Files(*)")); + if (!fName.isEmpty()) { + QFile outfile; + outfile.setFileName(fName); + if (outfile.open(QIODevice::WriteOnly | QIODevice::Text)) { //Append + QTextStream out(&outfile); + out << dispLog->toPlainText() << endl; + qDefs::Message(qDefs::INFORMATION, std::string("The Log has been successfully saved to " + "") + + fName.toAscii().constData(), + "qTabMessages::SaveLog"); + } else { + FILE_LOG(logWARNING) << "Attempt to save log file failed."; + qDefs::Message(qDefs::WARNING, "Attempt to save log file failed.", "qTabMessages::SaveLog"); + } + } } -//------------------------------------------------------------------------------------------------------------------------------------------------- - void qTabMessages::ClearLog() { - dispLog->clear(); -#ifdef VERBOSE - cout<<"Log Cleared"<clear(); + FILE_LOG(logINFO) << "Log Cleared"; } - - -//------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/slsDetectorGui/src/qTabPlot.cpp b/slsDetectorGui/src/qTabPlot.cpp old mode 100644 new mode 100755 index cbcda6ec5..41c051d85 --- a/slsDetectorGui/src/qTabPlot.cpp +++ b/slsDetectorGui/src/qTabPlot.cpp @@ -1,26 +1,17 @@ -/* - * qTabPlot.cpp - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ - #include "qTabPlot.h" #include "qDrawPlot.h" // Project Class Headers -#include "slsDetector.h" #include "multiSlsDetector.h" // Qt Include Headers #include // C++ Include Headers #include -#include #include -using namespace std; +#include //------------------------------------------------------------------------------------------------------------------------------------------------- -const QString qTabPlot::modeNames[5]={"None","Energy Scan","Threshold Scan","Trimbits Scan","Custom Script Scan"}; +// const QString qTabPlot::modeNames[5] = {"None", "Energy Scan", "Threshold Scan", "Trimbits Scan", "Custom Script Scan"}; QString qTabPlot::defaultPlotTitle(""); QString qTabPlot::defaultHistXAxisTitle("Channel Number"); @@ -29,1514 +20,1434 @@ QString qTabPlot::defaultImageXAxisTitle("Pixel"); QString qTabPlot::defaultImageYAxisTitle("Pixel"); QString qTabPlot::defaultImageZAxisTitle("Intensity"); - //------------------------------------------------------------------------------------------------------------------------------------------------- - -qTabPlot::qTabPlot(QWidget *parent,multiSlsDetector*& detector, qDrawPlot*& plot): - QWidget(parent), - myDet(detector), - myPlot(plot), - isOneD(false), - isOriginallyOneD(false), - wrongInterval(0), - stackedLayout(0), - spinNthFrame(0), - spinTimeGap(0), - comboTimeGapUnit(0), - btnGroupScan(0), - btnGroupPlotType(0), - btnGroupHistogram(0){ - setupUi(this); - SetupWidgetWindow(); - Initialization(); +qTabPlot::qTabPlot(QWidget *parent, multiSlsDetector *detector, qDrawPlot *plot) : QWidget(parent), + myDet(detector), + myPlot(plot), + isOneD(false), + isOriginallyOneD(false), + wrongInterval(0), + stackedLayout(0), + spinNthFrame(0), + spinTimeGap(0), + comboTimeGapUnit(0), + btnGroupScan(0), + btnGroupPlotType(0), + btnGroupHistogram(0) { + setupUi(this); + SetupWidgetWindow(); + Initialization(); + FILE_LOG(logDEBUG) << "Plot ready"; } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -qTabPlot::~qTabPlot(){ - delete myDet; - delete myPlot; +qTabPlot::~qTabPlot() { + delete myDet; + delete myPlot; } - //------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabPlot::SetupWidgetWindow() { + //error for interval between plots + red = new QPalette(); + ; + red->setColor(QPalette::Active, QPalette::WindowText, Qt::red); + intervalTip = boxFrequency->toolTip(); -void qTabPlot::SetupWidgetWindow(){ - //error for interval between plots - red = new QPalette();; - red->setColor(QPalette::Active,QPalette::WindowText,Qt::red); - intervalTip = boxFrequency->toolTip(); + //scan arguments + btnGroupScan = new QButtonGroup(this); + btnGroupScan->addButton(radioLevel0, 0); + btnGroupScan->addButton(radioLevel1, 1); + btnGroupScan->addButton(radioFileIndex, 2); + btnGroupScan->addButton(radioAllFrames, 3); + //plot type + btnGroupPlotType = new QButtonGroup(this); + btnGroupPlotType->addButton(radioNoPlot, 0); + btnGroupPlotType->addButton(radioDataGraph, 1); + btnGroupPlotType->addButton(radioHistogram, 2); -//scan arguments - btnGroupScan = new QButtonGroup(this); - btnGroupScan->addButton(radioLevel0,0); - btnGroupScan->addButton(radioLevel1,1); - btnGroupScan->addButton(radioFileIndex,2); - btnGroupScan->addButton(radioAllFrames,3); + //histogram arguments + btnGroupHistogram = new QButtonGroup(this); + btnGroupHistogram->addButton(radioHistIntensity, 0); + btnGroupHistogram->addButton(radioHistLevel0, 1); + btnGroupHistogram->addButton(radioHistLevel1, 2); -//plot type - btnGroupPlotType = new QButtonGroup(this); - btnGroupPlotType->addButton(radioNoPlot,0); - btnGroupPlotType->addButton(radioDataGraph,1); - btnGroupPlotType->addButton(radioHistogram,2); + // Plot Axis + dispTitle->setEnabled(false); + dispXAxis->setEnabled(false); + dispYAxis->setEnabled(false); + dispZAxis->setEnabled(false); + dispXMin->setEnabled(false); + dispYMin->setEnabled(false); + dispZMin->setEnabled(false); + dispXMax->setEnabled(false); + dispYMax->setEnabled(false); + dispZMax->setEnabled(false); + dispXMin->setValidator(new QDoubleValidator(dispXMin)); + dispYMin->setValidator(new QDoubleValidator(dispYMin)); + dispZMin->setValidator(new QDoubleValidator(dispZMin)); + dispXMax->setValidator(new QDoubleValidator(dispXMax)); + dispYMax->setValidator(new QDoubleValidator(dispYMax)); + dispZMax->setValidator(new QDoubleValidator(dispZMax)); -//histogram arguments - btnGroupHistogram = new QButtonGroup(this); - btnGroupHistogram->addButton(radioHistIntensity,0); - btnGroupHistogram->addButton(radioHistLevel0,1); - btnGroupHistogram->addButton(radioHistLevel1,2); + //default titles + dispTitle->setText(""); + myPlot->SetPlotTitlePrefix(""); + dispXAxis->setText(defaultHistXAxisTitle); + dispYAxis->setText(defaultHistYAxisTitle); + myPlot->SetHistXAxisTitle(defaultHistXAxisTitle); + myPlot->SetHistYAxisTitle(defaultHistYAxisTitle); + dispXAxis->setText(defaultImageXAxisTitle); + dispYAxis->setText(defaultImageYAxisTitle); + dispZAxis->setText(defaultImageZAxisTitle); + myPlot->SetImageXAxisTitle(defaultImageXAxisTitle); + myPlot->SetImageYAxisTitle(defaultImageYAxisTitle); + myPlot->SetImageZAxisTitle(defaultImageZAxisTitle); -// Plot Axis - dispTitle->setEnabled(false); - dispXAxis->setEnabled(false); - dispYAxis->setEnabled(false); - dispZAxis->setEnabled(false); - dispXMin->setEnabled(false); - dispYMin->setEnabled(false); - dispZMin->setEnabled(false); - dispXMax->setEnabled(false); - dispYMax->setEnabled(false); - dispZMax->setEnabled(false); - dispXMin->setValidator(new QDoubleValidator(dispXMin)); - dispYMin->setValidator(new QDoubleValidator(dispYMin)); - dispZMin->setValidator(new QDoubleValidator(dispZMin)); - dispXMax->setValidator(new QDoubleValidator(dispXMax)); - dispYMax->setValidator(new QDoubleValidator(dispYMax)); - dispZMax->setValidator(new QDoubleValidator(dispZMax)); + // Plotting Frequency - //default titles - dispTitle->setText(""); - myPlot->SetPlotTitlePrefix(""); - dispXAxis->setText(defaultHistXAxisTitle); - dispYAxis->setText(defaultHistYAxisTitle); - myPlot->SetHistXAxisTitle(defaultHistXAxisTitle); - myPlot->SetHistYAxisTitle(defaultHistYAxisTitle); - dispXAxis->setText(defaultImageXAxisTitle); - dispYAxis->setText(defaultImageYAxisTitle); - dispZAxis->setText(defaultImageZAxisTitle); - myPlot->SetImageXAxisTitle(defaultImageXAxisTitle); - myPlot->SetImageYAxisTitle(defaultImageYAxisTitle); - myPlot->SetImageZAxisTitle(defaultImageZAxisTitle); + stackedLayout = new QStackedLayout; + stackedLayout->setSpacing(0); + spinNthFrame = new QSpinBox; + spinNthFrame->setMinimum(1); + spinNthFrame->setMaximum(2000000000); + spinTimeGap = new QDoubleSpinBox; + spinTimeGap->setMinimum(0); + spinTimeGap->setDecimals(3); + spinTimeGap->setMaximum(999999); + spinTimeGap->setValue(myPlot->GetMinimumPlotTimer()); + comboTimeGapUnit = new QComboBox; + comboTimeGapUnit->addItem("hr"); + comboTimeGapUnit->addItem("min"); + comboTimeGapUnit->addItem("s"); + comboTimeGapUnit->addItem("ms"); + comboTimeGapUnit->setCurrentIndex(3); + QWidget *w = new QWidget; + QHBoxLayout *h1 = new QHBoxLayout; + w->setLayout(h1); + h1->setContentsMargins(0, 0, 0, 0); + h1->setSpacing(3); + h1->addWidget(spinTimeGap); + h1->addWidget(comboTimeGapUnit); - // Plotting Frequency + stackedLayout->addWidget(w); + stackedLayout->addWidget(spinNthFrame); + stackWidget->setLayout(stackedLayout); - stackedLayout = new QStackedLayout; - stackedLayout->setSpacing(0); - spinNthFrame = new QSpinBox; - spinNthFrame->setMinimum(1); - spinNthFrame->setMaximum(2000000000); - spinTimeGap = new QDoubleSpinBox; - spinTimeGap->setMinimum(0); - spinTimeGap->setDecimals(3); - spinTimeGap->setMaximum(999999); - spinTimeGap->setValue(myPlot->GetMinimumPlotTimer()); - comboTimeGapUnit = new QComboBox; - comboTimeGapUnit->addItem("hr"); - comboTimeGapUnit->addItem("min"); - comboTimeGapUnit->addItem("s"); - comboTimeGapUnit->addItem("ms"); - comboTimeGapUnit->setCurrentIndex(3); - QWidget *w = new QWidget; - QHBoxLayout *h1 = new QHBoxLayout; - w->setLayout(h1); - h1->setContentsMargins(0,0,0,0); - h1->setSpacing(3); - h1->addWidget(spinTimeGap); - h1->addWidget(comboTimeGapUnit); + stackedWidget->setCurrentIndex(0); + stackedWidget_2->setCurrentIndex(0); - stackedLayout->addWidget(w); - stackedLayout->addWidget(spinNthFrame); - stackWidget->setLayout(stackedLayout); + // Depending on whether the detector is 1d or 2d + switch (myDet->getDetectorTypeAsEnum()) { + case slsDetectorDefs::EIGER: + isOriginallyOneD = false; + pagePedestal->setEnabled(false); + pagePedestal_2->setEnabled(false); + chkBinary->setEnabled(false); + chkBinary_2->setEnabled(false); + chkGapPixels->setEnabled(true); + break; + case slsDetectorDefs::GOTTHARD: + isOriginallyOneD = true; + break; + case slsDetectorDefs::JUNGFRAU: + case slsDetectorDefs::MOENCH: + isOriginallyOneD = false; + chkGainPlot->setEnabled(true); + break; + default: + cout << "ERROR: Detector Type is Generic" << endl; + exit(-1); + } - stackedWidget->setCurrentIndex(0); - stackedWidget_2->setCurrentIndex(0); + Select1DPlot(isOriginallyOneD); - // Depending on whether the detector is 1d or 2d - switch(myDet->getDetectorsType()){ - case slsDetectorDefs::MYTHEN: - isOriginallyOneD = true; - pagePedestal->setEnabled(false); - pagePedestal_2->setEnabled(false); - chkBinary->setEnabled(false); - chkBinary_2->setEnabled(false); - break; - case slsDetectorDefs::EIGER: - isOriginallyOneD = false; - pagePedestal->setEnabled(false); - pagePedestal_2->setEnabled(false); - chkBinary->setEnabled(false); - chkBinary_2->setEnabled(false); - chkGapPixels->setEnabled(true); - break; - case slsDetectorDefs::GOTTHARD: - isOriginallyOneD = true; - break; - case slsDetectorDefs::PROPIX: - isOriginallyOneD = false; - break; - case slsDetectorDefs::MOENCH: - isOriginallyOneD = false; - break; - case slsDetectorDefs::JUNGFRAU: - case slsDetectorDefs::JUNGFRAUCTB: - isOriginallyOneD = false; - chkGainPlot->setEnabled(true); - break; - default: - cout << "ERROR: Detector Type is Generic" << endl; - exit(-1); - } + //to check if this should be enabled + // EnableScanBox(); - Select1DPlot(isOriginallyOneD); - - //to check if this should be enabled - EnableScanBox(); - - //disable histogram initially - boxHistogram->hide(); + //disable histogram initially + boxHistogram->hide(); if (chkGapPixels->isEnabled()) { - int ret = myDet->enableGapPixels(-1); - qDefs::checkErrorMessage(myDet,"qTabPlot::SetupWidgetWindow"); + int ret = myDet->enableGapPixels(-1); + qDefs::checkErrorMessage(myDet, "qTabPlot::SetupWidgetWindow"); chkGapPixels->setChecked((ret == 1) ? true : false); } - qDefs::checkErrorMessage(myDet,"qTabPlot::SetupWidgetWindow"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabPlot::SetPlotOptionsRightPage(){ - if(isOneD){ - int i = stackedWidget->currentIndex(); - if(i == (stackedWidget->count()-1)) - stackedWidget->setCurrentIndex(0); - else - stackedWidget->setCurrentIndex(i+1); - box1D->setTitle(QString("1D Plot Options %1").arg(stackedWidget->currentIndex()+1)); - } - else{ - int i = stackedWidget_2->currentIndex(); - if(i == (stackedWidget_2->count()-1)) - stackedWidget_2->setCurrentIndex(0); - else - stackedWidget_2->setCurrentIndex(i+1); - box2D->setTitle(QString("2D Plot Options %1").arg(stackedWidget_2->currentIndex()+1)); - } + qDefs::checkErrorMessage(myDet, "qTabPlot::SetupWidgetWindow"); } //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabPlot::SetPlotOptionsLeftPage(){ - if(isOneD){ - int i = stackedWidget->currentIndex(); - if(i == 0) - stackedWidget->setCurrentIndex(stackedWidget->count()-1); - else - stackedWidget->setCurrentIndex(i-1); - box1D->setTitle(QString("1D Plot Options %1").arg(stackedWidget->currentIndex()+1)); - } - else{ - int i = stackedWidget_2->currentIndex(); - if(i == 0) - stackedWidget_2->setCurrentIndex(stackedWidget_2->count()-1); - else - stackedWidget_2->setCurrentIndex(i-1); - box2D->setTitle(QString("2D Plot Options %1").arg(stackedWidget_2->currentIndex()+1)); - } +void qTabPlot::SetPlotOptionsRightPage() { + if (isOneD) { + int i = stackedWidget->currentIndex(); + if (i == (stackedWidget->count() - 1)) + stackedWidget->setCurrentIndex(0); + else + stackedWidget->setCurrentIndex(i + 1); + box1D->setTitle(QString("1D Plot Options %1").arg(stackedWidget->currentIndex() + 1)); + } else { + int i = stackedWidget_2->currentIndex(); + if (i == (stackedWidget_2->count() - 1)) + stackedWidget_2->setCurrentIndex(0); + else + stackedWidget_2->setCurrentIndex(i + 1); + box2D->setTitle(QString("2D Plot Options %1").arg(stackedWidget_2->currentIndex() + 1)); + } } - //------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabPlot::SetPlotOptionsLeftPage() { + if (isOneD) { + int i = stackedWidget->currentIndex(); + if (i == 0) + stackedWidget->setCurrentIndex(stackedWidget->count() - 1); + else + stackedWidget->setCurrentIndex(i - 1); + box1D->setTitle(QString("1D Plot Options %1").arg(stackedWidget->currentIndex() + 1)); + } else { + int i = stackedWidget_2->currentIndex(); + if (i == 0) + stackedWidget_2->setCurrentIndex(stackedWidget_2->count() - 1); + else + stackedWidget_2->setCurrentIndex(i - 1); + box2D->setTitle(QString("2D Plot Options %1").arg(stackedWidget_2->currentIndex() + 1)); + } +} -void qTabPlot::Select1DPlot(bool b){ +//------------------------------------------------------------------------------------------------------------------------------------------------- + +void qTabPlot::Select1DPlot(bool b) { #ifdef VERBOSE - if(b) - cout << "Selecting 1D Plot" << endl; - else - cout << "Selecting 2D Plot" << endl; + if (b) + cout << "Selecting 1D Plot" << endl; + else + cout << "Selecting 2D Plot" << endl; #endif - isOneD = b; - lblFrom->setEnabled(false); - lblTo->setEnabled(false); - lblFrom_2->setEnabled(false); - lblTo_2->setEnabled(false); - spinFrom->setEnabled(false); - spinFrom_2->setEnabled(false); - spinTo->setEnabled(false); - spinTo_2->setEnabled(false); - if(b){ - box1D->show(); - box2D->hide(); - chkZAxis->setEnabled(false); - chkZMin->setEnabled(false); - chkZMax->setEnabled(false); - myPlot->Select1DPlot(); - }else{ - box1D->hide(); - box2D->show(); - chkZAxis->setEnabled(true); - chkZMin->setEnabled(true); - chkZMax->setEnabled(true); - myPlot->Select2DPlot(); - } + isOneD = b; + lblFrom->setEnabled(false); + lblTo->setEnabled(false); + lblFrom_2->setEnabled(false); + lblTo_2->setEnabled(false); + spinFrom->setEnabled(false); + spinFrom_2->setEnabled(false); + spinTo->setEnabled(false); + spinTo_2->setEnabled(false); + if (b) { + box1D->show(); + box2D->hide(); + chkZAxis->setEnabled(false); + chkZMin->setEnabled(false); + chkZMax->setEnabled(false); + myPlot->Select1DPlot(); + } else { + box1D->hide(); + box2D->show(); + chkZAxis->setEnabled(true); + chkZMin->setEnabled(true); + chkZMax->setEnabled(true); + myPlot->Select2DPlot(); + } } - //------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabPlot::Initialization() { + // Plot arguments box + connect(btnGroupPlotType, SIGNAL(buttonClicked(int)), this, SLOT(SetPlot())); + // Histogram arguments box + connect(btnGroupHistogram, SIGNAL(buttonClicked(int)), this, SLOT(SetHistogramOptions())); + // Scan box + // connect(boxScan, SIGNAL(toggled(bool)), this, SLOT(EnableScanBox())); + // Snapshot box + connect(btnClone, SIGNAL(clicked()), myPlot, SLOT(ClonePlot())); + connect(btnCloseClones, SIGNAL(clicked()), myPlot, SLOT(CloseClones())); + connect(btnSaveClones, SIGNAL(clicked()), myPlot, SLOT(SaveClones())); + // 1D Plot box + //to change pages + connect(btnRight, SIGNAL(clicked()), this, SLOT(SetPlotOptionsRightPage())); + connect(btnLeft, SIGNAL(clicked()), this, SLOT(SetPlotOptionsLeftPage())); -void qTabPlot::Initialization(){ -// Plot arguments box - connect(btnGroupPlotType,SIGNAL(buttonClicked(int)),this, SLOT(SetPlot())); -// Histogram arguments box - connect(btnGroupHistogram,SIGNAL(buttonClicked(int)),this, SLOT(SetHistogramOptions())); -// Scan box - connect(boxScan, SIGNAL(toggled(bool)), this, SLOT(EnableScanBox())); -// Snapshot box - connect(btnClone, SIGNAL(clicked()),myPlot, SLOT(ClonePlot())); - connect(btnCloseClones, SIGNAL(clicked()),myPlot, SLOT(CloseClones())); - connect(btnSaveClones, SIGNAL(clicked()),myPlot, SLOT(SaveClones())); -// 1D Plot box - //to change pages - connect(btnRight, SIGNAL(clicked()), this, SLOT(SetPlotOptionsRightPage())); - connect(btnLeft, SIGNAL(clicked()), this, SLOT(SetPlotOptionsLeftPage())); + connect(chkSuperimpose, SIGNAL(toggled(bool)), this, SLOT(EnablePersistency(bool))); + connect(spinPersistency, SIGNAL(valueChanged(int)), myPlot, SLOT(SetPersistency(int))); + connect(chkPoints, SIGNAL(toggled(bool)), myPlot, SLOT(SetMarkers(bool))); + connect(chkLines, SIGNAL(toggled(bool)), myPlot, SLOT(SetLines(bool))); + connect(chk1DLog, SIGNAL(toggled(bool)), myPlot, SIGNAL(LogySignal(bool))); + connect(chkStatistics, SIGNAL(toggled(bool)), myPlot, SLOT(DisplayStatistics(bool))); - connect(chkSuperimpose, SIGNAL(toggled(bool)), this, SLOT(EnablePersistency(bool))); - connect(spinPersistency,SIGNAL(valueChanged(int)), myPlot,SLOT(SetPersistency(int))); - connect(chkPoints, SIGNAL(toggled(bool)), myPlot, SLOT(SetMarkers(bool))); - connect(chkLines, SIGNAL(toggled(bool)), myPlot, SLOT(SetLines(bool))); - connect(chk1DLog, SIGNAL(toggled(bool)), myPlot, SIGNAL(LogySignal(bool))); - connect(chkStatistics, SIGNAL(toggled(bool)), myPlot, SLOT(DisplayStatistics(bool))); + // 2D Plot box + connect(chkInterpolate, SIGNAL(toggled(bool)), myPlot, SIGNAL(InterpolateSignal(bool))); + connect(chkContour, SIGNAL(toggled(bool)), myPlot, SIGNAL(ContourSignal(bool))); + connect(chkLogz, SIGNAL(toggled(bool)), myPlot, SIGNAL(LogzSignal(bool))); + connect(chkStatistics_2, SIGNAL(toggled(bool)), myPlot, SLOT(DisplayStatistics(bool))); + // Plotting frequency box + connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + connect(comboTimeGapUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + connect(spinTimeGap, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + // Plot Axis * + connect(chkTitle, SIGNAL(toggled(bool)), this, SLOT(EnableTitles())); + connect(chkXAxis, SIGNAL(toggled(bool)), this, SLOT(EnableTitles())); + connect(chkYAxis, SIGNAL(toggled(bool)), this, SLOT(EnableTitles())); + connect(chkZAxis, SIGNAL(toggled(bool)), this, SLOT(EnableTitles())); + connect(dispTitle, SIGNAL(textChanged(const QString &)), this, SLOT(SetTitles())); + connect(dispXAxis, SIGNAL(textChanged(const QString &)), this, SLOT(SetTitles())); + connect(dispYAxis, SIGNAL(textChanged(const QString &)), this, SLOT(SetTitles())); + connect(dispZAxis, SIGNAL(textChanged(const QString &)), this, SLOT(SetTitles())); -// 2D Plot box - connect(chkInterpolate, SIGNAL(toggled(bool)),myPlot, SIGNAL(InterpolateSignal(bool))); - connect(chkContour, SIGNAL(toggled(bool)),myPlot, SIGNAL(ContourSignal(bool))); - connect(chkLogz, SIGNAL(toggled(bool)),myPlot, SIGNAL(LogzSignal(bool))); - connect(chkStatistics_2,SIGNAL(toggled(bool)),myPlot, SLOT(DisplayStatistics(bool))); -// Plotting frequency box - connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - connect(comboTimeGapUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - connect(spinTimeGap, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); -// Plot Axis * - connect(chkTitle, SIGNAL(toggled(bool)), this, SLOT(EnableTitles())); - connect(chkXAxis, SIGNAL(toggled(bool)), this, SLOT(EnableTitles())); - connect(chkYAxis, SIGNAL(toggled(bool)), this, SLOT(EnableTitles())); - connect(chkZAxis, SIGNAL(toggled(bool)), this, SLOT(EnableTitles())); - connect(dispTitle, SIGNAL(textChanged(const QString&)), this, SLOT(SetTitles())); - connect(dispXAxis, SIGNAL(textChanged(const QString&)), this, SLOT(SetTitles())); - connect(dispYAxis, SIGNAL(textChanged(const QString&)), this, SLOT(SetTitles())); - connect(dispZAxis, SIGNAL(textChanged(const QString&)), this, SLOT(SetTitles())); + connect(chkXMin, SIGNAL(toggled(bool)), this, SLOT(EnableXRange())); + connect(chkXMax, SIGNAL(toggled(bool)), this, SLOT(EnableXRange())); + connect(chkYMin, SIGNAL(toggled(bool)), this, SLOT(EnableYRange())); + connect(chkYMax, SIGNAL(toggled(bool)), this, SLOT(EnableYRange())); + connect(chkZMin, SIGNAL(toggled(bool)), this, SLOT(EnableZRange())); + connect(chkZMax, SIGNAL(toggled(bool)), this, SLOT(EnableZRange())); + connect(chkAspectRatio, SIGNAL(toggled(bool)), this, SLOT(checkAspectRatio())); + connect(this, SIGNAL(ResetZMinZMaxSignal(bool, bool, double, double)), myPlot, SIGNAL(ResetZMinZMaxSignal(bool, bool, double, double))); - connect(chkXMin, SIGNAL(toggled(bool)), this, SLOT(EnableXRange())); - connect(chkXMax, SIGNAL(toggled(bool)), this, SLOT(EnableXRange())); - connect(chkYMin, SIGNAL(toggled(bool)), this, SLOT(EnableYRange())); - connect(chkYMax, SIGNAL(toggled(bool)), this, SLOT(EnableYRange())); - connect(chkZMin, SIGNAL(toggled(bool)), this, SLOT(EnableZRange())); - connect(chkZMax, SIGNAL(toggled(bool)), this, SLOT(EnableZRange())); - connect(chkAspectRatio, SIGNAL(toggled(bool)), this, SLOT(checkAspectRatio())); - connect(this, SIGNAL(ResetZMinZMaxSignal(bool,bool,double,double)), myPlot, SIGNAL(ResetZMinZMaxSignal(bool,bool,double,double))); + connect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); + connect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); + connect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + connect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + connect(dispZMin, SIGNAL(editingFinished()), this, SLOT(SetZRange())); + connect(dispZMax, SIGNAL(editingFinished()), this, SLOT(SetZRange())); + // Save + connect(btnSave, SIGNAL(clicked()), myPlot, SLOT(SavePlot())); + connect(chkSaveAll, SIGNAL(toggled(bool)), myPlot, SLOT(SaveAll(bool))); - connect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); - connect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); - connect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); - connect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); - connect(dispZMin, SIGNAL(editingFinished()), this, SLOT(SetZRange())); - connect(dispZMax, SIGNAL(editingFinished()), this, SLOT(SetZRange())); -// Save - connect(btnSave, SIGNAL(clicked()), myPlot, SLOT(SavePlot())); - connect(chkSaveAll, SIGNAL(toggled(bool)), myPlot, SLOT(SaveAll(bool))); + //pedstal + connect(chkPedestal, SIGNAL(toggled(bool)), myPlot, SLOT(SetPedestal(bool))); + connect(btnRecalPedestal, SIGNAL(clicked()), myPlot, SLOT(RecalculatePedestal())); + connect(chkPedestal_2, SIGNAL(toggled(bool)), myPlot, SLOT(SetPedestal(bool))); + connect(btnRecalPedestal_2, SIGNAL(clicked()), myPlot, SLOT(RecalculatePedestal())); -//pedstal - connect(chkPedestal, SIGNAL(toggled(bool)), myPlot, SLOT(SetPedestal(bool))); - connect(btnRecalPedestal, SIGNAL(clicked()), myPlot, SLOT(RecalculatePedestal())); - connect(chkPedestal_2, SIGNAL(toggled(bool)), myPlot, SLOT(SetPedestal(bool))); - connect(btnRecalPedestal_2, SIGNAL(clicked()), myPlot, SLOT(RecalculatePedestal())); + //accumulate + connect(chkAccumulate, SIGNAL(toggled(bool)), myPlot, SLOT(SetAccumulate(bool))); + connect(btnResetAccumulate, SIGNAL(clicked()), myPlot, SLOT(ResetAccumulate())); + connect(chkAccumulate_2, SIGNAL(toggled(bool)), myPlot, SLOT(SetAccumulate(bool))); + connect(btnResetAccumulate_2, SIGNAL(clicked()), myPlot, SLOT(ResetAccumulate())); -//accumulate - connect(chkAccumulate, SIGNAL(toggled(bool)), myPlot, SLOT(SetAccumulate(bool))); - connect(btnResetAccumulate, SIGNAL(clicked()), myPlot, SLOT(ResetAccumulate())); - connect(chkAccumulate_2, SIGNAL(toggled(bool)), myPlot, SLOT(SetAccumulate(bool))); - connect(btnResetAccumulate_2, SIGNAL(clicked()), myPlot, SLOT(ResetAccumulate())); + //binary + connect(chkBinary, SIGNAL(toggled(bool)), this, SLOT(SetBinary())); + connect(chkBinary_2, SIGNAL(toggled(bool)), this, SLOT(SetBinary())); + connect(spinFrom, SIGNAL(valueChanged(int)), this, SLOT(SetBinary())); + connect(spinFrom_2, SIGNAL(valueChanged(int)), this, SLOT(SetBinary())); + connect(spinTo, SIGNAL(valueChanged(int)), this, SLOT(SetBinary())); + connect(spinTo_2, SIGNAL(valueChanged(int)), this, SLOT(SetBinary())); - //binary - connect(chkBinary, SIGNAL(toggled(bool)), this, SLOT(SetBinary())); - connect(chkBinary_2, SIGNAL(toggled(bool)), this, SLOT(SetBinary())); - connect(spinFrom, SIGNAL(valueChanged(int)), this, SLOT(SetBinary())); - connect(spinFrom_2, SIGNAL(valueChanged(int)), this, SLOT(SetBinary())); - connect(spinTo, SIGNAL(valueChanged(int)), this, SLOT(SetBinary())); - connect(spinTo_2, SIGNAL(valueChanged(int)), this, SLOT(SetBinary())); + //gainplot + if (chkGainPlot->isEnabled()) + connect(chkGainPlot, SIGNAL(toggled(bool)), myPlot, SIGNAL(GainPlotSignal(bool))); - //gainplot - if (chkGainPlot->isEnabled()) - connect(chkGainPlot, SIGNAL(toggled(bool)),myPlot, SIGNAL(GainPlotSignal(bool))); - - // gap pixels + // gap pixels if (chkGapPixels->isEnabled()) - connect(chkGapPixels, SIGNAL(toggled(bool)),this, SLOT(EnableGapPixels(bool))); + connect(chkGapPixels, SIGNAL(toggled(bool)), this, SLOT(EnableGapPixels(bool))); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabPlot::EnablePersistency(bool enable){ +void qTabPlot::EnablePersistency(bool enable) { #ifdef VERBOSE - if(enable) - cout << "Enabling Persistency" << endl; - else - cout << "Disabling Persistency" << endl; + if (enable) + cout << "Enabling Persistency" << endl; + else + cout << "Disabling Persistency" << endl; #endif - lblPersistency->setEnabled(enable); - spinPersistency->setEnabled(enable); - if(enable) myPlot->SetPersistency(spinPersistency->value()); - else myPlot->SetPersistency(0); - + lblPersistency->setEnabled(enable); + spinPersistency->setEnabled(enable); + if (enable) + myPlot->SetPersistency(spinPersistency->value()); + else + myPlot->SetPersistency(0); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabPlot::SetTitles(){ +void qTabPlot::SetTitles() { #ifdef VERBOSE - cout << "Setting Plot Titles" << endl; + cout << "Setting Plot Titles" << endl; #endif - // Plot Title - if(dispTitle->isEnabled()) - myPlot->SetPlotTitlePrefix(dispTitle->text()); - // X Axis - if(dispXAxis->isEnabled()){ - if(isOneD) myPlot->SetHistXAxisTitle(dispXAxis->text()); - else myPlot->SetImageXAxisTitle(dispXAxis->text()); - } - // Y Axis - if(dispYAxis->isEnabled()){ - if(isOneD) myPlot->SetHistYAxisTitle(dispYAxis->text()); - else myPlot->SetImageYAxisTitle(dispYAxis->text()); - } - // Z Axis - if(dispZAxis->isEnabled()) - myPlot->SetImageZAxisTitle(dispZAxis->text()); + // Plot Title + if (dispTitle->isEnabled()) + myPlot->SetPlotTitlePrefix(dispTitle->text()); + // X Axis + if (dispXAxis->isEnabled()) { + if (isOneD) + myPlot->SetHistXAxisTitle(dispXAxis->text()); + else + myPlot->SetImageXAxisTitle(dispXAxis->text()); + } + // Y Axis + if (dispYAxis->isEnabled()) { + if (isOneD) + myPlot->SetHistYAxisTitle(dispYAxis->text()); + else + myPlot->SetImageYAxisTitle(dispYAxis->text()); + } + // Z Axis + if (dispZAxis->isEnabled()) + myPlot->SetImageZAxisTitle(dispZAxis->text()); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabPlot::EnableTitles(){ - // Plot Title - dispTitle->setEnabled(chkTitle->isChecked()); - if(!chkTitle->isChecked()){ - myPlot->SetPlotTitlePrefix(""); - dispTitle->setText(""); - } - // X Axis - dispXAxis->setEnabled(chkXAxis->isChecked()); - if(!chkXAxis->isChecked()){ - if(isOneD){ - myPlot->SetHistXAxisTitle(defaultHistXAxisTitle); - dispXAxis->setText(defaultHistXAxisTitle); - } - else{ - myPlot->SetImageXAxisTitle(defaultImageXAxisTitle); - dispXAxis->setText(defaultImageXAxisTitle); - } - } - // Y Axis - dispYAxis->setEnabled(chkYAxis->isChecked()); - if(!chkYAxis->isChecked()){ - if(isOneD){ - myPlot->SetHistYAxisTitle(defaultHistYAxisTitle); - dispYAxis->setText(defaultHistYAxisTitle); - }else{ - myPlot->SetImageYAxisTitle(defaultImageYAxisTitle); - dispYAxis->setText(defaultImageYAxisTitle); - } - } - // Z Axis - dispZAxis->setEnabled(chkZAxis->isChecked()); - if(!chkZAxis->isChecked()){ - myPlot->SetImageZAxisTitle(defaultImageZAxisTitle); - dispZAxis->setText(defaultImageZAxisTitle); - } +void qTabPlot::EnableTitles() { + // Plot Title + dispTitle->setEnabled(chkTitle->isChecked()); + if (!chkTitle->isChecked()) { + myPlot->SetPlotTitlePrefix(""); + dispTitle->setText(""); + } + // X Axis + dispXAxis->setEnabled(chkXAxis->isChecked()); + if (!chkXAxis->isChecked()) { + if (isOneD) { + myPlot->SetHistXAxisTitle(defaultHistXAxisTitle); + dispXAxis->setText(defaultHistXAxisTitle); + } else { + myPlot->SetImageXAxisTitle(defaultImageXAxisTitle); + dispXAxis->setText(defaultImageXAxisTitle); + } + } + // Y Axis + dispYAxis->setEnabled(chkYAxis->isChecked()); + if (!chkYAxis->isChecked()) { + if (isOneD) { + myPlot->SetHistYAxisTitle(defaultHistYAxisTitle); + dispYAxis->setText(defaultHistYAxisTitle); + } else { + myPlot->SetImageYAxisTitle(defaultImageYAxisTitle); + dispYAxis->setText(defaultImageYAxisTitle); + } + } + // Z Axis + dispZAxis->setEnabled(chkZAxis->isChecked()); + if (!chkZAxis->isChecked()) { + myPlot->SetImageZAxisTitle(defaultImageZAxisTitle); + dispZAxis->setText(defaultImageZAxisTitle); + } } - //------------------------------------------------------------------------------------------------------------------------------------------------- - void qTabPlot::checkAspectRatio() { - if (chkAspectRatio->isChecked()) { - maintainAspectRatio(-1); - } + if (chkAspectRatio->isChecked()) { + maintainAspectRatio(-1); + } } - //------------------------------------------------------------------------------------------------------------------------------------------------- - void qTabPlot::maintainAspectRatio(int axis) { #ifdef VERBOSE - cout << "Maintaining Aspect Ratio" << endl; + cout << "Maintaining Aspect Ratio" << endl; #endif - disconnect(chkXMin, SIGNAL(toggled(bool)), this, SLOT(EnableXRange())); - disconnect(chkXMax, SIGNAL(toggled(bool)), this, SLOT(EnableXRange())); - disconnect(chkYMin, SIGNAL(toggled(bool)), this, SLOT(EnableYRange())); - disconnect(chkYMax, SIGNAL(toggled(bool)), this, SLOT(EnableYRange())); - disconnect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); - disconnect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); - disconnect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); - disconnect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + disconnect(chkXMin, SIGNAL(toggled(bool)), this, SLOT(EnableXRange())); + disconnect(chkXMax, SIGNAL(toggled(bool)), this, SLOT(EnableXRange())); + disconnect(chkYMin, SIGNAL(toggled(bool)), this, SLOT(EnableYRange())); + disconnect(chkYMax, SIGNAL(toggled(bool)), this, SLOT(EnableYRange())); + disconnect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); + disconnect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); + disconnect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + disconnect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); - double ranges[4]; - //get previous plot limits - ranges[qDefs::XMINIMUM] = myPlot->GetXMinimum(); - ranges[qDefs::XMAXIMUM] = myPlot->GetXMaximum(); - ranges[qDefs::YMINIMUM] = myPlot->GetYMinimum(); - ranges[qDefs::YMAXIMUM] = myPlot->GetYMaximum(); + double ranges[4]; + //get previous plot limits + ranges[qDefs::XMINIMUM] = myPlot->GetXMinimum(); + ranges[qDefs::XMAXIMUM] = myPlot->GetXMaximum(); + ranges[qDefs::YMINIMUM] = myPlot->GetYMinimum(); + ranges[qDefs::YMAXIMUM] = myPlot->GetYMaximum(); #ifdef VERYVERBOSE - cprintf(BLUE,"ideal values: xmin:%f, xmax:%f ymin:%f ymax:%f\n",ranges[qDefs::XMINIMUM],ranges[qDefs::XMAXIMUM],ranges[qDefs::YMINIMUM],ranges[qDefs::YMAXIMUM]); + cprintf(BLUE, "ideal values: xmin:%f, xmax:%f ymin:%f ymax:%f\n", ranges[qDefs::XMINIMUM], ranges[qDefs::XMAXIMUM], ranges[qDefs::YMINIMUM], ranges[qDefs::YMAXIMUM]); #endif - double idealAspectratio = (ranges[qDefs::XMAXIMUM] - ranges[qDefs::XMINIMUM]) / (ranges[qDefs::YMAXIMUM] - ranges[qDefs::YMINIMUM]); + double idealAspectratio = (ranges[qDefs::XMAXIMUM] - ranges[qDefs::XMINIMUM]) / (ranges[qDefs::YMAXIMUM] - ranges[qDefs::YMINIMUM]); - // enable all - chkXMin->setChecked(true); dispXMin->setEnabled(true); - chkXMax->setChecked(true); dispXMax->setEnabled(true); - chkYMin->setChecked(true); dispYMin->setEnabled(true); - chkYMax->setChecked(true); dispYMax->setEnabled(true); + // enable all + chkXMin->setChecked(true); + dispXMin->setEnabled(true); + chkXMax->setChecked(true); + dispXMax->setEnabled(true); + chkYMin->setChecked(true); + dispYMin->setEnabled(true); + chkYMax->setChecked(true); + dispYMax->setEnabled(true); - // if any empty, set it to previous plots boundaries - if (dispXMin->text().isEmpty()) dispXMin->setText(QString::number(myPlot->GetXMinimum())); - if (dispXMax->text().isEmpty()) dispXMax->setText(QString::number(myPlot->GetXMaximum())); - if (dispYMin->text().isEmpty()) dispYMin->setText(QString::number(myPlot->GetYMinimum())); - if (dispYMax->text().isEmpty()) dispYMax->setText(QString::number(myPlot->GetYMaximum())); + // if any empty, set it to previous plots boundaries + if (dispXMin->text().isEmpty()) + dispXMin->setText(QString::number(myPlot->GetXMinimum())); + if (dispXMax->text().isEmpty()) + dispXMax->setText(QString::number(myPlot->GetXMaximum())); + if (dispYMin->text().isEmpty()) + dispYMin->setText(QString::number(myPlot->GetYMinimum())); + if (dispYMax->text().isEmpty()) + dispYMax->setText(QString::number(myPlot->GetYMaximum())); - //get actual limits - ranges[qDefs::XMINIMUM] = dispXMin->text().toDouble(); - ranges[qDefs::XMAXIMUM] = dispXMax->text().toDouble(); - ranges[qDefs::YMINIMUM] = dispYMin->text().toDouble(); - ranges[qDefs::YMAXIMUM] = dispYMax->text().toDouble(); + //get actual limits + ranges[qDefs::XMINIMUM] = dispXMin->text().toDouble(); + ranges[qDefs::XMAXIMUM] = dispXMax->text().toDouble(); + ranges[qDefs::YMINIMUM] = dispYMin->text().toDouble(); + ranges[qDefs::YMAXIMUM] = dispYMax->text().toDouble(); #ifdef VERYVERBOSE - cprintf(BLUE,"new limits: xmin:%f, xmax:%f ymin:%f ymax:%f\n",ranges[qDefs::XMINIMUM],ranges[qDefs::XMAXIMUM],ranges[qDefs::YMINIMUM],ranges[qDefs::YMAXIMUM]); + cprintf(BLUE, "new limits: xmin:%f, xmax:%f ymin:%f ymax:%f\n", ranges[qDefs::XMINIMUM], ranges[qDefs::XMAXIMUM], ranges[qDefs::YMINIMUM], ranges[qDefs::YMAXIMUM]); #endif - // calcualte new aspect ratio - double newAspectRatio = (ranges[qDefs::XMAXIMUM] - ranges[qDefs::XMINIMUM]) / (ranges[qDefs::YMAXIMUM] - ranges[qDefs::YMINIMUM]); + // calcualte new aspect ratio + double newAspectRatio = (ranges[qDefs::XMAXIMUM] - ranges[qDefs::XMINIMUM]) / (ranges[qDefs::YMAXIMUM] - ranges[qDefs::YMINIMUM]); - // if not ideal aspect ratio - if (newAspectRatio != idealAspectratio) { + // if not ideal aspect ratio + if (newAspectRatio != idealAspectratio) { - // find the larger difference - if (axis == -1) { - if ((ranges[qDefs::XMAXIMUM] - ranges[qDefs::XMINIMUM]) > (ranges[qDefs::YMAXIMUM] - ranges[qDefs::YMINIMUM])) { - //change x - axis = 0; - } else { - //change y - axis = 1; - } - } + // find the larger difference + if (axis == -1) { + if ((ranges[qDefs::XMAXIMUM] - ranges[qDefs::XMINIMUM]) > (ranges[qDefs::YMAXIMUM] - ranges[qDefs::YMINIMUM])) { + //change x + axis = 0; + } else { + //change y + axis = 1; + } + } - // if x changed: y adjusted, y changed: x adjusted, aspect ratio clicked: larger one adjusted - double newval=0; - switch(axis) { - case 0: - //change x - newval = idealAspectratio * (ranges[qDefs::YMAXIMUM] - ranges[qDefs::YMINIMUM]) + ranges[qDefs::XMINIMUM]; - if (newval <= myPlot->GetXMaximum()) { - dispXMax->setText(QString::number(newval)); + // if x changed: y adjusted, y changed: x adjusted, aspect ratio clicked: larger one adjusted + double newval = 0; + switch (axis) { + case 0: + //change x + newval = idealAspectratio * (ranges[qDefs::YMAXIMUM] - ranges[qDefs::YMINIMUM]) + ranges[qDefs::XMINIMUM]; + if (newval <= myPlot->GetXMaximum()) { + dispXMax->setText(QString::number(newval)); #ifdef VERYVERBOSE - cprintf(BLUE,"new xmax: %f\n",newval); + cprintf(BLUE, "new xmax: %f\n", newval); #endif - } else { - newval = ranges[qDefs::XMAXIMUM] - (idealAspectratio * (ranges[qDefs::YMAXIMUM] - ranges[qDefs::YMINIMUM])); - dispXMin->setText(QString::number(newval)); + } else { + newval = ranges[qDefs::XMAXIMUM] - (idealAspectratio * (ranges[qDefs::YMAXIMUM] - ranges[qDefs::YMINIMUM])); + dispXMin->setText(QString::number(newval)); #ifdef VERYVERBOSE - cprintf(BLUE,"new xmin: %f\n",newval); + cprintf(BLUE, "new xmin: %f\n", newval); #endif - } + } - break; - case 1: - // change y - newval = ((ranges[qDefs::XMAXIMUM] - ranges[qDefs::XMINIMUM]) / idealAspectratio) + ranges[qDefs::YMINIMUM]; - if (newval <= myPlot->GetYMaximum()) { - dispYMax->setText(QString::number(newval)); - //#ifdef VERYVERBOSE - cprintf(BLUE,"new ymax: %f\n",newval); - //#endif - } else { - newval = ranges[qDefs::YMAXIMUM] - ((ranges[qDefs::XMAXIMUM] - ranges[qDefs::XMINIMUM]) / idealAspectratio); - dispYMin->setText(QString::number(newval)); + break; + case 1: + // change y + newval = ((ranges[qDefs::XMAXIMUM] - ranges[qDefs::XMINIMUM]) / idealAspectratio) + ranges[qDefs::YMINIMUM]; + if (newval <= myPlot->GetYMaximum()) { + dispYMax->setText(QString::number(newval)); + //#ifdef VERYVERBOSE + cprintf(BLUE, "new ymax: %f\n", newval); + //#endif + } else { + newval = ranges[qDefs::YMAXIMUM] - ((ranges[qDefs::XMAXIMUM] - ranges[qDefs::XMINIMUM]) / idealAspectratio); + dispYMin->setText(QString::number(newval)); #ifdef VERYVERBOSE - cprintf(BLUE,"new ymin: %f\n",newval); + cprintf(BLUE, "new ymin: %f\n", newval); #endif - } - break; - default: - break; - } - } + } + break; + default: + break; + } + } - connect(chkXMin, SIGNAL(toggled(bool)), this, SLOT(EnableXRange())); - connect(chkXMax, SIGNAL(toggled(bool)), this, SLOT(EnableXRange())); - connect(chkYMin, SIGNAL(toggled(bool)), this, SLOT(EnableYRange())); - connect(chkYMax, SIGNAL(toggled(bool)), this, SLOT(EnableYRange())); - connect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); - connect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); - connect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); - connect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + connect(chkXMin, SIGNAL(toggled(bool)), this, SLOT(EnableXRange())); + connect(chkXMax, SIGNAL(toggled(bool)), this, SLOT(EnableXRange())); + connect(chkYMin, SIGNAL(toggled(bool)), this, SLOT(EnableYRange())); + connect(chkYMax, SIGNAL(toggled(bool)), this, SLOT(EnableYRange())); + connect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); + connect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); + connect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + connect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); - // disable mouse zooming if any checked - myPlot->DisableZoom(true); - emit DisableZoomSignal(true); + // disable mouse zooming if any checked + myPlot->DisableZoom(true); + emit DisableZoomSignal(true); - // set XY values in plot - myPlot->SetXYRangeValues(dispXMin->text().toDouble(),qDefs::XMINIMUM); - myPlot->SetXYRangeValues(dispXMax->text().toDouble(),qDefs::XMAXIMUM); - myPlot->SetXYRangeValues(dispYMin->text().toDouble(),qDefs::YMINIMUM); - myPlot->SetXYRangeValues(dispYMax->text().toDouble(),qDefs::YMAXIMUM); + // set XY values in plot + myPlot->SetXYRangeValues(dispXMin->text().toDouble(), qDefs::XMINIMUM); + myPlot->SetXYRangeValues(dispXMax->text().toDouble(), qDefs::XMAXIMUM); + myPlot->SetXYRangeValues(dispYMin->text().toDouble(), qDefs::YMINIMUM); + myPlot->SetXYRangeValues(dispYMax->text().toDouble(), qDefs::YMAXIMUM); + myPlot->IsXYRangeValues(true, qDefs::XMINIMUM); + myPlot->IsXYRangeValues(true, qDefs::XMAXIMUM); + myPlot->IsXYRangeValues(true, qDefs::YMINIMUM); + myPlot->IsXYRangeValues(true, qDefs::YMAXIMUM); - myPlot->IsXYRangeValues(true,qDefs::XMINIMUM); - myPlot->IsXYRangeValues(true,qDefs::XMAXIMUM); - myPlot->IsXYRangeValues(true,qDefs::YMINIMUM); - myPlot->IsXYRangeValues(true,qDefs::YMAXIMUM); - - // To remind the updateplot in qdrawplot to set range after updating plot - myPlot->SetXYRange(true); + // To remind the updateplot in qdrawplot to set range after updating plot + myPlot->SetXYRange(true); } - //------------------------------------------------------------------------------------------------------------------------------------------------- -void qTabPlot::EnableXRange(){ +void qTabPlot::EnableXRange() { #ifdef VERBOSE - cout << "Enable X Axis Range" << endl; + cout << "Enable X Axis Range" << endl; #endif - // keeping aspect ratio - if (chkAspectRatio->isChecked()) { - maintainAspectRatio(1); - return; - } - disconnect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); - disconnect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); + // keeping aspect ratio + if (chkAspectRatio->isChecked()) { + maintainAspectRatio(1); + return; + } + disconnect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); + disconnect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); - // enable/disable lineedit - if(chkXMin->isChecked()) { - dispXMin->setEnabled(true); - // if any empty, set it to previous plots boundaries - if (dispXMin->text().isEmpty()) - dispXMin->setText(QString::number(myPlot->GetXMinimum())); - } else { - dispXMin->setEnabled(false); - } - // enable/disable lineedit - if(chkXMax->isChecked()) { - dispXMax->setEnabled(true); - // if any empty, set it to previous plots boundaries - if (dispXMax->text().isEmpty()) - dispXMax->setText(QString::number(myPlot->GetXMaximum())); - } else { - dispXMax->setEnabled(false); - } + // enable/disable lineedit + if (chkXMin->isChecked()) { + dispXMin->setEnabled(true); + // if any empty, set it to previous plots boundaries + if (dispXMin->text().isEmpty()) + dispXMin->setText(QString::number(myPlot->GetXMinimum())); + } else { + dispXMin->setEnabled(false); + } + // enable/disable lineedit + if (chkXMax->isChecked()) { + dispXMax->setEnabled(true); + // if any empty, set it to previous plots boundaries + if (dispXMax->text().isEmpty()) + dispXMax->setText(QString::number(myPlot->GetXMaximum())); + } else { + dispXMax->setEnabled(false); + } - connect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); - connect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); + connect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); + connect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); - EnableRange(); + EnableRange(); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabPlot::EnableYRange(){ +void qTabPlot::EnableYRange() { #ifdef VERBOSE - cout << "Enable Y Axis Range" << endl; + cout << "Enable Y Axis Range" << endl; #endif - // keeping aspect ratio - if (chkAspectRatio->isChecked()) { - maintainAspectRatio(0); - return; - } - disconnect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); - disconnect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + // keeping aspect ratio + if (chkAspectRatio->isChecked()) { + maintainAspectRatio(0); + return; + } + disconnect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + disconnect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); - // enable/disable lineedit - if(chkYMin->isChecked()) { - dispYMin->setEnabled(true); - // if any empty, set it to previous plots boundaries - if (dispYMin->text().isEmpty()) - dispYMin->setText(QString::number(myPlot->GetYMinimum())); - } else { - dispYMin->setEnabled(false); - } - // enable/disable lineedit - if(chkYMax->isChecked()) { - dispYMax->setEnabled(true); - // if any empty, set it to previous plots boundaries - if (dispYMax->text().isEmpty()) - dispYMax->setText(QString::number(myPlot->GetYMaximum())); - } else { - dispYMax->setEnabled(false); - } + // enable/disable lineedit + if (chkYMin->isChecked()) { + dispYMin->setEnabled(true); + // if any empty, set it to previous plots boundaries + if (dispYMin->text().isEmpty()) + dispYMin->setText(QString::number(myPlot->GetYMinimum())); + } else { + dispYMin->setEnabled(false); + } + // enable/disable lineedit + if (chkYMax->isChecked()) { + dispYMax->setEnabled(true); + // if any empty, set it to previous plots boundaries + if (dispYMax->text().isEmpty()) + dispYMax->setText(QString::number(myPlot->GetYMaximum())); + } else { + dispYMax->setEnabled(false); + } - connect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); - connect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + connect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + connect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); - EnableRange(); + EnableRange(); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabPlot::EnableRange(){ +void qTabPlot::EnableRange() { #ifdef VERBOSE - cout << "Enable Axes Range" << endl; + cout << "Enable Axes Range" << endl; #endif - // disable mouse zooming if any checked - bool disableZoom= false; - if(chkYMin->isChecked() || chkYMax->isChecked() || chkYMin->isChecked() || chkYMax->isChecked()) - disableZoom = true; - emit DisableZoomSignal(disableZoom); - SetAxesRange(); + // disable mouse zooming if any checked + bool disableZoom = false; + if (chkYMin->isChecked() || chkYMax->isChecked() || chkYMin->isChecked() || chkYMax->isChecked()) + disableZoom = true; + emit DisableZoomSignal(disableZoom); + SetAxesRange(); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabPlot::SetXAxisRange(){ +void qTabPlot::SetXAxisRange() { #ifdef VERBOSE - cout << "Setting X Axis Range" << endl; + cout << "Setting X Axis Range" << endl; #endif - disconnect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); - disconnect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); + disconnect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); + disconnect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); - if (dispXMin->text().toDouble() < myPlot->GetXMinimum()) { - qDefs::Message(qDefs::WARNING,"Outside Plot Range","qTabPlot::CheckZRange"); - dispXMin->setText(QString::number(myPlot->GetXMinimum())); - } + if (dispXMin->text().toDouble() < myPlot->GetXMinimum()) { + qDefs::Message(qDefs::WARNING, "Outside Plot Range", "qTabPlot::CheckZRange"); + dispXMin->setText(QString::number(myPlot->GetXMinimum())); + } - if (dispXMax->text().toDouble() > myPlot->GetXMaximum()) { - qDefs::Message(qDefs::WARNING,"Outside Plot Range","qTabPlot::CheckZRange"); - dispXMax->setText(QString::number(myPlot->GetXMaximum())); - } + if (dispXMax->text().toDouble() > myPlot->GetXMaximum()) { + qDefs::Message(qDefs::WARNING, "Outside Plot Range", "qTabPlot::CheckZRange"); + dispXMax->setText(QString::number(myPlot->GetXMaximum())); + } - connect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); - connect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); + connect(dispXMin, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); + connect(dispXMax, SIGNAL(editingFinished()), this, SLOT(SetXAxisRange())); - // keeping aspect ratio - if (chkAspectRatio->isChecked()) { - maintainAspectRatio(1); - return; - } + // keeping aspect ratio + if (chkAspectRatio->isChecked()) { + maintainAspectRatio(1); + return; + } - SetAxesRange(); + SetAxesRange(); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabPlot::SetYAxisRange(){ +void qTabPlot::SetYAxisRange() { #ifdef VERBOSE - cout << "Setting Y Axis Range" << endl; + cout << "Setting Y Axis Range" << endl; #endif - disconnect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); - disconnect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + disconnect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + disconnect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); - if (dispYMin->text().toDouble() < myPlot->GetYMinimum()) { - qDefs::Message(qDefs::WARNING,"Outside Plot Range","qTabPlot::CheckZRange"); - dispYMin->setText(QString::number(myPlot->GetYMinimum())); - } + if (dispYMin->text().toDouble() < myPlot->GetYMinimum()) { + qDefs::Message(qDefs::WARNING, "Outside Plot Range", "qTabPlot::CheckZRange"); + dispYMin->setText(QString::number(myPlot->GetYMinimum())); + } - if (dispYMax->text().toDouble() > myPlot->GetYMaximum()) { - qDefs::Message(qDefs::WARNING,"Outside Plot Range","qTabPlot::CheckZRange"); - dispYMax->setText(QString::number(myPlot->GetYMaximum())); - } + if (dispYMax->text().toDouble() > myPlot->GetYMaximum()) { + qDefs::Message(qDefs::WARNING, "Outside Plot Range", "qTabPlot::CheckZRange"); + dispYMax->setText(QString::number(myPlot->GetYMaximum())); + } - connect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); - connect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + connect(dispYMin, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + connect(dispYMax, SIGNAL(editingFinished()), this, SLOT(SetYAxisRange())); + // keeping aspect ratio + if (chkAspectRatio->isChecked()) { + maintainAspectRatio(0); + return; + } - // keeping aspect ratio - if (chkAspectRatio->isChecked()) { - maintainAspectRatio(0); - return; - } - - SetAxesRange(); + SetAxesRange(); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabPlot::SetAxesRange(){ +void qTabPlot::SetAxesRange() { #ifdef VERBOSE - cout << "Setting Axes Range" << endl; + cout << "Setting Axes Range" << endl; #endif - // x min - if (dispXMin->isEnabled()) { - myPlot->SetXYRangeValues(dispXMin->text().toDouble(),qDefs::XMINIMUM); - myPlot->IsXYRangeValues(true,qDefs::XMINIMUM); - } - else - myPlot->IsXYRangeValues(false,qDefs::XMINIMUM); - // x max - if (dispXMax->isEnabled()) { - myPlot->SetXYRangeValues(dispXMax->text().toDouble(),qDefs::XMAXIMUM); - myPlot->IsXYRangeValues(true,qDefs::XMAXIMUM); - } - else - myPlot->IsXYRangeValues(false,qDefs::XMAXIMUM); - // y min - if (dispYMin->isEnabled()) { - myPlot->SetXYRangeValues(dispYMin->text().toDouble(),qDefs::YMINIMUM); - myPlot->IsXYRangeValues(true,qDefs::YMINIMUM); - } - else - myPlot->IsXYRangeValues(false,qDefs::YMINIMUM); - // y max - if (dispYMax->isEnabled()) { - myPlot->SetXYRangeValues(dispYMax->text().toDouble(),qDefs::YMAXIMUM); - myPlot->IsXYRangeValues(true,qDefs::YMAXIMUM); - } - else - myPlot->IsXYRangeValues(false,qDefs::YMAXIMUM); + // x min + if (dispXMin->isEnabled()) { + myPlot->SetXYRangeValues(dispXMin->text().toDouble(), qDefs::XMINIMUM); + myPlot->IsXYRangeValues(true, qDefs::XMINIMUM); + } else + myPlot->IsXYRangeValues(false, qDefs::XMINIMUM); + // x max + if (dispXMax->isEnabled()) { + myPlot->SetXYRangeValues(dispXMax->text().toDouble(), qDefs::XMAXIMUM); + myPlot->IsXYRangeValues(true, qDefs::XMAXIMUM); + } else + myPlot->IsXYRangeValues(false, qDefs::XMAXIMUM); + // y min + if (dispYMin->isEnabled()) { + myPlot->SetXYRangeValues(dispYMin->text().toDouble(), qDefs::YMINIMUM); + myPlot->IsXYRangeValues(true, qDefs::YMINIMUM); + } else + myPlot->IsXYRangeValues(false, qDefs::YMINIMUM); + // y max + if (dispYMax->isEnabled()) { + myPlot->SetXYRangeValues(dispYMax->text().toDouble(), qDefs::YMAXIMUM); + myPlot->IsXYRangeValues(true, qDefs::YMAXIMUM); + } else + myPlot->IsXYRangeValues(false, qDefs::YMAXIMUM); - // To remind the updateplot in qdrawplot to set range after updating plot - myPlot->SetXYRange(true); + // To remind the updateplot in qdrawplot to set range after updating plot + myPlot->SetXYRange(true); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabPlot::SetZRange(){ - emit ResetZMinZMaxSignal( - (chkZMin->isChecked() && CheckZRange(dispZMin->text())), - (chkZMax->isChecked() && CheckZRange(dispZMax->text())), - dispZMin->text().toDouble(), - dispZMax->text().toDouble()); +void qTabPlot::SetZRange() { + emit ResetZMinZMaxSignal( + (chkZMin->isChecked() && CheckZRange(dispZMin->text())), + (chkZMax->isChecked() && CheckZRange(dispZMax->text())), + dispZMin->text().toDouble(), + dispZMax->text().toDouble()); } - //------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabPlot::EnableZRange() { -void qTabPlot::EnableZRange(){ + disconnect(dispZMin, SIGNAL(editingFinished()), this, SLOT(SetZRange())); + disconnect(dispZMax, SIGNAL(editingFinished()), this, SLOT(SetZRange())); - disconnect(dispZMin, SIGNAL(editingFinished()), this, SLOT(SetZRange())); - disconnect(dispZMax, SIGNAL(editingFinished()), this, SLOT(SetZRange())); + dispZMin->setEnabled(chkZMin->isChecked()); + dispZMax->setEnabled(chkZMax->isChecked()); + emit ResetZMinZMaxSignal( + (chkZMin->isChecked() && CheckZRange(dispZMin->text())), + (chkZMax->isChecked() && CheckZRange(dispZMax->text())), + dispZMin->text().toDouble(), + dispZMax->text().toDouble()); - dispZMin->setEnabled(chkZMin->isChecked()); - dispZMax->setEnabled(chkZMax->isChecked()); - emit ResetZMinZMaxSignal( - (chkZMin->isChecked() && CheckZRange(dispZMin->text())), - (chkZMax->isChecked() && CheckZRange(dispZMax->text())), - dispZMin->text().toDouble(), - dispZMax->text().toDouble()); - - connect(dispZMin, SIGNAL(editingFinished()), this, SLOT(SetZRange())); - connect(dispZMax, SIGNAL(editingFinished()), this, SLOT(SetZRange())); + connect(dispZMin, SIGNAL(editingFinished()), this, SLOT(SetZRange())); + connect(dispZMax, SIGNAL(editingFinished()), this, SLOT(SetZRange())); } - //------------------------------------------------------------------------------------------------------------------------------------------------- +bool qTabPlot::CheckZRange(QString value) { + if (value.isEmpty()) + return false; -bool qTabPlot::CheckZRange(QString value){ - if(value.isEmpty()) - return false; + bool ok; + value.toDouble(&ok); + if (!ok) { + qDefs::Message(qDefs::WARNING, "Check Z Range
" + "Zmin and Zmax should be in double", + "qTabPlot::CheckZRange"); + return false; + } - bool ok; - value.toDouble(&ok); - if(!ok) { - qDefs::Message(qDefs::WARNING,"Check Z Range
" - "Zmin and Zmax should be in double","qTabPlot::CheckZRange"); - return false; - } - - return true; + return true; } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabPlot::SetPlot(){ +void qTabPlot::SetPlot() { #ifdef VERBOSE - cout << "Entering Set Plot()" ; + cout << "Entering Set Plot()"; #endif - if(radioNoPlot->isChecked()){ - cout << " - No Plot" << endl; + if (radioNoPlot->isChecked()) { + cout << " - No Plot" << endl; - boxScan->show(); - boxHistogram->hide(); - myPlot->EnablePlot(false); - boxSnapshot->setEnabled(false); - boxSave->setEnabled(false); - boxFrequency->setEnabled(false); - boxPlotAxis->setEnabled(false); - boxScan->setEnabled(false); + boxScan->show(); + boxHistogram->hide(); + myPlot->EnablePlot(false); + boxSnapshot->setEnabled(false); + boxSave->setEnabled(false); + boxFrequency->setEnabled(false); + boxPlotAxis->setEnabled(false); + boxScan->setEnabled(false); - }else if(radioDataGraph->isChecked()){ - cout << " - DataGraph" << endl; + } else if (radioDataGraph->isChecked()) { + cout << " - DataGraph" << endl; - boxScan->show(); - boxHistogram->hide(); - myPlot->EnablePlot(true); - Select1DPlot(isOriginallyOneD); - boxSnapshot->setEnabled(true); - boxSave->setEnabled(true); - boxFrequency->setEnabled(true); - boxPlotAxis->setEnabled(true); - if(!myPlot->isRunning()) - EnableScanBox(); - // To remind the updateplot in qdrawplot to set range after updating plot - myPlot->SetXYRange(true); - } - else{ - //histogram and 2d scans dont work - if(boxScan->isChecked()){ - qDefs::Message(qDefs::WARNING,"Histogram cannot be used together with 2D Scan Plots.
" - "Uncheck 2D Scan plots to plot Histograms", "qTabPlot::SetPlot"); - radioDataGraph->setChecked(true); - boxScan->show(); - boxHistogram->hide(); - return; - } + boxScan->show(); + boxHistogram->hide(); + myPlot->EnablePlot(true); + Select1DPlot(isOriginallyOneD); + boxSnapshot->setEnabled(true); + boxSave->setEnabled(true); + boxFrequency->setEnabled(true); + boxPlotAxis->setEnabled(true); + // if(!myPlot->isRunning()) + // EnableScanBox(); + // To remind the updateplot in qdrawplot to set range after updating plot + myPlot->SetXYRange(true); + } else { + //histogram and 2d scans dont work + if (boxScan->isChecked()) { + qDefs::Message(qDefs::WARNING, "Histogram cannot be used together with 2D Scan Plots.
" + "Uncheck 2D Scan plots to plot Histograms", + "qTabPlot::SetPlot"); + radioDataGraph->setChecked(true); + boxScan->show(); + boxHistogram->hide(); + return; + } - cout << " - Histogram" << endl; + cout << " - Histogram" << endl; - if(radioHistIntensity->isChecked()){ - pageHistogram->setEnabled(true); - pageHistogram_2->setEnabled(true); - }else{ - pageHistogram->setEnabled(false); - pageHistogram_2->setEnabled(false); - } - boxScan->hide(); - boxHistogram->show(); - myPlot->EnablePlot(true); - Select1DPlot(isOriginallyOneD); - boxSnapshot->setEnabled(true); - boxSave->setEnabled(true); - boxFrequency->setEnabled(true); - boxPlotAxis->setEnabled(true); - if(!myPlot->isRunning()) - EnableScanBox(); + if (radioHistIntensity->isChecked()) { + pageHistogram->setEnabled(true); + pageHistogram_2->setEnabled(true); + } else { + pageHistogram->setEnabled(false); + pageHistogram_2->setEnabled(false); + } + boxScan->hide(); + boxHistogram->show(); + myPlot->EnablePlot(true); + Select1DPlot(isOriginallyOneD); + boxSnapshot->setEnabled(true); + boxSave->setEnabled(true); + boxFrequency->setEnabled(true); + boxPlotAxis->setEnabled(true); + // if(!myPlot->isRunning()) + // EnableScanBox(); - //qDefs::Message(qDefs::INFORMATION,"Please check the Plot Histogram Options below " - // "before Starting Acquitision","qTabPlot::SetPlot"); - } + //qDefs::Message(qDefs::INFORMATION,"Please check the Plot Histogram Options below " + // "before Starting Acquitision","qTabPlot::SetPlot"); + } } - //------------------------------------------------------------------------------------------------------------------------------------------------- -void qTabPlot::SetFrequency(){ +void qTabPlot::SetFrequency() { #ifdef VERBOSE - cout << "Setting Plot Interval Frequency" << endl; + cout << "Setting Plot Interval Frequency" << endl; #endif - disconnect(comboTimeGapUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - disconnect(spinTimeGap, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - disconnect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - disconnect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - double timeMS,acqPeriodMS; - double minPlotTimer = myPlot->GetMinimumPlotTimer(); - char cMin[200]; - sprintf(cMin,"%f ms",minPlotTimer); + disconnect(comboTimeGapUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + disconnect(spinTimeGap, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + disconnect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + disconnect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + double timeMS, acqPeriodMS; + double minPlotTimer = myPlot->GetMinimumPlotTimer(); + char cMin[200]; + sprintf(cMin, "%f ms", minPlotTimer); + acqPeriodMS = (myDet->setTimer(slsDetectorDefs::FRAME_PERIOD, -1) * (1E-6)); + //if period is 0, check exptime, if that is also 0, give warning and set to min timer + if (acqPeriodMS == 0) { + acqPeriodMS = (myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME, -1) * (1E-6)); - acqPeriodMS = (myDet->setTimer(slsDetectorDefs::FRAME_PERIOD,-1)*(1E-6)); - //if period is 0, check exptime, if that is also 0, give warning and set to min timer - if(acqPeriodMS==0){ - acqPeriodMS = (myDet->setTimer(slsDetectorDefs::ACQUISITION_TIME,-1)*(1E-6)); + if (acqPeriodMS == 0) { + //to reduce the warnings displayed + if ((comboFrequency->currentIndex() == 0) && (spinTimeGap->value() == minPlotTimer)) + ; + else + qDefs::Message(qDefs::WARNING, "Interval between Plots:
" + "Every Nth Image: Period betwen Frames and Exposure Time cannot both be 0 ms.
" + "Resetting to minimum plotting time interval", + "qTabPlot::SetFrequency"); + comboFrequency->setCurrentIndex(0); + stackedLayout->setCurrentIndex(comboFrequency->currentIndex()); + spinTimeGap->setValue(minPlotTimer); + comboTimeGapUnit->setCurrentIndex(qDefs::MILLISECONDS); + timeMS = minPlotTimer; + //This is done so that its known which one was selected + myPlot->SetFrameFactor(0); + // Setting the timer value(ms) between plots + myPlot->SetPlotTimer(timeMS); - if(acqPeriodMS==0){ - //to reduce the warnings displayed - if((comboFrequency->currentIndex() == 0) && (spinTimeGap->value() == minPlotTimer)); - else - qDefs::Message(qDefs::WARNING,"Interval between Plots:
" - "Every Nth Image: Period betwen Frames and Exposure Time cannot both be 0 ms.
" - "Resetting to minimum plotting time interval","qTabPlot::SetFrequency"); - comboFrequency->setCurrentIndex(0); - stackedLayout->setCurrentIndex(comboFrequency->currentIndex()); - spinTimeGap->setValue(minPlotTimer); - comboTimeGapUnit->setCurrentIndex(qDefs::MILLISECONDS); - timeMS=minPlotTimer; - //This is done so that its known which one was selected - myPlot->SetFrameFactor(0); - // Setting the timer value(ms) between plots - myPlot->SetPlotTimer(timeMS); + connect(comboTimeGapUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + connect(spinTimeGap, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + qDefs::checkErrorMessage(myDet, "qTabPlot::SetFrequency"); + return; + } + } - connect(comboTimeGapUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - connect(spinTimeGap, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - qDefs::checkErrorMessage(myDet,"qTabPlot::SetFrequency"); - return; - } - } + stackedLayout->setCurrentIndex(comboFrequency->currentIndex()); + switch (comboFrequency->currentIndex()) { + case 0: + // Get the time interval from gui in ms + timeMS = (qDefs::getNSTime((qDefs::timeUnit)comboTimeGapUnit->currentIndex(), spinTimeGap->value())) / (1e6); + if ((int)timeMS == 0) { + qDefs::Message(qDefs::WARNING, "Interval between Plots:
" + "Time Interval must be atleast >= 1 ms. Resetting to minimum plotting time interval.", + "qTabPlot::SetFrequency"); + spinTimeGap->setValue(minPlotTimer); + comboTimeGapUnit->setCurrentIndex(qDefs::MILLISECONDS); + timeMS = minPlotTimer; + } - stackedLayout->setCurrentIndex(comboFrequency->currentIndex()); - switch(comboFrequency->currentIndex()){ - case 0: - // Get the time interval from gui in ms - timeMS = (qDefs::getNSTime((qDefs::timeUnit)comboTimeGapUnit->currentIndex(),spinTimeGap->value()))/(1e6); + //show red if min intervalInterval between Plots: You might be losing Images!","Plot"); + boxFrequency->setPalette(*red); + boxFrequency->setTitle("Interval between Plots*"); + QString errTip = intervalTip + QString("

" + "Time Interval Condition: min of ") + + QString("%1").arg(minPlotTimer) + + QString("ms.
You might be losing images!
"); + boxFrequency->setToolTip(errTip); + } + //show red if acqPeriodInterval between Plots: You might be losing Images!","Plot"); + boxFrequency->setPalette(*red); + boxFrequency->setTitle("Interval between Plots*"); + QString errTip = intervalTip + QString("

" + "Time Interval Acquisition Period should be >= Time Interval between plots.
" + "You might be losing images!
"); + boxFrequency->setToolTip(errTip); + } + //correct + else { + boxFrequency->setPalette(boxSnapshot->palette()); + boxFrequency->setTitle("Interval between Plots"); + boxFrequency->setToolTip(intervalTip); + } - if((int)timeMS==0){ - qDefs::Message(qDefs::WARNING,"Interval between Plots:
" - "Time Interval must be atleast >= 1 ms. Resetting to minimum plotting time interval.","qTabPlot::SetFrequency"); - spinTimeGap->setValue(minPlotTimer); - comboTimeGapUnit->setCurrentIndex(qDefs::MILLISECONDS); - timeMS=minPlotTimer; - } - - - //show red if min intervalInterval between Plots: You might be losing Images!","Plot"); - boxFrequency->setPalette(*red); - boxFrequency->setTitle("Interval between Plots*"); - QString errTip = intervalTip + QString("

" - "Time Interval Condition: min of ")+QString("%1").arg(minPlotTimer)+ - QString("ms.
You might be losing images!
"); - boxFrequency->setToolTip(errTip); - } - //show red if acqPeriodInterval between Plots: You might be losing Images!","Plot"); - boxFrequency->setPalette(*red); - boxFrequency->setTitle("Interval between Plots*"); - QString errTip = intervalTip + QString("

" - "Time Interval Acquisition Period should be >= Time Interval between plots.
" - "You might be losing images!
"); - boxFrequency->setToolTip(errTip); - } - //correct - else{ - boxFrequency->setPalette(boxSnapshot->palette()); - boxFrequency->setTitle("Interval between Plots"); - boxFrequency->setToolTip(intervalTip); - } - - //This is done so that its known which one was selected - myPlot->SetFrameFactor(0); - // Setting the timer value(ms) between plots - myPlot->SetPlotTimer(timeMS); + //This is done so that its known which one was selected + myPlot->SetFrameFactor(0); + // Setting the timer value(ms) between plots + myPlot->SetPlotTimer(timeMS); #ifdef VERBOSE - cout << "Plotting Frequency: Time Gap - " << spinTimeGap->value() << qDefs::getUnitString((qDefs::timeUnit)comboTimeGapUnit->currentIndex()) << endl; + cout << "Plotting Frequency: Time Gap - " << spinTimeGap->value() << qDefs::getUnitString((qDefs::timeUnit)comboTimeGapUnit->currentIndex()) << endl; #endif - break; + break; + case 1: + // gets the acq period * number of nth frames + timeMS = (spinNthFrame->value()) * acqPeriodMS; + //Show red to make sure the period between plotting is not less than minimum plot timer in ms + if (timeMS < minPlotTimer) { + int minFrame = (int)(ceil)(minPlotTimer / acqPeriodMS); + //qDefs::Message(qDefs::WARNING,"Interval between Plots: You might be losing Images!","Plot"); + boxFrequency->setPalette(*red); + boxFrequency->setTitle("Interval between Plots*"); + QString errTip = intervalTip + QString("

" + "Every nth Image Condition: min nth Image for this time period: ") + + QString("%1").arg(minFrame) + + QString(".
You might be losing images!
"); + boxFrequency->setToolTip(errTip); + } else { + boxFrequency->setPalette(boxSnapshot->palette()); + boxFrequency->setTitle("Interval between Plots"); + boxFrequency->setToolTip(intervalTip); + } - case 1: - - // gets the acq period * number of nth frames - timeMS = (spinNthFrame->value())*acqPeriodMS; - - //Show red to make sure the period between plotting is not less than minimum plot timer in ms - if(timeMSInterval between Plots: You might be losing Images!","Plot"); - boxFrequency->setPalette(*red); - boxFrequency->setTitle("Interval between Plots*"); - QString errTip = intervalTip + QString("

" - "Every nth Image Condition: min nth Image for this time period: ")+QString("%1").arg(minFrame)+ - QString(".
You might be losing images!
"); - boxFrequency->setToolTip(errTip); - }else{ - boxFrequency->setPalette(boxSnapshot->palette()); - boxFrequency->setTitle("Interval between Plots"); - boxFrequency->setToolTip(intervalTip); - } - - // Setting the timer value (nth frames) between plots - myPlot->SetFrameFactor(spinNthFrame->value()); - + // Setting the timer value (nth frames) between plots + myPlot->SetFrameFactor(spinNthFrame->value()); #ifdef VERBOSE - cout << "Plotting Frequency: Nth Frame - " << spinNthFrame->value() << endl; + cout << "Plotting Frequency: Nth Frame - " << spinNthFrame->value() << endl; #endif - break; - } + break; + } - connect(comboTimeGapUnit,SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - connect(spinTimeGap, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - qDefs::checkErrorMessage(myDet,"qTabPlot::SetFrequency"); + connect(comboTimeGapUnit, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + connect(spinTimeGap, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + qDefs::checkErrorMessage(myDet, "qTabPlot::SetFrequency"); } - //------------------------------------------------------------------------------------------------------------------------------------------------- -void qTabPlot::EnableScanBox(){ -#ifdef VERBOSE - cout << "Entering Enable Scan Box"<< endl; -#endif - disconnect(btnGroupPlotType,SIGNAL(buttonClicked(int)),this, SLOT(SetPlot())); - disconnect(boxScan, SIGNAL(toggled(bool)), this, SLOT(EnableScanBox())); + void qTabPlot::EnableScanBox(){ + #ifdef VERBOSE + cout << "Entering Enable Scan Box"<< endl; + #endif + disconnect(btnGroupPlotType,SIGNAL(buttonClicked(int)),this, SLOT(SetPlot())); + disconnect(boxScan, SIGNAL(toggled(bool)), this, SLOT(EnableScanBox())); - int oldfreqvalue = myDet->setReadReceiverFrequency(); + int oldfreqvalue = myDet->setReadReceiverFrequency(); - int mode0 = myDet->getScanMode(0); - int mode1 = myDet->getScanMode(1); + int mode0 = myDet->getScanMode(0); + int mode1 = myDet->getScanMode(1); - radioHistLevel0->setEnabled(mode0); - radioHistLevel1->setEnabled(mode1); - int ang; - bool angConvert = myDet->getAngularConversion(ang); - myPlot->EnableAnglePlot(angConvert); + radioHistLevel0->setEnabled(mode0); + radioHistLevel1->setEnabled(mode1); + int ang; + bool angConvert = myDet->getAngularConversion(ang); + myPlot->EnableAnglePlot(angConvert); - radioDataGraph->setEnabled(true); - radioHistogram->setEnabled(true); - chkSuperimpose->setEnabled(true); - pageAccumulate->setEnabled(true); - pageAccumulate_2->setEnabled(true); - if((myDet->getDetectorsType() == slsDetectorDefs::GOTTHARD) || - (myDet->getDetectorsType() == slsDetectorDefs::PROPIX) || - (myDet->getDetectorsType() == slsDetectorDefs::JUNGFRAU) || - (myDet->getDetectorsType() == slsDetectorDefs::JUNGFRAUCTB) || - (myDet->getDetectorsType() == slsDetectorDefs::MOENCH)){ - pagePedestal->setEnabled(true); - pagePedestal_2->setEnabled(true); - chkBinary->setEnabled(true); - chkBinary_2->setEnabled(true); - } + radioDataGraph->setEnabled(true); + radioHistogram->setEnabled(true); + chkSuperimpose->setEnabled(true); + pageAccumulate->setEnabled(true); + pageAccumulate_2->setEnabled(true); + if((myDet->getDetectorsType() == slsDetectorDefs::GOTTHARD) || + (myDet->getDetectorsType() == slsDetectorDefs::PROPIX) || + (myDet->getDetectorsType() == slsDetectorDefs::JUNGFRAU) || + (myDet->getDetectorsType() == slsDetectorDefs::MOENCH)){ + pagePedestal->setEnabled(true); + pagePedestal_2->setEnabled(true); + chkBinary->setEnabled(true); + chkBinary_2->setEnabled(true); + } + //if angle plot or originally 2d, uncheck and disable scanbox + if ((angConvert) || (!isOriginallyOneD)){ + boxScan->setChecked(false); + boxScan->setEnabled(false); + /**Newly added*/ + // To remind the updateplot in qdrawplot to set range after updating plot + if(!isOriginallyOneD) + myPlot->SetXYRange(true); + //2d scans read every frame, not compulsory, but for historgrams + if((!isOriginallyOneD) && (mode0 || mode1)){ + //read every frame + disconnect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + disconnect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + comboFrequency->setCurrentIndex(1); + spinNthFrame->setValue(1); + SetFrequency(); + connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + } - //if angle plot or originally 2d, uncheck and disable scanbox - if ((angConvert) || (!isOriginallyOneD)){ - boxScan->setChecked(false); - boxScan->setEnabled(false); + //persistency, accumulate, pedestal, binary + if(angConvert){ + if(chkSuperimpose->isChecked()) chkSuperimpose->setChecked(false); + if(chkPedestal->isChecked()) chkPedestal->setChecked(false); + if(chkPedestal_2->isChecked()) chkPedestal_2->setChecked(false); + if(chkAccumulate->isChecked()) chkAccumulate->setChecked(false); + if(chkAccumulate_2->isChecked())chkAccumulate_2->setChecked(false); + if(chkBinary->isChecked()) chkBinary->setChecked(false); + if(chkBinary_2->isChecked()) chkBinary_2->setChecked(false); + pagePedestal->setEnabled(false); + pagePedestal_2->setEnabled(false); + chkBinary->setEnabled(false); + chkBinary_2->setEnabled(false); + pageAccumulate->setEnabled(false); + pageAccumulate_2->setEnabled(false); + } - /**Newly added*/ - // To remind the updateplot in qdrawplot to set range after updating plot - if(!isOriginallyOneD) - myPlot->SetXYRange(true); + if(angConvert){ + boxScan->setToolTip("Only 1D Plots enabled for Angle Plots"); + //disable histogram + if(radioHistogram->isChecked()){ + radioDataGraph->setChecked(true); + radioHistogram->setEnabled(false); + // To remind the updateplot in qdrawplot to set range after updating plot + myPlot->SetXYRange(true); + boxScan->show(); + boxHistogram->hide(); + } + } + } - //2d scans read every frame, not compulsory, but for historgrams - if((!isOriginallyOneD) && (mode0 || mode1)){ - //read every frame - disconnect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - disconnect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - comboFrequency->setCurrentIndex(1); - spinNthFrame->setValue(1); - SetFrequency(); - connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - } + //originally1d && not angle plot + else{ + boxScan->setToolTip(""); + boxScan->setEnabled(true); + /*if(mode0 || mode1) + boxScan->setChecked(true);*/ - //persistency, accumulate, pedestal, binary - if(angConvert){ - if(chkSuperimpose->isChecked()) chkSuperimpose->setChecked(false); - if(chkPedestal->isChecked()) chkPedestal->setChecked(false); - if(chkPedestal_2->isChecked()) chkPedestal_2->setChecked(false); - if(chkAccumulate->isChecked()) chkAccumulate->setChecked(false); - if(chkAccumulate_2->isChecked())chkAccumulate_2->setChecked(false); - if(chkBinary->isChecked()) chkBinary->setChecked(false); - if(chkBinary_2->isChecked()) chkBinary_2->setChecked(false); - pagePedestal->setEnabled(false); - pagePedestal_2->setEnabled(false); - chkBinary->setEnabled(false); - chkBinary_2->setEnabled(false); - pageAccumulate->setEnabled(false); - pageAccumulate_2->setEnabled(false); - } + //2d enabled with boxscan + if(boxScan->isChecked()){ - if(angConvert){ - boxScan->setToolTip("Only 1D Plots enabled for Angle Plots"); - //disable histogram - if(radioHistogram->isChecked()){ - radioDataGraph->setChecked(true); - radioHistogram->setEnabled(false); - // To remind the updateplot in qdrawplot to set range after updating plot - myPlot->SetXYRange(true); - boxScan->show(); - boxHistogram->hide(); - } - } - } + //2d for 1d detctors and histogram dont go + if(radioHistogram->isChecked()){ + radioDataGraph->setChecked(true); + // To remind the updateplot in qdrawplot to set range after updating plot + myPlot->SetXYRange(true); + boxScan->show(); + boxHistogram->hide(); + } + //read every frame + disconnect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + disconnect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + comboFrequency->setCurrentIndex(1); + spinNthFrame->setValue(1); + SetFrequency(); + connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + //enabling options + radioFileIndex->setEnabled(mode0||mode1); + if(mode0 && mode1){ + radioLevel0->setEnabled(false); + radioLevel1->setEnabled(false); + }else{ + radioLevel0->setEnabled(mode0); + radioLevel1->setEnabled(mode1); + } + //default is allframes if checked button is disabled + if(!btnGroupScan->checkedButton()->isEnabled()) + radioAllFrames->setChecked(true); + } + } + //histogram + if(radioHistogram->isChecked()){ + if(radioHistIntensity->isChecked()){ + pageHistogram->setEnabled(true); + pageHistogram_2->setEnabled(true); + }else{ + pageHistogram->setEnabled(false); + pageHistogram_2->setEnabled(false); + } + stackedWidget->setCurrentIndex(stackedWidget->count()-1); + stackedWidget_2->setCurrentIndex(stackedWidget_2->count()-1); + box1D->setTitle(QString("1D Plot Options %1 - Histogram").arg(stackedWidget->currentIndex()+1)); + box2D->setTitle(QString("2D Plot Options %1 - Histogram").arg(stackedWidget_2->currentIndex()+1)); - //originally1d && not angle plot - else{ - boxScan->setToolTip(""); - boxScan->setEnabled(true); - /*if(mode0 || mode1) - boxScan->setChecked(true);*/ + if(chkSuperimpose->isChecked()) chkSuperimpose->setChecked(false); + if(chkPedestal->isChecked()) chkPedestal->setChecked(false); + if(chkPedestal_2->isChecked()) chkPedestal_2->setChecked(false); + if(chkAccumulate->isChecked()) chkAccumulate->setChecked(false); + if(chkAccumulate_2->isChecked())chkAccumulate_2->setChecked(false); + if(chkBinary->isChecked()) chkBinary->setChecked(false); + if(chkBinary_2->isChecked()) chkBinary_2->setChecked(false); + pagePedestal->setEnabled(false); + pagePedestal_2->setEnabled(false); + chkBinary->setEnabled(false); + chkBinary_2->setEnabled(false); + pageAccumulate->setEnabled(false); + pageAccumulate_2->setEnabled(false); - //2d enabled with boxscan - if(boxScan->isChecked()){ + //read every frame + disconnect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + disconnect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + comboFrequency->setCurrentIndex(1); + spinNthFrame->setValue(1); + SetFrequency(); + connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - //2d for 1d detctors and histogram dont go - if(radioHistogram->isChecked()){ - radioDataGraph->setChecked(true); - // To remind the updateplot in qdrawplot to set range after updating plot - myPlot->SetXYRange(true); - boxScan->show(); - boxHistogram->hide(); - } + }else{ + pageHistogram->setEnabled(false); + pageHistogram_2->setEnabled(false); + } - //read every frame - disconnect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - disconnect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - comboFrequency->setCurrentIndex(1); - spinNthFrame->setValue(1); - SetFrequency(); - connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + // if it was set to read every frame + if (oldfreqvalue != 0 && (comboFrequency->currentIndex() != 1 || spinNthFrame->value() != oldfreqvalue)) { + disconnect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + disconnect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + comboFrequency->setCurrentIndex(1); + spinNthFrame->setValue(1); + SetFrequency(); + connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); + connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); + } - //enabling options - radioFileIndex->setEnabled(mode0||mode1); - if(mode0 && mode1){ - radioLevel0->setEnabled(false); - radioLevel1->setEnabled(false); - }else{ - radioLevel0->setEnabled(mode0); - radioLevel1->setEnabled(mode1); - } - //default is allframes if checked button is disabled - if(!btnGroupScan->checkedButton()->isEnabled()) - radioAllFrames->setChecked(true); - } - } - - - //histogram - if(radioHistogram->isChecked()){ - if(radioHistIntensity->isChecked()){ - pageHistogram->setEnabled(true); - pageHistogram_2->setEnabled(true); - }else{ - pageHistogram->setEnabled(false); - pageHistogram_2->setEnabled(false); - } - stackedWidget->setCurrentIndex(stackedWidget->count()-1); - stackedWidget_2->setCurrentIndex(stackedWidget_2->count()-1); - box1D->setTitle(QString("1D Plot Options %1 - Histogram").arg(stackedWidget->currentIndex()+1)); - box2D->setTitle(QString("2D Plot Options %1 - Histogram").arg(stackedWidget_2->currentIndex()+1)); - - if(chkSuperimpose->isChecked()) chkSuperimpose->setChecked(false); - if(chkPedestal->isChecked()) chkPedestal->setChecked(false); - if(chkPedestal_2->isChecked()) chkPedestal_2->setChecked(false); - if(chkAccumulate->isChecked()) chkAccumulate->setChecked(false); - if(chkAccumulate_2->isChecked())chkAccumulate_2->setChecked(false); - if(chkBinary->isChecked()) chkBinary->setChecked(false); - if(chkBinary_2->isChecked()) chkBinary_2->setChecked(false); - pagePedestal->setEnabled(false); - pagePedestal_2->setEnabled(false); - chkBinary->setEnabled(false); - chkBinary_2->setEnabled(false); - pageAccumulate->setEnabled(false); - pageAccumulate_2->setEnabled(false); - - //read every frame - disconnect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - disconnect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - comboFrequency->setCurrentIndex(1); - spinNthFrame->setValue(1); - SetFrequency(); - connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - - - }else{ - pageHistogram->setEnabled(false); - pageHistogram_2->setEnabled(false); - } - - - // if it was set to read every frame - if (oldfreqvalue != 0 && (comboFrequency->currentIndex() != 1 || spinNthFrame->value() != oldfreqvalue)) { - disconnect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - disconnect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - comboFrequency->setCurrentIndex(1); - spinNthFrame->setValue(1); - SetFrequency(); - connect(spinNthFrame, SIGNAL(editingFinished()), this, SLOT(SetFrequency())); - connect(comboFrequency, SIGNAL(currentIndexChanged(int)), this, SLOT(SetFrequency())); - } - - connect(btnGroupPlotType,SIGNAL(buttonClicked(int)),this, SLOT(SetPlot())); - connect(boxScan, SIGNAL(toggled(bool)), this, SLOT(EnableScanBox())); - -} + connect(btnGroupPlotType,SIGNAL(buttonClicked(int)),this, SLOT(SetPlot())); + connect(boxScan, SIGNAL(toggled(bool)), this, SLOT(EnableScanBox())); + } //------------------------------------------------------------------------------------------------------------------------------------------------- -void qTabPlot::SetScanArgument(){ -#ifdef VERYVERBOSE - cout << "Entering qTabPlot::SetScanArgument()" << endl; -#endif + void qTabPlot::SetScanArgument(){ + #ifdef VERYVERBOSE + cout << "Entering qTabPlot::SetScanArgument()" << endl; + #endif - //1d - if(isOriginallyOneD){ - dispXAxis->setText(defaultHistXAxisTitle); - dispYAxis->setText(defaultHistYAxisTitle); - myPlot->SetHistXAxisTitle(defaultHistXAxisTitle); - myPlot->SetHistYAxisTitle(defaultHistYAxisTitle); - Select1DPlot(true); - } - //2d - else{ - dispXAxis->setText(defaultImageXAxisTitle); - dispYAxis->setText(defaultImageYAxisTitle); - dispZAxis->setText(defaultImageZAxisTitle); - myPlot->SetImageXAxisTitle(defaultImageXAxisTitle); - myPlot->SetImageYAxisTitle(defaultImageYAxisTitle); - myPlot->SetImageZAxisTitle(defaultImageZAxisTitle); - Select1DPlot(false); - } + //1d + if(isOriginallyOneD){ + dispXAxis->setText(defaultHistXAxisTitle); + dispYAxis->setText(defaultHistYAxisTitle); + myPlot->SetHistXAxisTitle(defaultHistXAxisTitle); + myPlot->SetHistYAxisTitle(defaultHistYAxisTitle); + Select1DPlot(true); + } + //2d + else{ + dispXAxis->setText(defaultImageXAxisTitle); + dispYAxis->setText(defaultImageYAxisTitle); + dispZAxis->setText(defaultImageZAxisTitle); + myPlot->SetImageXAxisTitle(defaultImageXAxisTitle); + myPlot->SetImageYAxisTitle(defaultImageYAxisTitle); + myPlot->SetImageZAxisTitle(defaultImageZAxisTitle); + Select1DPlot(false); + } + //histogram default - set before setscanargument + int min = spinHistFrom->value(); + int max = spinHistTo->value(); + double size = spinHistSize->value(); + int histArg = qDefs::Intensity; + if(radioHistogram->isChecked()){ + if(!radioHistIntensity->isChecked()){ - //histogram default - set before setscanargument - int min = spinHistFrom->value(); - int max = spinHistTo->value(); - double size = spinHistSize->value(); - int histArg = qDefs::Intensity; - if(radioHistogram->isChecked()){ - if(!radioHistIntensity->isChecked()){ + int mode = 0; + histArg = qDefs::histLevel0; + if(radioHistLevel1->isChecked()){ + mode = 1; + histArg = qDefs::histLevel1; + } - int mode = 0; - histArg = qDefs::histLevel0; - if(radioHistLevel1->isChecked()){ - mode = 1; - histArg = qDefs::histLevel1; - } + int numSteps = myDet->getScanSteps(mode); + double *values = NULL; + min = 0;max = 1;size = 1; + if(numSteps > 0){ + values = new double[numSteps]; + myDet->getScanSteps(mode,values); + min = values[0]; + max = values[numSteps - 1]; + size = (max - min)/(numSteps - 1); + } + } - int numSteps = myDet->getScanSteps(mode); - double *values = NULL; - min = 0;max = 1;size = 1; + } - if(numSteps > 0){ - values = new double[numSteps]; - myDet->getScanSteps(mode,values); - min = values[0]; - max = values[numSteps - 1]; - size = (max - min)/(numSteps - 1); - } - } + //cout <<"min:"<SetHistogram(radioHistogram->isChecked(),histArg,min,max,size); - } + if(radioHistogram->isChecked()){ + if(radioHistIntensity->isChecked()) + dispXAxis->setText("Intensity"); + else if (radioHistLevel0->isChecked()) + dispXAxis->setText("Level 0"); + else + dispXAxis->setText("Level 1"); + dispYAxis->setText("Frequency"); + myPlot->SetHistXAxisTitle("Intensity"); + myPlot->SetHistYAxisTitle("Frequency"); + Select1DPlot(true); + } - //cout <<"min:"<SetHistogram(radioHistogram->isChecked(),histArg,min,max,size); + //angles (1D) + int ang; + if(myDet->getAngularConversion(ang)){ + dispXAxis->setText("Angles"); + myPlot->SetHistXAxisTitle("Angles"); + Select1DPlot(true); + } + //1d with scan + if(boxScan->isChecked()){ + myPlot->SetScanArgument(btnGroupScan->checkedId()+1); - if(radioHistogram->isChecked()){ - if(radioHistIntensity->isChecked()) - dispXAxis->setText("Intensity"); - else if (radioHistLevel0->isChecked()) - dispXAxis->setText("Level 0"); - else - dispXAxis->setText("Level 1"); - dispYAxis->setText("Frequency"); - myPlot->SetHistXAxisTitle("Intensity"); - myPlot->SetHistYAxisTitle("Frequency"); - Select1DPlot(true); - } + switch(btnGroupScan->checkedId()){ + case 0://level0 + dispYAxis->setText("Scan Level 0"); + myPlot->SetImageYAxisTitle("Scan Level 0"); + break; + case 1://level1 + dispYAxis->setText("Scan Level 1"); + myPlot->SetImageYAxisTitle("Scan Level 1"); + break; + break; + case 2://file index + dispYAxis->setText("Frame Index"); + myPlot->SetImageYAxisTitle("Frame Index"); + break; + case 3://all frames + dispYAxis->setText("All Frames"); + myPlot->SetImageYAxisTitle("All Frames"); + break; + } + Select1DPlot(false); + }else + myPlot->SetScanArgument(qDefs::None); - //angles (1D) - int ang; - if(myDet->getAngularConversion(ang)){ - dispXAxis->setText("Angles"); - myPlot->SetHistXAxisTitle("Angles"); - Select1DPlot(true); - } + //update the from and to labels to be enabled + SetBinary(); + qDefs::checkErrorMessage(myDet,"qTabPlot::SetScanArgument"); - //1d with scan - if(boxScan->isChecked()){ - myPlot->SetScanArgument(btnGroupScan->checkedId()+1); - - switch(btnGroupScan->checkedId()){ - case 0://level0 - dispYAxis->setText("Scan Level 0"); - myPlot->SetImageYAxisTitle("Scan Level 0"); - break; - case 1://level1 - dispYAxis->setText("Scan Level 1"); - myPlot->SetImageYAxisTitle("Scan Level 1"); - break; - break; - case 2://file index - dispYAxis->setText("Frame Index"); - myPlot->SetImageYAxisTitle("Frame Index"); - break; - case 3://all frames - dispYAxis->setText("All Frames"); - myPlot->SetImageYAxisTitle("All Frames"); - break; - } - Select1DPlot(false); - }else - myPlot->SetScanArgument(qDefs::None); - - //update the from and to labels to be enabled - SetBinary(); - - qDefs::checkErrorMessage(myDet,"qTabPlot::SetScanArgument"); - -} - + } //------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabPlot::SetBinary() { + //1d + if (isOneD) { + if (chkBinary->isChecked()) { +#ifdef VERBOSE + cout << endl + << "Enabling Binary" << endl; +#endif + lblFrom->setEnabled(true); + lblTo->setEnabled(true); + spinFrom->setEnabled(true); + spinTo->setEnabled(true); + myPlot->SetBinary(true, spinFrom->value(), spinTo->value()); + } else { +#ifdef VERBOSE + cout << endl + << "Disabling Binary" << endl; +#endif + lblFrom->setEnabled(false); + lblTo->setEnabled(false); + spinFrom->setEnabled(false); + spinTo->setEnabled(false); + myPlot->SetBinary(false); + } + } + //2d + else { + if (chkBinary_2->isChecked()) { +#ifdef VERBOSE + cout << endl + << "Enabling Binary" << endl; +#endif + lblFrom_2->setEnabled(true); + lblTo_2->setEnabled(true); + spinFrom_2->setEnabled(true); + spinTo_2->setEnabled(true); + myPlot->SetBinary(true, spinFrom_2->value(), spinTo_2->value()); -void qTabPlot::SetBinary(){ - //1d - if(isOneD){ - if(chkBinary->isChecked()){ + } else { #ifdef VERBOSE - cout << endl << "Enabling Binary" << endl; -#endif - lblFrom->setEnabled(true); - lblTo->setEnabled(true); - spinFrom->setEnabled(true); - spinTo->setEnabled(true); - myPlot->SetBinary(true,spinFrom->value(),spinTo->value()); - }else{ -#ifdef VERBOSE - cout << endl << "Disabling Binary" << endl; -#endif - lblFrom->setEnabled(false); - lblTo->setEnabled(false); - spinFrom->setEnabled(false); - spinTo->setEnabled(false); - myPlot->SetBinary(false); - } - } - //2d - else{ - if(chkBinary_2->isChecked()){ -#ifdef VERBOSE - cout << endl << "Enabling Binary" << endl; -#endif - lblFrom_2->setEnabled(true); - lblTo_2->setEnabled(true); - spinFrom_2->setEnabled(true); - spinTo_2->setEnabled(true); - myPlot->SetBinary(true,spinFrom_2->value(),spinTo_2->value()); - - }else{ -#ifdef VERBOSE - cout << endl << "Disabling Binary" << endl; + cout << endl + << "Disabling Binary" << endl; #endif - lblFrom_2->setEnabled(false); - lblTo_2->setEnabled(false); - spinFrom_2->setEnabled(false); - spinTo_2->setEnabled(false); - myPlot->SetBinary(false); - } - } + lblFrom_2->setEnabled(false); + lblTo_2->setEnabled(false); + spinFrom_2->setEnabled(false); + spinTo_2->setEnabled(false); + myPlot->SetBinary(false); + } + } } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabPlot::SetHistogramOptions(){ - if(radioHistIntensity->isChecked()){ - pageHistogram->setEnabled(true); - pageHistogram_2->setEnabled(true); - }else { - pageHistogram->setEnabled(false); - pageHistogram_2->setEnabled(false); - } +void qTabPlot::SetHistogramOptions() { + if (radioHistIntensity->isChecked()) { + pageHistogram->setEnabled(true); + pageHistogram_2->setEnabled(true); + } else { + pageHistogram->setEnabled(false); + pageHistogram_2->setEnabled(false); + } } - - //------------------------------------------------------------------------------------------------------------------------------------------------- - void qTabPlot::EnableGapPixels(bool enable) { #ifdef VERBOSE - cout << "Setting Gap pixels to " << enable << endl; + cout << "Setting Gap pixels to " << enable << endl; #endif - disconnect(chkGapPixels, SIGNAL(toggled(bool)),this, SLOT(EnableGapPixels(bool))); + disconnect(chkGapPixels, SIGNAL(toggled(bool)), this, SLOT(EnableGapPixels(bool))); myDet->enableGapPixels(enable); - int ret = myDet->enableGapPixels(-1); - qDefs::checkErrorMessage(myDet,"qTabPlot::SetScanArgument"); + int ret = myDet->enableGapPixels(-1); + qDefs::checkErrorMessage(myDet, "qTabPlot::SetScanArgument"); chkGapPixels->setChecked((ret == 1) ? true : false); - connect(chkGapPixels, SIGNAL(toggled(bool)),this, SLOT(EnableGapPixels(bool))); + connect(chkGapPixels, SIGNAL(toggled(bool)), this, SLOT(EnableGapPixels(bool))); } - //------------------------------------------------------------------------------------------------------------------------------------------------- - -void qTabPlot::Refresh(){ +void qTabPlot::Refresh() { #ifdef VERBOSE - cout << endl << "**Updating Plot Tab" << endl; + cout << endl + << "**Updating Plot Tab" << endl; #endif - if(!myPlot->isRunning()){ - if (!radioNoPlot->isChecked()) - boxFrequency->setEnabled(true); - connect(boxScan, SIGNAL(toggled(bool)), this, SLOT(EnableScanBox())); - EnableScanBox(); - /*if(myDet->getDetectorsType() == slsDetectorDefs::EIGER) - comboFrequency->setCurrentIndex(1);*/ - SetFrequency(); + if (!myPlot->isRunning()) { + if (!radioNoPlot->isChecked()) + boxFrequency->setEnabled(true); + SetFrequency(); - if (chkGapPixels->isEnabled()) { - disconnect(chkGapPixels, SIGNAL(toggled(bool)),this, SLOT(EnableGapPixels(bool))); - int ret = myDet->enableGapPixels(-1); - qDefs::checkErrorMessage(myDet,"qTabPlot::Refresh"); - chkGapPixels->setChecked((ret == 1) ? true : false); - connect(chkGapPixels, SIGNAL(toggled(bool)),this, SLOT(EnableGapPixels(bool))); - } + if (chkGapPixels->isEnabled()) { + disconnect(chkGapPixels, SIGNAL(toggled(bool)), this, SLOT(EnableGapPixels(bool))); + int ret = myDet->enableGapPixels(-1); + qDefs::checkErrorMessage(myDet, "qTabPlot::Refresh"); + chkGapPixels->setChecked((ret == 1) ? true : false); + connect(chkGapPixels, SIGNAL(toggled(bool)), this, SLOT(EnableGapPixels(bool))); + } - }else{ - boxFrequency->setEnabled(false); - disconnect(boxScan, SIGNAL(toggled(bool)), this, SLOT(EnableScanBox())); - boxScan->setEnabled(false); - pageHistogram->setEnabled(false); - pageHistogram_2->setEnabled(false); - if(radioHistogram->isChecked()) - radioDataGraph->setEnabled(false); - else - radioHistogram->setEnabled(false); - } + } else { + boxFrequency->setEnabled(false); + disconnect(boxScan, SIGNAL(toggled(bool)), this, SLOT(EnableScanBox())); + boxScan->setEnabled(false); + pageHistogram->setEnabled(false); + pageHistogram_2->setEnabled(false); + if (radioHistogram->isChecked()) + radioDataGraph->setEnabled(false); + else + radioHistogram->setEnabled(false); + } #ifdef VERBOSE - cout << "**Updated Plot Tab" << endl << endl; + cout << "**Updated Plot Tab" << endl + << endl; #endif } - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - diff --git a/slsDetectorGui/src/qTabSettings.cpp b/slsDetectorGui/src/qTabSettings.cpp old mode 100644 new mode 100755 index aa3849f4e..b1d48f867 --- a/slsDetectorGui/src/qTabSettings.cpp +++ b/slsDetectorGui/src/qTabSettings.cpp @@ -1,385 +1,304 @@ -/* - * qTabSettings.cpp - * - * Created on: May 10, 2012 - * Author: l_maliakal_d - */ - #include "qTabSettings.h" -// Project Class Headers -#include "slsDetector.h" + #include "multiSlsDetector.h" -// C++ Include Headers -#include + +#include + #include -using namespace std; +#include -//------------------------------------------------------------------------------------------------------------------------------------------------- +qTabSettings::qTabSettings(QWidget *parent, multiSlsDetector *detector) + : QWidget(parent), myDet(detector), detType(slsDetectorDefs::GENERIC) { -qTabSettings::qTabSettings(QWidget *parent,multiSlsDetector*& detector): - QWidget(parent),myDet(detector),expertMode(false){ - - for(int i=0;igetDetectorTypeAsEnum(); + + // Settings + comboSettings->setCurrentIndex(UNINITIALIZED); + if (detType == slsDetectorDefs::MOENCH) { + lblSettings->setEnabled(false); + comboSettings->setEnabled(false); + } else { + SetupDetectorSettings(); + GetSettings(); + } + + // Dynamic Range + GetDynamicRange(); + // cannot change dr for other types + if (detType != slsDetectorDefs::EIGER) { + lblDynamicRange->setEnabled(false); + comboDynamicRange->setEnabled(false); + } + + // threshold energy + if (detType == slsDetectorDefs::EIGER) { + qDefs::IgnoreNonCriticalExceptions( + spinThreshold, + &QSpinBox::setValue, + myDet, + std::string("qTabSettings::SetupWidgetWindow"), + &multiSlsDetector::getThresholdEnergy, -1); + } else { + lblThreshold->setEnabled(false); + spinThreshold->setEnabled(false); + } } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabSettings::SetupDetectorSettings() { -void qTabSettings::SetupWidgetWindow(){ - // Detector Type - detType=myDet->getDetectorsType(); + // To be able to index items on a combo box + QStandardItemModel *model = + qobject_cast(comboSettings->model()); + if (model) { + QModelIndex index[NUMSETTINGS]; + QStandardItem *item[NUMSETTINGS]; + for (int i = 0; i < NUMSETTINGS; ++i) { + index[i] = model->index(i, comboSettings->modelColumn(), + comboSettings->rootModelIndex()); + item[i] = model->itemFromIndex(index[i]); + } - // Settings - if (detType != slsReceiverDefs::JUNGFRAUCTB) { - SetupDetectorSettings(); - } else - comboSettings->setEnabled(false); + item[(int)UNDEFINED]->setEnabled(false); + item[(int)UNINITIALIZED]->setEnabled(false); - //threshold - if((detType == slsDetectorDefs::MYTHEN) || (detType == slsDetectorDefs::EIGER)) - spinThreshold->setValue(myDet->getThresholdEnergy()); + switch (detType) { + case slsDetectorDefs::EIGER: + item[(int)STANDARD]->setEnabled(true); + item[(int)HIGHGAIN]->setEnabled(true); + item[(int)LOWGAIN]->setEnabled(true); + item[(int)VERYHIGHGAIN]->setEnabled(true); + item[(int)VERLOWGAIN]->setEnabled(true); - //expert mode is not enabled initially - lblThreshold->setEnabled(false); - spinThreshold->setEnabled(false); + item[(int)FAST]->setEnabled(false); + item[(int)DYNAMICGAIN]->setEnabled(false); + item[(int)MEDIUMGAIN]->setEnabled(false); + item[(int)LOWNOISE]->setEnabled(false); + item[(int)DYNAMICHG0]->setEnabled(false); + item[(int)FIXGAIN1]->setEnabled(false); + item[(int)FIXGAIN2]->setEnabled(false); + item[(int)FORCESWITCHG1]->setEnabled(false); + item[(int)FORCESWITCHG2]->setEnabled(false); + break; - // Number of Modules - spinNumModules->setMaximum(myDet->getMaxNumberOfModules()); - spinNumModules->setValue(myDet->setNumberOfModules()); + case slsDetectorDefs::GOTTHARD: + item[(int)HIGHGAIN]->setEnabled(true); + item[(int)DYNAMICGAIN]->setEnabled(true); + item[(int)LOWGAIN]->setEnabled(true); + item[(int)MEDIUMGAIN]->setEnabled(true); + item[(int)VERYHIGHGAIN]->setEnabled(true); - Initialization(); + item[(int)STANDARD]->setEnabled(false); + item[(int)FAST]->setEnabled(false); + item[(int)LOWNOISE]->setEnabled(false); + item[(int)DYNAMICHG0]->setEnabled(false); + item[(int)FIXGAIN1]->setEnabled(false); + item[(int)FIXGAIN2]->setEnabled(false); + item[(int)FORCESWITCHG1]->setEnabled(false); + item[(int)FORCESWITCHG2]->setEnabled(false); + item[(int)VERLOWGAIN]->setEnabled(false); + break; - // Dynamic Range - GetDynamicRange(); + case slsDetectorDefs::JUNGFRAU: + item[(int)DYNAMICGAIN]->setEnabled(true); + item[(int)DYNAMICHG0]->setEnabled(true); + item[(int)FIXGAIN1]->setEnabled(true); + item[(int)FIXGAIN2]->setEnabled(true); + item[(int)FORCESWITCHG1]->setEnabled(true); + item[(int)FORCESWITCHG2]->setEnabled(true); - qDefs::checkErrorMessage(myDet,"qTabSettings::SetupWidgetWindow"); + item[(int)STANDARD]->setEnabled(false); + item[(int)FAST]->setEnabled(false); + item[(int)HIGHGAIN]->setEnabled(false); + item[(int)LOWGAIN]->setEnabled(false); + item[(int)MEDIUMGAIN]->setEnabled(false); + item[(int)VERYHIGHGAIN]->setEnabled(false); + item[(int)LOWNOISE]->setEnabled(false); + item[(int)VERLOWGAIN]->setEnabled(false); + break; + + default: + FILE_LOG(logDEBUG) << "Unknown detector type. Exiting GUI."; + qDefs::Message(qDefs::CRITICAL, + "Unknown detector type. Exiting GUI.", + "qTabSettings::SetupDetectorSettings"); + exit(-1); + } + } } - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabSettings::GetDynamicRange(int setvalue){ -#ifdef VERBOSE - cout << "Getting dynamic range" << endl; -#endif - int ret = myDet->setDynamicRange(-1); - if(detType == slsDetectorDefs::MYTHEN) { - if(ret==24) - ret=32; - else if(ret==24) - cout<<"ret:"<setCurrentIndex(0); break; - case 16: comboDynamicRange->setCurrentIndex(1); break; - case 8: comboDynamicRange->setCurrentIndex(2); break; - case 4: comboDynamicRange->setCurrentIndex(3); break; - default: comboDynamicRange->setCurrentIndex(0); break; - } - connect(comboDynamicRange, SIGNAL(activated(int)), this, SLOT(SetDynamicRange(int))); +void qTabSettings::Initialization() { + // Settings + if (comboSettings->isEnabled()) + connect(comboSettings, SIGNAL(currentIndexChanged(int)), this, + SLOT(SetSettings(int))); + // Dynamic Range + if (comboDynamicRange->isEnabled()) + connect(comboDynamicRange, SIGNAL(activated(int)), this, + SLOT(SetDynamicRange(int))); + // Threshold + if (spinThreshold->isEnabled()) + connect(spinThreshold, SIGNAL(valueChanged(int)), this, + SLOT(SetEnergy())); } +void qTabSettings::GetSettings() { + FILE_LOG(logDEBUG) << "Getting settings"; -//------------------------------------------------------------------------------------------------------------------------------------------------- + int sett = qDefs::IgnoreNonCriticalExceptionsandReturn( + myDet, std::string("qTabSettings::SetupWidgetWindow"), + &multiSlsDetector::getSettings, -1); + FILE_LOG(logDEBUG) << "Settings from Detector:" << sett; -void qTabSettings::SetupDetectorSettings(){ - // Get detector settings from detector - int sett = (int)myDet->getSettings();cout<<"sett:"<(comboSettings->model()); - if (model) { - for(int i=0;iindex(i, comboSettings->modelColumn(), comboSettings->rootModelIndex()); - item[i] = model->itemFromIndex(index[i]); - } + if (sett == -1) + sett = UNDEFINED; + if (sett == slsDetectorDefs::UNDEFINED) + sett = UNDEFINED; + else if (sett == slsDetectorDefs::UNINITIALIZED) + sett = UNINITIALIZED; - switch(detType){ - case slsDetectorDefs::MYTHEN: - item[(int)Standard]->setEnabled(true); - item[(int)Fast]->setEnabled(true); - item[(int)HighGain]->setEnabled(true); - item[(int)DynamicGain]->setEnabled(false); - item[(int)LowGain]->setEnabled(false); - item[(int)MediumGain]->setEnabled(false); - item[(int)VeryHighGain]->setEnabled(false); - item[(int)LowNoise]->setEnabled(false); - item[(int)DynamicHG0]->setEnabled(false); - item[(int)FixGain1]->setEnabled(false); - item[(int)FixGain2]->setEnabled(false); - item[(int)ForceSwitchG1]->setEnabled(false); - item[(int)ForceSwitchG2]->setEnabled(false); - item[(int)VeryLowGain]->setEnabled(false); - break; - case slsDetectorDefs::EIGER: - item[(int)Standard]->setEnabled(true); - item[(int)Fast]->setEnabled(false); - item[(int)HighGain]->setEnabled(true); - item[(int)DynamicGain]->setEnabled(false); - item[(int)LowGain]->setEnabled(true); - item[(int)MediumGain]->setEnabled(false); - item[(int)VeryHighGain]->setEnabled(true); - item[(int)LowNoise]->setEnabled(false); - item[(int)DynamicHG0]->setEnabled(false); - item[(int)FixGain1]->setEnabled(false); - item[(int)FixGain2]->setEnabled(false); - item[(int)ForceSwitchG1]->setEnabled(false); - item[(int)ForceSwitchG2]->setEnabled(false); - item[(int)VeryLowGain]->setEnabled(true); - break; - case slsDetectorDefs::MOENCH: - case slsDetectorDefs::PROPIX: - case slsDetectorDefs::GOTTHARD: - item[(int)Standard]->setEnabled(false); - item[(int)Fast]->setEnabled(false); - item[(int)HighGain]->setEnabled(true); - item[(int)DynamicGain]->setEnabled(true); - item[(int)LowGain]->setEnabled(true); - item[(int)MediumGain]->setEnabled(true); - item[(int)VeryHighGain]->setEnabled(true); - item[(int)LowNoise]->setEnabled(false); - item[(int)DynamicHG0]->setEnabled(false); - item[(int)FixGain1]->setEnabled(false); - item[(int)FixGain2]->setEnabled(false); - item[(int)ForceSwitchG1]->setEnabled(false); - item[(int)ForceSwitchG2]->setEnabled(false); - item[(int)VeryLowGain]->setEnabled(false); - break; - case slsDetectorDefs::JUNGFRAU: - item[(int)Standard]->setEnabled(false); - item[(int)Fast]->setEnabled(false); - item[(int)HighGain]->setEnabled(false); - item[(int)DynamicGain]->setEnabled(true); - item[(int)LowGain]->setEnabled(false); - item[(int)MediumGain]->setEnabled(false); - item[(int)VeryHighGain]->setEnabled(false); - item[(int)LowNoise]->setEnabled(false); - item[(int)DynamicHG0]->setEnabled(true); - item[(int)FixGain1]->setEnabled(true); - item[(int)FixGain2]->setEnabled(true); - item[(int)ForceSwitchG1]->setEnabled(true); - item[(int)ForceSwitchG2]->setEnabled(true); - item[(int)VeryLowGain]->setEnabled(false); - break; - default: - cout << "Unknown detector type. Exiting GUI." << endl; - qDefs::Message(qDefs::CRITICAL,"Unknown detector type. Exiting GUI.","qTabSettings::SetupDetectorSettings"); - exit(-1); - break; - } - // detector settings selected NOT ENABLED. - // This should not happen -only if the server and gui has a mismatch - // on which all modes are allowed in detectors - if(!(item[sett]->isEnabled())){ - qDefs::Message(qDefs::CRITICAL,"Unknown Detector Settings retrieved from detector. Exiting GUI.","qTabSettings::SetupDetectorSettings"); -#ifdef VERBOSE - cout << "ERROR: Unknown Detector Settings retrieved from detector." << endl; -#endif - sett= Undefined; - // exit(-1); - } - // Setting the detector settings - else comboSettings->setCurrentIndex(sett); - } + comboSettings->setCurrentIndex(sett); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabSettings::GetDynamicRange() { + FILE_LOG(logDEBUG) << "Getting dynamic range"; -void qTabSettings::Initialization(){ - // Settings - if (detType != slsReceiverDefs::JUNGFRAUCTB) - connect(comboSettings, SIGNAL(currentIndexChanged(int)), this, SLOT(setSettings(int))); - // Number of Modules - connect(spinNumModules, SIGNAL(valueChanged(int)), this, SLOT(SetNumberOfModules(int))); - // Dynamic Range - connect(comboDynamicRange, SIGNAL(activated(int)), this, SLOT(SetDynamicRange(int))); - // Threshold - connect(spinThreshold, SIGNAL(valueChanged(int)), this, SLOT(SetEnergy())); + int ret = qDefs::IgnoreNonCriticalExceptionsandReturn( + myDet, std::string("qTabSettings::GetDynamicRange"), + &multiSlsDetector::setDynamicRange, -1, -1); + + // set the final value on gui + switch (ret) { + case 32: + comboDynamicRange->setCurrentIndex(0); + break; + case 16: + comboDynamicRange->setCurrentIndex(1); + break; + case 8: + comboDynamicRange->setCurrentIndex(2); + break; + case 4: + comboDynamicRange->setCurrentIndex(3); + break; + default: + if (ret != -1) { + qDefs::Message(qDefs::WARNING, + "Unknown Dyanmic Range " + std::to_string(ret) + ".", + "qTabSettings::SetupDetectorSettings"); + } + break; + } } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabSettings::SetSettings(int index) { + slsDetectorDefs::detectorSettings sett = + myDet->setSettings((slsDetectorDefs::detectorSettings)index); + FILE_LOG(logINFO) << "Settings set to " + << myDet->slsDetectorDefs::getDetectorSettings(sett); -void qTabSettings::setSettings(int index){ - //dont set it if settings is set to undefined or uninitialized - if((index==Undefined)||(index==Uninitialized)){ - qDefs::Message(qDefs::WARNING,"Cannot change settings to Undefined or Uninitialized.","qTabSettings::setSettings"); - disconnect(comboSettings, SIGNAL(currentIndexChanged(int)), this, SLOT(setSettings(int))); - int sett = (int)myDet->getSettings(); - if(sett==-1) sett = Undefined; - if(sett == slsDetectorDefs::UNDEFINED) sett = Undefined; - else if(sett == slsDetectorDefs::UNINITIALIZED) sett = Uninitialized; - comboSettings->setCurrentIndex(sett); - connect(comboSettings, SIGNAL(currentIndexChanged(int)), this, SLOT(setSettings(int))); - } + // threshold + if (spinThreshold->isEnabled()) { + SetEnergy(); + } - else{ - slsDetectorDefs::detectorSettings sett = myDet->setSettings((slsDetectorDefs::detectorSettings)index); - #ifdef VERBOSE - cout << endl << "Settings have been set to " << myDet->slsDetectorBase::getDetectorSettings(sett) << endl; - #endif - - //threshold - if((detType==slsDetectorDefs::MYTHEN)||(detType==slsDetectorDefs::EIGER)){ - lblThreshold->setEnabled(true); - spinThreshold->setEnabled(true); - SetEnergy(); - //also update trimbits plot - if(expertMode) emit UpdateTrimbitSignal(0); - } - } - - qDefs::checkErrorMessage(myDet,"qTabSettings::setSettings"); + qDefs::checkErrorMessage(myDet, "qTabSettings::SetSettings"); } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabSettings::SetDynamicRange(int index) { + int dr; + switch (index) { + case 0: + dr = 32; + break; + case 1: + dr = 16; + break; + case 2: + dr = 8; + break; + case 3: + dr = 4; + break; + default: + break; + } + int ret = myDet->setDynamicRange(dr); + FILE_LOG(logINFO) << "Setting dynamic range to " << dr; + qDefs::checkErrorMessage(myDet, "qTabSettings::SetDynamicRange"); -void qTabSettings::SetNumberOfModules(int index){ -#ifdef VERBOSE - cout << "Setting number of modules to "<< index << endl; -#endif - int i = myDet->setNumberOfModules(index); - if(index!=i) - qDefs::Message(qDefs::WARNING,"Number of modules cannot be set for this value.","qTabSettings::SetNumberOfModules"); -#ifdef VERBOSE - cout << "ERROR: Setting number of modules to "<< i << endl; -#endif - spinNumModules->setValue(i); - - qDefs::checkErrorMessage(myDet,"qTabSettings::SetNumberOfModules"); + // check + if (ret != dr) { + qDefs::Message(qDefs::WARNING, "Could not set dynamic range.", + "qTabSettings::SetDynamicRange"); + disconnect(comboDynamicRange, SIGNAL(activated(int)), this, + SLOT(SetDynamicRange(int))); + GetDynamicRange(); + connect(comboDynamicRange, SIGNAL(activated(int)), this, + SLOT(SetDynamicRange(int))); + } } -//------------------------------------------------------------------------------------------------------------------------------------------------- +void qTabSettings::SetEnergy() { + int index = spinThreshold->value(); + FILE_LOG(logINFO) << "Settings threshold energy to " << index; + myDet->setThresholdEnergy(index); + int ret = myDet->getThresholdEnergy(); + if ((ret - index) > 200) { + qDefs::Message(qDefs::WARNING, + "Threshold energy could not be set (tolerance 200).", + "qTabSettings::SetEnergy"); + } + disconnect(spinThreshold, SIGNAL(valueChanged(int)), this, + SLOT(SetEnergy())); + spinThreshold->setValue(ret); + connect(spinThreshold, SIGNAL(valueChanged(int)), this, SLOT(SetEnergy())); -void qTabSettings::SetDynamicRange(int index){ - int dr; - switch (index) { - case 0: dr=32; break; - case 1: dr=16; break; - case 2: dr=8; break; - case 3: dr=4; break; - default: dr=32; break; - } - myDet->setDynamicRange(dr); -#ifdef VERBOSE - cout << "Setting dynamic range to "<< dr << endl; -#endif - //check - GetDynamicRange(dr); - qDefs::checkErrorMessage(myDet,"qTabSettings::SetDynamicRange"); + qDefs::checkErrorMessage(myDet, "qTabSettings::SetEnergy"); } +void qTabSettings::Refresh() { + FILE_LOG(logDEBUG) << "\n**Updating Settings Tab"; -//------------------------------------------------------------------------------------------------------------------------------------------------- + // settings + if (comboSettings->isEnabled()) { + disconnect(comboSettings, SIGNAL(currentIndexChanged(int)), this, + SLOT(SetSettings(int))); + GetSettings(); + connect(comboSettings, SIGNAL(currentIndexChanged(int)), this, + SLOT(SetSettings(int))); + } + // threshold + if (spinThreshold->isEnabled()) { + disconnect(spinThreshold, SIGNAL(valueChanged(int)), this, + SLOT(SetEnergy())); + spinThreshold->setValue(myDet->getThresholdEnergy()); + connect(spinThreshold, SIGNAL(valueChanged(int)), this, + SLOT(SetEnergy())); + } -void qTabSettings::SetEnergy(){ - int index = spinThreshold->value(); -#ifdef VERBOSE - cout << "Settings threshold energy to "<< index << endl; -#endif - myDet->setThresholdEnergy(index); - int ret = (int)myDet->getThresholdEnergy(); - if((ret-index)>200){ - qDefs::Message(qDefs::WARNING,"Threshold energy could not be set. The difference is greater than 200.","qTabSettings::SetEnergy"); - } - disconnect(spinThreshold, SIGNAL(valueChanged(int)), this, SLOT(SetEnergy())); - spinThreshold->setValue(ret); - connect(spinThreshold, SIGNAL(valueChanged(int)), this, SLOT(SetEnergy())); + // Dynamic Range + if (comboDynamicRange->isEnabled()) { + disconnect(comboDynamicRange, SIGNAL(activated(int)), this, + SLOT(SetDynamicRange(int))); + GetDynamicRange(); + connect(comboDynamicRange, SIGNAL(activated(int)), this, + SLOT(SetDynamicRange(int))); + } - qDefs::checkErrorMessage(myDet,"qTabSettings::SetEnergy"); + FILE_LOG(logDEBUG) << "**Updated Settings Tab"; + + qDefs::checkErrorMessage(myDet, "qTabSettings::Refresh"); } - - -//------------------------------------------------------------------------------------------------------------------------------------------------- - - -void qTabSettings::Refresh(){ -#ifdef VERBOSE - cout << endl << "**Updating Settings Tab" << endl; -#endif - - if (detType != slsReceiverDefs::JUNGFRAUCTB) - disconnect(comboSettings, SIGNAL(currentIndexChanged(int)), this, SLOT(setSettings(int))); - disconnect(spinNumModules, SIGNAL(valueChanged(int)), this, SLOT(SetNumberOfModules(int))); - disconnect(spinThreshold, SIGNAL(valueChanged(int)), this, SLOT(SetEnergy())); - - - // Number of Modules -#ifdef VERBOSE - cout << "Getting number of modules:" ; -#endif - int numMod = myDet->setNumberOfModules(); -#ifdef VERBOSE - cout << numMod << endl; -#endif - spinNumModules->setValue(numMod); - - // Dynamic Range - GetDynamicRange(); - - // Settings - if (detType != slsReceiverDefs::JUNGFRAUCTB) { -#ifdef VERBOSE - cout << "Getting settings" << endl; -#endif - int sett = (int)myDet->getSettings(); - if(sett==-1) sett = Undefined;//slsDetectorDefs::UNDEFINED; - if(sett == slsDetectorDefs::UNDEFINED) sett = Undefined; - else if(sett == slsDetectorDefs::UNINITIALIZED) sett = Uninitialized; - comboSettings->setCurrentIndex(sett); - - //threshold - sett = comboSettings->currentIndex(); - if((detType==slsDetectorDefs::MYTHEN)||(detType==slsDetectorDefs::EIGER)){ - if((sett==Undefined)||(sett==Uninitialized)){ - lblThreshold->setEnabled(false); - spinThreshold->setEnabled(false); - }else{ - lblThreshold->setEnabled(true); - spinThreshold->setEnabled(true); -#ifdef VERBOSE - cout << "Getting threshold energy" << endl; -#endif - spinThreshold->setValue(myDet->getThresholdEnergy()); - } - } -} - - if (detType != slsReceiverDefs::JUNGFRAUCTB) - connect(comboSettings, SIGNAL(currentIndexChanged(int)), this, SLOT(setSettings(int))); - connect(spinNumModules, SIGNAL(valueChanged(int)), this, SLOT(SetNumberOfModules(int))); - connect(spinThreshold, SIGNAL(valueChanged(int)), this, SLOT(SetEnergy())); - -#ifdef VERBOSE - cout << "**Updated Settings Tab" << endl << endl; -#endif - - qDefs::checkErrorMessage(myDet,"qTabSettings::Refresh"); -} - - -//------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/slsDetectorGui/updateGitVersion.sh b/slsDetectorGui/updateGitVersion.sh deleted file mode 100755 index f82322712..000000000 --- a/slsDetectorGui/updateGitVersion.sh +++ /dev/null @@ -1,26 +0,0 @@ -MAINDIR=slsDetectorsPackage -SPECDIR=slsDetectorGui -TMPFILE=include/gitInfoGuiTmp.h -INCLFILE=include/gitInfoGui.h -WD=$PWD - -#evaluate the variables -EVALFILE=../evalVersionVariables.sh -source $EVALFILE - -#get modified date -#RDATE1='git log --pretty=format:"%ci" -1' -RDATE1="find . -type f -exec stat --format '%Y :%y %n' '{}' \; | sort -nr | cut -d: -f2- | egrep -v 'gitInfo|build|.git|updateGitVersion|ui*.h|*.o|Makefile.gui' | head -n 1" -RDATE=`eval $RDATE1` -NEWDATE=$(sed "s/-//g" <<< $RDATE | awk '{print $1;}') -NEWDATE=${NEWDATE/#/0x} - -#get old date from INCLFILE -OLDDATE=$(more $INCLFILE | grep '#define GITDATE' | awk '{print $3}') -#update INCLFILE if changes -#if [ "$OLDDATE" != "$NEWDATE" ]; then - echo Path: ${MAINDIR}/${SPECDIR} $'\n'URL: ${GITREPO} $'\n'Repository Root: ${GITREPO} $'\n'Repsitory UUID: ${REPUID} $'\n'Revision: ${FOLDERREV} $'\n'Branch: ${BRANCH} $'\n'Last Changed Author: ${AUTH1}_${AUTH2} $'\n'Last Changed Rev: ${REV} $'\n'Last Changed Date: ${RDATE} > gitInfo.txt - cd .. - ./genVersionHeader.sh $SPECDIR/gitInfo.txt $SPECDIR/$TMPFILE $SPECDIR/$INCLFILE - cd $WD -#fi diff --git a/slsDetectorServers/ctbDetectorServer/AD7689.h b/slsDetectorServers/ctbDetectorServer/AD7689.h new file mode 120000 index 000000000..fe4d6e3ce --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/AD7689.h @@ -0,0 +1 @@ +../slsDetectorServer/AD7689.h \ No newline at end of file diff --git a/slsDetectorSoftware/gotthardDetectorServer/AD9257.h b/slsDetectorServers/ctbDetectorServer/AD9257.h similarity index 100% rename from slsDetectorSoftware/gotthardDetectorServer/AD9257.h rename to slsDetectorServers/ctbDetectorServer/AD9257.h diff --git a/slsDetectorServers/ctbDetectorServer/ALTERA_PLL.h b/slsDetectorServers/ctbDetectorServer/ALTERA_PLL.h new file mode 120000 index 000000000..e665f009d --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/ALTERA_PLL.h @@ -0,0 +1 @@ +../slsDetectorServer/ALTERA_PLL.h \ No newline at end of file diff --git a/slsDetectorServers/ctbDetectorServer/I2C.h b/slsDetectorServers/ctbDetectorServer/I2C.h new file mode 120000 index 000000000..88ae4a2f3 --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/I2C.h @@ -0,0 +1 @@ +../slsDetectorServer/I2C.h \ No newline at end of file diff --git a/slsDetectorServers/ctbDetectorServer/INA226.h b/slsDetectorServers/ctbDetectorServer/INA226.h new file mode 120000 index 000000000..685ac1f8f --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/INA226.h @@ -0,0 +1 @@ +../slsDetectorServer/INA226.h \ No newline at end of file diff --git a/slsDetectorServers/ctbDetectorServer/LTC2620.h b/slsDetectorServers/ctbDetectorServer/LTC2620.h new file mode 120000 index 000000000..13157cb8b --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/LTC2620.h @@ -0,0 +1 @@ +../slsDetectorServer/LTC2620.h \ No newline at end of file diff --git a/slsDetectorServers/ctbDetectorServer/MAX1932.h b/slsDetectorServers/ctbDetectorServer/MAX1932.h new file mode 120000 index 000000000..8f7b239ea --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/MAX1932.h @@ -0,0 +1 @@ +../slsDetectorServer/MAX1932.h \ No newline at end of file diff --git a/slsDetectorServers/ctbDetectorServer/Makefile b/slsDetectorServers/ctbDetectorServer/Makefile new file mode 100755 index 000000000..b26f833d1 --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/Makefile @@ -0,0 +1,34 @@ +CROSS = bfin-uclinux- +CC = $(CROSS)gcc +CFLAGS += -Wall -DCHIPTESTBOARDD -DSTOP_SERVER -DDEBUG1 #-DJCTB -DVERBOSEI #-DVERBOSE +LDLIBS += -lm -lstdc++ + +PROGS = ctbDetectorServer +DESTDIR ?= bin +INSTMODE = 0777 + +SRC_CLNT = communication_funcs.c slsDetectorServer.c slsDetectorServer_funcs.c slsDetectorFunctionList.c +OBJS = $(SRC_CLNT:.c=.o) + +all: clean versioning $(PROGS) + +boot: $(OBJS) + +version_name=APICTB +version_path=slsDetectorServers/ctbDetectorServer +versioning: + cd ../../ && echo $(PWD) && echo `tput setaf 6; ./updateAPIVersion.sh $(version_name) $(version_path); tput sgr0;` + + +$(PROGS): $(OBJS) +# echo $(OBJS) + mkdir -p $(DESTDIR) + $(CC) -o $@ $^ $(CFLAGS) $(LDLIBS) + mv $(PROGS) $(DESTDIR) + rm *.gdb + +clean: + rm -rf $(DESTDIR)/$(PROGS) *.o *.gdb + + + diff --git a/slsDetectorSoftware/jungfrauDetectorServer/Makefile b/slsDetectorServers/ctbDetectorServer/Makefile.virtual similarity index 66% rename from slsDetectorSoftware/jungfrauDetectorServer/Makefile rename to slsDetectorServers/ctbDetectorServer/Makefile.virtual index a1c89973e..cfaacf70e 100755 --- a/slsDetectorSoftware/jungfrauDetectorServer/Makefile +++ b/slsDetectorServers/ctbDetectorServer/Makefile.virtual @@ -1,9 +1,8 @@ -CROSS = bfin-uclinux- -CC = $(CROSS)gcc -CFLAGS += -Wall -DJUNGFRAUD -DSLS_DETECTOR_FUNCTION_LIST -DDACS_INT -DSTOP_SERVER #-DVERBOSEI #-DVERBOSE -LDLIBS += -lm -lstdc++ +CC = gcc +CFLAGS += -Wall -DCHIPTESTBOARDD -DVIRTUAL -DSTOP_SERVER #-DVERBOSEI #-DVERBOSE +LDLIBS += -lm -lstdc++ -pthread -PROGS = jungfrauDetectorServer +PROGS = ctbDetectorServer_virtual DESTDIR ?= bin INSTMODE = 0777 @@ -16,16 +15,13 @@ boot: $(OBJS) versioning: @echo `tput setaf 6; ./updateGitVersion.sh; tput sgr0;` - + $(PROGS): $(OBJS) # echo $(OBJS) mkdir -p $(DESTDIR) $(CC) -o $@ $^ $(CFLAGS) $(LDLIBS) mv $(PROGS) $(DESTDIR) - rm *.gdb clean: rm -rf $(DESTDIR)/$(PROGS) *.o - - \ No newline at end of file diff --git a/slsDetectorServers/ctbDetectorServer/RegisterDefs.h b/slsDetectorServers/ctbDetectorServer/RegisterDefs.h new file mode 100755 index 000000000..f14f02e6d --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/RegisterDefs.h @@ -0,0 +1,551 @@ +#pragma once + +/* Definitions for FPGA */ +#define MEM_MAP_SHIFT 1 + +/* FPGA Version RO register */ +#define FPGA_VERSION_REG (0x00 << MEM_MAP_SHIFT) + +#define FPGA_VERSION_BRD_RVSN_OFST (0) +#define FPGA_VERSION_BRD_RVSN_MSK (0x00FFFFFF << FPGA_VERSION_BRD_RVSN_OFST) +#define FPGA_VERSION_DTCTR_TYP_OFST (24) +#define FPGA_VERSION_DTCTR_TYP_MSK (0x000000FF << FPGA_VERSION_DTCTR_TYP_OFST) +#define FPGA_VERSION_DTCTR_TYP_CTB_VAL ((0x4 << FPGA_VERSION_DTCTR_TYP_OFST) & FPGA_VERSION_DTCTR_TYP_MSK) + +/* Fix pattern RO register */ +#define FIX_PATT_REG (0x01 << MEM_MAP_SHIFT) + +#define FIX_PATT_VAL (0xACDC2016) + +/* Status RO register */ +#define STATUS_REG (0x02 << MEM_MAP_SHIFT) + +#define STATUS_RN_BSY_OFST (0) +#define STATUS_RN_BSY_MSK (0x00000001 << STATUS_RN_BSY_OFST) +#define STATUS_RDT_BSY_OFST (1) +#define STATUS_RDT_BSY_MSK (0x00000001 << STATUS_RDT_BSY_OFST) +#define STATUS_ANY_FF_FLL_OFST (2) +#define STATUS_ANY_FF_FLL_MSK (0x00000001 << STATUS_ANY_FF_FLL_OFST) +#define STATUS_WTNG_FR_TRGGR_OFST (3) +#define STATUS_WTNG_FR_TRGGR_MSK (0x00000001 << STATUS_WTNG_FR_TRGGR_OFST) +#define STATUS_DLY_BFR_OFST (4) +#define STATUS_DLY_BFR_MSK (0x00000001 << STATUS_DLY_BFR_OFST) +#define STATUS_DLY_AFTR_OFST (5) +#define STATUS_DLY_AFTR_MSK (0x00000001 << STATUS_DLY_AFTR_OFST) +#define STATUS_EXPSNG_OFST (6) +#define STATUS_EXPSNG_MSK (0x00000001 << STATUS_EXPSNG_OFST) +#define STATUS_CNT_ENBL_OFST (7) +#define STATUS_CNT_ENBL_MSK (0x00000001 << STATUS_CNT_ENBL_OFST) +#define STATUS_SM_FF_FLL_OFST (11) +#define STATUS_SM_FF_FLL_MSK (0x00000001 << STATUS_SM_FF_FLL_OFST) +#define STATUS_STPPD_OFST (15) +#define STATUS_STPPD_MSK (0x00000001 << STATUS_STPPD_OFST) +#define STATUS_ALL_FF_EMPTY_OFST (16) +#define STATUS_ALL_FF_EMPTY_MSK (0x00000001 << STATUS_ALL_FF_EMPTY_OFST) +#define STATUS_CYCL_RN_BSY_OFST (17) +#define STATUS_CYCL_RN_BSY_MSK (0x00000001 << STATUS_CYCL_RN_BSY_OFST) +#define STATUS_FRM_RN_BSY_OFST (18) +#define STATUS_FRM_RN_BSY_MSK (0x00000001 << STATUS_FRM_RN_BSY_OFST) +#define STATUS_ADC_DESERON_OFST (19) +#define STATUS_ADC_DESERON_MSK (0x00000001 << STATUS_ADC_DESERON_OFST) +#define STATUS_PLL_RCNFG_BSY_OFST (20) +#define STATUS_PLL_RCNFG_BSY_MSK (0x00000001 << STATUS_PLL_RCNFG_BSY_OFST) +#define STATUS_DT_STRMNG_BSY_OFST (21) +#define STATUS_DT_STRMNG_BSY_MSK (0x00000001 << STATUS_DT_STRMNG_BSY_OFST) +#define STATUS_FRM_PCKR_BSY_OFST (22) +#define STATUS_FRM_PCKR_BSY_MSK (0x00000001 << STATUS_FRM_PCKR_BSY_OFST) +#define STATUS_PLL_PHS_DN_OFST (23) +#define STATUS_PLL_PHS_DN_MSK (0x00000001 << STATUS_PLL_PHS_DN_OFST) +#define STATUS_PT_CNTRL_STTS_OFF_OFST (24) +#define STATUS_PT_CNTRL_STTS_OFF_MSK (0x000000FF << STATUS_PT_CNTRL_STTS_OFF_OFST) +#define STATUS_IDLE_MSK (0x677FF) + +/* Look at me RO register TODO */ +#define LOOK_AT_ME_REG (0x03 << MEM_MAP_SHIFT) + +/* System Status RO register */ +#define SYSTEM_STATUS_REG (0x04 << MEM_MAP_SHIFT) + +#define SYSTEM_STATUS_DDR3_CLBRTN_OK_OFST (0) +#define SYSTEM_STATUS_DDR3_CLBRTN_OK_MSK (0x00000001 << SYSTEM_STATUS_DDR3_CLBRTN_OK_OFST) +#define SYSTEM_STATUS_DDR3_CLBRTN_FL_OFST (1) +#define SYSTEM_STATUS_DDR3_CLBRTN_FL_MSK (0x00000001 << SYSTEM_STATUS_DDR3_CLBRTN_FL_OFST) +#define SYSTEM_STATUS_DDR3_INT_DN_OFST (2) +#define SYSTEM_STATUS_DDR3_INT_DN_MSK (0x00000001 << SYSTEM_STATUS_DDR3_INT_DN_OFST) +#define SYSTEM_STATUS_RCNFG_PLL_LCK_OFST (3) +#define SYSTEM_STATUS_RCNFG_PLL_LCK_MSK (0x00000001 << SYSTEM_STATUS_RCNFG_PLL_LCK_OFST) +#define SYSTEM_STATUS_PLL_A_LCK_OFST (4) +#define SYSTEM_STATUS_PLL_A_LCK_MSK (0x00000001 << SYSTEM_STATUS_PLL_A_LCK_OFST) + +/* PLL Param (Reconfiguratble PLL Parameter) RO register TODO FIXME: Same as PLL_PARAM_REG 0x50 */ +//#define PLL_PARAM_REG (0x05 << MEM_MAP_SHIFT) + +/* FIFO Data RO register TODO */ +#define FIFO_DATA_REG (0x06 << MEM_MAP_SHIFT) + +#define FIFO_DATA_HRDWR_SRL_NMBR_OFST (0) +#define FIFO_DATA_HRDWR_SRL_NMBR_MSK (0x0000FFFF << FIFO_DATA_HRDWR_SRL_NMBR_OFST) +//#define FIFO_DATA_WRD_OFST (16) +//#define FIFO_DATA_WRD_MSK (0x0000FFFF << FIFO_DATA_WRD_OFST) + +/* FIFO Status RO register TODO */ +#define FIFO_STATUS_REG (0x07 << MEM_MAP_SHIFT) + +/* FIFO Empty RO register TODO */ +#define FIFO_EMPTY_REG (0x08 << MEM_MAP_SHIFT) +#define FIFO_EMPTY_ALL_EMPTY_MSK (0xFFFFFFFF) + +/* FIFO Full RO register TODO */ +#define FIFO_FULL_REG (0x09 << MEM_MAP_SHIFT) + +/* MCB Serial Number RO register */ +#define MOD_SERIAL_NUMBER_REG (0x0A << MEM_MAP_SHIFT) + +#define MOD_SERIAL_NUMBER_OFST (0) +#define MOD_SERIAL_NUMBER_MSK (0x000000FF << MOD_SERIAL_NUMBER_OFST) +#define MOD_SERIAL_NUMBER_VRSN_OFST (16) +#define MOD_SERIAL_NUMBER_VRSN_MSK (0x0000003F << MOD_SERIAL_NUMBER_VRSN_OFST) + +/* API Version RO register */ +#define API_VERSION_REG (0x0F << MEM_MAP_SHIFT) + +#define API_VERSION_OFST (0) +#define API_VERSION_MSK (0x00FFFFFF << API_VERSION_OFST) +#define API_VERSION_DTCTR_TYP_OFST (24) +#define API_VERSION_DTCTR_TYP_MSK (0x000000FF << API_VERSION_DTCTR_TYP_OFST) + +/* Time from Start 64 bit RO register. t = GCLK x 50 ns. Reset using CONTROL_CRST. TODO */ +#define TIME_FROM_START_LSB_REG (0x10 << MEM_MAP_SHIFT) +#define TIME_FROM_START_MSB_REG (0x11 << MEM_MAP_SHIFT) + +/* Delay Left 64 bit RO register. t = DLY x 50 ns. TODO */ +#define DELAY_LEFT_LSB_REG (0x12 << MEM_MAP_SHIFT) +#define DELAY_LEFT_MSB_REG (0x13 << MEM_MAP_SHIFT) + +/* Cycles Left 64 bit RO register TODO */ +#define CYCLES_LEFT_LSB_REG (0x14 << MEM_MAP_SHIFT) +#define CYCLES_LEFT_MSB_REG (0x15 << MEM_MAP_SHIFT) + +/* Frames Left 64 bit RO register TODO */ +#define FRAMES_LEFT_LSB_REG (0x16 << MEM_MAP_SHIFT) +#define FRAMES_LEFT_MSB_REG (0x17 << MEM_MAP_SHIFT) + +/* Period Left 64 bit RO register. t = T x 50 ns. TODO */ +#define PERIOD_LEFT_LSB_REG (0x18 << MEM_MAP_SHIFT) +#define PERIOD_LEFT_MSB_REG (0x19 << MEM_MAP_SHIFT) + +/* Exposure Time Left 64 bit RO register */ +//#define EXPTIME_LEFT_LSB_REG (0x1A << MEM_MAP_SHIFT) // Not used in FW +//#define EXPTIME_LEFT_MSB_REG (0x1B << MEM_MAP_SHIFT) // Not used in FW + +/* Gates Left 64 bit RO register */ +//#define GATES_LEFT_LSB_REG (0x1C << MEM_MAP_SHIFT) // Not used in FW +//#define GATES_LEFT_MSB_REG (0x1D << MEM_MAP_SHIFT) // Not used in FW + +/* Data In 64 bit RO register TODO */ +#define DATA_IN_LSB_REG (0x1E << MEM_MAP_SHIFT) +#define DATA_IN_MSB_REG (0x1F << MEM_MAP_SHIFT) + +/* Pattern Out 64 bit RO register */ +#define PATTERN_OUT_LSB_REG (0x20 << MEM_MAP_SHIFT) +#define PATTERN_OUT_MSB_REG (0x21 << MEM_MAP_SHIFT) + +/* Frames From Start 64 bit RO register TODO */ +//#define FRAMES_FROM_START_LSB_REG (0x22 << MEM_MAP_SHIFT) // Not used in FW +//#define FRAMES_FROM_START_MSB_REG (0x23 << MEM_MAP_SHIFT) // Not used in FW + +/* Frames From Start PG 64 bit RO register. Reset using CONTROL_CRST. TODO */ +#define FRAMES_FROM_START_PG_LSB_REG (0x24 << MEM_MAP_SHIFT) +#define FRAMES_FROM_START_PG_MSB_REG (0x25 << MEM_MAP_SHIFT) + +/* Start Frame Time (Measurement Time) 64 bit register (timestamp at a frame start until reset) TODO */ +#define START_FRAME_TIME_LSB_REG (0x26 << MEM_MAP_SHIFT) +#define START_FRAME_TIME_MSB_REG (0x27 << MEM_MAP_SHIFT) + +/* Power Status RO register */ +#define POWER_STATUS_REG (0x29 << MEM_MAP_SHIFT) + +#define POWER_STATUS_ALRT_OFST (27) +#define POWER_STATUS_ALRT_MSK (0x0000001F << POWER_STATUS_ALRT_OFST) + +/* DAC Value Out RO register */ +//#define DAC_VAL_OUT_REG (0x2A << MEM_MAP_SHIFT) + +/* Slow ADC SPI Value RO register */ +#define ADC_SPI_SLOW_VAL_REG (0x2B << MEM_MAP_SHIFT) + +/* FIFO Digital In Status RO register */ +#define FIFO_DIN_STATUS_REG (0x3B << MEM_MAP_SHIFT) +#define FIFO_DIN_STATUS_FIFO_FULL_OFST (30) +#define FIFO_DIN_STATUS_FIFO_FULL_MSK (0x00000001 << FIFO_DIN_STATUS_FIFO_FULL_OFST) +#define FIFO_DIN_STATUS_FIFO_EMPTY_OFST (31) +#define FIFO_DIN_STATUS_FIFO_EMPTY_MSK (0x00000001 << FIFO_DIN_STATUS_FIFO_EMPTY_OFST) + +/* FIFO Digital In 64 bit RO register */ +#define FIFO_DIN_LSB_REG (0x3C << MEM_MAP_SHIFT) +#define FIFO_DIN_MSB_REG (0x3D << MEM_MAP_SHIFT) + +/* SPI (Serial Peripheral Interface) DAC, HV RW register */ +#define SPI_REG (0x40 << MEM_MAP_SHIFT) + +#define SPI_DAC_SRL_DGTL_OTPT_OFST (0) +#define SPI_DAC_SRL_DGTL_OTPT_MSK (0x00000001 << SPI_DAC_SRL_DGTL_OTPT_OFST) +#define SPI_DAC_SRL_CLK_OTPT_OFST (1) +#define SPI_DAC_SRL_CLK_OTPT_MSK (0x00000001 << SPI_DAC_SRL_CLK_OTPT_OFST) +#define SPI_DAC_SRL_CS_OTPT_OFST (2) +#define SPI_DAC_SRL_CS_OTPT_MSK (0x00000001 << SPI_DAC_SRL_CS_OTPT_OFST) +#define SPI_HV_SRL_DGTL_OTPT_OFST (8) +#define SPI_HV_SRL_DGTL_OTPT_MSK (0x00000001 << SPI_HV_SRL_DGTL_OTPT_OFST) +#define SPI_HV_SRL_CLK_OTPT_OFST (9) +#define SPI_HV_SRL_CLK_OTPT_MSK (0x00000001 << SPI_HV_SRL_CLK_OTPT_OFST) +#define SPI_HV_SRL_CS_OTPT_OFST (10) +#define SPI_HV_SRL_CS_OTPT_MSK (0x00000001 << SPI_HV_SRL_CS_OTPT_OFST) + +/* ADC SPI (Serial Peripheral Interface) RW register */ +#define ADC_SPI_REG (0x41 << MEM_MAP_SHIFT) + +#define ADC_SPI_SRL_CLK_OTPT_OFST (0) +#define ADC_SPI_SRL_CLK_OTPT_MSK (0x00000001 << ADC_SPI_SRL_CLK_OTPT_OFST) +#define ADC_SPI_SRL_DT_OTPT_OFST (1) +#define ADC_SPI_SRL_DT_OTPT_MSK (0x00000001 << ADC_SPI_SRL_DT_OTPT_OFST) +#define ADC_SPI_SRL_CS_OTPT_OFST (2) +#define ADC_SPI_SRL_CS_OTPT_MSK (0x0000000F << ADC_SPI_SRL_CS_OTPT_OFST) +#define ADC_SPI_SLOW_SRL_DT_OFST (8) +#define ADC_SPI_SLOW_SRL_DT_MSK (0x00000001 << ADC_SPI_SLOW_SRL_DT_OFST) +#define ADC_SPI_SLOW_SRL_CLK_OFST (9) +#define ADC_SPI_SLOW_SRL_CLK_MSK (0x00000001 << ADC_SPI_SLOW_SRL_CLK_OFST) +#define ADC_SPI_SLOW_SRL_CNV_OFST (10) +#define ADC_SPI_SLOW_SRL_CNV_MSK (0x00000001 << ADC_SPI_SLOW_SRL_CNV_OFST) + +/* ADC Offset RW register */ +#define ADC_OFFSET_REG (0x42 << MEM_MAP_SHIFT) + +#define ADC_OFFSET_ADC_PPLN_OFST (0) +#define ADC_OFFSET_ADC_PPLN_MSK (0x000000FF << ADC_OFFSET_ADC_PPLN_OFST) +#define ADC_OFFSET_DBT_PPLN_OFST (16) +#define ADC_OFFSET_DBT_PPLN_MSK (0x000000FF << ADC_OFFSET_DBT_PPLN_OFST) + +/* ADC Port Invert RW register */ +#define ADC_PORT_INVERT_REG (0x43 << MEM_MAP_SHIFT) + +#define ADC_PORT_INVERT_0_INPT_OFST (0) +#define ADC_PORT_INVERT_0_INPT_MSK (0x000000FF << ADC_PORT_INVERT_0_INPT_OFST) +#define ADC_PORT_INVERT_1_INPT_OFST (8) +#define ADC_PORT_INVERT_1_INPT_MSK (0x000000FF << ADC_PORT_INVERT_1_INPT_OFST) +#define ADC_PORT_INVERT_2_INPT_OFST (16) +#define ADC_PORT_INVERT_2_INPT_MSK (0x000000FF << ADC_PORT_INVERT_2_INPT_OFST) +#define ADC_PORT_INVERT_3_INPT_OFST (24) +#define ADC_PORT_INVERT_3_INPT_MSK (0x000000FF << ADC_PORT_INVERT_3_INPT_OFST) + +/* Dummy RW register */ +#define DUMMY_REG (0x44 << MEM_MAP_SHIFT) + +#define DUMMY_FIFO_CHNNL_SLCT_OFST (0) +#define DUMMY_FIFO_CHNNL_SLCT_MSK (0x0000003F << DUMMY_FIFO_CHNNL_SLCT_OFST) +#define DUMMY_ANLG_FIFO_RD_STRBE_OFST (8) +#define DUMMY_ANLG_FIFO_RD_STRBE_MSK (0x00000001 << DUMMY_ANLG_FIFO_RD_STRBE_OFST) +#define DUMMY_DGTL_FIFO_RD_STRBE_OFST (9) +#define DUMMY_DGTL_FIFO_RD_STRBE_MSK (0x00000001 << DUMMY_DGTL_FIFO_RD_STRBE_OFST) + +/* Receiver IP Address RW register */ +#define RX_IP_REG (0x45 << MEM_MAP_SHIFT) + +/* UDP Port RW register */ +#define UDP_PORT_REG (0x46 << MEM_MAP_SHIFT) + +#define UDP_PORT_RX_OFST (0) +#define UDP_PORT_RX_MSK (0x0000FFFF << UDP_PORT_RX_OFST) +#define UDP_PORT_TX_OFST (16) +#define UDP_PORT_TX_MSK (0x0000FFFF << UDP_PORT_TX_OFST) + +/* Receiver Mac Address 64 bit RW register */ +#define RX_MAC_LSB_REG (0x47 << MEM_MAP_SHIFT) +#define RX_MAC_MSB_REG (0x48 << MEM_MAP_SHIFT) + +#define RX_MAC_LSB_OFST (0) +#define RX_MAC_LSB_MSK (0xFFFFFFFF << RX_MAC_LSB_OFST) +#define RX_MAC_MSB_OFST (0) +#define RX_MAC_MSB_MSK (0x0000FFFF << RX_MAC_MSB_OFST) + +/* Detector/ Transmitter Mac Address 64 bit RW register */ +#define TX_MAC_LSB_REG (0x49 << MEM_MAP_SHIFT) +#define TX_MAC_MSB_REG (0x4A << MEM_MAP_SHIFT) + +#define TX_MAC_LSB_OFST (0) +#define TX_MAC_LSB_MSK (0xFFFFFFFF << TX_MAC_LSB_OFST) +#define TX_MAC_MSB_OFST (0) +#define TX_MAC_MSB_MSK (0x0000FFFF << TX_MAC_MSB_OFST) + +/* Detector/ Transmitter IP Address RW register */ +#define TX_IP_REG (0x4B << MEM_MAP_SHIFT) + +/* Detector/ Transmitter IP Checksum RW register */ +#define TX_IP_CHECKSUM_REG (0x4C << MEM_MAP_SHIFT) + +#define TX_IP_CHECKSUM_OFST (0) +#define TX_IP_CHECKSUM_MSK (0x0000FFFF << TX_IP_CHECKSUM_OFST) + +/* Configuration RW register */ +#define CONFIG_REG (0x4D << MEM_MAP_SHIFT) + +#define CONFIG_LED_DSBL_OFST (0) +#define CONFIG_LED_DSBL_MSK (0x00000001 << CONFIG_LED_DSBL_OFST) +#define CONFIG_DSBL_ANLG_OTPT_OFST (8) +#define CONFIG_DSBL_ANLG_OTPT_MSK (0x00000001 << CONFIG_DSBL_ANLG_OTPT_OFST) +#define CONFIG_ENBLE_DGTL_OTPT_OFST (9) +#define CONFIG_ENBLE_DGTL_OTPT_MSK (0x00000001 << CONFIG_ENBLE_DGTL_OTPT_OFST) +#define CONFIG_GB10_SND_UDP_OFST (12) +#define CONFIG_GB10_SND_UDP_MSK (0x00000001 << CONFIG_GB10_SND_UDP_OFST) + +/* External Signal RW register */ +#define EXT_SIGNAL_REG (0x4E << MEM_MAP_SHIFT) + +#define EXT_SIGNAL_OFST (0) +#define EXT_SIGNAL_MSK (0x00000001 << EXT_SIGNAL_OFST) +#define EXT_SIGNAL_AUTO_VAL ((0x0 << EXT_SIGNAL_OFST) & EXT_SIGNAL_MSK) +#define EXT_SIGNAL_TRGGR_VAL ((0x1 << EXT_SIGNAL_OFST) & EXT_SIGNAL_MSK) + +/* Control RW register */ +#define CONTROL_REG (0x4F << MEM_MAP_SHIFT) + +#define CONTROL_STRT_ACQSTN_OFST (0) +#define CONTROL_STRT_ACQSTN_MSK (0x00000001 << CONTROL_STRT_ACQSTN_OFST) +#define CONTROL_STP_ACQSTN_OFST (1) +#define CONTROL_STP_ACQSTN_MSK (0x00000001 << CONTROL_STP_ACQSTN_OFST) +//#define CONTROL_STRT_FF_TST_OFST (2) +//#define CONTROL_STRT_FF_TST_MSK (0x00000001 << CONTROL_STRT_FF_TST_OFST) +//#define CONTROL_STP_FF_TST_OFST (3) +//#define CONTROL_STP_FF_TST_MSK (0x00000001 << CONTROL_STP_FF_TST_OFST) +//#define CONTROL_STRT_RDT_OFST (4) +//#define CONTROL_STRT_RDT_MSK (0x00000001 << CONTROL_STRT_RDT_OFST) +//#define CONTROL_STP_RDT_OFST (5) +//#define CONTROL_STP_RDT_MSK (0x00000001 << CONTROL_STP_RDT_OFST) +#define CONTROL_STRT_EXPSR_OFST (6) +#define CONTROL_STRT_EXPSR_MSK (0x00000001 << CONTROL_STRT_EXPSR_OFST) +//#define CONTROL_STP_EXPSR_OFST (7) +//#define CONTROL_STP_EXPSR_MSK (0x00000001 << CONTROL_STP_RDT_OFST) +//#define CONTROL_STRT_TRN_OFST (8) +//#define CONTROL_STRT_TRN_MSK (0x00000001 << CONTROL_STRT_RDT_OFST) +//#define CONTROL_STP_TRN_OFST (9) +//#define CONTROL_STP_TRN_MSK (0x00000001 << CONTROL_STP_RDT_OFST) +#define CONTROL_CRE_RST_OFST (10) +#define CONTROL_CRE_RST_MSK (0x00000001 << CONTROL_CRE_RST_OFST) +#define CONTROL_PRPHRL_RST_OFST (11) // Only GBE10? +#define CONTROL_PRPHRL_RST_MSK (0x00000001 << CONTROL_PRPHRL_RST_OFST) +#define CONTROL_MMRY_RST_OFST (12) +#define CONTROL_MMRY_RST_MSK (0x00000001 << CONTROL_MMRY_RST_OFST) +//#define CONTROL_PLL_RCNFG_WR_OFST (13) +//#define CONTROL_PLL_RCNFG_WR_MSK (0x00000001 << CONTROL_PLL_RCNFG_WR_OFST) +#define CONTROL_SND_10GB_PCKT_OFST (14) +#define CONTROL_SND_10GB_PCKT_MSK (0x00000001 << CONTROL_SND_10GB_PCKT_OFST) +#define CONTROL_CLR_ACQSTN_FIFO_OFST (15) +#define CONTROL_CLR_ACQSTN_FIFO_MSK (0x00000001 << CONTROL_CLR_ACQSTN_FIFO_OFST) + +/* Reconfiguratble PLL Paramater RW register */ +#define PLL_PARAM_REG (0x50 << MEM_MAP_SHIFT) + +/* Reconfiguratble PLL Control RW regiser */ +#define PLL_CNTRL_REG (0x51 << MEM_MAP_SHIFT) + +#define PLL_CNTRL_RCNFG_PRMTR_RST_OFST (0) +#define PLL_CNTRL_RCNFG_PRMTR_RST_MSK (0x00000001 << PLL_CNTRL_RCNFG_PRMTR_RST_OFST) +#define PLL_CNTRL_WR_PRMTR_OFST (2) +#define PLL_CNTRL_WR_PRMTR_MSK (0x00000001 << PLL_CNTRL_WR_PRMTR_OFST) +#define PLL_CNTRL_PLL_RST_OFST (3) +#define PLL_CNTRL_PLL_RST_MSK (0x00000001 << PLL_CNTRL_PLL_RST_OFST) +#define PLL_CNTRL_ADDR_OFST (16) +#define PLL_CNTRL_ADDR_MSK (0x0000003F << PLL_CNTRL_ADDR_OFST) + +/* Pattern Control RW register */ +#define PATTERN_CNTRL_REG (0x52 << MEM_MAP_SHIFT) + +#define PATTERN_CNTRL_WR_OFST (0) +#define PATTERN_CNTRL_WR_MSK (0x00000001 << PATTERN_CNTRL_WR_OFST) +#define PATTERN_CNTRL_RD_OFST (1) +#define PATTERN_CNTRL_RD_MSK (0x00000001 << PATTERN_CNTRL_RD_OFST) +#define PATTERN_CNTRL_ADDR_OFST (16) +#define PATTERN_CNTRL_ADDR_MSK (0x0000FFFF << PATTERN_CNTRL_ADDR_OFST) + +/* Pattern Limit RW regiser */ +#define PATTERN_LIMIT_REG (0x53 << MEM_MAP_SHIFT) + +#define PATTERN_LIMIT_STRT_OFST (0) +#define PATTERN_LIMIT_STRT_MSK (0x0000FFFF << PATTERN_LIMIT_STRT_OFST) +#define PATTERN_LIMIT_STP_OFST (16) +#define PATTERN_LIMIT_STP_MSK (0x0000FFFF << PATTERN_LIMIT_STP_OFST) + +/* Pattern Loop 0 Address RW regiser */ +#define PATTERN_LOOP_0_ADDR_REG (0x54 << MEM_MAP_SHIFT) + +#define PATTERN_LOOP_0_ADDR_STRT_OFST (0) +#define PATTERN_LOOP_0_ADDR_STRT_MSK (0x0000FFFF << PATTERN_LOOP_0_ADDR_STRT_OFST) +#define PATTERN_LOOP_0_ADDR_STP_OFST (16) +#define PATTERN_LOOP_0_ADDR_STP_MSK (0x0000FFFF << PATTERN_LOOP_0_ADDR_STP_OFST) + +/* Pattern Loop 0 Iteration RW regiser */ +#define PATTERN_LOOP_0_ITERATION_REG (0x55 << MEM_MAP_SHIFT) + +/* Pattern Loop 1 Address RW regiser */ +#define PATTERN_LOOP_1_ADDR_REG (0x56 << MEM_MAP_SHIFT) + +#define PATTERN_LOOP_1_ADDR_STRT_OFST (0) +#define PATTERN_LOOP_1_ADDR_STRT_MSK (0x0000FFFF << PATTERN_LOOP_1_ADDR_STRT_OFST) +#define PATTERN_LOOP_1_ADDR_STP_OFST (16) +#define PATTERN_LOOP_1_ADDR_STP_MSK (0x0000FFFF << PATTERN_LOOP_1_ADDR_STP_OFST) + +/* Pattern Loop 1 Iteration RW regiser */ +#define PATTERN_LOOP_1_ITERATION_REG (0x57 << MEM_MAP_SHIFT) + +/* Pattern Loop 2 Address RW regiser */ +#define PATTERN_LOOP_2_ADDR_REG (0x58 << MEM_MAP_SHIFT) + +#define PATTERN_LOOP_2_ADDR_STRT_OFST (0) +#define PATTERN_LOOP_2_ADDR_STRT_MSK (0x0000FFFF << PATTERN_LOOP_2_ADDR_STRT_OFST) +#define PATTERN_LOOP_2_ADDR_STP_OFST (16) +#define PATTERN_LOOP_2_ADDR_STP_MSK (0x0000FFFF << PATTERN_LOOP_2_ADDR_STP_OFST) + +/* Pattern Loop 2 Iteration RW regiser */ +#define PATTERN_LOOP_2_ITERATION_REG (0x59 << MEM_MAP_SHIFT) + +/* Pattern Wait 0 RW regiser */ +#define PATTERN_WAIT_0_ADDR_REG (0x5A << MEM_MAP_SHIFT) + +#define PATTERN_WAIT_0_ADDR_OFST (0) +#define PATTERN_WAIT_0_ADDR_MSK (0x0000FFFF << PATTERN_WAIT_0_ADDR_OFST) +//FIXME: is mask 3FF + +/* Pattern Wait 1 RW regiser */ +#define PATTERN_WAIT_1_ADDR_REG (0x5B << MEM_MAP_SHIFT) + +#define PATTERN_WAIT_1_ADDR_OFST (0) +#define PATTERN_WAIT_1_ADDR_MSK (0x0000FFFF << PATTERN_WAIT_1_ADDR_OFST) + +/* Pattern Wait 2 RW regiser */ +#define PATTERN_WAIT_2_ADDR_REG (0x5C << MEM_MAP_SHIFT) + +#define PATTERN_WAIT_2_ADDR_OFST (0) +#define PATTERN_WAIT_2_ADDR_MSK (0x0000FFFF << PATTERN_WAIT_2_ADDR_OFST) + +/* Samples RW register */ +#define SAMPLES_REG (0x5D << MEM_MAP_SHIFT) + +/** Power RW register */ +#define POWER_REG (0x5E << MEM_MAP_SHIFT) + +#define POWER_ENBL_VLTG_RGLTR_OFST (16) +#define POWER_ENBL_VLTG_RGLTR_MSK (0x0000001F << POWER_ENBL_VLTG_RGLTR_OFST) +#define POWER_HV_SLCT_OFST (31) +#define POWER_HV_SLCT_MSK (0x00000001 << POWER_HV_SLCT_OFST) + +/* Number of Words RW register TODO */ +#define NUMBER_OF_WORDS_REG (0x5F << MEM_MAP_SHIFT) + + +/* Delay 64 bit RW register. t = DLY x 50 ns. */ +#define DELAY_LSB_REG (0x60 << MEM_MAP_SHIFT) +#define DELAY_MSB_REG (0x61 << MEM_MAP_SHIFT) + +/* Cycles 64 bit RW register */ +#define CYCLES_LSB_REG (0x62 << MEM_MAP_SHIFT) +#define CYCLES_MSB_REG (0x63 << MEM_MAP_SHIFT) + +/* Frames 64 bit RW register */ +#define FRAMES_LSB_REG (0x64 << MEM_MAP_SHIFT) +#define FRAMES_MSB_REG (0x65 << MEM_MAP_SHIFT) + +/* Period 64 bit RW register */ +#define PERIOD_LSB_REG (0x66 << MEM_MAP_SHIFT) +#define PERIOD_MSB_REG (0x67 << MEM_MAP_SHIFT) + +/* Period 64 bit RW register */ +//#define EXPTIME_LSB_REG (0x68 << MEM_MAP_SHIFT) // Not used in FW +//#define EXPTIME_MSB_REG (0x69 << MEM_MAP_SHIFT) // Not used in FW + +/* Gates 64 bit RW register */ +//#define GATES_LSB_REG (0x6A << MEM_MAP_SHIFT) // Not used in FW +//#define GATES_MSB_REG (0x6B << MEM_MAP_SHIFT) // Not used in FW + +/* Pattern IO Control 64 bit RW regiser + * Each bit configured as output(1)/ input(0) */ +#define PATTERN_IO_CNTRL_LSB_REG (0x6C << MEM_MAP_SHIFT) +#define PATTERN_IO_CNTRL_MSB_REG (0x6D << MEM_MAP_SHIFT) + +/* Pattern IO Clock Control 64 bit RW regiser + * When bit n enabled (1), clocked output for DIO[n] (T run clock) + * When bit n disabled (0), Dio[n] driven by its pattern output */ +#define PATTERN_IO_CLK_CNTRL_LSB_REG (0x6E << MEM_MAP_SHIFT) +#define PATTERN_IO_CLK_CNTRL_MSB_REG (0x6F << MEM_MAP_SHIFT) + +/* Pattern In 64 bit RW register */ +#define PATTERN_IN_LSB_REG (0x70 << MEM_MAP_SHIFT) +#define PATTERN_IN_MSB_REG (0x71 << MEM_MAP_SHIFT) + +/* Pattern Wait Timer 0 64 bit RW register. t = PWT1 x T run clock */ +#define PATTERN_WAIT_TIMER_0_LSB_REG (0x72 << MEM_MAP_SHIFT) +#define PATTERN_WAIT_TIMER_0_MSB_REG (0x73 << MEM_MAP_SHIFT) + +/* Pattern Wait Timer 1 64 bit RW register. t = PWT2 x T run clock */ +#define PATTERN_WAIT_TIMER_1_LSB_REG (0x74 << MEM_MAP_SHIFT) +#define PATTERN_WAIT_TIMER_1_MSB_REG (0x75 << MEM_MAP_SHIFT) + +/* Pattern Wait Timer 2 64 bit RW register. t = PWT3 x T run clock */ +#define PATTERN_WAIT_TIMER_2_LSB_REG (0x76 << MEM_MAP_SHIFT) +#define PATTERN_WAIT_TIMER_2_MSB_REG (0x77 << MEM_MAP_SHIFT) + +/* ADC Disable RW register TODO */ +#define ADC_DISABLE_REG (0x78 << MEM_MAP_SHIFT) + +/* DAC Value RW register TODO */ +//#define DAC_VALUE_REG (0x79 << MEM_MAP_SHIFT) + +/* DAC Number RW register TODO */ +//#define DAC_NUMBER_REG (0x7A << MEM_MAP_SHIFT) + +/* Digital Bit External Trigger RW register */ +#define DBIT_EXT_TRG_REG (0x7B << MEM_MAP_SHIFT) + +#define DBIT_EXT_TRG_SRC_OFST (0) +#define DBIT_EXT_TRG_SRC_MSK (0x0000003F << DBIT_EXT_TRG_SRC_OFST) +#define DBIT_EXT_TRG_OPRTN_MD_OFST (16) +#define DBIT_EXT_TRG_OPRTN_MD_MSK (0x00000001 << DBIT_EXT_TRG_OPRTN_MD_OFST) + +/* Pin Delay 0 RW register */ +#define OUTPUT_DELAY_0_REG (0x7C << MEM_MAP_SHIFT) +#define OUTPUT_DELAY_0_OTPT_STTNG_STEPS (25) +#define OUTPUT_DELAY_0_OTPT_STTNG_OFST (0) //t = OTPT_STTNG * 25 ps, max for Cyclone V = 775 ps +#define OUTPUT_DELAY_0_OTPT_STTNG_MSK (0x0000001F << OUTPUT_DELAY_0_OTPT_STTNG_OFST) +// 1: load dynamic output settings, 0: trigger start of dynamic output delay configuration pn falling edge of ODT (output delay trigger) bit +#define OUTPUT_DELAY_0_OTPT_TRGGR_OFST (31) +#define OUTPUT_DELAY_0_OTPT_TRGGR_MSK (0x00000001 << OUTPUT_DELAY_0_OTPT_TRGGR_OFST) +#define OUTPUT_DELAY_0_OTPT_TRGGR_LD_VAL (1) +#define OUTPUT_DELAY_0_OTPT_TRGGR_STRT_VAL (0) + +/* Pin Delay 1 RW register + * Each bit configured as enable for dynamic output delay configuration */ +#define PIN_DELAY_1_REG (0x7D << MEM_MAP_SHIFT) + +/** Pattern Mask 64 bit RW regiser */ +#define PATTERN_MASK_LSB_REG (0x80 << MEM_MAP_SHIFT) +#define PATTERN_MASK_MSB_REG (0x81 << MEM_MAP_SHIFT) + +/** Pattern Set 64 bit RW regiser */ +#define PATTERN_SET_LSB_REG (0x82 << MEM_MAP_SHIFT) +#define PATTERN_SET_MSB_REG (0x83 << MEM_MAP_SHIFT) + +/** I2C Control register */ +#define I2C_TRANSFER_COMMAND_FIFO_REG (0x100 << MEM_MAP_SHIFT) +#define I2C_RX_DATA_FIFO_REG (0x101 << MEM_MAP_SHIFT) +#define I2C_CONTROL_REG (0x102 << MEM_MAP_SHIFT) +#define I2C_STATUS_REG (0x105 << MEM_MAP_SHIFT) +#define I2C_RX_DATA_FIFO_LEVEL_REG (0x107 << MEM_MAP_SHIFT) +#define I2C_SCL_LOW_COUNT_REG (0x108 << MEM_MAP_SHIFT) +#define I2C_SCL_HIGH_COUNT_REG (0x109 << MEM_MAP_SHIFT) +#define I2C_SDA_HOLD_REG (0x10A << MEM_MAP_SHIFT) +//fixme: upto 0x10f + + + + + + + diff --git a/slsDetectorServers/ctbDetectorServer/UDPPacketHeaderGenerator.h b/slsDetectorServers/ctbDetectorServer/UDPPacketHeaderGenerator.h new file mode 120000 index 000000000..eb0223a3e --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/UDPPacketHeaderGenerator.h @@ -0,0 +1 @@ +../slsDetectorServer/UDPPacketHeaderGenerator.h \ No newline at end of file diff --git a/slsDetectorServers/ctbDetectorServer/ansi.h b/slsDetectorServers/ctbDetectorServer/ansi.h new file mode 120000 index 000000000..4a82d0575 --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/ansi.h @@ -0,0 +1 @@ +../../slsSupportLib/include/ansi.h \ No newline at end of file diff --git a/slsDetectorServers/ctbDetectorServer/bin/ctbDetectorServer_refactor b/slsDetectorServers/ctbDetectorServer/bin/ctbDetectorServer_refactor new file mode 100755 index 000000000..341d61559 Binary files /dev/null and b/slsDetectorServers/ctbDetectorServer/bin/ctbDetectorServer_refactor differ diff --git a/slsDetectorSoftware/jungfrauDetectorServer/blackfin.h b/slsDetectorServers/ctbDetectorServer/blackfin.h similarity index 100% rename from slsDetectorSoftware/jungfrauDetectorServer/blackfin.h rename to slsDetectorServers/ctbDetectorServer/blackfin.h diff --git a/slsDetectorServers/ctbDetectorServer/common.h b/slsDetectorServers/ctbDetectorServer/common.h new file mode 120000 index 000000000..6776eb607 --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/common.h @@ -0,0 +1 @@ +../slsDetectorServer/common.h \ No newline at end of file diff --git a/slsDetectorSoftware/gotthardDetectorServer/commonServerFunctions.h b/slsDetectorServers/ctbDetectorServer/commonServerFunctions.h similarity index 100% rename from slsDetectorSoftware/gotthardDetectorServer/commonServerFunctions.h rename to slsDetectorServers/ctbDetectorServer/commonServerFunctions.h diff --git a/slsDetectorServers/ctbDetectorServer/communication_funcs.c b/slsDetectorServers/ctbDetectorServer/communication_funcs.c new file mode 120000 index 000000000..30435fdc4 --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/communication_funcs.c @@ -0,0 +1 @@ +../slsDetectorServer/communication_funcs.c \ No newline at end of file diff --git a/slsDetectorServers/ctbDetectorServer/communication_funcs.h b/slsDetectorServers/ctbDetectorServer/communication_funcs.h new file mode 120000 index 000000000..c0c144994 --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/communication_funcs.h @@ -0,0 +1 @@ +../slsDetectorServer/communication_funcs.h \ No newline at end of file diff --git a/slsDetectorServers/ctbDetectorServer/communication_funcs_UDP.h b/slsDetectorServers/ctbDetectorServer/communication_funcs_UDP.h new file mode 120000 index 000000000..0d434a97d --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/communication_funcs_UDP.h @@ -0,0 +1 @@ +../slsDetectorServer/communication_funcs_UDP.h \ No newline at end of file diff --git a/slsDetectorServers/ctbDetectorServer/logger.h b/slsDetectorServers/ctbDetectorServer/logger.h new file mode 120000 index 000000000..ff1930ce3 --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/logger.h @@ -0,0 +1 @@ +../slsDetectorServer/logger.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/programfpga.h b/slsDetectorServers/ctbDetectorServer/programfpga.h similarity index 100% rename from slsDetectorSoftware/jungfrauDetectorServer/programfpga.h rename to slsDetectorServers/ctbDetectorServer/programfpga.h diff --git a/slsDetectorServers/ctbDetectorServer/slsDetectorFunctionList.c b/slsDetectorServers/ctbDetectorServer/slsDetectorFunctionList.c new file mode 100755 index 000000000..4df427af2 --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/slsDetectorFunctionList.c @@ -0,0 +1,2512 @@ +#include "slsDetectorFunctionList.h" +#include "versionAPI.h" +#include "logger.h" + +#include "communication_funcs_UDP.h" +#include "UDPPacketHeaderGenerator.h" +#include "AD9257.h" // commonServerFunctions.h, blackfin.h, ansi.h +#include "AD7689.h" // slow adcs +#include "LTC2620.h" // dacs +#include "MAX1932.h" // hv +#include "INA226.h" // i2c +#include "ALTERA_PLL.h" // pll +#ifndef VIRTUAL +#include "programfpga.h" +#else +#include "blackfin.h" +#include +#include // usleep +#include +#include +#endif + +// Global variable from slsDetectorServer_funcs +extern int debugflag; + +// Global variable from UDPPacketHeaderGenerator +extern uint64_t udpFrameNumber; +extern uint32_t udpPacketNumber; + +int firmware_compatibility = OK; +int firmware_check_done = 0; +char firmware_message[MAX_STR_LENGTH]; + +#ifdef VIRTUAL +pthread_t pthread_virtual_tid; +int virtual_status = 0; +int virtual_stop = 0; +#endif + +int dataBytes = 0; +char* ramValues = 0; +char udpPacketData[UDP_PACKET_DATA_BYTES + sizeof(sls_detector_header)]; + +int32_t clkPhase[NUM_CLOCKS] = {0, 0, 0, 0}; +uint32_t clkDivider[NUM_CLOCKS] = {40, 20, 20, 200}; + +int dacValues[NDAC] = {0}; +// software limit that depends on the current chip on the ctb +int vLimit = 0; + +int highvoltage = 0; +ROI rois[MAX_ROIS]; +int nROI = 0; +uint32_t adcDisableMask = 0; +int analogEnable = 1; +int digitalEnable = 0; +int nSamples = 1; +char volatile *now_ptr = 0; + +int isFirmwareCheckDone() { + return firmware_check_done; +} + +int getFirmwareCheckResult(char** mess) { + *mess = firmware_message; + return firmware_compatibility; +} + +void basictests() { + firmware_compatibility = OK; + firmware_check_done = 0; + memset(firmware_message, 0, MAX_STR_LENGTH); +#ifdef VIRTUAL + FILE_LOG(logINFOBLUE, ("******** Chip Test Board Virtual Server *****************\n")); + if (mapCSP0() == FAIL) { + strcpy(firmware_message, + "Could not map to memory. Dangerous to continue.\n"); + FILE_LOG(logERROR, (firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + firmware_check_done = 1; + return; +#else + + defineGPIOpins(); + resetFPGA(); + if (mapCSP0() == FAIL) { + strcpy(firmware_message, + "Could not map to memory. Dangerous to continue.\n"); + FILE_LOG(logERROR, ("%s\n\n", firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + + // does check only if flag is 0 (by default), set by command line + if ((!debugflag) && ((checkType() == FAIL) || (testFpga() == FAIL) || (testBus() == FAIL))) { + strcpy(firmware_message, + "Could not pass basic tests of FPGA and bus. Dangerous to continue.\n"); + FILE_LOG(logERROR, ("%s\n\n", firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + + uint16_t hversion = getHardwareVersionNumber(); + uint16_t hsnumber = getHardwareSerialNumber(); + uint32_t ipadd = getDetectorIP(); + uint64_t macadd = getDetectorMAC(); + int64_t fwversion = getDetectorId(DETECTOR_FIRMWARE_VERSION); + int64_t swversion = getDetectorId(DETECTOR_SOFTWARE_VERSION); + int64_t sw_fw_apiversion = 0; + int64_t client_sw_apiversion = getDetectorId(CLIENT_SOFTWARE_API_VERSION); + + + if (fwversion >= MIN_REQRD_VRSN_T_RD_API) + sw_fw_apiversion = getDetectorId(SOFTWARE_FIRMWARE_API_VERSION); + FILE_LOG(logINFOBLUE, ("************ Chip Test Board Server *********************\n" + "Hardware Version:\t\t 0x%x\n" + "Hardware Serial Nr:\t\t 0x%x\n" + + "Detector IP Addr:\t\t 0x%x\n" + "Detector MAC Addr:\t\t 0x%llx\n\n" + + "Firmware Version:\t\t 0x%llx\n" + "Software Version:\t\t 0x%llx\n" + "F/w-S/w API Version:\t\t 0x%llx\n" + "Required Firmware Version:\t 0x%x\n" + "Client-Software API Version:\t 0x%llx\n" + "********************************************************\n", + hversion, hsnumber, + ipadd, + (long long unsigned int)macadd, + (long long int)fwversion, + (long long int)swversion, + (long long int)sw_fw_apiversion, + REQRD_FRMWR_VRSN, + (long long int)client_sw_apiversion + )); + + // return if flag is not zero, debug mode + if (debugflag) { + firmware_check_done = 1; + return; + } + + + //cant read versions + FILE_LOG(logINFO, ("Testing Firmware-software compatibility:\n")); + if(!fwversion || !sw_fw_apiversion){ + strcpy(firmware_message, + "Cant read versions from FPGA. Please update firmware.\n"); + FILE_LOG(logERROR, (firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + + //check for API compatibility - old server + if(sw_fw_apiversion > REQRD_FRMWR_VRSN){ + sprintf(firmware_message, + "This detector software software version (0x%llx) is incompatible.\n" + "Please update detector software (min. 0x%llx) to be compatible with this firmware.\n", + (long long int)sw_fw_apiversion, + (long long int)REQRD_FRMWR_VRSN); + FILE_LOG(logERROR, (firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + + //check for firmware compatibility - old firmware + if( REQRD_FRMWR_VRSN > fwversion) { + sprintf(firmware_message, + "This firmware version (0x%llx) is incompatible.\n" + "Please update firmware (min. 0x%llx) to be compatible with this server.\n", + (long long int)fwversion, + (long long int)REQRD_FRMWR_VRSN); + FILE_LOG(logERROR, (firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + FILE_LOG(logINFO, ("\tCompatibility - success\n")); + firmware_check_done = 1; +#endif +} + +int checkType() { +#ifdef VIRTUAL + return OK; +#endif + uint32_t type = ((bus_r(FPGA_VERSION_REG) & FPGA_VERSION_DTCTR_TYP_MSK) >> FPGA_VERSION_DTCTR_TYP_OFST); + uint32_t expectedType = (((FPGA_VERSION_DTCTR_TYP_CTB_VAL) & FPGA_VERSION_DTCTR_TYP_MSK) >> FPGA_VERSION_DTCTR_TYP_OFST); + + if (type != expectedType) { + FILE_LOG(logERROR, ("(Type Fail) - This is not a Chip Test Board Server (read %d, expected %d)\n", + type, expectedType)); + return FAIL; + } + return OK; +} + +int testFpga() { +#ifdef VIRTUAL + return OK; +#endif + FILE_LOG(logINFO, ("Testing FPGA:\n")); + + //fixed pattern + int ret = OK; + uint32_t val = bus_r(FIX_PATT_REG); + if (val == FIX_PATT_VAL) { + FILE_LOG(logINFO, ("\tFixed pattern: successful match (0x%08x)\n",val)); + } else { + FILE_LOG(logERROR, ("Fixed pattern does not match! Read 0x%08x, expected 0x%08x\n", val, FIX_PATT_VAL)); + ret = FAIL; + } + + if (ret == OK) { + // Delay LSB reg + FILE_LOG(logINFO, ("\tTesting Delay LSB Register:\n")); + uint32_t addr = DELAY_LSB_REG; + + // store previous delay value + uint32_t previousValue = bus_r(addr); + + volatile uint32_t val = 0, readval = 0; + int times = 1000 * 1000; + int i = 0; + for (i = 0; i < times; ++i) { + val = 0x5A5A5A5A - i; + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("1:Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + break; + } + val = (i + (i << 10) + (i << 20)); + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("2:Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + break; + } + val = 0x0F0F0F0F; + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("3:Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + break; + } + val = 0xF0F0F0F0; + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("4:Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + break; + } + } + // write back previous value + bus_w(addr, previousValue); + if (ret == OK) { + FILE_LOG(logINFO, ("\tSuccessfully tested FPGA Delay LSB Register %d times\n", times)); + } + } + + return ret; +} + +int testBus() { +#ifdef VIRTUAL + return OK; +#endif + FILE_LOG(logINFO, ("Testing Bus:\n")); + + int ret = OK; + uint32_t addr = DELAY_LSB_REG; + + // store previous delay value + uint32_t previousValue = bus_r(addr); + + volatile uint32_t val = 0, readval = 0; + int times = 1000 * 1000; + int i = 0; + + for (i = 0; i < times; ++i) { + val += 0xbbbbb; + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + } + } + + // write back previous value + bus_w(addr, previousValue); + + if (ret == OK) { + FILE_LOG(logINFO, ("\tSuccessfully tested bus %d times\n", times)); + } + return ret; +} + +int detectorTest( enum digitalTestMode arg){ +#ifdef VIRTUAL + return OK; +#endif + switch(arg){ + case DETECTOR_FIRMWARE_TEST: return testFpga(); + case DETECTOR_BUS_TEST: return testBus(); + default: + FILE_LOG(logERROR, ("Test %s not implemented for this detector\n", (int)arg)); + break; + } + return OK; +} + + +/* Ids */ + +int64_t getDetectorId(enum idMode arg){ + int64_t retval = -1; + + switch(arg){ + case DETECTOR_SERIAL_NUMBER: + return getDetectorNumber(); + case DETECTOR_FIRMWARE_VERSION: + return getFirmwareVersion(); + case SOFTWARE_FIRMWARE_API_VERSION: + return getFirmwareAPIVersion(); + case DETECTOR_SOFTWARE_VERSION: + case CLIENT_SOFTWARE_API_VERSION: + return APICTB; + default: + return retval; + } +} + +uint64_t getFirmwareVersion() { +#ifdef VIRTUAL + return 0; +#endif + return ((bus_r(FPGA_VERSION_REG) & FPGA_VERSION_BRD_RVSN_MSK) >> FPGA_VERSION_BRD_RVSN_OFST); +} + +uint64_t getFirmwareAPIVersion() { +#ifdef VIRTUAL + return 0; +#endif + return ((bus_r(API_VERSION_REG) & API_VERSION_MSK) >> API_VERSION_OFST); +} + +uint16_t getHardwareVersionNumber() { +#ifdef VIRTUAL + return 0; +#endif + return ((bus_r(MOD_SERIAL_NUMBER_REG) & MOD_SERIAL_NUMBER_VRSN_MSK) >> MOD_SERIAL_NUMBER_VRSN_OFST); +} + +uint16_t getHardwareSerialNumber() { +#ifdef VIRTUAL + return 0; +#endif + return ((bus_r(MOD_SERIAL_NUMBER_REG) & MOD_SERIAL_NUMBER_MSK) >> MOD_SERIAL_NUMBER_OFST); +} + +uint32_t getDetectorNumber(){ +#ifdef VIRTUAL + return 0; +#endif + return bus_r(MOD_SERIAL_NUMBER_REG); +} + +uint64_t getDetectorMAC() { +#ifdef VIRTUAL + return 0; +#else + char output[255],mac[255]=""; + uint64_t res=0; + FILE* sysFile = popen("ifconfig eth0 | grep HWaddr | cut -d \" \" -f 11", "r"); + fgets(output, sizeof(output), sysFile); + pclose(sysFile); + //getting rid of ":" + char * pch; + pch = strtok (output,":"); + while (pch != NULL){ + strcat(mac,pch); + pch = strtok (NULL, ":"); + } + sscanf(mac,"%llx",&res); + return res; +#endif +} + +uint32_t getDetectorIP(){ +#ifdef VIRTUAL + return 0; +#endif + char temp[50]=""; + uint32_t res=0; + //execute and get address + char output[255]; + FILE* sysFile = popen("ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2", "r"); + fgets(output, sizeof(output), sysFile); + pclose(sysFile); + + //converting IPaddress to hex. + char* pcword = strtok (output,"."); + while (pcword != NULL) { + sprintf(output,"%02x",atoi(pcword)); + strcat(temp,output); + pcword = strtok (NULL, "."); + } + strcpy(output,temp); + sscanf(output, "%x", &res); + //FILE_LOG(logINFO, ("ip:%x\n",res); + + return res; +} + + +/* initialization */ + +void initControlServer(){ + setupDetector(); +} + +void initStopServer() { + + usleep(CTRL_SRVR_INIT_TIME_US); + if (mapCSP0() == FAIL) { + FILE_LOG(logERROR, ("Stop Server: Map Fail. Dangerous to continue. Goodbye!\n")); + exit(EXIT_FAILURE); + } +} + + +/* set up detector */ + +void setupDetector() { + FILE_LOG(logINFO, ("This Server is for 1 Chip Test Board module\n")); + + // default variables + dataBytes = 0; + if (ramValues) { + free(ramValues); + ramValues = 0; + } + { + int i = 0; + for (i = 0; i < NUM_CLOCKS; ++i) { + clkPhase[i] = 0; + } + clkDivider[RUN_CLK] = DEFAULT_RUN_CLK; + clkDivider[ADC_CLK] = DEFAULT_ADC_CLK; + clkDivider[SYNC_CLK] = DEFAULT_SYNC_CLK; + clkDivider[DBIT_CLK] = DEFAULT_DBIT_CLK; + for (i = 0; i < NDAC; ++i) + dacValues[i] = -1; + } + vLimit = DEFAULT_VLIMIT; + highvoltage = 0; + nROI = 0; + adcDisableMask = 0; + analogEnable = 1; + digitalEnable = 0; + nSamples = 1; + now_ptr = 0; + + + ALTERA_PLL_ResetPLLAndReconfiguration(); + resetCore(); + resetPeripheral(); + cleanFifos(); + + // hv + MAX1932_SetDefines(SPI_REG, SPI_HV_SRL_CS_OTPT_MSK, SPI_HV_SRL_CLK_OTPT_MSK, SPI_HV_SRL_DGTL_OTPT_MSK, SPI_HV_SRL_DGTL_OTPT_OFST, HIGHVOLTAGE_MIN, HIGHVOLTAGE_MAX); + MAX1932_Disable(); + setHighVoltage(DEFAULT_HIGH_VOLTAGE); + + // power off voltage regulators + powerOff(); + + // adcs + AD9257_SetDefines(ADC_SPI_REG, ADC_SPI_SRL_CS_OTPT_MSK, ADC_SPI_SRL_CLK_OTPT_MSK, ADC_SPI_SRL_DT_OTPT_MSK, ADC_SPI_SRL_DT_OTPT_OFST); + AD9257_Disable(); + AD9257_Configure(); + + // slow adcs + AD7689_SetDefines(ADC_SPI_REG, ADC_SPI_SLOW_VAL_REG, ADC_SPI_SLOW_SRL_CNV_MSK, ADC_SPI_SLOW_SRL_CLK_MSK, ADC_SPI_SLOW_SRL_DT_MSK, ADC_SPI_SLOW_SRL_DT_OFST); + AD7689_Disable(); + AD7689_Configure(); + + // dacs + LTC2620_SetDefines(SPI_REG, SPI_DAC_SRL_CS_OTPT_MSK, SPI_DAC_SRL_CLK_OTPT_MSK, SPI_DAC_SRL_DGTL_OTPT_MSK, SPI_DAC_SRL_DGTL_OTPT_OFST, NDAC, DAC_MIN_MV, DAC_MAX_MV); //has to be before setvchip + LTC2620_Disable(); + LTC2620_Configure(); + // switch off dacs (power regulators most likely only sets to minimum (if power enable on)) + FILE_LOG(logINFOBLUE, ("Powering down all dacs\n")); + { + int idac = 0; + for (idac = 0; idac < NDAC; ++idac) { + setDAC(idac, LTC2620_PWR_DOWN_VAL, 0); //has to be before setvchip + } + } + + // power regulators + // I2C + INA226_ConfigureI2CCore(I2C_SHUNT_RESISTER_OHMS, I2C_CONTROL_REG, I2C_STATUS_REG, I2C_RX_DATA_FIFO_REG, I2C_RX_DATA_FIFO_LEVEL_REG, I2C_SCL_LOW_COUNT_REG, I2C_SCL_HIGH_COUNT_REG, I2C_SDA_HOLD_REG, I2C_TRANSFER_COMMAND_FIFO_REG); + INA226_CalibrateCurrentRegister(I2C_POWER_VIO_DEVICE_ID); + INA226_CalibrateCurrentRegister(I2C_POWER_VA_DEVICE_ID); + INA226_CalibrateCurrentRegister(I2C_POWER_VB_DEVICE_ID); + INA226_CalibrateCurrentRegister(I2C_POWER_VC_DEVICE_ID); + INA226_CalibrateCurrentRegister(I2C_POWER_VD_DEVICE_ID); + setVchip(VCHIP_MIN_MV); + + // altera pll + ALTERA_PLL_SetDefines(PLL_CNTRL_REG, PLL_PARAM_REG, PLL_CNTRL_RCNFG_PRMTR_RST_MSK, PLL_CNTRL_WR_PRMTR_MSK, PLL_CNTRL_PLL_RST_MSK, PLL_CNTRL_ADDR_MSK, PLL_CNTRL_ADDR_OFST); + + bus_w(ADC_PORT_INVERT_REG, 0);// depends on chip + + FILE_LOG(logINFOBLUE, ("Setting Default parameters\n")); + cleanFifos(); // FIXME: why twice? + resetCore(); + + // 1G UDP + enableTenGigabitEthernet(0); + + //Initialization of acquistion parameters + setTimer(SAMPLES, DEFAULT_NUM_SAMPLES); // update databytes and allocate ram + setTimer(FRAME_NUMBER, DEFAULT_NUM_FRAMES); + setTimer(ACQUISITION_TIME, DEFAULT_EXPTIME); + setTimer(CYCLES_NUMBER, DEFAULT_NUM_CYCLES); + setTimer(FRAME_PERIOD, DEFAULT_PERIOD); + setTimer(DELAY_AFTER_TRIGGER, DEFAULT_DELAY); + setTiming(DEFAULT_TIMING_MODE); + setReadOutFlags(NORMAL_READOUT); + + // clear roi + { + int ret = OK, retvalsize = 0; + setROI(0, rois, &retvalsize, &ret); + } +} + +int allocateRAM() { + int oldDataBytes = dataBytes; + updateDataBytes(); + + // only allcoate RAM for 1 giga udp (if 10G, return) + if (enableTenGigabitEthernet(-1)) + return OK; + + + // update only if change in databytes + if (dataBytes == oldDataBytes) { + FILE_LOG(logDEBUG1, ("RAM of size %d already allocated. Nothing to be done.\n", dataBytes)); + return OK; + } + // Zero databytes + if (dataBytes <= 0) { + FILE_LOG(logERROR, ("Can not allocate RAM for 0 bytes (databytes: 0).\n")); + return FAIL; + } + // clear RAM + if (ramValues) { + free(ramValues); + ramValues = 0; + } + // allocate RAM + ramValues = malloc(dataBytes); + // cannot malloc + if (ramValues == NULL) { + FILE_LOG(logERROR, ("Can not allocate RAM for even 1 frame. " + "Probably cause: Memory Leak.\n")); + return FAIL; + } + + FILE_LOG(logINFO, ("\tRAM allocated to %d bytes\n", dataBytes)); + return OK; +} + +void updateDataBytes() { + int oldDataBytes = dataBytes; + dataBytes = NCHIP * getChannels() * NUM_BYTES_PER_PIXEL * nSamples; + if (dataBytes != oldDataBytes) { + FILE_LOG(logINFO, ("\tUpdating Databytes: %d\n", dataBytes)); + } +} + +int getChannels() { + int nchans = 0; + + if (analogEnable) { + nchans += NCHAN_ANALOG; + // remove the channels disabled + int ichan = 0; + for (ichan = 0; ichan < NCHAN_ANALOG; ++ichan) { + if (adcDisableMask & (1 << ichan)) + --nchans; + } + } + if (digitalEnable) + nchans += NCHAN_DIGITAL; + FILE_LOG(logINFO, ("\tNumber of Channels calculated: %d\n", nchans)) + return nchans; +} + + +/* firmware functions (resets) */ + +void cleanFifos() { +#ifdef VIRTUAL + return; +#endif + FILE_LOG(logINFO, ("Clearing Acquisition Fifos\n")); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_CLR_ACQSTN_FIFO_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_CLR_ACQSTN_FIFO_MSK); +} + +void resetCore() { +#ifdef VIRTUAL + return; +#endif + FILE_LOG(logINFO, ("Resetting Core\n")); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_CRE_RST_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_CRE_RST_MSK); +} + +void resetPeripheral() { +#ifdef VIRTUAL + return; +#endif + FILE_LOG(logINFO, ("Resetting Peripheral\n")); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_PRPHRL_RST_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_PRPHRL_RST_MSK); +} + + +/* set parameters - dr, roi */ + +int setDynamicRange(int dr){ + return DYNAMIC_RANGE; +} + +ROI* setROI(int n, ROI arg[], int *retvalsize, int *ret) { + uint32_t addr = ADC_DISABLE_REG; + + // set ROI + if(n >= 0) { + // clear roi + if (!n) { + FILE_LOG(logINFO, ("Clearing ROI\n")); + adcDisableMask = 0; + } + // set roi + else { + FILE_LOG(logINFO, ("Setting ROI:\n")); + adcDisableMask = 0xffffffff; + int iroi = 0; + // for every roi + for (iroi = 0; iroi < n; ++iroi) { + FILE_LOG(logINFO, ("\t%d: (%d, %d)\n", iroi, arg[iroi].xmin, arg[iroi].xmax)); + // swap if xmin > xmax + if (arg[iroi].xmin > arg[iroi].xmax) { + int temp = arg[iroi].xmin; + arg[iroi].xmin = arg[iroi].xmax; + arg[iroi].xmax = temp; + FILE_LOG(logINFORED, ("\tCorrected %d: (%d, %d)\n", iroi, arg[iroi].xmin, arg[iroi].xmax)); + } + int ich = 0; + // for the roi specified + for (ich = arg[iroi].xmin; ich <= arg[iroi].xmax; ++ich) { + // valid channel (disable) + if (ich >= 0 && ich < NCHAN_ANALOG) + adcDisableMask &= ~(1 << ich); + + FILE_LOG(logDEBUG1, ("%d: ich:%d adcDisableMask:0x%08x\n", + iroi, ich, adcDisableMask)); + } + } + } + FILE_LOG(logINFO, ("\tSetting adcDisableMask to 0x%08x\n", adcDisableMask)); + bus_w(addr, adcDisableMask); + } + + // get roi + adcDisableMask = bus_r(addr); + FILE_LOG(logDEBUG1, ("Getting adcDisableMask: 0x%08x\n", adcDisableMask)); + + nROI = 0; + if (adcDisableMask) { + int ich = 0; + // loop through channels + for (ich = 0; ich < NCHAN_ANALOG; ++ich) { + // channel disabled + if ((~adcDisableMask) & (1 << ich)) { + // first channel + if (ich == 0) { + ++nROI; + rois[nROI - 1].xmin = ich; + rois[nROI - 1].xmax = ich; + rois[nROI - 1].ymin = -1; + rois[nROI - 1].ymax = -1; + } + // not first channel + else { + // previous channel enabled (so increase roi) + if ((adcDisableMask) & (1 << (ich - 1))) { + ++nROI; + // max roi level + if (nROI > MAX_ROIS) { + nROI = -1; + *ret = FAIL; + FILE_LOG(logERROR, ("Max ROI reached!\n")); + break; + } + rois[nROI - 1].xmin = ich; + rois[nROI - 1].ymin = -1; + rois[nROI - 1].ymax = -1; + } + // set max as current one each time + rois[nROI - 1].xmax = ich; + } + } + } + } + + // print + if (!nROI) { + FILE_LOG(logINFO, ("\tROI: None\n")); + } else { + FILE_LOG(logINFO, ("ROI:\n")); + int i = 0; + for (i = 0; i < nROI; ++i) { + FILE_LOG(logINFO, ("\t%d: (%d, %d)\n", i, rois[i].xmin, rois[i].xmax)); + + } + } + + // validate and update databytes + if (n >= 0) { + // validate + if((n != 0) && ((arg[0].xmin != rois[0].xmin)|| + (arg[0].xmax != rois[0].xmax)|| + (arg[0].ymin != rois[0].ymin)|| + (arg[0].ymax != rois[0].ymax))) { + *ret = FAIL; + FILE_LOG(logERROR, ("\tCould not set given ROI\n")); + } + if(n != nROI) { + *ret = FAIL; + FILE_LOG(logERROR, ("\tCould not set or clear ROIs\n")); + } + // update databytes (now that mask is up to date from fpga) and allocate ram + if (allocateRAM() == FAIL) { + *ret = FAIL; + nROI = -2; + } + } + + *retvalsize = nROI; + return rois; +} + + +/* parameters - speed, readout */ + +void setSpeed(enum speedVariable ind, int val, int mode) { + switch(ind) { + case ADC_PHASE: + FILE_LOG(logINFOBLUE, ("Configuring ADC Phase\n")); + configurePhase(ADC_CLK, val, mode); + break; + case DBIT_PHASE: + FILE_LOG(logINFOBLUE, ("Configuring Dbit Phase\n")); + configurePhase(DBIT_CLK, val, mode); + break; + case ADC_CLOCK: + FILE_LOG(logINFOBLUE, ("Configuring ADC Clock\n")); + configureFrequency(ADC_CLK, val); + configureSyncFrequency(ADC_CLK); + break; + case DBIT_CLOCK: + FILE_LOG(logINFOBLUE, ("Configuring Dbit Clock\n")); + configureFrequency(DBIT_CLK, val); + configureSyncFrequency(DBIT_CLK); + break; + case ADC_PIPELINE: + setAdcOffsetRegister(1, val); + break; + case DBIT_PIPELINE: + setAdcOffsetRegister(0, val); + break; + case CLOCK_DIVIDER: + FILE_LOG(logINFOBLUE, ("Configuring Run Clock\n")); + configureFrequency(RUN_CLK, val); + configureSyncFrequency(RUN_CLK); + break; + default: + return; + } +} + +int getSpeed(enum speedVariable ind, int mode) { + switch(ind) { + case ADC_PHASE: + return getPhase(ADC_CLK, mode); + case DBIT_PHASE: + return getPhase(DBIT_CLK, mode); + case MAX_ADC_PHASE_SHIFT: + return getMaxPhase(ADC_CLK); + case MAX_DBIT_PHASE_SHIFT: + return getMaxPhase(DBIT_CLK); + case ADC_CLOCK: + return getFrequency(ADC_CLK); + case DBIT_CLOCK: + return getFrequency(DBIT_CLK); + case CLOCK_DIVIDER: + return getFrequency(RUN_CLK); + case ADC_PIPELINE: + return getAdcOffsetRegister(1); + case DBIT_PIPELINE: + return getAdcOffsetRegister(0); + default: + return -1; + } +} + +enum readOutFlags setReadOutFlags(enum readOutFlags val) { + enum readOutFlags retval = GET_READOUT_FLAGS; + uint32_t addr = CONFIG_REG; + + // set + if (val != GET_READOUT_FLAGS) { + switch(val) { + case NORMAL_READOUT: + FILE_LOG(logINFO, ("Setting Normal Readout\n")); + bus_w(addr, bus_r(addr) & (~CONFIG_DSBL_ANLG_OTPT_MSK) & (~CONFIG_ENBLE_DGTL_OTPT_MSK)); + break; + case DIGITAL_ONLY: + FILE_LOG(logINFO, ("Setting Digital Only Readout\n")); + bus_w(addr, bus_r(addr) | CONFIG_DSBL_ANLG_OTPT_MSK | CONFIG_ENBLE_DGTL_OTPT_MSK); + break; + case ANALOG_AND_DIGITAL: + FILE_LOG(logINFO, ("Setting Analog & Digital Readout\n")); + bus_w(addr, (bus_r(addr) & (~CONFIG_DSBL_ANLG_OTPT_MSK)) | CONFIG_ENBLE_DGTL_OTPT_MSK); + break; + default: + FILE_LOG(logERROR, ("Cannot set unknown readout flag. 0x%x\n", val)); + return retval; + } + } + + // get + uint32_t regval = bus_r(addr); + FILE_LOG(logDEBUG1, ("Config Reg: 0x%08x\n", regval)); + // this bit reads analog disable, so inverse + analogEnable = (((regval & CONFIG_DSBL_ANLG_OTPT_MSK) >> CONFIG_DSBL_ANLG_OTPT_OFST) ? 0 : 1); + digitalEnable = ((regval & CONFIG_ENBLE_DGTL_OTPT_MSK) >> CONFIG_ENBLE_DGTL_OTPT_OFST); + + if (analogEnable && digitalEnable) { + retval = ANALOG_AND_DIGITAL; + FILE_LOG(logDEBUG1, ("Getting readout: Analog & Digital 0x%x\n", retval)); + } else if (analogEnable && !digitalEnable) { + retval = NORMAL_READOUT; + FILE_LOG(logDEBUG1, ("Getting readout: Normal 0x%x\n", retval)); + } else if (!analogEnable && digitalEnable) { + retval = DIGITAL_ONLY; + FILE_LOG(logDEBUG1, ("Getting readout: Digital Only 0x%x\n", retval)); + } else { + FILE_LOG(logERROR, ("Read unknown readout (Both digital and analog are disabled). " + "Config reg: 0x%x\n", regval)); + return retval; + } + + // update databytes and allocate ram + if (allocateRAM() == FAIL) { + return -2; + } + + return retval; +} + + + +/* parameters - timer */ +int64_t setTimer(enum timerIndex ind, int64_t val) { + + int64_t retval = -1; + switch(ind){ + + case FRAME_NUMBER: + if(val >= 0) { + FILE_LOG(logINFO, ("Setting #frames: %lld\n",(long long int)val)); + } + retval = set64BitReg(val, FRAMES_LSB_REG, FRAMES_MSB_REG); + FILE_LOG(logINFO, ("\tGetting #frames: %lld\n", (long long int)retval)); + break; + + case ACQUISITION_TIME: + if(val >= 0){ + FILE_LOG(logINFO, ("Setting exptime (pattern wait time level 0): %lldns\n",(long long int)val)); + val *= (1E-3 * clkDivider[RUN_CLK]); + setPatternWaitTime(0, val); + } + retval = setPatternWaitTime(0, -1) / (1E-3 * clkDivider[RUN_CLK]); + FILE_LOG(logINFO, ("\tGetting exptime (pattern wait time level 0): %lldns\n", (long long int)retval)); + break; + + case FRAME_PERIOD: + if(val >= 0){ + FILE_LOG(logINFO, ("Setting period: %lldns\n",(long long int)val)); + val *= (1E-3 * clkDivider[SYNC_CLK]); + } + retval = set64BitReg(val, PERIOD_LSB_REG, PERIOD_MSB_REG )/ (1E-3 * clkDivider[SYNC_CLK]); + FILE_LOG(logINFO, ("\tGetting period: %lldns\n", (long long int)retval)); + break; + + case DELAY_AFTER_TRIGGER: + if(val >= 0){ + FILE_LOG(logINFO, ("Setting delay: %lldns\n", (long long int)val)); + val *= (1E-3 * clkDivider[SYNC_CLK]); + } + retval = set64BitReg(val, DELAY_LSB_REG, DELAY_MSB_REG) / (1E-3 * clkDivider[SYNC_CLK]); + FILE_LOG(logINFO, ("\tGetting delay: %lldns\n", (long long int)retval)); + break; + + case CYCLES_NUMBER: + if(val >= 0) { + FILE_LOG(logINFO, ("Setting #cycles: %lld\n", (long long int)val)); + } + retval = set64BitReg(val, CYCLES_LSB_REG, CYCLES_MSB_REG); + FILE_LOG(logINFO, ("\tGetting #cycles: %lld\n", (long long int)retval)); + break; + + case SAMPLES: + if(val >= 0) { + FILE_LOG(logINFO, ("Setting #samples: %lld\n", (long long int)val)); + nSamples = val; + bus_w(SAMPLES_REG, val); + if (allocateRAM() == FAIL) { + return -1; + } + } + retval = nSamples; + FILE_LOG(logINFO, ("\tGetting #samples: %lld\n", (long long int)retval)); + break; + + default: + FILE_LOG(logERROR, ("Timer Index not implemented for this detector: %d\n", ind)); + break; + } + + return retval; + +} + + + +int64_t getTimeLeft(enum timerIndex ind){ +#ifdef VIRTUAL + return 0; +#endif + int64_t retval = -1; + switch(ind){ + + case FRAME_NUMBER: + retval = get64BitReg(FRAMES_LEFT_LSB_REG, FRAMES_LEFT_MSB_REG); + FILE_LOG(logINFO, ("Getting number of frames left: %lld\n",(long long int)retval)); + break; + + case FRAME_PERIOD: + retval = get64BitReg(PERIOD_LEFT_LSB_REG, PERIOD_LEFT_MSB_REG) / (1E-3 * clkDivider[SYNC_CLK]); + FILE_LOG(logINFO, ("Getting period left: %lldns\n", (long long int)retval)); + break; + + case DELAY_AFTER_TRIGGER: + retval = get64BitReg(DELAY_LEFT_LSB_REG, DELAY_LEFT_MSB_REG) / (1E-3 * clkDivider[SYNC_CLK]); + FILE_LOG(logINFO, ("Getting delay left: %lldns\n", (long long int)retval)); + break; + + case CYCLES_NUMBER: + retval = get64BitReg(CYCLES_LEFT_LSB_REG, CYCLES_LEFT_MSB_REG); + FILE_LOG(logINFO, ("Getting number of cycles left: %lld\n", (long long int)retval)); + break; + + case ACTUAL_TIME: + retval = get64BitReg(TIME_FROM_START_LSB_REG, TIME_FROM_START_MSB_REG) / (1E-3 * CLK_FREQ); + FILE_LOG(logINFO, ("Getting actual time (time from start): %lld\n", (long long int)retval)); + break; + + case MEASUREMENT_TIME: + retval = get64BitReg(START_FRAME_TIME_LSB_REG, START_FRAME_TIME_MSB_REG) / (1E-3 * CLK_FREQ); + FILE_LOG(logINFO, ("Getting measurement time (timestamp/ start frame time): %lld\n", (long long int)retval)); + break; + + case FRAMES_FROM_START: + case FRAMES_FROM_START_PG: + retval = get64BitReg(FRAMES_FROM_START_PG_LSB_REG, FRAMES_FROM_START_PG_MSB_REG); + FILE_LOG(logINFO, ("Getting frames from start run control %lld\n", (long long int)retval)); + break; + + default: + FILE_LOG(logERROR, ("Remaining Timer index not implemented for this detector: %d\n", ind)); + break; + } + + return retval; +} + + +int validateTimer(enum timerIndex ind, int64_t val, int64_t retval) { + if (val < 0) + return OK; + switch(ind) { + case FRAME_PERIOD: + case DELAY_AFTER_TRIGGER: + // convert to freq + val *= (1E-3 * clkDivider[SYNC_CLK]); + // convert back to timer + val = (val) / (1E-3 * clkDivider[SYNC_CLK]); + if (val != retval) { + return FAIL; + } + break; + case ACQUISITION_TIME: + // convert to freq + val *= (1E-3 * clkDivider[RUN_CLK]); + // convert back to timer + val = (val) / (1E-3 * clkDivider[RUN_CLK]); + if (val != retval) { + return FAIL; + } + break; + default: + break; + } + return OK; +} + + +/* parameters - settings */ +enum detectorSettings getSettings() { + return UNDEFINED; +} + +/* parameters - dac, adc, hv */ + + +void setDAC(enum DACINDEX ind, int val, int mV) { + if (val < 0 && val != LTC2620_PWR_DOWN_VAL) + return; + + FILE_LOG(logDEBUG1, ("Setting dac[%d]: %d %s \n", (int)ind, val, (mV ? "mV" : "dac units"))); + int dacval = val; +#ifdef VIRTUAL + if (!mV) { + dacValues[ind] = val; + } + // convert to dac units + else if (LTC2620_VoltageToDac(val, &dacval) == OK) { + dacValues[ind] = dacval; + } +#else + if (LTC2620_SetDACValue((int)ind, val, mV, &dacval) == OK) + dacValues[ind] = dacval; +#endif +} + +int getDAC(enum DACINDEX ind, int mV) { + if (!mV) { + FILE_LOG(logDEBUG1, ("Getting DAC %d : %d dac\n",ind, dacValues[ind])); + return dacValues[ind]; + } + int voltage = -1; + LTC2620_DacToVoltage(dacValues[ind], &voltage); + FILE_LOG(logDEBUG1, ("Getting DAC %d : %d dac (%d mV)\n",ind, dacValues[ind], voltage)); + return voltage; +} + +int getMaxDacSteps() { + return LTC2620_MAX_STEPS; +} + +int dacToVoltage(int dac) { + int val; + LTC2620_DacToVoltage(dac, &val); + return val; +} + +int checkVLimitCompliant(int mV) { + if (vLimit > 0 && mV > vLimit) + return FAIL; + return OK; +} + +int checkVLimitDacCompliant(int dac) { + if (vLimit > 0) { + int mv = 0; + // could not convert + if (LTC2620_DacToVoltage(dac, &mv) == FAIL) + return FAIL; + if (mv > vLimit) + return FAIL; + } + return OK; +} + +int getVLimit() { + return vLimit; +} + +void setVLimit(int l) { + if (l >= 0) + vLimit = l; +} + +int isVchipValid(int val) { + if (val < VCHIP_MIN_MV || val > VCHIP_MAX_MV) { + return 0; + } + return 1; +} + +int getVchip() { + // not set yet + if (dacValues[D_PWR_CHIP] == -1 || dacValues[D_PWR_CHIP] == LTC2620_PWR_DOWN_VAL) + return dacValues[D_PWR_CHIP]; + int voltage = -1; + // dac to voltage + ConvertToDifferentRange(LTC2620_MAX_VAL, LTC2620_MIN_VAL, VCHIP_MIN_MV, VCHIP_MAX_MV, + dacValues[D_PWR_CHIP], &voltage); + return voltage; +} + +void setVchip(int val) { + // set vchip + if (val != -1) { + FILE_LOG(logINFOBLUE, ("Setting Vchip to %d mV\n", val)); + + int dacval = LTC2620_PWR_DOWN_VAL; + + // validate & convert it to dac + if (val != LTC2620_PWR_DOWN_VAL) { + // convert voltage to dac + if (ConvertToDifferentRange(VCHIP_MIN_MV, VCHIP_MAX_MV, LTC2620_MAX_VAL, LTC2620_MIN_VAL, //min val is max V + val, &dacval) == FAIL) { + FILE_LOG(logERROR, ("\tVChip %d mV invalid. Is not between %d and %d mV\n", val, VCHIP_MIN_MV, VCHIP_MAX_MV)); + return; + } + } + FILE_LOG(logINFO, ("Setting Vchip (DAC %d): %d dac (%d mV)\n",D_PWR_CHIP, dacval, val)); + // set + setDAC(D_PWR_CHIP, dacval, 0); + } +} + +int getVChipToSet(enum DACINDEX ind, int val) { + FILE_LOG(logDEBUG1, ("Calculating vchip to set\n")); + // validate index & get adc index + int adcIndex = getADCIndexFromDACIndex(ind); + if (adcIndex == -1) { + return -1; + } + + // get maximum value of the adc values (minimum is 0) + int max = 0; + + int ipwr = 0; + // loop through the adcs + for (ipwr = 0; ipwr < NPWR -1; ++ipwr) { + + // get the dac values for each adc + int dacmV = getPower(getDACIndexFromADCIndex(ipwr)); + + // if current index, replace with value to be set + if (ipwr == adcIndex) { + dacmV = val; + } + + // update max + max = (dacmV > max) ? dacmV : max; + } + + // increment to get vchip value + max += VCHIP_POWER_INCRMNT; + + // validate with vchip minimum value + if (max < VCHIP_MIN_MV) + max = VCHIP_MIN_MV; + // with correct calulations, vchip val should never be greater than vchipmax + if (max > VCHIP_MAX_MV) { + FILE_LOG(logERROR, ("Vchip value to set %d is beyond its maximum (WEIRD)\n", max)); + return -1; + } + return max; +} + +int getDACIndexFromADCIndex(enum ADCINDEX ind) { + switch (ind) { + case V_PWR_IO: + return D_PWR_IO; + case V_PWR_A: + return D_PWR_A; + case V_PWR_B: + return D_PWR_B; + case V_PWR_C: + return D_PWR_C; + case V_PWR_D: + return D_PWR_D; + default: + FILE_LOG(logERROR, ("ADC index %d is not defined to get DAC index\n", ind)); + return -1; + } +} + +int getADCIndexFromDACIndex(enum DACINDEX ind) { + switch (ind) { + case D_PWR_IO: + return V_PWR_IO; + case D_PWR_A: + return V_PWR_A; + case D_PWR_B: + return V_PWR_B; + case D_PWR_C: + return V_PWR_C; + case D_PWR_D: + return V_PWR_D; + default: + FILE_LOG(logERROR, ("DAC index %d is not defined to get ADC index\n", ind)); + return -1; + } +} + +int isPowerValid(enum DACINDEX ind, int val) { + int min = (ind == D_PWR_IO) ? VIO_MIN_MV : POWER_RGLTR_MIN; + + // not power_rgltr_max because it is allowed only upto vchip max - 200 + if (val != 0 && (val != LTC2620_PWR_DOWN_VAL) && (val < min || val > (VCHIP_MAX_MV - VCHIP_POWER_INCRMNT))) { + return 0; + } + return 1; +} + +int getPower(enum DACINDEX ind) { + // validate index & get adc index + int adcIndex = getADCIndexFromDACIndex(ind); + if (adcIndex == -1) { + return -1; + } + + // powered enable off + { + uint32_t addr = POWER_REG; + uint32_t offset = POWER_ENBL_VLTG_RGLTR_OFST + adcIndex; + uint32_t mask = (1 << offset); + if (!(bus_r(addr) & mask)) + return 0; + } + + // not set yet + if (dacValues[ind] == -1) { + FILE_LOG(logERROR, ("Power enabled, but unknown dac value for power index %d!", ind)); + return -1; + } + + // dac powered off + if (dacValues[ind] == LTC2620_PWR_DOWN_VAL) { + FILE_LOG(logWARNING, ("Power %d enabled, dac value %d, voltage at minimum or 0\n", ind, LTC2620_PWR_DOWN_VAL)); + return LTC2620_PWR_DOWN_VAL; + } + + // vchip not set, weird error, should not happen (as vchip set to max in the beginning) + // unless user set vchip to LTC2620_PWR_DOWN_VAL and then tried to get a power regulator value + if (dacValues[D_PWR_CHIP] == -1 || dacValues[D_PWR_CHIP] == LTC2620_PWR_DOWN_VAL) { + FILE_LOG(logERROR, ("Cannot read power regulator %d (vchip not set)." + "Set a power regulator, which will also set vchip.\n")); + return -1; + } + + // convert dac to voltage + int retval = -1; + ConvertToDifferentRange(LTC2620_MAX_VAL, LTC2620_MIN_VAL, POWER_RGLTR_MIN, POWER_RGLTR_MAX, + dacValues[ind], &retval); + return retval; +} + +void setPower(enum DACINDEX ind, int val) { + // validate index & get adc index + int adcIndex = getADCIndexFromDACIndex(ind); + if (adcIndex == -1) { + return; + } + + uint32_t addr = POWER_REG; + uint32_t offset = POWER_ENBL_VLTG_RGLTR_OFST + adcIndex; + uint32_t mask = (1 << offset); + + // set power + if (val != -1) { + FILE_LOG(logINFO, ("Setting Power to %d mV\n", val)); + + // validate value (already checked at tcp) + if (!isPowerValid(ind, val)) { + FILE_LOG(logERROR, ("Invalid value of %d mV for Power %d. Is not between %d and %d mV\n", + val, ind, (ind == D_PWR_IO ? VIO_MIN_MV : POWER_RGLTR_MIN), POWER_RGLTR_MAX)); + return; + } + + // get vchip to set vchip (calculated now before switching off power enable) + int vchip = getVChipToSet(ind, val); + FILE_LOG(logDEBUG1, ("Vchip to set: %d\n", vchip)); + // index problem of vchip calculation problem + if (vchip == -1) + return; + + // Switch off power enable + FILE_LOG(logDEBUG1, ("Switching off power enable\n")); + bus_w(addr, bus_r(addr) & ~(mask)); + + // power down dac + FILE_LOG(logDEBUG1, ("Powering off P%d (DAC %d)\n", adcIndex, ind)); + setDAC(ind, LTC2620_PWR_DOWN_VAL, 0); + + // set vchip + setVchip(vchip); + if (getVchip() != vchip) { + FILE_LOG(logERROR, ("Weird, Could not set vchip. Set %d, read %d\n.", vchip, getVchip())); + return; + } + + //(power off is anyway done with power enable) + if (val == 0) + val = LTC2620_PWR_DOWN_VAL; + + // convert it to dac (power off is anyway done with power enable) + if (val != LTC2620_PWR_DOWN_VAL) { + FILE_LOG(logDEBUG1, ("Convert Power of %d mV to dac units\n", val)); + + int dacval = -1; + // convert voltage to dac + if (ConvertToDifferentRange(POWER_RGLTR_MIN, POWER_RGLTR_MAX, LTC2620_MAX_VAL, LTC2620_MIN_VAL, + val, &dacval) == FAIL) { + FILE_LOG(logERROR, ("\tPower index %d of value %d mV invalid. Is not between %d and %d mV\n", + ind, val, POWER_RGLTR_MIN, vchip - VCHIP_POWER_INCRMNT)); + return; + } + + // set and power on/ update dac + FILE_LOG(logINFO, ("Setting P%d (DAC %d): %d dac (%d mV)\n", adcIndex, ind, dacval, val)); + setDAC(ind, dacval, 0); + + // to be sure of valid conversion + if (dacval >= 0) { + FILE_LOG(logDEBUG1, ("Switching on power enable\n")); + bus_w(addr, bus_r(addr) | mask); + } + } + } +} + +void powerOff() { + uint32_t addr = POWER_REG; + FILE_LOG(logINFO, ("Powering off all voltage regulators\n")); + bus_w(addr, bus_r(addr) & (~POWER_ENBL_VLTG_RGLTR_MSK)); + FILE_LOG(logDEBUG1, ("Power Register: 0x%08x\n", bus_r(addr))); +} + + +int getADC(enum ADCINDEX ind){ +#ifdef VIRTUAL + return 0; +#endif + switch(ind) { + case V_PWR_IO: + case V_PWR_A: + case V_PWR_B: + case V_PWR_C: + case V_PWR_D: + FILE_LOG(logDEBUG1, ("Reading I2C Voltage for device Id: %d\n", (int)ind)); + return INA226_ReadVoltage(I2C_POWER_VIO_DEVICE_ID + (int)ind); + case I_PWR_IO: + case I_PWR_A: + case I_PWR_B: + case I_PWR_C: + case I_PWR_D: + FILE_LOG(logDEBUG1, ("Reading I2C Current for device Id: %d\n", (int)ind)); + return INA226_ReadCurrent(I2C_POWER_VIO_DEVICE_ID + (int)(ind - I_PWR_IO)); + + // slow adcs + case SLOW_ADC_TEMP: + FILE_LOG(logDEBUG1, ("Reading Slow ADC Temperature\n")); + return AD7689_GetTemperature(); + case SLOW_ADC0: + case SLOW_ADC1: + case SLOW_ADC2: + case SLOW_ADC3: + case SLOW_ADC4: + case SLOW_ADC5: + case SLOW_ADC6: + case SLOW_ADC7: + FILE_LOG(logDEBUG1, ("Reading Slow ADC Channel %d\n", (int)ind - SLOW_ADC0)); + return AD7689_GetChannel((int)ind - SLOW_ADC0); + default: + FILE_LOG(logERROR, ("Adc Index %d not defined \n", (int)ind)); + return -1; + } +} + + +int setHighVoltage(int val){ +#ifdef VIRTUAL + if (val >= 0) + highvoltage = val; + return highvoltage; +#endif + + // setting hv + if (val >= 0) { + FILE_LOG(logINFO, ("Setting High voltage: %d V\n", val)); + uint32_t addr = POWER_REG; + + // switch off high voltage + bus_w(addr, bus_r(addr) & (~POWER_HV_SLCT_MSK)); + + MAX1932_Set(val); + + // switch on high voltage if val > 0 + if (val > 0) + bus_w(addr, bus_r(addr) | POWER_HV_SLCT_MSK); + + highvoltage = val; + } + return highvoltage; +} + + + + + + +/* parameters - timing, extsig */ + + +void setTiming( enum externalCommunicationMode arg){ + + if(arg != GET_EXTERNAL_COMMUNICATION_MODE){ + switch((int)arg){ + case AUTO_TIMING: + FILE_LOG(logINFO, ("Set Timing: Auto\n")); + bus_w(EXT_SIGNAL_REG, bus_r(EXT_SIGNAL_REG) & ~EXT_SIGNAL_MSK); + break; + case TRIGGER_EXPOSURE: + FILE_LOG(logINFO, ("Set Timing: Trigger\n")); + bus_w(EXT_SIGNAL_REG, bus_r(EXT_SIGNAL_REG) | EXT_SIGNAL_MSK); + break; + default: + FILE_LOG(logERROR, ("Unknown timing mode %d\n", arg)); + return; + } + } +} + + +enum externalCommunicationMode getTiming() { + if (bus_r(EXT_SIGNAL_REG) == EXT_SIGNAL_MSK) + return TRIGGER_EXPOSURE; + return AUTO_TIMING; +} + + + +/* configure mac */ + + +long int calcChecksum(int sourceip, int destip) { + ip_header ip; + ip.ip_ver = 0x4; + ip.ip_ihl = 0x5; + ip.ip_tos = 0x0; + ip.ip_len = IP_PACKETSIZE; + ip.ip_ident = 0x0000; + ip.ip_flag = 0x2; //not nibble aligned (flag& offset + ip.ip_offset = 0x000; + ip.ip_ttl = 0x40; + ip.ip_protocol = 0x11; + ip.ip_chksum = 0x0000 ; // pseudo + ip.ip_sourceip = sourceip; + ip.ip_destip = destip; + + int count = sizeof(ip); + + unsigned short *addr; + addr = (unsigned short*) &(ip); /* warning: assignment from incompatible pointer type */ + + long int sum = 0; + while( count > 1 ) { + sum += *addr++; + count -= 2; + } + if (count > 0) + sum += *addr; // Add left-over byte, if any + while (sum>>16) + sum = (sum & 0xffff) + (sum >> 16);// Fold 32-bit sum to 16 bits + long int checksum = (~sum) & 0xffff; + FILE_LOG(logINFO, ("IP checksum is 0x%lx\n",checksum)); + return checksum; +} + + + +int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport){ +#ifdef VIRTUAL + return OK; +#endif + FILE_LOG(logINFOBLUE, ("Configuring MAC\n")); + // 1 giga udp + if (!enableTenGigabitEthernet(-1)) { + // if it was in 10G mode, it was not allocating RAM + if (allocateRAM() == FAIL) + return -1; + char cDestIp[MAX_STR_LENGTH]; + memset(cDestIp, 0, MAX_STR_LENGTH); + sprintf(cDestIp, "%d.%d.%d.%d", (destip>>24)&0xff,(destip>>16)&0xff,(destip>>8)&0xff,(destip)&0xff); + FILE_LOG(logINFO, ("1G UDP: Destination (IP: %s, port:%d)\n", cDestIp, udpport)); + if (setUDPDestinationDetails(cDestIp, udpport) == FAIL) { + FILE_LOG(logERROR, ("could not set udp 1G destination IP and port\n")); + return FAIL; + } + return OK; + } + + // 10 G + else { + uint32_t sourceport = DEFAULT_TX_UDP_PORT; + + FILE_LOG(logINFO, ("\tSource IP : %d.%d.%d.%d \t\t(0x%08x)\n", + (sourceip>>24)&0xff,(sourceip>>16)&0xff,(sourceip>>8)&0xff,(sourceip)&0xff, sourceip)); + FILE_LOG(logINFO, ("\tSource MAC : %02x:%02x:%02x:%02x:%02x:%02x \t(0x%010llx)\n", + (unsigned int)((sourcemac>>40)&0xFF), + (unsigned int)((sourcemac>>32)&0xFF), + (unsigned int)((sourcemac>>24)&0xFF), + (unsigned int)((sourcemac>>16)&0xFF), + (unsigned int)((sourcemac>>8)&0xFF), + (unsigned int)((sourcemac>>0)&0xFF), + (long long unsigned int)sourcemac)); + FILE_LOG(logINFO, ("\tSource Port : %d \t\t\t(0x%08x)\n",sourceport, sourceport)); + + FILE_LOG(logINFO, ("\tDest. IP : %d.%d.%d.%d \t\t(0x%08x)\n", + (destip>>24)&0xff,(destip>>16)&0xff,(destip>>8)&0xff,(destip)&0xff, destip)); + FILE_LOG(logINFO, ("\tDest. MAC : %02x:%02x:%02x:%02x:%02x:%02x \t(0x%010llx)\n", + (unsigned int)((destmac>>40)&0xFF), + (unsigned int)((destmac>>32)&0xFF), + (unsigned int)((destmac>>24)&0xFF), + (unsigned int)((destmac>>16)&0xFF), + (unsigned int)((destmac>>8)&0xFF), + (unsigned int)((destmac>>0)&0xFF), + (long long unsigned int)destmac)); + FILE_LOG(logINFO, ("\tDest. Port : %d \t\t\t(0x%08x)\n",udpport, udpport)); + + long int checksum=calcChecksum(sourceip, destip); + bus_w(TX_IP_REG, sourceip); + bus_w(RX_IP_REG, destip); + + uint32_t val = 0; + + val = ((sourcemac >> LSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(TX_MAC_LSB_REG, val); + FILE_LOG(logDEBUG1, ("Read from TX_MAC_LSB_REG: 0x%08x\n", bus_r(TX_MAC_LSB_REG))); + + val = ((sourcemac >> MSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(TX_MAC_MSB_REG,val); + FILE_LOG(logDEBUG1, ("Read from TX_MAC_MSB_REG: 0x%08x\n", bus_r(TX_MAC_MSB_REG))); + + val = ((destmac >> LSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(RX_MAC_LSB_REG, val); + FILE_LOG(logDEBUG1, ("Read from RX_MAC_LSB_REG: 0x%08x\n", bus_r(RX_MAC_LSB_REG))); + + val = ((destmac >> MSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(RX_MAC_MSB_REG, val); + FILE_LOG(logDEBUG1, ("Read from RX_MAC_MSB_REG: 0x%08x\n", bus_r(RX_MAC_MSB_REG))); + + val = (((sourceport << UDP_PORT_TX_OFST) & UDP_PORT_TX_MSK) | + ((udpport << UDP_PORT_RX_OFST) & UDP_PORT_RX_MSK)); + bus_w(UDP_PORT_REG, val); + FILE_LOG(logDEBUG1, ("Read from UDP_PORT_REG: 0x%08x\n", bus_r(UDP_PORT_REG))); + + bus_w(TX_IP_CHECKSUM_REG,(checksum << TX_IP_CHECKSUM_OFST) & TX_IP_CHECKSUM_MSK); + FILE_LOG(logDEBUG1, ("Read from TX_IP_CHECKSUM_REG: 0x%08x\n", bus_r(TX_IP_CHECKSUM_REG))); + + cleanFifos();//FIXME: resetPerpheral() for ctb? + resetPeripheral(); + usleep(WAIT_TIME_CONFIGURE_MAC); // todo maybe without + } + + return OK; +} + +int enableTenGigabitEthernet(int val) { + uint32_t addr = CONFIG_REG; + + // set + if (val != -1) { + FILE_LOG(logINFO, ("Setting 10Gbe: %d\n", (val > 0) ? 1 : 0)); + if (val > 0) { + bus_w(addr, bus_r(addr) | CONFIG_GB10_SND_UDP_MSK); + } else { + bus_w(addr, bus_r(addr) & (~CONFIG_GB10_SND_UDP_MSK)); + } + //configuremac called from client + } + return ((bus_r(addr) & CONFIG_GB10_SND_UDP_MSK) >> CONFIG_GB10_SND_UDP_OFST); +} + + + + +/* ctb specific - configure frequency, phase, pll */ + + +// ind can only be ADC_CLK or DBIT_CLK +void configurePhase(enum CLKINDEX ind, int val, int degrees) { + char clock_names[4][10]={"run_clk","adc_clk", "sync_clk", "dbit_clk"}; + int maxShift = getMaxPhase(ind); + + // validation + if (degrees && (val < 0 || val > 359)) { + FILE_LOG(logERROR, ("\tPhase provided for C%d(%s) outside limits (0 - 359°C)\n", ind, clock_names[ind])); + return; + } + if (!degrees && (val < 0 || val > maxShift - 1)) { + FILE_LOG(logERROR, ("\tPhase provided for C%d(%s) outside limits (0 - %d phase shifts)\n", ind, clock_names[ind], maxShift - 1)); + return; + } + + FILE_LOG(logINFO, ("\tConfiguring Phase of C%d(%s) to %d (degree mode: %d)\n", ind, clock_names[ind], val, degrees)); + int valShift = val; + // convert to phase shift + if (degrees) { + ConvertToDifferentRange(0, 359, 0, maxShift - 1, val, &valShift); + } + FILE_LOG(logDEBUG1, ("phase shift: %d (degrees/shift: %d)\n", valShift, val)); + + int relativePhase = valShift - clkPhase[ind]; + FILE_LOG(logDEBUG1, ("relative phase shift: %d (Current phase: %d)\n", relativePhase, clkPhase[ind])); + + // same phase + if (!relativePhase) { + FILE_LOG(logINFO, ("\tNothing to do in Phase Shift\n")); + return; + } + + int phase = 0; + if (relativePhase > 0) { + phase = (maxShift - relativePhase); + } else { + phase = (-1) * relativePhase; + } + FILE_LOG(logDEBUG1, ("[Single Direction] Phase:%d (0x%x). Max Phase shifts:%d\n", phase, phase, maxShift)); + + ALTERA_PLL_SetPhaseShift(phase, (int)ind, 0); + + clkPhase[ind] = valShift; +} + +int getPhase(enum CLKINDEX ind, int degrees) { + if (!degrees) + return clkPhase[ind]; + // convert back to degrees + int val = 0; + ConvertToDifferentRange(0, getMaxPhase(ind) - 1, 0, 359, clkPhase[ind], &val); + return val; +} + +int getMaxPhase(enum CLKINDEX ind) { + int ret = ((double)PLL_VCO_FREQ_MHZ / (double)clkDivider[ind]) * MAX_PHASE_SHIFTS_STEPS; + + char clock_names[4][10]={"run_clk","adc_clk", "sync_clk", "dbit_clk"}; + FILE_LOG(logDEBUG1, ("Max Phase Shift (%s): %d (Clock: %d MHz, VCO:%d MHz)\n", + clock_names[ind], ret, clkDivider[ind], PLL_VCO_FREQ_MHZ)); + + return ret; +} + +int validatePhaseinDegrees(enum speedVariable ind, int val, int retval) { + if (val == -1) + return OK; + enum CLKINDEX clkIndex; + switch(ind) { + case ADC_PHASE: + clkIndex = ADC_CLK; + break; + case DBIT_PHASE: + clkIndex = DBIT_CLK; + break; + default: + FILE_LOG(logERROR, ("Unknown speed enum %d for validating phase in degrees\n", (int)ind)); + } + FILE_LOG(logDEBUG1, ("validating phase in degrees for clk %d\n", clkIndex)); + int maxShift = getMaxPhase(clkIndex); + // convert degrees to shift + // convert degrees to shift + int valShift = 0; + ConvertToDifferentRange(0, 359, 0, maxShift - 1, val, &valShift); + // convert back to degrees + ConvertToDifferentRange(0, maxShift - 1, 0, 359, valShift, &val); + + if (val == retval) + return OK; + return FAIL; +} + +void configureFrequency(enum CLKINDEX ind, int val) { + char clock_names[4][10]={"run_clk","adc_clk", "sync_clk", "dbit_clk"}; + if (val <= 0) + return; + + FILE_LOG(logINFO, ("\tConfiguring Frequency of C%d(%s) to %d MHz\n", ind, clock_names[ind], val)); + + // check adc clk too high + if (ind == ADC_CLK && val > MAXIMUM_ADC_CLK) { + FILE_LOG(logERROR, ("Frequency %d MHz too high for ADC\n", val)); + return; + } + + // reset phase + if (ind == ADC_CLK || ind == DBIT_CLK) { + FILE_LOG(logINFO, ("\tReseting phase of %s\n", clock_names[ind])); + configurePhase(ind, 0, 0); + } + + // Calculate and set output frequency + clkDivider[ind] = ALTERA_PLL_SetOuputFrequency (ind, PLL_VCO_FREQ_MHZ, val); + FILE_LOG(logINFO, ("\tC%d(%s): Frequency set to %d MHz\n", ind, clock_names[ind], clkDivider[ind])); +} + +int getFrequency(enum CLKINDEX ind) { + return clkDivider[ind]; +} + +void configureSyncFrequency(enum CLKINDEX ind) { + char clock_names[4][10]={"run_clk","adc_clk", "sync_clk", "dbit_clk"}; + int clka = 0, clkb = 0; + switch(ind) { + case ADC_CLK: + clka = DBIT_CLK; + clkb = RUN_CLK; + break; + case DBIT_CLK: + clka = ADC_CLK; + clkb = RUN_CLK; + break; + case RUN_CLK: + clka = DBIT_CLK; + clkb = ADC_CLK; + break; + default: + return; + } + + int syncFreq = getFrequency(SYNC_CLK); + int retval = getFrequency(ind); + int aFreq = getFrequency(clka); + int bFreq = getFrequency(clkb); + FILE_LOG(logDEBUG1, ("Sync Frequncy:%d, RetvalFreq(%s):%d, aFreq(%s):%d, bFreq(%s):%d\n", + syncFreq, clock_names[ind], retval, clock_names[clka], aFreq, clock_names[clkb], bFreq)); + + int configure = 0; + + // find the smallest frequency + int min = (aFreq < bFreq) ? aFreq : bFreq; + min = (retval < min) ? retval : min; + + // sync is greater than min + if (syncFreq > retval) { + FILE_LOG(logINFO, ("\t--Configuring Sync Clock\n")); + configure = 1; + } + + // sync is smaller than min + else if (syncFreq < min) { + FILE_LOG(logINFO, ("\t++Configuring Sync Clock\n")); + configure = 1; + } + + // configure sync to current + if (configure) + configureFrequency(SYNC_CLK, min); +} + +void setAdcOffsetRegister(int adc, int val) { + if (val < 0) + return; + + FILE_LOG(logINFO, ("Setting %s Pipeline to %d\n", (adc ? "ADC" : "Dbit"), val)); + uint32_t offset = ADC_OFFSET_ADC_PPLN_OFST; + uint32_t mask = ADC_OFFSET_ADC_PPLN_MSK; + if (!adc) { + offset = ADC_OFFSET_DBT_PPLN_OFST; + mask = ADC_OFFSET_DBT_PPLN_MSK; + } + + uint32_t addr = ADC_OFFSET_REG; + // reset value + bus_w(addr, bus_r(addr) & ~ mask); + // set value + bus_w(addr, bus_r(addr) | ((val << offset) & mask)); + FILE_LOG(logDEBUG1, (" %s Offset: 0x%8x\n", (adc ? "ADC" : "Dbit"), bus_r(addr))); +} + +int getAdcOffsetRegister(int adc) { + if (adc) + return ((bus_r(ADC_OFFSET_REG) & ADC_OFFSET_ADC_PPLN_MSK) >> ADC_OFFSET_ADC_PPLN_OFST); + return ((bus_r(ADC_OFFSET_REG) & ADC_OFFSET_DBT_PPLN_MSK) >> ADC_OFFSET_DBT_PPLN_OFST); +} + + +// patterns + +uint64_t writePatternIOControl(uint64_t word) { + if (word != -1) { + FILE_LOG(logINFO, ("Setting Pattern - I/O Control: 0x%llx\n", (long long int) word)); + set64BitReg(word, PATTERN_IO_CNTRL_LSB_REG, PATTERN_IO_CNTRL_MSB_REG); + } + uint64_t retval = get64BitReg(PATTERN_IO_CNTRL_LSB_REG, PATTERN_IO_CNTRL_MSB_REG); + FILE_LOG(logDEBUG1, (" I/O Control: 0x%llx\n", (long long int) retval)); + return retval; +} + +uint64_t writePatternClkControl(uint64_t word) { + if (word != -1) { + FILE_LOG(logINFO, ("Setting Pattern - Clock Control: 0x%llx\n", (long long int) word)); + set64BitReg(word, PATTERN_IO_CLK_CNTRL_LSB_REG, PATTERN_IO_CLK_CNTRL_MSB_REG); + } + uint64_t retval = get64BitReg(PATTERN_IO_CLK_CNTRL_LSB_REG, PATTERN_IO_CLK_CNTRL_MSB_REG); + FILE_LOG(logDEBUG1, (" Clock Control: 0x%llx\n", (long long int) retval)); + return retval; +} + +uint64_t readPatternWord(int addr) { + // error (handled in tcp) + if (addr < 0 || addr > MAX_PATTERN_LENGTH) { + FILE_LOG(logERROR, ("Cannot get Pattern - Word. Invalid addr 0x%x. " + "Should be <= 0x%x\n", addr, MAX_PATTERN_LENGTH)); + return -1; + } + + FILE_LOG(logDEBUG1, (" Reading Pattern - Word (addr:0x%x)\n", addr)); + uint32_t reg = PATTERN_CNTRL_REG; + + // overwrite with only addr + bus_w(reg, ((addr << PATTERN_CNTRL_ADDR_OFST) & PATTERN_CNTRL_ADDR_MSK)); + + // set read strobe + bus_w(reg, bus_r(reg) | PATTERN_CNTRL_RD_MSK); + + // unset read strobe + bus_w(reg, bus_r(reg) & (~PATTERN_CNTRL_RD_MSK)); + usleep(WAIT_TIME_PATTERN_READ); + + // read value + uint64_t retval = get64BitReg(PATTERN_OUT_LSB_REG, PATTERN_OUT_MSB_REG); + FILE_LOG(logDEBUG1, (" Word(addr:0x%x): 0x%llx\n", addr, (long long int) retval)); + + return retval; +} + +uint64_t writePatternWord(int addr, uint64_t word) { + // get + if (word == -1) + return readPatternWord(addr); + + // error (handled in tcp) + if (addr < 0 || addr > MAX_PATTERN_LENGTH) { + FILE_LOG(logERROR, ("Cannot set Pattern - Word. Invalid addr 0x%x. " + "Should be <= 0x%x\n", addr, MAX_PATTERN_LENGTH)); + return -1; + } + + FILE_LOG(logINFO, ("Setting Pattern - Word (addr:0x%x, word:0x%llx)\n", addr, (long long int) word)); + uint32_t reg = PATTERN_CNTRL_REG; + + // write word + set64BitReg(word, PATTERN_IN_LSB_REG, PATTERN_IN_MSB_REG); + FILE_LOG(logDEBUG1, (" Wrote word. PatternIn Reg: 0x%llx\n", get64BitReg(PATTERN_IN_LSB_REG, PATTERN_IN_MSB_REG))); + + // overwrite with only addr + bus_w(reg, ((addr << PATTERN_CNTRL_ADDR_OFST) & PATTERN_CNTRL_ADDR_MSK)); + + // set write strobe + bus_w(reg, bus_r(reg) | PATTERN_CNTRL_WR_MSK); + + // unset write strobe + bus_w(reg, bus_r(reg) & (~PATTERN_CNTRL_WR_MSK)); + + return word; + //return readPatternWord(addr); // will start executing the pattern +} + +int setPatternWaitAddress(int level, int addr) { + + // error (handled in tcp) + if (addr > MAX_PATTERN_LENGTH) { + FILE_LOG(logERROR, ("Cannot set Pattern - Wait Address. Invalid addr 0x%x. " + "Should be <= 0x%x\n", addr, MAX_PATTERN_LENGTH)); + return -1; + } + + uint32_t reg = 0; + uint32_t offset = 0; + uint32_t mask = 0; + + switch (level) { + case 0: + reg = PATTERN_WAIT_0_ADDR_REG; + offset = PATTERN_WAIT_0_ADDR_OFST; + mask = PATTERN_WAIT_0_ADDR_MSK; + break; + case 1: + reg = PATTERN_WAIT_1_ADDR_REG; + offset = PATTERN_WAIT_1_ADDR_OFST; + mask = PATTERN_WAIT_1_ADDR_MSK; + break; + case 2: + reg = PATTERN_WAIT_2_ADDR_REG; + offset = PATTERN_WAIT_2_ADDR_OFST; + mask = PATTERN_WAIT_2_ADDR_MSK; + break; + default: + FILE_LOG(logERROR, ("Cannot set Pattern - Wait Address. Invalid level 0x%x. " + "Should be between 0 and 2.\n", level)); + return -1; + } + + // set + if (addr >= 0) { + FILE_LOG(logINFO, ("Setting Pattern - Wait Address (level:%d, addr:0x%x)\n", level, addr)); + bus_w(reg, ((addr << offset) & mask)); + } + + // get + uint32_t regval = bus_r((reg & mask) >> offset); + FILE_LOG(logDEBUG1, (" Wait Address (level:%d, addr:0x%x)\n", level, regval)); + return regval; +} + +uint64_t setPatternWaitTime(int level, uint64_t t) { + uint32_t regl = 0; + uint32_t regm = 0; + + switch (level) { + case 0: + regl = PATTERN_WAIT_TIMER_0_LSB_REG; + regm = PATTERN_WAIT_TIMER_0_MSB_REG; + break; + case 1: + regl = PATTERN_WAIT_TIMER_1_LSB_REG; + regm = PATTERN_WAIT_TIMER_1_MSB_REG; + break; + case 2: + regl = PATTERN_WAIT_TIMER_2_LSB_REG; + regm = PATTERN_WAIT_TIMER_2_MSB_REG; + break; + default: + FILE_LOG(logERROR, ("Cannot set Pattern - Wait Time. Invalid level %d. " + "Should be between 0 and 2.\n", level)); + return -1; + } + + // set + if (t >= 0) { + FILE_LOG(logINFO, ("Setting Pattern - Wait Time (level:%d, t:%lld)\n", level, (long long int)t)); + set64BitReg(t, regl, regm); + } + + // get + uint64_t regval = get64BitReg(regl, regm); + FILE_LOG(logDEBUG1, (" Wait Time (level:%d, t:%lld)\n", level, (long long int)regval)); + return regval; +} + +void setPatternLoop(int level, int *startAddr, int *stopAddr, int *nLoop) { + + // level 0-2, addr upto patternlength + 1 (checked at tcp) + if ((level != -1) && + (*startAddr > MAX_PATTERN_LENGTH || *stopAddr > MAX_PATTERN_LENGTH)) { + FILE_LOG(logERROR, ("Cannot set Pattern (Pattern Loop, level:%d, startaddr:0x%x, stopaddr:0x%x). " + "Addr must be <= 0x%x\n", + level, *startAddr, *stopAddr, MAX_PATTERN_LENGTH)); + } + + //level -1, addr upto patternlength (checked at tcp) + else if ((level == -1) && + (*startAddr > MAX_PATTERN_LENGTH || *stopAddr > MAX_PATTERN_LENGTH)) { + FILE_LOG(logERROR, ("Cannot set Pattern (Pattern Loop, complete pattern, startaddr:0x%x, stopaddr:0x%x). " + "Addr must be <= 0x%x\n", + *startAddr, *stopAddr, MAX_PATTERN_LENGTH)); + } + + uint32_t addr = 0; + uint32_t nLoopReg = 0; + uint32_t startOffset = 0; + uint32_t startMask = 0; + uint32_t stopOffset = 0; + uint32_t stopMask = 0; + + switch (level) { + case 0: + addr = PATTERN_LOOP_0_ADDR_REG; + nLoopReg = PATTERN_LOOP_0_ITERATION_REG; + startOffset = PATTERN_LOOP_0_ADDR_STRT_OFST; + startMask = PATTERN_LOOP_0_ADDR_STRT_MSK; + stopOffset = PATTERN_LOOP_0_ADDR_STP_OFST; + stopMask = PATTERN_LOOP_0_ADDR_STP_MSK; + break; + case 1: + addr = PATTERN_LOOP_1_ADDR_REG; + nLoopReg = PATTERN_LOOP_1_ITERATION_REG; + startOffset = PATTERN_LOOP_1_ADDR_STRT_OFST; + startMask = PATTERN_LOOP_1_ADDR_STRT_MSK; + stopOffset = PATTERN_LOOP_1_ADDR_STP_OFST; + stopMask = PATTERN_LOOP_1_ADDR_STP_MSK; + break; + case 2: + addr = PATTERN_LOOP_2_ADDR_REG; + nLoopReg = PATTERN_LOOP_2_ITERATION_REG; + startOffset = PATTERN_LOOP_2_ADDR_STRT_OFST; + startMask = PATTERN_LOOP_2_ADDR_STRT_MSK; + stopOffset = PATTERN_LOOP_2_ADDR_STP_OFST; + stopMask = PATTERN_LOOP_2_ADDR_STP_MSK; + break; + case -1: + // complete pattern + addr = PATTERN_LIMIT_REG; + nLoopReg = -1; + startOffset = PATTERN_LIMIT_STRT_OFST; + startMask = PATTERN_LIMIT_STRT_MSK; + stopOffset = PATTERN_LIMIT_STP_OFST; + stopMask = PATTERN_LIMIT_STP_MSK; + break; + default: + // already checked at tcp interface + FILE_LOG(logERROR, ("Cannot set Pattern - Pattern loop. Invalid level %d. " + "Should be between -1 and 2.\n", level)); + *startAddr = 0; + *stopAddr = 0; + *nLoop = 0; + } + + // set iterations + if (level >= 0) { + // set iteration + if (*nLoop >= 0) { + FILE_LOG(logINFO, ("Setting Pattern - Pattern Loop (level:%d, nLoop:%d)\n", + level, *nLoop)); + bus_w(nLoopReg, *nLoop); + } + *nLoop = bus_r(nLoopReg); + } + + // set + if (*startAddr != -1 && *stopAddr != -1) { + // writing start and stop addr + FILE_LOG(logINFO, ("Setting Pattern - Pattern Loop (level:%d, startaddr:0x%x, stopaddr:0x%x)\n", + level, *startAddr, *stopAddr)); + bus_w(addr, ((*startAddr << startOffset) & startMask) | ((*stopAddr << stopOffset) & stopMask)); + FILE_LOG(logDEBUG1, ("Addr:0x%x, val:0x%x\n", addr, bus_r(addr))); + } + + // get + else { + *startAddr = ((bus_r(addr) & startMask) >> startOffset); + FILE_LOG(logDEBUG1, ("Getting Pattern - Pattern Loop Start Address (level:%d, Read startAddr:0x%x)\n", + level, *startAddr)); + + *stopAddr = ((bus_r(addr) & stopMask) >> stopOffset); + FILE_LOG(logDEBUG1, ("Getting Pattern - Pattern Loop Stop Address (level:%d, Read stopAddr:0x%x)\n", + level, *stopAddr)); + } +} + + +int setLEDEnable(int enable) { + uint32_t addr = CONFIG_REG; + + // set + if (enable >= 0) { + FILE_LOG(logINFO, ("Switching LED %s\n", (enable > 0) ? "ON" : "OFF")); + // disable + if (enable == 0) { + bus_w(addr, bus_r(addr) | CONFIG_LED_DSBL_MSK); + } + // enable + else { + bus_w(addr, bus_r(addr) & (~CONFIG_LED_DSBL_MSK)); + } + } + // ~ to get the opposite + return (((~bus_r(addr)) & CONFIG_LED_DSBL_MSK) >> CONFIG_LED_DSBL_OFST); +} + +void setDigitalIODelay(uint64_t pinMask, int delay) { + FILE_LOG(logINFO, ("Setings Digital IO Delay (pinMask:0x%llx, delay: %d ps)\n", + (long long unsigned int)pinMask, delay)); + + int delayunit = delay / OUTPUT_DELAY_0_OTPT_STTNG_STEPS; + FILE_LOG(logDEBUG1, ("delay unit: 0x%x (steps of 25ps)\n", delayunit)); + + // set pin mask + bus_w(PIN_DELAY_1_REG, pinMask); + + uint32_t addr = OUTPUT_DELAY_0_REG; + // set delay + bus_w(addr, bus_r(addr) & (~OUTPUT_DELAY_0_OTPT_STTNG_MSK)); + bus_w(addr, (bus_r(addr) | ((delayunit << OUTPUT_DELAY_0_OTPT_STTNG_OFST) & OUTPUT_DELAY_0_OTPT_STTNG_MSK))); + + // load value + bus_w(addr, bus_r(addr) | OUTPUT_DELAY_0_OTPT_TRGGR_MSK); + + // trigger configuration + bus_w(addr, bus_r(addr) & (~OUTPUT_DELAY_0_OTPT_TRGGR_MSK)); +} + +void setPatternMask(uint64_t mask) { + set64BitReg(mask, PATTERN_MASK_LSB_REG, PATTERN_MASK_MSB_REG); +} + +uint64_t getPatternMask() { + return get64BitReg(PATTERN_MASK_LSB_REG, PATTERN_MASK_MSB_REG); +} + +void setPatternBitMask(uint64_t mask) { + set64BitReg(mask, PATTERN_SET_LSB_REG, PATTERN_SET_MSB_REG); +} + +uint64_t getPatternBitMask() { + return get64BitReg(PATTERN_SET_LSB_REG, PATTERN_SET_MSB_REG); +} + + +/* aquisition */ + +int startStateMachine(){ +#ifdef VIRTUAL + virtual_status = 1; + virtual_stop = 0; + if(pthread_create(&pthread_virtual_tid, NULL, &start_timer, NULL)) { + virtual_status = 0; + FILE_LOG(logERROR, ("Could not start Virtual acquisition thread\n")); + return FAIL; + } + FILE_LOG(logINFOGREEN, ("Virtual Acquisition started\n")); + return OK; +#endif + // 1 giga udp + if (!enableTenGigabitEthernet(-1)) { + // create udp socket + if(createUDPSocket() != OK) { + return FAIL; + } + // update header with modId, detType and version. Reset offset and fnum + createUDPPacketHeader(udpPacketData, getHardwareSerialNumber()); + } + + FILE_LOG(logINFOBLUE, ("Starting State Machine\n")); + cleanFifos(); + unsetFifoReadStrobes(); // FIXME: unnecessary to write bus_w(dumm, 0) as it is 0 in the beginnig and the strobes are always unset if set + + //start state machine + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_STRT_ACQSTN_MSK | CONTROL_STRT_EXPSR_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_STRT_ACQSTN_MSK & ~CONTROL_STRT_EXPSR_MSK); + + FILE_LOG(logINFO, ("Status Register: %08x\n",bus_r(STATUS_REG))); + return OK; +} + + +#ifdef VIRTUAL +void* start_timer(void* arg) { + int wait_in_s = (setTimer(FRAME_NUMBER, -1) * + setTimer(CYCLES_NUMBER, -1) * + (setTimer(FRAME_PERIOD, -1)/(1E9))); + FILE_LOG(logDEBUG1, ("going to wait for %d s\n", wait_in_s)); + while(!virtual_stop && (wait_in_s >= 0)) { + usleep(1000 * 1000); + wait_in_s--; + } + FILE_LOG(logINFOGREEN, ("Virtual Timer Done\n")); + + virtual_status = 0; + return NULL; +} +#endif + +int stopStateMachine(){ + FILE_LOG(logINFORED, ("Stopping State Machine\n")); +#ifdef VIRTUAL + virtual_stop = 0; + return OK; +#endif + //stop state machine + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_STP_ACQSTN_MSK); + usleep(WAIT_TIME_US_STP_ACQ); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_STP_ACQSTN_MSK); + + FILE_LOG(logINFO, ("Status Register: %08x\n",bus_r(STATUS_REG))); + + return OK; +} + + + + + +enum runStatus getRunStatus(){ +#ifdef VIRTUAL + if(virtual_status == 0){ + FILE_LOG(logINFOBLUE, ("Status: IDLE\n")); + return IDLE; + }else{ + FILE_LOG(logINFOBLUE, ("Status: RUNNING\n")); + return RUNNING; + } +#endif + FILE_LOG(logDEBUG1, ("Getting status\n")); + + uint32_t retval = bus_r(STATUS_REG); + FILE_LOG(logINFO, ("Status Register: %08x\n",retval)); + + // error + //if (retval & STATUS_SM_FF_FLL_MSK) { This bit is high when a analog fifo is full Or when external stop + if (retval & STATUS_ANY_FF_FLL_MSK) { // if adc or digital fifo is full + FILE_LOG(logINFORED, ("Status: Error (Any fifo full)\n")); + return ERROR; + } + + // running + if(retval & STATUS_RN_BSY_MSK) { + if (retval & STATUS_WTNG_FR_TRGGR_MSK) { + FILE_LOG(logINFOBLUE, ("Status: Waiting for Trigger\n")); + return WAITING; + } + + FILE_LOG(logINFOBLUE, ("Status: Running\n")); + return RUNNING; + + } + + // not running + else { + if (retval & STATUS_STPPD_MSK) { + FILE_LOG(logINFOBLUE, ("Status: Stopped\n")); + return STOPPED; + } + + if (retval & STATUS_FRM_RN_BSY_MSK) { + FILE_LOG(logINFOBLUE, ("Status: Transmitting (Read machine busy)\n")); + return TRANSMITTING; + } + + + if (! (retval & STATUS_IDLE_MSK)) { + FILE_LOG(logINFOBLUE, ("Status: Idle\n")); + return IDLE; + } + + FILE_LOG(logERROR, ("Status: Unknown status %08x\n", retval)); + return ERROR; + } +} + + +void readandSendUDPFrames(int *ret, char *mess) { + FILE_LOG(logDEBUG1, ("Reading from 1G UDP\n")); + + // validate udp socket + if (getUdPSocketDescriptor() <= 0) { + *ret = FAIL; + sprintf(mess,"UDP Socket not created. sockfd:%d\n", getUdPSocketDescriptor()); + FILE_LOG(logERROR, (mess)); + return; + } + + // every frame read + while(readFrameFromFifo() == OK) { + int bytesToSend = 0, n = 0; + while((bytesToSend = fillUDPPacket(udpPacketData))) { + n += sendUDPPacket(udpPacketData, bytesToSend); + } + if (n >= dataBytes) { + FILE_LOG(logINFO, (" Frame %lld sent (%d packets, %d databytes, n:%d bytes sent)\n", + udpFrameNumber, udpPacketNumber + 1, dataBytes, n)); + } + } + closeUDPSocket(); +} + + +void readFrame(int *ret, char *mess) { +#ifdef VIRTUAL + while(virtual_status) { + //FILE_LOG(logERROR, ("Waiting for finished flag\n"); + usleep(5000); + } + return; +#endif + // 1G + if (!enableTenGigabitEthernet(-1)) { + readandSendUDPFrames(ret, mess); + } + // 10G + else { + // wait for acquisition to be done + while(runBusy()){ + usleep(500); // random + } + } + + // ret could be fail in 1gudp for not creating udp sockets + if (*ret != FAIL) { + // frames left to give status + int64_t retval = getTimeLeft(FRAME_NUMBER) + 2; + if ( retval > 1) { + *ret = (int)FAIL; + sprintf(mess,"No data and run stopped: %lld frames left\n",(long long int)retval); + FILE_LOG(logERROR, (mess)); + } else { + *ret = (int)OK; + FILE_LOG(logINFOGREEN, ("Acquisition successfully finished\n")); + } + } +} + +void unsetFifoReadStrobes() { + bus_w(DUMMY_REG, bus_r(DUMMY_REG) & (~DUMMY_ANLG_FIFO_RD_STRBE_MSK) & (~DUMMY_DGTL_FIFO_RD_STRBE_MSK)); +} + +void readSample(int ns) { + uint32_t addr = DUMMY_REG; + + // read adcs + if (analogEnable) { + + uint32_t fifoAddr = FIFO_DATA_REG; + + // read strobe to all analog fifos + bus_w(addr, bus_r(addr) | DUMMY_ANLG_FIFO_RD_STRBE_MSK); + bus_w(addr, bus_r(addr) & (~DUMMY_ANLG_FIFO_RD_STRBE_MSK)); + // wait as it is connected directly to fifo running on a different clock + //usleep(WAIT_TIME_FIFO_RD_STROBE); + if (!(ns%1000)) { + FILE_LOG(logDEBUG1, ("Reading sample ns:%d of %d AEmtpy:0x%x AFull:0x%x Status:0x%x\n", + ns, nSamples, bus_r(FIFO_EMPTY_REG), bus_r(FIFO_FULL_REG), bus_r(STATUS_REG))); + } + + // loop through all channels + int ich = 0; + for (ich = 0; ich < NCHAN_ANALOG; ++ich) { + + // if channel is in ROI + if ((1 << ich) & ~(adcDisableMask)) { + + // unselect channel + bus_w(addr, bus_r(addr) & ~(DUMMY_FIFO_CHNNL_SLCT_MSK)); + + // select channel + bus_w(addr, bus_r(addr) | ((ich << DUMMY_FIFO_CHNNL_SLCT_OFST) & DUMMY_FIFO_CHNNL_SLCT_MSK)); + + // read fifo and write it to current position of data pointer + *((uint16_t*)now_ptr) = bus_r16(fifoAddr); + + // keep reading till the value is the same + /* while (*((uint16_t*)now_ptr) != bus_r16(fifoAddr)) { + FILE_LOG(logDEBUG1, ("%d ", ich)); + *((uint16_t*)now_ptr) = bus_r16(fifoAddr); + }*/ + + // increment pointer to data out destination + now_ptr += 2; + } + } + } + + // read digital output + if (digitalEnable) { + // read strobe to digital fifo + bus_w(addr, bus_r(addr) | DUMMY_DGTL_FIFO_RD_STRBE_MSK); + bus_w(addr, bus_r(addr) & (~DUMMY_DGTL_FIFO_RD_STRBE_MSK)); + // wait as it is connected directly to fifo running on a different clock + if (!(ns%1000)) { + FILE_LOG(logDEBUG1, ("Reading sample ns:%d of %d DEmtpy:%d DFull:%d Status:0x%x\n", + ns, nSamples, + ((bus_r(FIFO_DIN_STATUS_REG) & FIFO_DIN_STATUS_FIFO_EMPTY_MSK) >> FIFO_DIN_STATUS_FIFO_EMPTY_OFST), + ((bus_r(FIFO_DIN_STATUS_REG) & FIFO_DIN_STATUS_FIFO_FULL_MSK) >> FIFO_DIN_STATUS_FIFO_FULL_OFST), + bus_r(STATUS_REG))); + } + + // read fifo and write it to current position of data pointer + *((uint64_t*)now_ptr) = get64BitReg(FIFO_DIN_LSB_REG, FIFO_DIN_MSB_REG); + now_ptr += 8; + } +} + +uint32_t checkDataInFifo() { + uint32_t dataPresent = 0; + if (analogEnable) { + uint32_t analogFifoEmpty = bus_r(FIFO_EMPTY_REG); + FILE_LOG(logDEBUG2, ("Analog Fifo Empty (32 channels): 0x%x\n", analogFifoEmpty)); + dataPresent = (~analogFifoEmpty); + } + if (!dataPresent && digitalEnable) { + int digitalFifoEmpty = ((bus_r(FIFO_DIN_STATUS_REG) & FIFO_DIN_STATUS_FIFO_EMPTY_MSK) >> FIFO_DIN_STATUS_FIFO_EMPTY_OFST); + FILE_LOG(logDEBUG2, ("Digital Fifo Empty: %d\n",digitalFifoEmpty)); + dataPresent = (digitalFifoEmpty ? 0 : 1); + } + FILE_LOG(logDEBUG2, ("Data in Fifo :0x%x\n", dataPresent)); + return dataPresent; +} + +// only called for first sample +int checkFifoForEndOfAcquisition() { + uint32_t dataPresent = checkDataInFifo(); + FILE_LOG(logDEBUG2, ("status:0x%x\n", bus_r(STATUS_REG))); + + // as long as no data + while (!dataPresent) { + // acquisition done + if (!runBusy()) { + // wait to be sure there is no data in fifo + usleep(WAIT_TME_US_FR_ACQDONE_REG); + + // still no data + if (!checkDataInFifo()) { + FILE_LOG(logINFO, ("Acquisition Finished (State: 0x%08x), " + "no frame found .\n", bus_r(STATUS_REG))); + return FAIL; + } + // got data, exit + else { + break; + } + } + // check if data in fifo again + dataPresent = checkDataInFifo(); + } + FILE_LOG(logDEBUG1, ("Got data :0x%x\n", dataPresent)); + return OK; +} + +int readFrameFromFifo() { + int ns = 0; + // point the data pointer to the starting position of data + now_ptr = ramValues; + + // no data for this frame + if (checkFifoForEndOfAcquisition() == FAIL) { + return FAIL; + } + + // read Sample + while(ns < nSamples) { + // chceck if no data in fifo, return ns?//FIXME: ask Anna + readSample(ns); + ns++; + } + + // got frame + return OK; +} + +uint32_t runBusy() { +#ifdef VIRTUAL + return virtual_status; +#endif + uint32_t s = (bus_r(STATUS_REG) & STATUS_RN_BSY_MSK); + //FILE_LOG(logDEBUG1, ("Status Register: %08x\n", s)); + return s; +} + + + + + + + + +/* common */ + +int calculateDataBytes(){ + return dataBytes; +} + +int getTotalNumberOfChannels(){return ((int)getNumberOfChannelsPerChip() * (int)getNumberOfChips());} +int getNumberOfChips(){return NCHIP;} +int getNumberOfDACs(){return NDAC;} +int getNumberOfChannelsPerChip(){return NCHAN;} + + diff --git a/slsDetectorSoftware/eigerDetectorServer/slsDetectorFunctionList.h b/slsDetectorServers/ctbDetectorServer/slsDetectorFunctionList.h similarity index 100% rename from slsDetectorSoftware/eigerDetectorServer/slsDetectorFunctionList.h rename to slsDetectorServers/ctbDetectorServer/slsDetectorFunctionList.h diff --git a/slsDetectorSoftware/eigerDetectorServer/slsDetectorServer.c b/slsDetectorServers/ctbDetectorServer/slsDetectorServer.c similarity index 100% rename from slsDetectorSoftware/eigerDetectorServer/slsDetectorServer.c rename to slsDetectorServers/ctbDetectorServer/slsDetectorServer.c diff --git a/slsDetectorServers/ctbDetectorServer/slsDetectorServer_defs.h b/slsDetectorServers/ctbDetectorServer/slsDetectorServer_defs.h new file mode 100755 index 000000000..b1271dbcb --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/slsDetectorServer_defs.h @@ -0,0 +1,99 @@ +#pragma once +#include "sls_detector_defs.h" +#include "RegisterDefs.h" + + +#define MIN_REQRD_VRSN_T_RD_API 0x181130 +#define REQRD_FRMWR_VRSN 0x190402 + +#define CTRL_SRVR_INIT_TIME_US (1 * 1000 * 1000) + +/* Struct Definitions */ +typedef struct ip_header_struct { + uint16_t ip_len; + uint8_t ip_tos; + uint8_t ip_ihl:4 ,ip_ver:4; + uint16_t ip_offset:13,ip_flag:3; + uint16_t ip_ident; + uint16_t ip_chksum; + uint8_t ip_protocol; + uint8_t ip_ttl; + uint32_t ip_sourceip; + uint32_t ip_destip; +} ip_header; + +/* Enums */ +enum CLKINDEX {RUN_CLK, ADC_CLK, SYNC_CLK, DBIT_CLK, NUM_CLOCKS}; +enum ADCINDEX {V_PWR_IO, V_PWR_A, V_PWR_B, V_PWR_C, V_PWR_D, I_PWR_IO, I_PWR_A, I_PWR_B, I_PWR_C, I_PWR_D}; +enum DACINDEX {D0, D1, D2, D3, D4, D5, D6, D7, D8, D9, + D10, D11, D12, D13, D14, D15, D16, D17, + D_PWR_D, D_PWR_CHIP, D_PWR_C, D_PWR_B, D_PWR_A, D_PWR_IO}; + +/* Hardware Definitions */ +#define NCHAN (36) +#define NCHAN_ANALOG (32) +#define NCHAN_DIGITAL (4) +#define NCHIP (1) +#define NDAC (24) +#define NPWR (6) +#define NDAC_ONLY (NDAC - NPWR) +#define DYNAMIC_RANGE (16) +#define NUM_BYTES_PER_PIXEL (DYNAMIC_RANGE / 8) +#define CLK_FREQ (156.25) /* MHz */ +#define I2C_POWER_VIO_DEVICE_ID (0x40) +#define I2C_POWER_VA_DEVICE_ID (0x41) +#define I2C_POWER_VB_DEVICE_ID (0x42) +#define I2C_POWER_VC_DEVICE_ID (0x43) +#define I2C_POWER_VD_DEVICE_ID (0x44) +#define I2C_SHUNT_RESISTER_OHMS (0.005) + +/** Default Parameters */ +#define DEFAULT_DATA_BYTES (NCHIP * NCHAN * NUM_BITS_PER_PIXEL) +#define DEFAULT_NUM_SAMPLES (1) +#define DEFAULT_NUM_FRAMES (1) +#define DEFAULT_EXPTIME (0) +#define DEFAULT_NUM_CYCLES (1) +#define DEFAULT_PERIOD (1 * 1000 * 1000) //ns +#define DEFAULT_DELAY (0) +#define DEFAULT_HIGH_VOLTAGE (0) +#define DEFAULT_VLIMIT (-100) +#define DEFAULT_TIMING_MODE (AUTO_TIMING) +#define DEFAULT_TX_UDP_PORT (0x7e9a) +#define DEFAULT_RUN_CLK (40) +#define DEFAULT_ADC_CLK (20) +#define DEFAULT_SYNC_CLK (20) +#define DEFAULT_DBIT_CLK (200) + +#define HIGHVOLTAGE_MIN (60) +#define HIGHVOLTAGE_MAX (200) // min dac val +#define DAC_MIN_MV (0) +#define DAC_MAX_MV (2500) +#define VCHIP_MIN_MV (1673) +#define VCHIP_MAX_MV (2668) // min dac val +#define POWER_RGLTR_MIN (636) +#define POWER_RGLTR_MAX (2638) // min dac val (not vchip-max) because of dac conversions +#define VCHIP_POWER_INCRMNT (200) +#define VIO_MIN_MV (1200) // for fpga to function + +/* Defines in the Firmware */ +#define MAX_PATTERN_LENGTH (0xFFFF) +#define DIGITAL_IO_DELAY_MAXIMUM_PS ((OUTPUT_DELAY_0_OTPT_STTNG_MSK >> OUTPUT_DELAY_0_OTPT_STTNG_OFST) * OUTPUT_DELAY_0_OTPT_STTNG_STEPS) +#define MAX_PHASE_SHIFTS_STEPS (8) + +#define WAIT_TME_US_FR_ACQDONE_REG (100) // wait time in us after acquisition done to ensure there is no data in fifo +#define WAIT_TIME_US_PLL (10 * 1000) +#define WAIT_TIME_US_STP_ACQ (100) +#define WAIT_TIME_CONFIGURE_MAC (500 * 1000) +#define WAIT_TIME_PATTERN_READ (10) +#define WAIT_TIME_FIFO_RD_STROBE (10) + +/* MSB & LSB DEFINES */ +#define MSB_OF_64_BIT_REG_OFST (32) +#define LSB_OF_64_BIT_REG_OFST (0) +#define BIT_32_MSK (0xFFFFFFFF) + +#define IP_PACKETSIZE (0x2032) +#define ADC_PORT_INVERT_VAL (0x453b2593) +#define MAXIMUM_ADC_CLK (65) +#define PLL_VCO_FREQ_MHZ (800) + diff --git a/slsDetectorSoftware/eigerDetectorServer/slsDetectorServer_funcs.c b/slsDetectorServers/ctbDetectorServer/slsDetectorServer_funcs.c similarity index 100% rename from slsDetectorSoftware/eigerDetectorServer/slsDetectorServer_funcs.c rename to slsDetectorServers/ctbDetectorServer/slsDetectorServer_funcs.c diff --git a/slsDetectorSoftware/eigerDetectorServer/slsDetectorServer_funcs.h b/slsDetectorServers/ctbDetectorServer/slsDetectorServer_funcs.h similarity index 100% rename from slsDetectorSoftware/eigerDetectorServer/slsDetectorServer_funcs.h rename to slsDetectorServers/ctbDetectorServer/slsDetectorServer_funcs.h diff --git a/slsDetectorServers/ctbDetectorServer/sls_detector_defs.h b/slsDetectorServers/ctbDetectorServer/sls_detector_defs.h new file mode 120000 index 000000000..2af30d73a --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/sls_detector_defs.h @@ -0,0 +1 @@ +../../slsSupportLib/include/sls_detector_defs.h \ No newline at end of file diff --git a/slsDetectorServers/ctbDetectorServer/sls_detector_funcs.h b/slsDetectorServers/ctbDetectorServer/sls_detector_funcs.h new file mode 120000 index 000000000..3f48959a9 --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/sls_detector_funcs.h @@ -0,0 +1 @@ +../../slsSupportLib/include/sls_detector_funcs.h \ No newline at end of file diff --git a/slsDetectorServers/ctbDetectorServer/versionAPI.h b/slsDetectorServers/ctbDetectorServer/versionAPI.h new file mode 120000 index 000000000..5e580d8bb --- /dev/null +++ b/slsDetectorServers/ctbDetectorServer/versionAPI.h @@ -0,0 +1 @@ +../../slsSupportLib/include/versionAPI.h \ No newline at end of file diff --git a/slsDetectorSoftware/eigerDetectorServer/9mhvserial_bf.c b/slsDetectorServers/eigerDetectorServer/9mhvserial_bf.c old mode 100644 new mode 100755 similarity index 69% rename from slsDetectorSoftware/eigerDetectorServer/9mhvserial_bf.c rename to slsDetectorServers/eigerDetectorServer/9mhvserial_bf.c index 0746c4ac1..2ca3a99e3 --- a/slsDetectorSoftware/eigerDetectorServer/9mhvserial_bf.c +++ b/slsDetectorServers/eigerDetectorServer/9mhvserial_bf.c @@ -25,13 +25,13 @@ int i2c_open(const char* file,unsigned int addr){ //device file int fd = open( file, O_RDWR ); if (fd < 0) { - cprintf(RED,"Warning: Unable to open file %s\n",file); + FILE_LOG(logERROR, ("Warning: Unable to open file %s\n",file)); return -1; } //device address if( ioctl( fd, I2C_SLAVE, addr&0x7F ) < 0 ) { - cprintf(RED,"Warning: Unable to set slave address:0x%x \n",addr); + FILE_LOG(logERROR, ("Warning: Unable to set slave address:0x%x \n",addr)); return -2; } return fd; @@ -45,17 +45,17 @@ int i2c_read(){ unsigned char buf = reg; if (write(fd, &buf, 1)!= 1){ - cprintf(RED,"Warning: Unable to write read request to register %d\n", reg); + FILE_LOG(logERROR, ("Warning: Unable to write read request to register %d\n", reg)); return -1; } //read and update value (but old value read out) if(read(fd, &buf, 1) != 1){ - cprintf(RED,"Warning: Unable to read register %d\n", reg); + FILE_LOG(logERROR, ("Warning: Unable to read register %d\n", reg)); return -2; } //read again to read the updated value if(read(fd, &buf, 1) != 1){ - cprintf(RED,"Warning: Unable to read register %d\n", reg); + FILE_LOG(logERROR, ("Warning: Unable to read register %d\n", reg)); return -2; } close(fd); @@ -76,7 +76,7 @@ int i2c_write(unsigned int value){ buf[0] = reg; buf[1] = val; if (write(fd, buf, 2) != 2) { - cprintf(RED,"Warning: Unable to write %d to register %d\n",val, reg); + FILE_LOG(logERROR, ("Warning: Unable to write %d to register %d\n",val, reg)); return -1; } @@ -92,10 +92,10 @@ int main(int argc, char* argv[]) { int fd = open(PORTNAME, O_RDWR | O_NOCTTY | O_SYNC); if(fd < 0){ - cprintf(RED,"Warning: Unable to open port %s\n", PORTNAME); + FILE_LOG(logERROR, ("Warning: Unable to open port %s\n", PORTNAME)); return -1; } - cprintf(GREEN,"opened port at %s\n",PORTNAME); + FILE_LOG(logINFO, ("opened port at %s\n",PORTNAME)); struct termios serial_conf; // reset structure @@ -110,17 +110,17 @@ int main(int argc, char* argv[]) { serial_conf.c_lflag = ICANON; // flush input if(tcflush(fd, TCIOFLUSH) < 0){ - cprintf(RED,"Warning: error form tcflush %d\n", errno); + FILE_LOG(logERROR, ("Warning: error form tcflush %d\n", errno)); return 0; } // set new options for the port, TCSANOW:changes occur immediately without waiting for data to complete if(tcsetattr(fd, TCSANOW, &serial_conf) < 0){ - cprintf(RED,"Warning: error form tcsetattr %d\n", errno); + FILE_LOG(logERROR, ("Warning: error form tcsetattr %d\n", errno)); return 0; } if(tcsetattr(fd, TCSAFLUSH, &serial_conf) < 0){ - cprintf(RED,"Warning: error form tcsetattr %d\n", errno); + FILE_LOG(logERROR, ("Warning: error form tcsetattr %d\n", errno)); return 0; } @@ -130,27 +130,25 @@ int main(int argc, char* argv[]) { char buffer[BUFFERSIZE]; memset(buffer,0,BUFFERSIZE); buffer[BUFFERSIZE-1] = '\n'; - cprintf(GREEN,"Ready...\n"); + FILE_LOG(logINFO, ("Ready...\n")); while(ret != GOODBYE){ memset(buffer,0,BUFFERSIZE); n = read(fd,buffer,BUFFERSIZE); -#ifdef VERBOSE - cprintf(BLUE,"Received %d Bytes\n", n); -#endif - cprintf(BLUE,"Got message: '%s'\n",buffer); + FILE_LOG(logDEBUG1, ("Received %d Bytes\n", n)); + FILE_LOG(logINFO, ("Got message: '%s'\n",buffer)); switch(buffer[0]){ case '\0': - cprintf(GREEN,"Got Start (Detector restart)\n"); + FILE_LOG(logINFO, ("Got Start (Detector restart)\n")); break; case 's': - cprintf(GREEN,"Got Start \n"); + FILE_LOG(logINFO, ("Got Start \n")); break; case 'p': if (!sscanf(&buffer[1],"%d",&ival)){ - cprintf(RED,"Warning: cannot scan voltage value\n"); + FILE_LOG(logERROR, ("Warning: cannot scan voltage value\n")); break; } // ok/ fail @@ -160,11 +158,9 @@ int main(int argc, char* argv[]) { strcpy(buffer,"fail "); else strcpy(buffer,"success "); - cprintf(GREEN,"Sending: '%s'\n",buffer); + FILE_LOG(logINFO, ("Sending: '%s'\n",buffer)); n = write(fd, buffer, BUFFERSIZE); -#ifdef VERBOSE - cprintf(GREEN,"Sent %d Bytes\n", n); -#endif + FILE_LOG(logDEBUG1, ("Sent %d Bytes\n", n)); break; case 'g': @@ -177,21 +173,17 @@ int main(int argc, char* argv[]) { else strcpy(buffer,"success "); n = write(fd, buffer, BUFFERSIZE); - cprintf(GREEN,"Sending: '%s'\n",buffer); -#ifdef VERBOSE - cprintf(GREEN,"Sent %d Bytes\n", n); -#endif + FILE_LOG(logINFO, ("Sending: '%s'\n",buffer)); + FILE_LOG(logDEBUG1, ("Sent %d Bytes\n", n)); //value memset(buffer,0,BUFFERSIZE); buffer[BUFFERSIZE-1] = '\n'; if(ival >= 0){ - cprintf(GREEN,"Sending: '%d'\n",ival); + FILE_LOG(logINFO, ("Sending: '%d'\n",ival)); sprintf(buffer,"%d ",ival); n = write(fd, buffer, BUFFERSIZE); -#ifdef VERBOSE - cprintf(GREEN,"Sent %d Bytes\n", n); -#endif - }else cprintf(RED,"%s\n",buffer); + FILE_LOG(logINFO, ("Sent %d Bytes\n", n)); + }else FILE_LOG(logERROR, ("%s\n",buffer)); break; case 'e': @@ -199,7 +191,7 @@ int main(int argc, char* argv[]) { ret = GOODBYE; break; default: - cprintf(RED,"Unknown Command. buffer:'%s'\n",buffer); + FILE_LOG(logERROR, ("Unknown Command. buffer:'%s'\n",buffer)); break; } } diff --git a/slsDetectorSoftware/eigerDetectorServer/Beb.c b/slsDetectorServers/eigerDetectorServer/Beb.c old mode 100644 new mode 100755 similarity index 54% rename from slsDetectorSoftware/eigerDetectorServer/Beb.c rename to slsDetectorServers/eigerDetectorServer/Beb.c index dc4e139fa..69cfdec51 --- a/slsDetectorSoftware/eigerDetectorServer/Beb.c +++ b/slsDetectorServers/eigerDetectorServer/Beb.c @@ -1,59 +1,44 @@ - -/** - * @author Ian Johnson - * @version 1.0 - */ +#include "logger.h" +#include "Beb.h" +#include "FebRegisterDefs.h" +#include "xparameters.h" - -//return reversed 1 means good, 0 means failed - - - -#include -#include -#include #include #include - - - -#include "xfs_types.h" -#include "xparameters.h" -#include "FebRegisterDefs.h" - -#include "Beb.h" +#include +#include #define MAX(x, y) (((x) > (y)) ? (x) : (y)) - struct BebInfo beb_infos[10]; - int bebInfoSize = 0; +struct BebInfo beb_infos[10]; +int bebInfoSize = 0; - struct LocalLinkInterface ll_beb_local,* ll_beb; +struct LocalLinkInterface ll_beb_local,* ll_beb; - struct udp_header_type udp_header; +struct udp_header_type udp_header; - int Beb_send_ndata; - unsigned int Beb_send_buffer_size; - unsigned int* Beb_send_data_raw; - unsigned int* Beb_send_data; +int Beb_send_ndata; +unsigned int Beb_send_buffer_size; +unsigned int* Beb_send_data_raw; +unsigned int* Beb_send_data; - int Beb_recv_ndata; - unsigned int Beb_recv_buffer_size; - unsigned int* Beb_recv_data_raw; - unsigned int* Beb_recv_data; +int Beb_recv_ndata; +unsigned int Beb_recv_buffer_size; +unsigned int* Beb_recv_data_raw; +unsigned int* Beb_recv_data; - short Beb_bit_mode; - int BEB_MMAP_SIZE = 0x1000; +short Beb_bit_mode; +int BEB_MMAP_SIZE = 0x1000; - int Beb_activated = 1; +int Beb_activated = 1; - uint32_t Beb_detid = 0; - int Beb_top =0; +uint32_t Beb_detid = 0; +int Beb_top =0; -void BebInfo_BebInfo(struct BebInfo* bebInfo, unsigned int beb_num){ +void BebInfo_BebInfo(struct BebInfo* bebInfo, unsigned int beb_num) { bebInfo->beb_number=beb_num; bebInfo->serial_address=0; strcpy(bebInfo->src_mac_1GbE,""); @@ -64,18 +49,18 @@ void BebInfo_BebInfo(struct BebInfo* bebInfo, unsigned int beb_num){ } -int BebInfo_SetSerialAddress(struct BebInfo* bebInfo, unsigned int a){ - //address pre shifted - if(a>0xff) return 0; - bebInfo->serial_address = 0x04000000 | ((a&0xff)<<16); - return 1; +int BebInfo_SetSerialAddress(struct BebInfo* bebInfo, unsigned int a) { + //address pre shifted + if (a>0xff) return 0; + bebInfo->serial_address = 0x04000000 | ((a&0xff)<<16); + return 1; } -int BebInfo_SetHeaderInfo(struct BebInfo* bebInfo, int ten_gig, char* src_mac, char* src_ip, unsigned int src_port){ - if(ten_gig){ strcpy(bebInfo->src_mac_10GbE,src_mac); strcpy(bebInfo->src_ip_10GbE,src_ip); bebInfo->src_port_10GbE = src_port;} - else { strcpy(bebInfo->src_mac_1GbE,src_mac); strcpy(bebInfo->src_ip_1GbE,src_ip); bebInfo->src_port_1GbE = src_port;} - return 1; +int BebInfo_SetHeaderInfo(struct BebInfo* bebInfo, int ten_gig, char* src_mac, char* src_ip, unsigned int src_port) { + if (ten_gig) { strcpy(bebInfo->src_mac_10GbE,src_mac); strcpy(bebInfo->src_ip_10GbE,src_ip); bebInfo->src_port_10GbE = src_port;} + else { strcpy(bebInfo->src_mac_1GbE,src_mac); strcpy(bebInfo->src_ip_1GbE,src_ip); bebInfo->src_port_1GbE = src_port;} + return 1; } @@ -87,20 +72,29 @@ char* BebInfo_GetSrcIP(struct BebInfo* bebInfo, int ten_gig) {return ten_gig unsigned int BebInfo_GetSrcPort(struct BebInfo* bebInfo, int ten_gig) {return ten_gig ? bebInfo->src_port_10GbE : bebInfo->src_port_1GbE;} -void BebInfo_Print(struct BebInfo* bebInfo){ - printf("\t%d) Beb Info.\n",bebInfo->beb_number); - printf("\t\tSerial Add: 0x%x\n",bebInfo->serial_address); - printf("\t\tMAC 1GbE: %s\n",bebInfo->src_mac_1GbE); - printf("\t\tIP 1GbE: %s\n",bebInfo->src_ip_1GbE); - printf("\t\tport 1GbE: %d\n",bebInfo->src_port_1GbE); - printf("\t\tMAC 10GbE: %s\n",bebInfo->src_mac_10GbE); - printf("\t\tIP 10GbE: %s\n",bebInfo->src_ip_10GbE); - printf("\t\tport 10GbE: %d\n",bebInfo->src_port_10GbE); +void BebInfo_Print(struct BebInfo* bebInfo) { + FILE_LOG(logINFO, ( + "%d) Beb Info:\n" + "\tSerial Add: 0x%x\n" + "\tMAC 1GbE: %s\n" + "\tIP 1GbE: %s\n" + "\tPort 1GbE: %d\n" + "\tMAC 10GbE: %s\n" + "\tIP 10GbE: %s\n" + "\tPort 10GbE: %d\n", + bebInfo->beb_number, + bebInfo->serial_address, + bebInfo->src_mac_1GbE, + bebInfo->src_ip_1GbE, + bebInfo->src_port_1GbE, + bebInfo->src_mac_10GbE, + bebInfo->src_ip_10GbE, + bebInfo->src_port_10GbE)); } -void Beb_Beb(){ - +void Beb_Beb(int id) { + Beb_detid = id; Beb_send_ndata = 0; Beb_send_buffer_size = 1026; Beb_send_data_raw = malloc((Beb_send_buffer_size+1) * sizeof(unsigned int)); @@ -111,76 +105,76 @@ void Beb_Beb(){ Beb_recv_data_raw = malloc((Beb_recv_buffer_size+1) * sizeof(unsigned int)); Beb_recv_data = &Beb_recv_data_raw[1]; - udp_header= (struct udp_header_type){ - {0x00, 0x50, 0xc5, 0xb2, 0xcb, 0x46}, // DST MAC - {0x00, 0x50, 0xc2, 0x46, 0xd9, 0x02}, // SRC MAC - {0x08, 0x00}, - {0x45}, - {0x00}, - {0x00, 0x00}, - {0x00, 0x00}, - {0x40}, - {0x00}, - {0xff}, - {0x11}, - {0x00, 0x00}, - {129, 205, 205, 128}, // Src IP - {129, 205, 205, 122}, // Dst IP - {0x0f, 0xa1}, - {0x13, 0x89}, - {0x00, 0x00}, //{0x00, 0x11}, - {0x00, 0x00} - }; + udp_header= (struct udp_header_type) { + {0x00, 0x50, 0xc5, 0xb2, 0xcb, 0x46}, // DST MAC + {0x00, 0x50, 0xc2, 0x46, 0xd9, 0x02}, // SRC MAC + {0x08, 0x00}, + {0x45}, + {0x00}, + {0x00, 0x00}, + {0x00, 0x00}, + {0x40}, + {0x00}, + {0xff}, + {0x11}, + {0x00, 0x00}, + {129, 205, 205, 128}, // Src IP + {129, 205, 205, 122}, // Dst IP + {0x0f, 0xa1}, + {0x13, 0x89}, + {0x00, 0x00}, //{0x00, 0x11}, + {0x00, 0x00} + }; - if(!Beb_InitBebInfos()) exit(1); + if (!Beb_InitBebInfos()) exit(1); - printf("Printing Beb infos:\n"); - unsigned int i; - for(i=1;i 0) + if (fd > 0) Beb_close(fd,csp0base); return ret; } /* do not work at the moment */ -int Beb_SetSlaveViaSoftware(){ +int Beb_SetSlaveViaSoftware() { - if(!Beb_activated) + if (!Beb_activated) return 0; //mapping new memory @@ -347,66 +338,69 @@ int Beb_SetSlaveViaSoftware(){ //open file pointer int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_SYS_BASEADDR); - if(fd < 0) - cprintf(BG_RED,"Set Slave FAIL\n"); - else{ + if (fd < 0) { + FILE_LOG(logERROR, ("Set Slave FAIL\n")); + } else { value = Beb_Read32(csp0base, MASTERCONFIG_OFFSET); value&=~MASTER_BIT; value|=OVERWRITE_HARDWARE_BIT; int newval = Beb_Write32(csp0base, MASTERCONFIG_OFFSET,value); - if(newval!=value) - cprintf(BG_RED,"Could not set Slave via Software\n"); - else + if (newval!=value) { + FILE_LOG(logERROR, ("Could not set Slave via Software\n")); + } else { ret = 0; + } } //close file pointer - if(fd > 0) + if (fd > 0) Beb_close(fd,csp0base); return ret; } -int Beb_Activate(int enable){ +int Beb_Activate(int enable) { //mapping new memory u_int32_t* csp0base=0; u_int32_t value = 0, ret = -1; //open file pointer int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_SYS_BASEADDR); - if(fd < 0) - cprintf(BG_RED,"Deactivate FAIL\n"); - else{ - if(enable > -1){ + if (fd < 0) { + FILE_LOG(logERROR, ("Deactivate FAIL\n")); + } else { + if (enable > -1) { value = Beb_Read32(csp0base, MASTERCONFIG_OFFSET); - printf("Deactivate register value before:%d\n",value); - if(enable) + FILE_LOG(logINFO, ("Deactivate register value before:%d\n",value)); + if (enable) value&=~DEACTIVATE_BIT; else value|=DEACTIVATE_BIT; int newval = Beb_Write32(csp0base, MASTERCONFIG_OFFSET,value); - if(newval!=value){ - if(enable) - cprintf(BG_RED,"Could not activate via Software\n"); - else - cprintf(BG_RED,"Could not deactivate via Software\n"); + if (newval!=value) { + if (enable) { + FILE_LOG(logERROR, ("Could not activate via Software\n")); + } else { + FILE_LOG(logERROR, ("Could not deactivate via Software\n")); + } } } value = Beb_Read32(csp0base, MASTERCONFIG_OFFSET); - if(value&DEACTIVATE_BIT) ret = 0; + if (value&DEACTIVATE_BIT) ret = 0; else ret = 1; - if(enable == -1){ - if(ret) - cprintf(BLUE,"Detector is active. Register value:%d\n", value); - else - cprintf(BG_RED,"Detector is deactivated! Register value:%d\n", value); + if (enable == -1) { + if (ret) { + FILE_LOG(logINFOBLUE, ("Detector is active. Register value:%d\n", value)); + } else { + FILE_LOG(logERROR, ("Detector is deactivated! Register value:%d\n", value)); + } } } //close file pointer - if(fd > 0) + if (fd > 0) Beb_close(fd,csp0base); Beb_activated = ret; @@ -416,23 +410,23 @@ int Beb_Activate(int enable){ int Beb_Set32bitOverflow(int val) { - if(!Beb_activated) + if (!Beb_activated) return val; //mapping new memory u_int32_t* csp0base=0; u_int32_t valueread = 0; u_int32_t offset = FLOW_REG_OFFSET; - if(val>0) val = 1; + if (val>0) val = 1; //open file pointer int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_SYS_BASEADDR); - if(fd < 0){ - cprintf(BG_RED,"Could not read register to set overflow flag in 32 bit mode. FAIL\n"); + if (fd < 0) { + FILE_LOG(logERROR, ("Could not read register to set overflow flag in 32 bit mode. FAIL\n")); return -1; } - else{ - if(val > -1){ + else { + if (val > -1) { // reset bit valueread = Beb_Read32(csp0base, offset); Beb_Write32(csp0base, offset,valueread & ~FLOW_REG_OVERFLOW_32_BIT_MSK); @@ -446,15 +440,15 @@ int Beb_Set32bitOverflow(int val) { valueread = (Beb_Read32(csp0base, offset) & FLOW_REG_OVERFLOW_32_BIT_MSK) >> FLOW_REG_OVERFLOW_32_BIT_OFST; } //close file pointer - if(fd > 0) + if (fd > 0) Beb_close(fd,csp0base); return valueread; } -int Beb_SetNetworkParameter(enum NETWORKINDEX mode, int val){ +int Beb_SetNetworkParameter(enum NETWORKINDEX mode, int val) { - if(!Beb_activated) + if (!Beb_activated) return val; @@ -464,7 +458,7 @@ int Beb_SetNetworkParameter(enum NETWORKINDEX mode, int val){ u_int32_t offset = TXM_DELAY_LEFT_OFFSET; char modename[100] = ""; - switch(mode){ + switch(mode) { case TXN_LEFT: offset = TXM_DELAY_LEFT_OFFSET; strcpy(modename,"Transmission Delay Left"); @@ -480,18 +474,18 @@ int Beb_SetNetworkParameter(enum NETWORKINDEX mode, int val){ case FLOWCTRL_10G: offset = FLOW_REG_OFFSET; strcpy(modename,"Flow Control for 10G"); - if(val>0) val = 1; + if (val>0) val = 1; break; - default: cprintf(BG_RED,"Unrecognized mode in network parameter: %d\n",mode); return -1; + default: FILE_LOG(logERROR, ("Unrecognized mode in network parameter: %d\n",mode)); return -1; } //open file pointer int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_SYS_BASEADDR); - if(fd < 0){ - cprintf(BG_RED,"Could not read register to set network parameter. FAIL\n"); + if (fd < 0) { + FILE_LOG(logERROR, ("Could not read register to set network parameter. FAIL\n")); return -1; } - else{ - if(val > -1){ + else { + if (val > -1) { if (mode != FLOWCTRL_10G) { valueread = Beb_Read32(csp0base, offset); Beb_Write32(csp0base, offset,val); @@ -517,16 +511,16 @@ int Beb_SetNetworkParameter(enum NETWORKINDEX mode, int val){ } //close file pointer - if(fd > 0) + if (fd > 0) Beb_close(fd,csp0base); return valueread; } -int Beb_ResetToHardwareSettings(){ +int Beb_ResetToHardwareSettings() { - if(!Beb_activated) + if (!Beb_activated) return 1; //mapping new memory @@ -535,18 +529,19 @@ int Beb_ResetToHardwareSettings(){ //open file pointer int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_SYS_BASEADDR); - if(fd < 0) - cprintf(BG_RED,"Reset to Hardware Settings FAIL\n"); - else{ + if (fd < 0) { + FILE_LOG(logERROR, ("Reset to Hardware Settings FAIL\n")); + } else { value = Beb_Write32(csp0base, MASTERCONFIG_OFFSET,0); - if(value) - cprintf(BG_RED,"Could not reset to hardware settings\n"); - else + if (value) { + FILE_LOG(logERROR, ("Could not reset to hardware settings\n")); + } else { ret = 0; + } } //close file pointer - if(fd > 0) + if (fd > 0) Beb_close(fd,csp0base); return ret; @@ -554,95 +549,97 @@ int Beb_ResetToHardwareSettings(){ -u_int32_t Beb_GetFirmwareRevision(){ +u_int32_t Beb_GetFirmwareRevision() { //mapping new memory u_int32_t* csp0base=0; u_int32_t value = 0; //open file pointer int fd = Beb_open(&csp0base,XPAR_VERSION); - if(fd < 0) - cprintf(BG_RED,"Firmware Revision Read FAIL\n"); - else{ + if (fd < 0) { + FILE_LOG(logERROR, ("Firmware Revision Read FAIL\n")); + } else { value = Beb_Read32(csp0base, FIRMWARE_VERSION_OFFSET); - if(!value) - cprintf(BG_RED,"Firmware Revision Number does not exist in this version\n"); + if (!value) { + FILE_LOG(logERROR, ("Firmware Revision Number does not exist in this version\n")); + } } //close file pointer - if(fd > 0) + if (fd > 0) Beb_close(fd,csp0base); return value; } -u_int32_t Beb_GetFirmwareSoftwareAPIVersion(){ +u_int32_t Beb_GetFirmwareSoftwareAPIVersion() { //mapping new memory u_int32_t* csp0base=0; u_int32_t value = 0; //open file pointer int fd = Beb_open(&csp0base,XPAR_VERSION); - if(fd < 0) - cprintf(BG_RED,"Firmware Software API Version Read FAIL\n"); - else{ + if (fd < 0) { + FILE_LOG(logERROR, ("Firmware Software API Version Read FAIL\n")); + } else { value = Beb_Read32(csp0base, FIRMWARESOFTWARE_API_OFFSET); - if(!value) - cprintf(BG_RED,"Firmware Software API Version does not exist in this version\n"); + if (!value) { + FILE_LOG(logERROR, ("Firmware Software API Version does not exist in this version\n")); + } } //close file pointer - if(fd > 0) + if (fd > 0) Beb_close(fd,csp0base); return value; } -void Beb_ResetFrameNumber(){ +void Beb_ResetFrameNumber() { - if(!Beb_activated) + if (!Beb_activated) return; //mapping new memory to read master top module configuration u_int32_t* csp0base=0; //open file pointer int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_SYS_BASEADDR); - if(fd < 0){ - cprintf(BG_RED,"Reset Frame Number FAIL\n"); - }else{ + if (fd < 0) { + FILE_LOG(logERROR, ("Reset Frame Number FAIL\n")); + } else { //write a 1 Beb_Write32(csp0base, FRAME_NUM_RESET_OFFSET, 1); usleep(100000); //100ms //write a 0 Beb_Write32(csp0base, FRAME_NUM_RESET_OFFSET, 0); - printf("Frame Number Reset OK\n"); + FILE_LOG(logINFO, ("Frame Number Reset OK\n")); //close file pointer Beb_close(fd,csp0base); } } -void Beb_ClearBebInfos(){ +void Beb_ClearBebInfos() { //unsigned int i; - //for(i=0;i=bebInfoSize){ - printf("WriteTo index error.\n"); - return 0; - } + if (index>=bebInfoSize) { + FILE_LOG(logERROR, ("WriteTo index error.\n")); + return 0; + } - Beb_send_data_raw[0] = 0x90000000 | BebInfo_GetSerialAddress(&beb_infos[index]); - if(Local_Write(ll_beb,4,Beb_send_data_raw)!=4) return 0; + Beb_send_data_raw[0] = 0x90000000 | BebInfo_GetSerialAddress(&beb_infos[index]); + if (Local_Write(ll_beb,4,Beb_send_data_raw)!=4) return 0; - Beb_send_data_raw[0] = 0xc0000000; - if((Beb_send_ndata+1)*4!=Local_Write(ll_beb,(Beb_send_ndata+1)*4,Beb_send_data_raw)) return 0; + Beb_send_data_raw[0] = 0xc0000000; + if ((Beb_send_ndata+1)*4!=Local_Write(ll_beb,(Beb_send_ndata+1)*4,Beb_send_data_raw)) return 0; - return 1; + return 1; } -void Beb_SwapDataFun(int little_endian, unsigned int n, unsigned int *d){ +void Beb_SwapDataFun(int little_endian, unsigned int n, unsigned int *d) { unsigned int i; - if(little_endian) for(i=0;i>8) | ((d[i]&0xff000000)>>24)); //little_endian - else for(i=0;i>16)); + if (little_endian) for(i=0;i>8) | ((d[i]&0xff000000)>>24)); //little_endian + else for(i=0;i>16)); } -int Beb_SetByteOrder(){ - return 1; +int Beb_SetByteOrder() { + return 1; } -int Beb_SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header_number, char* dst_mac, char* dst_ip, unsigned int dst_port){ +int Beb_SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header_number, char* dst_mac, char* dst_ip, unsigned int dst_port) { - if(!Beb_activated) + if (!Beb_activated) return 1; u_int32_t bram_phy_addr; @@ -757,14 +755,14 @@ int Beb_SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header else bram_phy_addr = 0xC6001000; - if(!Beb_SetHeaderData(beb_number,ten_gig,dst_mac,dst_ip,dst_port)) return 0; + if (!Beb_SetHeaderData(beb_number,ten_gig,dst_mac,dst_ip,dst_port)) return 0; int fd = Beb_open(&csp0base,bram_phy_addr); - if(fd < 0){ - cprintf(BG_RED,"Set up UDP Header FAIL\n"); - }else{ + if (fd < 0) { + FILE_LOG(logERROR, ("Set up UDP Header FAIL\n")); + } else { //read data memcpy(csp0base+header_number*16, &udp_header, sizeof(udp_header)); //close file pointer @@ -774,34 +772,17 @@ int Beb_SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header } -//int Beb_SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header_number, char* dst_mac, char* dst_ip, unsigned int dst_port){ -// unsigned int i = 1;/*Beb_GetBebInfoIndex(beb_number);*/ -// -// /***********************************if(!i) return 0; *************************************///i must be greater than 0, zero is the global send -// -// Beb_send_ndata = 14; -// Beb_send_data[0] = ten_gig ? 0x00020000 : 0x00010000; //write to fanout numbers 1 or 2 -// Beb_send_data[1] = ((header_number*8)<<16); -// if(!Beb_SetHeaderData(beb_number,ten_gig,dst_mac,dst_ip,dst_port)) return 0; -// -// Beb_SwapDataFun(1,12,&(Beb_send_data[2])); -// -// if(!Beb_WriteTo(i)) return 0; -// printf("beb dst_port:%d\n",dst_port); -// return 1; -//} - -int Beb_SetHeaderData(unsigned int beb_number, int ten_gig, char* dst_mac, char* dst_ip, unsigned int dst_port){ - unsigned int i = 1;/*Beb_GetBebInfoIndex(beb_number);*/ - /***********************************if(!i) return 0; *************************************///i must be greater than 0, zero is the global send - return Beb_SetHeaderData1(BebInfo_GetSrcMAC(&beb_infos[i],ten_gig),BebInfo_GetSrcIP(&beb_infos[i],ten_gig),BebInfo_GetSrcPort(&beb_infos[i],ten_gig),dst_mac,dst_ip,dst_port); +int Beb_SetHeaderData(unsigned int beb_number, int ten_gig, char* dst_mac, char* dst_ip, unsigned int dst_port) { + unsigned int i = 1;/*Beb_GetBebInfoIndex(beb_number);*/ + /***********************************if (!i) return 0; *************************************///i must be greater than 0, zero is the global send + return Beb_SetHeaderData1(BebInfo_GetSrcMAC(&beb_infos[i],ten_gig),BebInfo_GetSrcIP(&beb_infos[i],ten_gig),BebInfo_GetSrcPort(&beb_infos[i],ten_gig),dst_mac,dst_ip,dst_port); } -int Beb_SetHeaderData1(char* src_mac, char* src_ip, unsigned int src_port, char* dst_mac, char* dst_ip, unsigned int dst_port){ - /* example header*/ - //static unsigned int* word_ptr = new unsigned int [16]; - /*static*/ +int Beb_SetHeaderData1(char* src_mac, char* src_ip, unsigned int src_port, char* dst_mac, char* dst_ip, unsigned int dst_port) { + /* example header*/ + //static unsigned int* word_ptr = new unsigned int [16]; + /*static*/ /* udp_header_type udp_header = { {0x00, 0x50, 0xc5, 0xb2, 0xcb, 0x46}, // DST MAC @@ -823,46 +804,46 @@ int Beb_SetHeaderData1(char* src_mac, char* src_ip, unsigned int src_port, char* {0x00, 0x00}, //{0x00, 0x11}, {0x00, 0x00} }; -*/ + */ - if(!Beb_SetMAC(src_mac,&(udp_header.src_mac[0]))) return 0; - printf("Setting Source MAC to %s\n",src_mac); - if(!Beb_SetIP(src_ip,&(udp_header.src_ip[0]))) return 0; - printf("Setting Source IP to %s\n",src_ip); - if(!Beb_SetPortNumber(src_port,&(udp_header.src_port[0]))) return 0; - printf("Setting Source port to %d\n",src_port); + if (!Beb_SetMAC(src_mac,&(udp_header.src_mac[0]))) return 0; + FILE_LOG(logINFO, ("Setting Source MAC to %s\n",src_mac)); + if (!Beb_SetIP(src_ip,&(udp_header.src_ip[0]))) return 0; + FILE_LOG(logINFO, ("Setting Source IP to %s\n",src_ip)); + if (!Beb_SetPortNumber(src_port,&(udp_header.src_port[0]))) return 0; + FILE_LOG(logINFO, ("Setting Source port to %d\n",src_port)); - if(!Beb_SetMAC(dst_mac,&(udp_header.dst_mac[0]))) return 0; - printf("Setting Destination MAC to %s\n",dst_mac); - if(!Beb_SetIP(dst_ip,&(udp_header.dst_ip[0]))) return 0; - printf("Setting Destination IP to %s\n",dst_ip); - if(!Beb_SetPortNumber(dst_port,&(udp_header.dst_port[0]))) return 0; - printf("Setting Destination port to %d\n",dst_port); + if (!Beb_SetMAC(dst_mac,&(udp_header.dst_mac[0]))) return 0; + FILE_LOG(logINFO, ("Setting Destination MAC to %s\n",dst_mac)); + if (!Beb_SetIP(dst_ip,&(udp_header.dst_ip[0]))) return 0; + FILE_LOG(logINFO, ("Setting Destination IP to %s\n",dst_ip)); + if (!Beb_SetPortNumber(dst_port,&(udp_header.dst_port[0]))) return 0; + FILE_LOG(logINFO, ("Setting Destination port to %d\n",dst_port)); - Beb_AdjustIPChecksum(&udp_header); + Beb_AdjustIPChecksum(&udp_header); - unsigned int* base_ptr = (unsigned int *) &udp_header; - unsigned int num_words = ( sizeof(struct udp_header_type) + 3 ) / 4; - // for(unsigned int i=0; i %s\n",macVal); + while (pch != NULL) { + if (strlen(pch)!=2) { + FILE_LOG(logERROR, ("Error: in mac address -> %s\n",macVal)); return 0; } @@ -875,15 +856,15 @@ int Beb_SetMAC(char* mac, uint8_t* dst_ptr){ return 1; } -int Beb_SetIP(char* ip, uint8_t* dst_ptr){ +int Beb_SetIP(char* ip, uint8_t* dst_ptr) { char ipVal[50];strcpy(ipVal,ip); int i = 0; char *pch = strtok (ipVal,"."); - while (pch != NULL){ - if(((i!=3) && ((strlen(pch)>3) || (strlen(pch)<1))) || ((i==3)&&((strlen(pch)<1) || (strlen(pch) > 3)))){ - printf("Error: in ip address -> %s\n",ipVal); - return 0; - } + while (pch != NULL) { + if (((i!=3) && ((strlen(pch)>3) || (strlen(pch)<1))) || ((i==3)&&((strlen(pch)<1) || (strlen(pch) > 3)))) { + FILE_LOG(logERROR, ("Error: in ip address -> %s\n",ipVal)); + return 0; + } int itemp; sscanf(pch,"%d",&itemp); @@ -894,98 +875,94 @@ int Beb_SetIP(char* ip, uint8_t* dst_ptr){ return 1; } -int Beb_SetPortNumber(unsigned int port_number, uint8_t* dst_ptr){ - dst_ptr[0] = (port_number >> 8) & 0xff ; - dst_ptr[1] = port_number & 0xff; - return 1; +int Beb_SetPortNumber(unsigned int port_number, uint8_t* dst_ptr) { + dst_ptr[0] = (port_number >> 8) & 0xff ; + dst_ptr[1] = port_number & 0xff; + return 1; } -void Beb_AdjustIPChecksum(struct udp_header_type *ip){ - unsigned char *cptr = (unsigned char *) ip->ver_headerlen; +void Beb_AdjustIPChecksum(struct udp_header_type *ip) { + unsigned char *cptr = (unsigned char *) ip->ver_headerlen; - ip->ip_header_checksum[0] = 0; - ip->ip_header_checksum[1] = 0; - ip->total_length[0] = 0; - ip->total_length[1] = 28; // IP + UDP Header Length - - // calc ip checksum - unsigned int ip_checksum = 0; - unsigned int i; - for(i=0; i<10; i++){ - ip_checksum += ( (cptr[2*i] << 8) + (cptr[2*i + 1]) ); - if (ip_checksum & 0x00010000) ip_checksum = (ip_checksum + 1) & 0x0000ffff; - } - - ip->ip_header_checksum[0] = (ip_checksum >> 8) & 0xff ; - ip->ip_header_checksum[1] = ip_checksum & 0xff ; -} + ip->ip_header_checksum[0] = 0; + ip->ip_header_checksum[1] = 0; + ip->total_length[0] = 0; + ip->total_length[1] = 28; // IP + UDP Header Length - - -int Beb_SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, int stop_read_when_fifo_empty){ - -// This is a dead function, will be removed in future -// ================================================== - - unsigned int i = 1;/*Beb_GetBebInfoIndex(beb_number); //zero is the global send*/ - - Beb_send_ndata = 3; - if(left_right == 1) Beb_send_data[0] = 0x00040000; - else if(left_right == 2) Beb_send_data[0] = 0x00080000; - else if(left_right == 3) Beb_send_data[0] = 0x000c0000; - else return 0; - - //packet_size/=2; - if(dst_number>0x3f) return 0; - if(packet_size>0x3ff) return 0; - if(npackets==0||npackets>0x100) return 0; - npackets--; - - - Beb_send_data[1] = 0x62000000 | (!stop_read_when_fifo_empty) << 27 | (ten_gig==1) << 24 | packet_size << 14 | dst_number << 8 | npackets; -#ifdef MARTIN - cprintf(GREEN, "Beb_send_data[1]:%X\n",Beb_send_data[1]); -#endif - Beb_send_data[2] = 0; - - Beb_SwapDataFun(0,2,&(Beb_send_data[1])); -#ifdef MARTIN - cprintf(GREEN, "Beb_send_data[1] Swapped:%X\n",Beb_send_data[1]); -#endif - - if(Beb_activated){ - if(!Beb_WriteTo(i)) return 0; + // calc ip checksum + unsigned int ip_checksum = 0; + unsigned int i; + for(i=0; i<10; i++) { + ip_checksum += ( (cptr[2*i] << 8) + (cptr[2*i + 1]) ); + if (ip_checksum & 0x00010000) ip_checksum = (ip_checksum + 1) & 0x0000ffff; } - return 1; + ip->ip_header_checksum[0] = (ip_checksum >> 8) & 0xff ; + ip->ip_header_checksum[1] = ip_checksum & 0xff ; } -int Beb_SetUpTransferParameters(short the_bit_mode){ - if(the_bit_mode!=4&&the_bit_mode!=8&&the_bit_mode!=16&&the_bit_mode!=32) return 0; - Beb_bit_mode = the_bit_mode; - - //nimages = the_number_of_images; - // on_dst = 0; - return 1; +int Beb_SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, int stop_read_when_fifo_empty) { + + // This is a dead function, will be removed in future + // ================================================== + + unsigned int i = 1;/*Beb_GetBebInfoIndex(beb_number); //zero is the global send*/ + + Beb_send_ndata = 3; + if (left_right == 1) Beb_send_data[0] = 0x00040000; + else if (left_right == 2) Beb_send_data[0] = 0x00080000; + else if (left_right == 3) Beb_send_data[0] = 0x000c0000; + else return 0; + + //packet_size/=2; + if (dst_number>0x3f) return 0; + if (packet_size>0x3ff) return 0; + if (npackets==0||npackets>0x100) return 0; + npackets--; + + + Beb_send_data[1] = 0x62000000 | (!stop_read_when_fifo_empty) << 27 | (ten_gig==1) << 24 | packet_size << 14 | dst_number << 8 | npackets; + FILE_LOG(logDEBUG1, ("Beb_send_data[1]:%X\n",Beb_send_data[1])); + Beb_send_data[2] = 0; + + Beb_SwapDataFun(0,2,&(Beb_send_data[1])); + FILE_LOG(logDEBUG1, ("Beb_send_data[1] Swapped:%X\n",Beb_send_data[1])); + + if (Beb_activated) { + if (!Beb_WriteTo(i)) return 0; + } + + return 1; +} + + +int Beb_SetUpTransferParameters(short the_bit_mode) { + if (the_bit_mode!=4&&the_bit_mode!=8&&the_bit_mode!=16&&the_bit_mode!=32) return 0; + Beb_bit_mode = the_bit_mode; + + //nimages = the_number_of_images; + // on_dst = 0; + + return 1; } int Beb_StopAcquisition() { - if(!Beb_activated) + if (!Beb_activated) return 1; u_int32_t* csp0base=0; volatile u_int32_t valuel,valuer; //open file pointer int fd = Beb_open(&csp0base,XPAR_CMD_GENERATOR); - if(fd < 0){ - cprintf(BG_RED,"Beb Stop Acquisition FAIL\n"); + if (fd < 0) { + FILE_LOG(logERROR, ("Beb Stop Acquisition FAIL\n")); return 0; - }else{ + } else { //find value valuel = Beb_Read32(csp0base, (LEFT_OFFSET+STOP_ACQ_OFFSET)); valuer = Beb_Read32(csp0base, (RIGHT_OFFSET+STOP_ACQ_OFFSET)); @@ -996,19 +973,19 @@ int Beb_StopAcquisition() Beb_Write32(csp0base, (LEFT_OFFSET + STOP_ACQ_OFFSET),(valuel&(~STOP_ACQ_BIT))); Beb_Write32(csp0base, (RIGHT_OFFSET + STOP_ACQ_OFFSET),(valuer&(~STOP_ACQ_BIT))); - printf("Beb Stop Acquisition OK\n"); + FILE_LOG(logINFO, ("Beb Stop Acquisition OK\n")); //close file pointer Beb_close(fd,csp0base); } return 1; } -int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_number, unsigned int nimages, int test_just_send_out_packets_no_wait){ +int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_number, unsigned int nimages, int test_just_send_out_packets_no_wait) { - if(!Beb_activated) + if (!Beb_activated) return 1; - if(dst_number>64) return 0; + if (dst_number>64) return 0; unsigned int header_size = 4; //4*64 bits unsigned int packet_size = ten_gig ? 0x200 : 0x80; // 4k or 1k packets @@ -1020,12 +997,13 @@ int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_nu u_int32_t send_header_command; u_int32_t send_frame_command; - if(in_two_requests) npackets/=2; + if (in_two_requests) npackets/=2; -#ifdef MARTIN - cprintf(RED, "----Beb_RequestNImages Start----\n"); - cprintf(RED, "beb_number:%X, ten_gig:%X,dst_number:%X,npackets:%X,Beb_bit_mode:%X,header_size:%X,nimages:%d,test_just_send_out_packets_no_wait:%X\n",beb_number,ten_gig,dst_number,npackets,Beb_bit_mode,header_size,nimages,test_just_send_out_packets_no_wait); -#endif + FILE_LOG(logDEBUG1, ("----Beb_RequestNImages Start----\n")); + FILE_LOG(logDEBUG1, ("beb_number:%X, ten_gig:%X,dst_number:%X, npackets:%X, " + "Beb_bit_mode:%X, header_size:%X, nimages:%d, test_just_send_out_packets_no_wait:%X\n", + beb_number, ten_gig, dst_number, npackets, Beb_bit_mode, header_size, + nimages, test_just_send_out_packets_no_wait)); // CMD_GEN core registers // @@ -1061,26 +1039,24 @@ int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_nu volatile u_int32_t value; //open file pointer int fd = Beb_open(&csp0base,XPAR_CMD_GENERATOR); - if(fd < 0){ - cprintf(BG_RED,"Beb Request N Images FAIL\n"); + if (fd < 0) { + FILE_LOG(logERROR, ("Beb Request N Images FAIL\n")); return 0; - }else{ - -#ifdef MARTIN - int i; - for (i=0; i < 10; i++) - printf("%X\n",Beb_Read32(baseaddr, (LEFT_OFFSET + i*4))); -#endif + } else { + { + int i; + for (i=0; i < 10; i++) + FILE_LOG(logDEBUG1, ("%X\n",Beb_Read32(csp0base, (LEFT_OFFSET + i*4)))); + } // Generating commands send_header_command = 0x62000000 | (!test_just_send_out_packets_no_wait) << 27 | (ten_gig==1) << 24 | header_size << 14 | 0; send_frame_command = 0x62000000 | (!test_just_send_out_packets_no_wait) << 27 | (ten_gig==1) << 24 | packet_size << 14 | (npackets-1); - -#ifdef MARTIN - for (i=0; i < 10; i++) - printf("%X\n",Beb_Read32(baseaddr, (LEFT_OFFSET + i*4))); - printf("%d\n",in_two_requests); -#endif - + { + int i; + for (i=0; i < 10; i++) + FILE_LOG(logDEBUG1, ("%X\n",Beb_Read32(csp0base, (LEFT_OFFSET + i*4)))); + FILE_LOG(logDEBUG1, ("%d\n",in_two_requests)); + } //"0x20 << 8" is dst_number (0x00 for left, 0x20 for right) //Left Beb_Write32(csp0base, (LEFT_OFFSET + FIRST_CMD_PART1_OFFSET),0); @@ -1088,7 +1064,7 @@ int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_nu Beb_Write32(csp0base, (LEFT_OFFSET + SECOND_CMD_PART1_OFFSET),0); Beb_Write32(csp0base, (LEFT_OFFSET + SECOND_CMD_PART2_OFFSET),send_frame_command); value = Beb_Read32(csp0base,(LEFT_OFFSET + TWO_REQUESTS_OFFSET)); - if(in_two_requests) Beb_Write32(csp0base, (LEFT_OFFSET + TWO_REQUESTS_OFFSET),(value | TWO_REQUESTS_BIT)); + if (in_two_requests) Beb_Write32(csp0base, (LEFT_OFFSET + TWO_REQUESTS_OFFSET),(value | TWO_REQUESTS_BIT)); else Beb_Write32(csp0base, (LEFT_OFFSET + TWO_REQUESTS_OFFSET),(value &~(TWO_REQUESTS_BIT))); // Right @@ -1097,62 +1073,59 @@ int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_nu Beb_Write32(csp0base, (RIGHT_OFFSET + SECOND_CMD_PART1_OFFSET),0); Beb_Write32(csp0base, (RIGHT_OFFSET + SECOND_CMD_PART2_OFFSET),send_frame_command | right_port_value); value = Beb_Read32(csp0base,(RIGHT_OFFSET + TWO_REQUESTS_OFFSET)); - if(in_two_requests) Beb_Write32(csp0base, (RIGHT_OFFSET + TWO_REQUESTS_OFFSET),(value | TWO_REQUESTS_BIT)); + if (in_two_requests) Beb_Write32(csp0base, (RIGHT_OFFSET + TWO_REQUESTS_OFFSET),(value | TWO_REQUESTS_BIT)); else Beb_Write32(csp0base, (RIGHT_OFFSET + TWO_REQUESTS_OFFSET),(value &~(TWO_REQUESTS_BIT))); // Set number of frames Beb_Write32(csp0base, (LEFT_OFFSET + COMMAND_COUNTER_OFFSET), nimages*(2+in_two_requests)); Beb_Write32(csp0base, (RIGHT_OFFSET + COMMAND_COUNTER_OFFSET), nimages*(2+in_two_requests)); - -#ifdef MARTIN - for (i=0; i < 10; i++) - printf("%X\n",Beb_Read32(baseaddr, (LEFT_OFFSET + i*4))); //*(ptrl+i)); - printf("%d\n",in_two_requests); -#endif - + { + int i; + for (i=0; i < 10; i++) + FILE_LOG(logDEBUG1, ("%X\n",Beb_Read32(csp0base, (LEFT_OFFSET + i*4)))); //*(ptrl+i)); + FILE_LOG(logDEBUG1, ("%d\n",in_two_requests)); + } Beb_close(fd,csp0base); -#ifdef MARTIN - printf("----Beb_RequestNImages----\n"); -#endif + FILE_LOG(logDEBUG1, ("----Beb_RequestNImages----\n")); } return 1; } -int Beb_Test(unsigned int beb_number){ - printf("Testing module number: %d\n",beb_number); - +int Beb_Test(unsigned int beb_number) { + FILE_LOG(logINFO, ("Testing module number: %d\n",beb_number)); - //int SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header_number, string dst_mac, string dst_ip, unsigned int dst_port){ - //SetUpUDPHeader(26,0,0,"60:fb:42:f4:e3:d2","129.129.205.186",22000); - unsigned int index = Beb_GetBebInfoIndex(beb_number); - if(!index){ - printf("Error beb number (%d)not in list????\n",beb_number); - return 0; - } + //int SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header_number, string dst_mac, string dst_ip, unsigned int dst_port) { + //SetUpUDPHeader(26,0,0,"60:fb:42:f4:e3:d2","129.129.205.186",22000); - unsigned int i; - for(i=0;i<64;i++){ - if(!Beb_SetUpUDPHeader(beb_number,0,i,"60:fb:42:f4:e3:d2","129.129.205.186",22000+i)){ - printf("Error setting up header table....\n"); - return 0; - } - } + unsigned int index = Beb_GetBebInfoIndex(beb_number); + if (!index) { + FILE_LOG(logERROR, ("Error beb number (%d)not in list????\n",beb_number)); + return 0; + } - // SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, int stop_read_when_fifo_empty=1); - for(i=0;i<64;i++){ - if(!Beb_SendMultiReadRequest(beb_number,i%3+1,0,i,1,0,1)){ - printf("Error requesting data....\n"); - return 0; - } - } - + unsigned int i; + for(i=0;i<64;i++) { + if (!Beb_SetUpUDPHeader(beb_number,0,i,"60:fb:42:f4:e3:d2","129.129.205.186",22000+i)) { + FILE_LOG(logERROR, ("Error setting up header table....\n")); + return 0; + } + } - return 1; + // SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, int stop_read_when_fifo_empty=1); + for(i=0;i<64;i++) { + if (!Beb_SendMultiReadRequest(beb_number,i%3+1,0,i,1,0,1)) { + FILE_LOG(logERROR, ("Error requesting data....\n")); + return 0; + } + } + + + return 1; } // Returns the FPGA temperature from the xps sysmon ip core @@ -1165,9 +1138,9 @@ int Beb_GetBebFPGATemp() int ret; //open file pointer int fd = Beb_open(&csp0base,XPAR_SYSMON_0_BASEADDR); - if(fd < 0){ - cprintf(BG_RED,"Module Configuration FAIL\n"); - }else{ + if (fd < 0) { + FILE_LOG(logERROR, ("Module Configuration FAIL\n")); + } else { //read data ret = Beb_Read32(csp0base, FPGA_TEMP_OFFSET); temperature = ((((float)(ret)/65536.0f)/0.00198421639f ) - 273.15f)*1000; // Static conversation, copied from xps sysmon standalone driver @@ -1180,56 +1153,55 @@ int Beb_GetBebFPGATemp() void Beb_SetDetectorNumber(uint32_t detid) { - if(!Beb_activated) + if (!Beb_activated) return; uint32_t swapid = Beb_swap_uint16(detid); - //cprintf(GREEN, "detector id %d swapped %d\n", detid, swapid); + //FILE_LOG(logINFO, "detector id %d swapped %d\n", detid, swapid)); u_int32_t* csp0base=0; int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_TEST_BASEADDR); - if(fd < 0){ - cprintf(BG_RED,"Set Detector ID FAIL\n"); + if (fd < 0) { + FILE_LOG(logERROR, ("Set Detector ID FAIL\n")); return; - }else{ + } else { uint32_t value = Beb_Read32(csp0base, UDP_HEADER_A_LEFT_OFST); value &= UDP_HEADER_X_MSK; // to keep previous x value Beb_Write32(csp0base, UDP_HEADER_A_LEFT_OFST, value | ((swapid << UDP_HEADER_ID_OFST) & UDP_HEADER_ID_MSK)); value = Beb_Read32(csp0base, UDP_HEADER_A_LEFT_OFST); - if((value & UDP_HEADER_ID_MSK) != ((swapid << UDP_HEADER_ID_OFST) & UDP_HEADER_ID_MSK)) - cprintf(BG_RED,"Set Detector ID FAIL\n"); - + if ((value & UDP_HEADER_ID_MSK) != ((swapid << UDP_HEADER_ID_OFST) & UDP_HEADER_ID_MSK)) { + FILE_LOG(logERROR, ("Set Detector ID FAIL\n")); + } value = Beb_Read32(csp0base, UDP_HEADER_A_RIGHT_OFST); value &= UDP_HEADER_X_MSK; // to keep previous x value Beb_Write32(csp0base, UDP_HEADER_A_RIGHT_OFST, value | ((swapid << UDP_HEADER_ID_OFST) & UDP_HEADER_ID_MSK)); value = Beb_Read32(csp0base, UDP_HEADER_A_RIGHT_OFST); - if((value & UDP_HEADER_ID_MSK) != ((swapid << UDP_HEADER_ID_OFST) & UDP_HEADER_ID_MSK)) - cprintf(BG_RED,"Set Detector ID FAIL\n"); - + if ((value & UDP_HEADER_ID_MSK) != ((swapid << UDP_HEADER_ID_OFST) & UDP_HEADER_ID_MSK)) { + FILE_LOG(logERROR, ("Set Detector ID FAIL\n")); + } Beb_close(fd,csp0base); } - printf("detector id %d has been set in udp header\n", detid); + FILE_LOG(logINFO, ("Detector id %d set in UDP Header\n\n", detid)); } int Beb_SetDetectorPosition(int pos[]) { - if(!Beb_activated) + if (!Beb_activated) return OK; - cprintf(BLUE,"Got Position values %d %d %d...\n", pos[0],pos[1], pos[2]); + FILE_LOG(logINFO, ("Got Position values %d %d...\n", pos[0],pos[1])); pos[0] = Beb_swap_uint16(pos[0]); //pos[1] = Beb_swap_uint16(pos[1]); - pos[2] = Beb_swap_uint16(pos[2]); int ret = FAIL; //mapping new memory to read master top module configuration u_int32_t* csp0base=0; //open file pointer int fd = Beb_open(&csp0base,XPAR_PLB_GPIO_TEST_BASEADDR); - if(fd < 0){ - cprintf(BG_RED,"Set Detector Position FAIL\n"); + if (fd < 0) { + FILE_LOG(logERROR, ("Set Detector Position FAIL\n")); return FAIL; - }else{ + } else { uint32_t value = 0; ret = OK; // x left @@ -1237,63 +1209,54 @@ int Beb_SetDetectorPosition(int pos[]) { value &= UDP_HEADER_ID_MSK; // to keep previous id value Beb_Write32(csp0base, UDP_HEADER_A_LEFT_OFST, value | ((pos[0] << UDP_HEADER_X_OFST) & UDP_HEADER_X_MSK)); value = Beb_Read32(csp0base, UDP_HEADER_A_LEFT_OFST); - if((value & UDP_HEADER_X_MSK) != ((pos[0] << UDP_HEADER_X_OFST) & UDP_HEADER_X_MSK)) + if ((value & UDP_HEADER_X_MSK) != ((pos[0] << UDP_HEADER_X_OFST) & UDP_HEADER_X_MSK)) { + FILE_LOG(logERROR, ("Could not set row position for left port\n")); ret = FAIL; - + } // x right value = Beb_Read32(csp0base, UDP_HEADER_A_RIGHT_OFST); value &= UDP_HEADER_ID_MSK; // to keep previous id value Beb_Write32(csp0base, UDP_HEADER_A_RIGHT_OFST, value | ((pos[0] << UDP_HEADER_X_OFST) & UDP_HEADER_X_MSK)); value = Beb_Read32(csp0base, UDP_HEADER_A_RIGHT_OFST); - if((value & UDP_HEADER_X_MSK) != ((pos[0] << UDP_HEADER_X_OFST) & UDP_HEADER_X_MSK)) + if ((value & UDP_HEADER_X_MSK) != ((pos[0] << UDP_HEADER_X_OFST) & UDP_HEADER_X_MSK)) { + FILE_LOG(logERROR, ("Could not set row position for right port\n")); ret = FAIL; + } // y left (column) - // overwriting z anyway, so no need to look at previous z value int posval = Beb_swap_uint16(Beb_top ? pos[1] : (pos[1]+1)); - Beb_Write32(csp0base, UDP_HEADER_B_LEFT_OFST, ((posval << UDP_HEADER_Y_OFST) & UDP_HEADER_Y_MSK)); value = Beb_Read32(csp0base, UDP_HEADER_B_LEFT_OFST); - if(value != ((posval << UDP_HEADER_Y_OFST) & UDP_HEADER_Y_MSK)) + value &= UDP_HEADER_Z_MSK; // to keep previous z value + Beb_Write32(csp0base, UDP_HEADER_B_LEFT_OFST, value | ((posval << UDP_HEADER_Y_OFST) & UDP_HEADER_Y_MSK)); + value = Beb_Read32(csp0base, UDP_HEADER_B_LEFT_OFST); + if ((value & UDP_HEADER_Y_MSK) != ((posval << UDP_HEADER_Y_OFST) & UDP_HEADER_Y_MSK)) { + FILE_LOG(logERROR, ("Could not set column position for left port\n")); ret = FAIL; + } // y right - // overwriting z anyway, so no need to look at previous z value + value = Beb_Read32(csp0base, UDP_HEADER_B_RIGHT_OFST); + value &= UDP_HEADER_Z_MSK; // to keep previous z value posval = Beb_swap_uint16(Beb_top ? (pos[1]+1) : pos[1]); - Beb_Write32(csp0base, UDP_HEADER_B_RIGHT_OFST, ((posval << UDP_HEADER_Y_OFST) & UDP_HEADER_Y_MSK)); + Beb_Write32(csp0base, UDP_HEADER_B_RIGHT_OFST, value | ((posval << UDP_HEADER_Y_OFST) & UDP_HEADER_Y_MSK)); value = Beb_Read32(csp0base, UDP_HEADER_B_RIGHT_OFST); - if(value != ((posval << UDP_HEADER_Y_OFST) & UDP_HEADER_Y_MSK)) - ret = FAIL; - - - - // z left - value = Beb_Read32(csp0base, UDP_HEADER_B_LEFT_OFST); - value &= UDP_HEADER_Y_MSK; // to keep previous y value - Beb_Write32(csp0base, UDP_HEADER_B_LEFT_OFST, value | ((pos[2] << UDP_HEADER_Z_OFST) & UDP_HEADER_Z_MSK)); - value = Beb_Read32(csp0base, UDP_HEADER_B_LEFT_OFST); - if((value & UDP_HEADER_Z_MSK) != ((pos[2] << UDP_HEADER_Z_OFST) & UDP_HEADER_Z_MSK)) - ret = FAIL; - - // z right - value = Beb_Read32(csp0base, UDP_HEADER_B_RIGHT_OFST); - value &= UDP_HEADER_Y_MSK; // to keep previous y value - Beb_Write32(csp0base, UDP_HEADER_B_RIGHT_OFST, value | ((pos[2] << UDP_HEADER_Z_OFST) & UDP_HEADER_Z_MSK)); - value = Beb_Read32(csp0base, UDP_HEADER_B_RIGHT_OFST); - if((value & UDP_HEADER_Z_MSK) != ((pos[2] << UDP_HEADER_Z_OFST) & UDP_HEADER_Z_MSK)) + if ((value & UDP_HEADER_Y_MSK) != ((posval << UDP_HEADER_Y_OFST) & UDP_HEADER_Y_MSK)) { + FILE_LOG(logERROR, ("Could not set column position for right port\n")); ret = FAIL; + } //close file pointer Beb_close(fd,csp0base); } if (ret == OK) { - cprintf(BLUE, "Position set to...\n" - "Left: [%d, %d, %d]\n" - "Right:[%d, %d, %d]\n", - Beb_swap_uint16(pos[0]), Beb_top ? pos[1] : (pos[1]+1), Beb_swap_uint16(pos[2]), - Beb_swap_uint16(pos[0]), Beb_top ? (pos[1]+1) : pos[1], Beb_swap_uint16(pos[2])); + FILE_LOG(logINFO, ("Position set to...\n" + "\tLeft: [%d, %d]\n" + "\tRight:[%d, %d]\n", + Beb_swap_uint16(pos[0]), Beb_top ? pos[1] : (pos[1]+1)), + Beb_swap_uint16(pos[0]), Beb_top ? (pos[1]+1) : pos[1]); } return ret; @@ -1301,46 +1264,42 @@ int Beb_SetDetectorPosition(int pos[]) { uint16_t Beb_swap_uint16( uint16_t val) { - return (val << 8) | (val >> 8 ); + return (val << 8) | (val >> 8 ); } -int Beb_open(u_int32_t** csp0base, u_int32_t offset){ +int Beb_open(u_int32_t** csp0base, u_int32_t offset) { int fd = open("/dev/mem", O_RDWR | O_SYNC, 0); - if (fd == -1) - cprintf(BG_RED,"\nCan't find /dev/mem!\n"); - else{ -#ifdef VERBOSE - printf("/dev/mem opened\n"); -#endif + if (fd == -1) { + FILE_LOG(logERROR, ("\nCan't find /dev/mem!\n")); + } else { + FILE_LOG(logDEBUG1, ("/dev/mem opened\n")); *csp0base = (u_int32_t*)mmap(0, BEB_MMAP_SIZE, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, offset); if (*csp0base == MAP_FAILED) { - cprintf(BG_RED,"\nCan't map memmory area!!\n"); + FILE_LOG(logERROR, ("\nCan't map memmory area!!\n")); fd = -1; } -#ifdef VERBOSE - else printf("CSP0 mapped %p\n",(void*)*csp0base); -#endif + else FILE_LOG(logDEBUG1, ("CSP0 mapped %p\n",(void*)*csp0base)); } return fd; } -u_int32_t Beb_Read32 (u_int32_t* baseaddr, u_int32_t offset){ +u_int32_t Beb_Read32 (u_int32_t* baseaddr, u_int32_t offset) { volatile u_int32_t value; value=* (u_int32_t*)(baseaddr + offset/(sizeof(u_int32_t))); return value; } -u_int32_t Beb_Write32 (u_int32_t* baseaddr, u_int32_t offset, u_int32_t data){ +u_int32_t Beb_Write32 (u_int32_t* baseaddr, u_int32_t offset, u_int32_t data) { volatile u_int32_t *ptr1; ptr1=(u_int32_t*)(baseaddr + offset/(sizeof(u_int32_t))); *ptr1 = data; return *ptr1; } -void Beb_close(int fd,u_int32_t* csp0base){ - if(fd >= 0) +void Beb_close(int fd,u_int32_t* csp0base) { + if (fd >= 0) close(fd); munmap(csp0base,BEB_MMAP_SIZE); } diff --git a/slsDetectorServers/eigerDetectorServer/Beb.h b/slsDetectorServers/eigerDetectorServer/Beb.h new file mode 100755 index 000000000..6ab1338e8 --- /dev/null +++ b/slsDetectorServers/eigerDetectorServer/Beb.h @@ -0,0 +1,84 @@ +#pragma once + + +#include "LocalLinkInterface.h" +#include "slsDetectorServer_defs.h" + + +struct BebInfo{ + unsigned int beb_number; + unsigned int serial_address; + char src_mac_1GbE[50]; + char src_mac_10GbE[50]; + char src_ip_1GbE[50]; + char src_ip_10GbE[50]; + unsigned int src_port_1GbE; + unsigned int src_port_10GbE; +}; + + +void BebInfo_BebInfo(struct BebInfo* bebInfo, unsigned int beb_num); +void BebInfo_BebDstInfo(struct BebInfo* bebInfo, unsigned int beb_num); +int BebInfo_SetSerialAddress(struct BebInfo* bebInfo, unsigned int add); +int BebInfo_SetHeaderInfo(struct BebInfo* bebInfo, int ten_gig, char* src_mac, char* src_ip, unsigned int src_port);//src_port fixed 42000+beb_number or 52000 + beb_number); +unsigned int BebInfo_GetBebNumber(struct BebInfo* bebInfo); +unsigned int BebInfo_GetSerialAddress(struct BebInfo* bebInfo); +char* BebInfo_GetSrcMAC(struct BebInfo* bebInfo, int ten_gig); +char* BebInfo_GetSrcIP(struct BebInfo* bebInfo, int ten_gig); +unsigned int BebInfo_GetSrcPort(struct BebInfo* bebInfo, int ten_gig); +void BebInfo_Print(struct BebInfo* bebInfo); +void Beb_ClearBebInfos(); +int Beb_InitBebInfos(); +int Beb_CheckSourceStuffBebInfo(); +unsigned int Beb_GetBebInfoIndex(unsigned int beb_numb); + + +void Beb_GetModuleConfiguration(int* master, int* top, int* normal); +void Beb_EndofDataSend(int tengiga); + +int Beb_SetMasterViaSoftware(); +int Beb_SetSlaveViaSoftware(); +int Beb_Activate(int enable); +int Beb_Set32bitOverflow(int val); +int Beb_SetNetworkParameter(enum NETWORKINDEX mode, int val); +int Beb_ResetToHardwareSettings(); +u_int32_t Beb_GetFirmwareRevision(); +u_int32_t Beb_GetFirmwareSoftwareAPIVersion(); +void Beb_ResetFrameNumber(); +int Beb_WriteTo(unsigned int index); +int Beb_SetMAC(char* mac, uint8_t* dst_ptr); +int Beb_SetIP(char* ip, uint8_t* dst_ptr); +int Beb_SetPortNumber(unsigned int port_number, uint8_t* dst_ptr); +void Beb_AdjustIPChecksum(struct udp_header_type *ip); + +int Beb_SetHeaderData(unsigned int beb_number, int ten_gig, char* dst_mac, char* dst_ip, unsigned int dst_port); +int Beb_SetHeaderData1(char* src_mac, char* src_ip, unsigned int src_port, char* dst_mac, char* dst_ip, unsigned int dst_port); + +void Beb_SwapDataFun(int little_endian, unsigned int n, unsigned int *d); +int Beb_SetByteOrder(); +void Beb_Beb(); +int Beb_SetBebSrcHeaderInfos(unsigned int beb_number, int ten_gig, char* src_mac, char* src_ip, unsigned int src_port); +int Beb_SetUpUDPHeader(unsigned int beb_number, int ten_gig, unsigned int header_number, char* dst_mac, char* dst_ip, unsigned int dst_port); + +/*int Beb_SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, int stop_read_when_fifo_empty=1);*/ +int Beb_SendMultiReadRequest(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int npackets, unsigned int packet_size, int stop_read_when_fifo_empty); + +int Beb_StopAcquisition(); +int Beb_SetUpTransferParameters(short the_bit_mode); +/*int Beb_RequestNImages(unsigned int beb_number, unsigned int left_right, int ten_gig, unsigned int dst_number, unsigned int nimages, int test_just_send_out_packets_no_wait=0); //all images go to the same destination!*/ +int Beb_RequestNImages(unsigned int beb_number, int ten_gig, unsigned int dst_number, unsigned int nimages, int test_just_send_out_packets_no_wait); + +int Beb_Test(unsigned int beb_number); + +int Beb_GetBebFPGATemp(); + +void Beb_SetDetectorNumber(uint32_t detid); +int Beb_SetDetectorPosition(int pos[]); + +uint16_t Beb_swap_uint16( uint16_t val); +int Beb_open(u_int32_t** csp0base, u_int32_t offset); +u_int32_t Beb_Read32 (u_int32_t* baseaddr, u_int32_t offset); +u_int32_t Beb_Write32 (u_int32_t* baseaddr, u_int32_t offset, u_int32_t data); +void Beb_close(int fd,u_int32_t* csp0base); + + diff --git a/slsDetectorSoftware/eigerDetectorServer/FebControl.c b/slsDetectorServers/eigerDetectorServer/FebControl.c old mode 100644 new mode 100755 similarity index 50% rename from slsDetectorSoftware/eigerDetectorServer/FebControl.c rename to slsDetectorServers/eigerDetectorServer/FebControl.c index b686f020b..8c787db94 --- a/slsDetectorSoftware/eigerDetectorServer/FebControl.c +++ b/slsDetectorServers/eigerDetectorServer/FebControl.c @@ -1,31 +1,22 @@ +#include "FebControl.h" +#include "FebRegisterDefs.h" +#include "slsDetectorServer_defs.h" +#include "logger.h" +#include "Beb.h" -/** - * @author Ian Johnson - * @version 1.0 - */ - - - -#include -#include #include #include #include #include #include // POSIX terminal control definitions(CS8, CREAD, CLOCAL..) #include - -#include "FebRegisterDefs.h" -#include "FebControl.h" -#include "Beb.h" -#include "slsDetectorServer_defs.h" +#include - -//GetDAQStatusRegister(512,current_mode_bits_from_fpga)){ +//GetDAQStatusRegister(512,current_mode_bits_from_fpga)) { unsigned int Module_ndacs = 16; -char Module_dac_names[16][10]={"SvP","Vtr","Vrf","Vrs","SvN","Vtgstv","Vcmp_ll","Vcmp_lr","cal","Vcmp_rl","rxb_rb","rxb_lb","Vcmp_rr","Vcp","Vcn","Vis"};; +char Module_dac_names[16][10]={"SvP","Vtr","Vrf","Vrs","SvN","Vtgstv","Vcmp_ll","Vcmp_lr","cal","Vcmp_rl","rxb_rb","rxb_lb","Vcmp_rr","Vcp","Vcn","Vis"}; @@ -68,7 +59,7 @@ int Feb_Control_activated = 1; int Feb_Control_hv_fd = -1; -void Module_Module(struct Module* mod,unsigned int number, unsigned int address_top){ +void Module_Module(struct Module* mod,unsigned int number, unsigned int address_top) { unsigned int i; mod->module_number = number; mod->top_address_valid = 1; @@ -86,7 +77,7 @@ void Module_Module(struct Module* mod,unsigned int number, unsigned int address_ } -void Module_ModuleBottom(struct Module* mod,unsigned int number, unsigned int address_bottom){ +void Module_ModuleBottom(struct Module* mod,unsigned int number, unsigned int address_bottom) { unsigned int i; mod->module_number = number; mod->top_address_valid = 0; @@ -108,7 +99,7 @@ void Module_ModuleBottom(struct Module* mod,unsigned int number, unsigned int ad -void Module_Module1(struct Module* mod,unsigned int number, unsigned int address_top, unsigned int address_bottom){ +void Module_Module1(struct Module* mod,unsigned int number, unsigned int address_top, unsigned int address_bottom) { unsigned int i; mod->module_number = number; mod->top_address_valid = 1; @@ -154,23 +145,23 @@ int Module_GetBottomDACValue(struct Module* mod,unsigned int i) -void Feb_Control_activate(int activate){ +void Feb_Control_activate(int activate) { Feb_Control_activated = activate; } -int Feb_Control_IsBottomModule(){ - if(Module_BottomAddressIsValid(&modules[Feb_Control_current_index])) +int Feb_Control_IsBottomModule() { + if (Module_BottomAddressIsValid(&modules[Feb_Control_current_index])) return 1; return 0; } -int Feb_Control_GetModuleNumber(){ +int Feb_Control_GetModuleNumber() { return Feb_Control_module_number; } -void Feb_Control_FebControl(){ +void Feb_Control_FebControl() { Feb_Control_staticBits=Feb_Control_acquireNReadoutMode=Feb_Control_triggerMode=Feb_Control_externalEnableMode=Feb_Control_subFrameMode=0; Feb_Control_trimbit_size=263680; Feb_Control_last_downloaded_trimbits = malloc(Feb_Control_trimbit_size * sizeof(int)); @@ -180,7 +171,7 @@ void Feb_Control_FebControl(){ -int Feb_Control_Init(int master, int top, int normal, int module_num){ +int Feb_Control_Init(int master, int top, int normal, int module_num) { unsigned int i; Feb_Control_module_number = 0; Feb_Control_current_index = 0; @@ -193,7 +184,7 @@ int Feb_Control_Init(int master, int top, int normal, int module_num){ Feb_Control_module_number = (module_num & 0xFF); int serial = !top; - printf("serial: %d\n",serial); + FILE_LOG(logDEBUG1, ("serial: %d\n",serial)); Feb_Control_current_index = 1; @@ -205,12 +196,12 @@ int Feb_Control_Init(int master, int top, int normal, int module_num){ unsigned int nfebs = 0; unsigned int* feb_list = malloc(moduleSize*4 * sizeof(unsigned int)); - for(i=1;i3){ - cprintf(RED,"Error SetIDelay chip_pos %d doesn't exist.\n",chip_pos);; + if (chip_pos>3) { + FILE_LOG(logERROR, ("SetIDelay chip_pos %d doesn't exist.\n",chip_pos)); return 0; } unsigned int module_index=0; - if(!Feb_Control_GetModuleIndex(module_num,&module_index)){ - cprintf(RED,"Error could not set i delay module number %d invalid.\n",module_num); + if (!Feb_Control_GetModuleIndex(module_num,&module_index)) { + FILE_LOG(logERROR, ("could not set i delay module number %d invalid.\n",module_num)); return 0; } int ok = 1; - if(chip_pos/2==0){ //left fpga - if(Module_TopAddressIsValid(&modules[module_index])){ - if(Feb_Control_SendIDelays(Module_GetTopLeftAddress(&modules[module_index]),chip_pos%2==0,0xffffffff,ndelay_units)){ - if(module_index!=0) Module_SetTopIDelay(&modules[module_index],chip_pos,ndelay_units); - else{ + if (chip_pos/2==0) { //left fpga + if (Module_TopAddressIsValid(&modules[module_index])) { + if (Feb_Control_SendIDelays(Module_GetTopLeftAddress(&modules[module_index]),chip_pos%2==0,0xffffffff,ndelay_units)) { + if (module_index!=0) Module_SetTopIDelay(&modules[module_index],chip_pos,ndelay_units); + else { for(i=0;i0x3ff) ndelay_units=0x3ff; +int Feb_Control_SendIDelays(unsigned int dst_num, int chip_lr, unsigned int channels, unsigned int ndelay_units) { + if (ndelay_units>0x3ff) ndelay_units=0x3ff; // this is global unsigned int delay_data_valid_nclks = 15 - ((ndelay_units&0x3c0)>>6); //data valid delay upto 15 clks ndelay_units &= 0x3f; @@ -520,18 +522,19 @@ int Feb_Control_SendIDelays(unsigned int dst_num, int chip_lr, unsigned int chan unsigned int set_left_delay_channels = chip_lr ? channels:0; unsigned int set_right_delay_channels = chip_lr ? 0:channels; - printf("\tSetting delays of "); - if(set_left_delay_channels!=0) printf("left chips of dst_num %d",dst_num); - else if(set_right_delay_channels!=0) printf("right chips of dst_num %d",dst_num); - printf(", tracks 0x%x to: %d, %d clks and %d units.\n",channels,(((15-delay_data_valid_nclks)<<6)|ndelay_units),delay_data_valid_nclks,ndelay_units); + FILE_LOG(logDEBUG1, ("\tSetting delays of %s chips of dst_num %d, " + "tracks 0x%x to %d, %d clks and %d units.\n", + ((set_left_delay_channels != 0) ? "left" : "right"), + dst_num, channels, (((15-delay_data_valid_nclks)<<6)|ndelay_units), + delay_data_valid_nclks, ndelay_units)); - if(Feb_Control_activated){ - if(!Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG2, 1<<31 | delay_data_valid_nclks<<16 | ndelay_units,0,0) || //the 1<<31 time enables the setting of the data valid delays + if (Feb_Control_activated) { + if (!Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG2, 1<<31 | delay_data_valid_nclks<<16 | ndelay_units,0,0) || //the 1<<31 time enables the setting of the data valid delays !Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG3,set_left_delay_channels,0,0) || !Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG4,set_right_delay_channels,0,0) || - !Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG_CTRL,CHIP_DATA_OUT_DELAY_SET,1,1)){ - cprintf(RED,"Warning: could not SetChipDataInputDelays(...).\n"); + !Feb_Interface_WriteRegister(dst_num,CHIP_DATA_OUT_DELAY_REG_CTRL,CHIP_DATA_OUT_DELAY_SET,1,1)) { + FILE_LOG(logERROR, ("could not SetChipDataInputDelays(...).\n")); return 0; } } @@ -540,20 +543,20 @@ int Feb_Control_SendIDelays(unsigned int dst_num, int chip_lr, unsigned int chan } -int Feb_Control_VoltageToDAC(float value, unsigned int* digital,unsigned int nsteps,float vmin,float vmax){ - if(valuevmax) return 0; +int Feb_Control_VoltageToDAC(float value, unsigned int* digital,unsigned int nsteps,float vmin,float vmax) { + if (valuevmax) return 0; *digital = (int)(((value-vmin)/(vmax-vmin))*(nsteps-1) + 0.5); return 1; } -float Feb_Control_DACToVoltage(unsigned int digital,unsigned int nsteps,float vmin,float vmax){ +float Feb_Control_DACToVoltage(unsigned int digital,unsigned int nsteps,float vmin,float vmax) { return vmin+(vmax-vmin)*digital/(nsteps-1); } //only master gets to call this function -int Feb_Control_SetHighVoltage(int value){ - printf(" Setting High Voltage:\t"); +int Feb_Control_SetHighVoltage(int value) { + FILE_LOG(logDEBUG1, (" Setting High Voltage:\t")); /* * maximum voltage of the hv dc/dc converter: * 300 for single module power distribution board @@ -562,7 +565,7 @@ int Feb_Control_SetHighVoltage(int value){ */ const float vmin=0; float vmax=200; - if(Feb_control_normal) + if (Feb_control_normal) vmax=300; const float vlimit=200; const unsigned int ntotalsteps = 256; @@ -570,21 +573,22 @@ int Feb_Control_SetHighVoltage(int value){ unsigned int dacval = 0; //calculate dac value - if(!Feb_Control_VoltageToDAC(value,&dacval,nsteps,vmin,vlimit)){ - cprintf(RED,"\nWarning: SetHighVoltage bad value, %d. The range is 0 to %d V.\n",value, (int)vlimit); + if (!Feb_Control_VoltageToDAC(value,&dacval,nsteps,vmin,vlimit)) { + FILE_LOG(logERROR, ("SetHighVoltage bad value, %d. The range is 0 to %d V.\n",value, (int)vlimit)); return -1; } - printf("(%d dac):\t%dV\n", dacval, value); + FILE_LOG(logINFO, ("High Voltage set to %dV\n", value)); + FILE_LOG(logDEBUG1, ("High Voltage set to (%d dac):\t%dV\n", dacval, value)); return Feb_Control_SendHighVoltage(dacval); } -int Feb_Control_GetHighVoltage(int* value){ - printf(" Getting High Voltage:\t"); +int Feb_Control_GetHighVoltage(int* value) { + FILE_LOG(logDEBUG1, (" Getting High Voltage:\t")); unsigned int dacval = 0; - if(!Feb_Control_ReceiveHighVoltage(&dacval)) + if (!Feb_Control_ReceiveHighVoltage(&dacval)) return 0; //ok, convert dac to v @@ -596,25 +600,25 @@ int Feb_Control_GetHighVoltage(int* value){ */ const float vmin=0; float vmax=200; - if(Feb_control_normal) + if (Feb_control_normal) vmax=300; const float vlimit=200; const unsigned int ntotalsteps = 256; unsigned int nsteps = ntotalsteps*vlimit/vmax; *value = (int)(Feb_Control_DACToVoltage(dacval,nsteps,vmin,vlimit)+0.5); - printf("(%d dac)\t%dV\n", dacval, *value); - + FILE_LOG(logINFO, ("High Voltage read %dV\n", *value)); + FILE_LOG(logDEBUG1, ("High Voltage read (%d dac)\t%dV\n", dacval, *value)); return 1; } -int Feb_Control_SendHighVoltage(int dacvalue){ +int Feb_Control_SendHighVoltage(int dacvalue) { //normal - if(Feb_control_normal){ + if (Feb_control_normal) { //open file FILE* fd=fopen(NORMAL_HIGHVOLTAGE_OUTPUTPORT,"w"); - if(fd==NULL){ - cprintf(RED,"\nWarning: Could not open file for writing to set high voltage\n"); + if (fd==NULL) { + FILE_LOG(logERROR, ("Could not open file for writing to set high voltage\n")); return 0; } //convert to string, add 0 and write to file @@ -623,10 +627,10 @@ int Feb_Control_SendHighVoltage(int dacvalue){ } //9m - else{ + else { /*Feb_Control_OpenSerialCommunication();*/ - if (Feb_Control_hv_fd == -1){ - cprintf(RED,"\nWarning: High voltage serial communication not set up for 9m\n"); + if (Feb_Control_hv_fd == -1) { + FILE_LOG(logERROR, ("High voltage serial communication not set up for 9m\n")); return 0; } @@ -635,34 +639,34 @@ int Feb_Control_SendHighVoltage(int dacvalue){ buffer[SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE-1]='\n'; int n; sprintf(buffer,"p%d",dacvalue); - cprintf(GREEN,"Sending HV: '%s'\n",buffer); + FILE_LOG(logINFO, ("Sending HV: '%s'\n",buffer)); n = write(Feb_Control_hv_fd, buffer, SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE); if (n < 0) { - cprintf(RED,"\nWarning: Error writing to i2c bus\n"); + FILE_LOG(logERROR, ("writing to i2c bus\n")); return 0; } #ifdef VERBOSEI - cprintf(GREEN,"Sent %d Bytes\n", n); + FILE_LOG(logINFO, ("Sent %d Bytes\n", n)); #endif //ok/fail memset(buffer,0,SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE); buffer[SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE-1] = '\n'; n = read(Feb_Control_hv_fd, buffer, SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE); if (n < 0) { - cprintf(RED,"\nWarning: Error reading from i2c bus\n"); + FILE_LOG(logERROR, ("reading from i2c bus\n")); return 0; } #ifdef VERBOSEI - cprintf(GREEN,"Received %d Bytes\n", n); + FILE_LOG(logINFO, ("Received %d Bytes\n", n)); #endif - cprintf(GREEN,"Received HV: '%s'\n",buffer); + FILE_LOG(logINFO, ("Received HV: '%s'\n",buffer)); fflush(stdout); /*Feb_Control_CloseSerialCommunication();*/ - if(buffer[0] != 's'){ - cprintf(RED,"\nError: Failed to set high voltage\n"); + if (buffer[0] != 's') { + FILE_LOG(logERROR, ("\nError: Failed to set high voltage\n")); return 0; } - cprintf(GREEN,"%s\n",buffer); + FILE_LOG(logINFO, ("%s\n",buffer)); } @@ -675,22 +679,22 @@ int Feb_Control_SendHighVoltage(int dacvalue){ -int Feb_Control_ReceiveHighVoltage(unsigned int* value){ +int Feb_Control_ReceiveHighVoltage(unsigned int* value) { //normal - if(Feb_control_normal){ + if (Feb_control_normal) { //open file FILE* fd=fopen(NORMAL_HIGHVOLTAGE_INPUTPORT,"r"); - if(fd==NULL){ - cprintf(RED,"\nWarning: Could not open file for writing to get high voltage\n"); + if (fd==NULL) { + FILE_LOG(logERROR, ("Could not open file for writing to get high voltage\n")); return 0; } //read, assigning line to null and readbytes to 0 then getline allocates initial buffer size_t readbytes=0; char* line=NULL; - if(getline(&line, &readbytes, fd) == -1){ - cprintf(RED,"\nWarning: could not read file to get high voltage\n"); + if (getline(&line, &readbytes, fd) == -1) { + FILE_LOG(logERROR, ("could not read file to get high voltage\n")); return 0; } //read again to read the updated value @@ -698,8 +702,8 @@ int Feb_Control_ReceiveHighVoltage(unsigned int* value){ free(line); readbytes=0; readbytes = getline(&line, &readbytes, fd); - if(readbytes == -1){ - cprintf(RED,"\nWarning: could not read file to get high voltage\n"); + if (readbytes == -1) { + FILE_LOG(logERROR, ("could not read file to get high voltage\n")); return 0; } // Remove the trailing 0 @@ -710,11 +714,11 @@ int Feb_Control_ReceiveHighVoltage(unsigned int* value){ //9m - else{ + else { /*Feb_Control_OpenSerialCommunication();*/ - if (Feb_Control_hv_fd == -1){ - cprintf(RED,"\nWarning: High voltage serial communication not set up for 9m\n"); + if (Feb_Control_hv_fd == -1) { + FILE_LOG(logERROR, ("High voltage serial communication not set up for 9m\n")); return 0; } char buffer[SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE]; @@ -723,14 +727,14 @@ int Feb_Control_ReceiveHighVoltage(unsigned int* value){ //request strcpy(buffer,"g "); - cprintf(GREEN,"\nSending HV: '%s'\n",buffer); + FILE_LOG(logINFO, ("\nSending HV: '%s'\n",buffer)); n = write(Feb_Control_hv_fd, buffer, SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE); if (n < 0) { - cprintf(RED,"\nWarning: Error writing to i2c bus\n"); + FILE_LOG(logERROR, ("writing to i2c bus\n")); return 0; } #ifdef VERBOSEI - cprintf(GREEN,"Sent %d Bytes\n", n); + FILE_LOG(logINFO, ("Sent %d Bytes\n", n)); #endif //ok/fail @@ -738,15 +742,15 @@ int Feb_Control_ReceiveHighVoltage(unsigned int* value){ buffer[SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE-1] = '\n'; n = read(Feb_Control_hv_fd, buffer, SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE); if (n < 0) { - cprintf(RED,"\nWarning: Error reading from i2c bus\n"); + FILE_LOG(logERROR, ("reading from i2c bus\n")); return 0; } #ifdef VERBOSEI - cprintf(GREEN,"Received %d Bytes\n", n); + FILE_LOG(logINFO, ("Received %d Bytes\n", n)); #endif - cprintf(GREEN,"Received HV: '%s'\n",buffer); - if(buffer[0] != 's'){ - cprintf(RED,"\nWarning: failed to read high voltage\n"); + FILE_LOG(logINFO, ("Received HV: '%s'\n",buffer)); + if (buffer[0] != 's') { + FILE_LOG(logERROR, ("failed to read high voltage\n")); return 0; } @@ -754,16 +758,16 @@ int Feb_Control_ReceiveHighVoltage(unsigned int* value){ buffer[SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE-1] = '\n'; n = read(Feb_Control_hv_fd, buffer, SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE); if (n < 0) { - cprintf(RED,"\nWarning: Error reading from i2c bus\n"); + FILE_LOG(logERROR, ("reading from i2c bus\n")); return 0; } #ifdef VERBOSEI - cprintf(GREEN,"Received %d Bytes\n", n); + FILE_LOG(logINFO, ("Received %d Bytes\n", n)); #endif - cprintf(GREEN,"Received HV: '%s'\n",buffer); + FILE_LOG(logINFO, ("Received HV: '%s'\n",buffer)); /*Feb_Control_OpenSerialCommunication();*/ - if (!sscanf(buffer,"%d",value)){ - cprintf(RED,"\nWarning: failed to scan high voltage read\n"); + if (!sscanf(buffer,"%d",value)) { + FILE_LOG(logERROR, ("failed to scan high voltage read\n")); return 0; } } @@ -773,87 +777,87 @@ int Feb_Control_ReceiveHighVoltage(unsigned int* value){ -int Feb_Control_DecodeDACString(char* dac_str, unsigned int* module_index, int* top, int* bottom, unsigned int* dac_ch){ +int Feb_Control_DecodeDACString(char* dac_str, unsigned int* module_index, int* top, int* bottom, unsigned int* dac_ch) { char* local_s = dac_str; *module_index = Feb_Control_current_index; *top = 1;//make them both 1 instead of this *bottom = 1; - if(Module_BottomAddressIsValid(&modules[*module_index])) + if (Module_BottomAddressIsValid(&modules[*module_index])) *top=0; else *bottom=0; *dac_ch = 0; - if(!Feb_Control_GetDACNumber(local_s,dac_ch)){ - cprintf(RED,"Error in dac_name: %s (%s)\n",dac_str,local_s); + if (!Feb_Control_GetDACNumber(local_s,dac_ch)) { + FILE_LOG(logERROR, ("invalid dac_name: %s (%s)\n",dac_str,local_s)); return 0; } return 1; } -int Feb_Control_SetDAC(char* dac_str, int value, int is_a_voltage_mv){ +int Feb_Control_SetDAC(char* dac_str, int value, int is_a_voltage_mv) { unsigned int i; unsigned int module_index, dac_ch; int top, bottom; - if(!Feb_Control_DecodeDACString(dac_str,&module_index,&top,&bottom,&dac_ch)) return 0; + if (!Feb_Control_DecodeDACString(dac_str,&module_index,&top,&bottom,&dac_ch)) return 0; unsigned int v = value; - if(is_a_voltage_mv&&!Feb_Control_VoltageToDAC(value,&v,4096,0,2048)){ - cprintf(RED,"Warning: SetDac bad value, %d. The range is 0 to 2048 mV.\n",value); + if (is_a_voltage_mv&&!Feb_Control_VoltageToDAC(value,&v,4096,0,2048)) { + FILE_LOG(logERROR, ("SetDac bad value, %d. The range is 0 to 2048 mV.\n",value)); return 0; } - if(v<0||v>4095){ - cprintf(RED,"Warning: SetDac bad value, %d. The range is 0 to 4095.\n",v); + if (v<0||v>4095) { + FILE_LOG(logERROR, ("SetDac bad value, %d. The range is 0 to 4095.\n",v)); return 0; } - if(top&&Module_TopAddressIsValid(&modules[module_index])){ + if (top&&Module_TopAddressIsValid(&modules[module_index])) { - if(!Feb_Control_SendDACValue(Module_GetTopRightAddress(&modules[module_index]),dac_ch,&v)) return 0; + if (!Feb_Control_SendDACValue(Module_GetTopRightAddress(&modules[module_index]),dac_ch,&v)) return 0; - if(module_index!=0) Module_SetTopDACValue(&modules[module_index],dac_ch,v); + if (module_index!=0) Module_SetTopDACValue(&modules[module_index],dac_ch,v); else for(i=0;i=Module_ndacs){ - cprintf(RED,"Warning: GetDACName index out of range, %d invalid.\n",dac_num); +int Feb_Control_GetDACName(unsigned int dac_num, char* s) { + if (dac_num>=Module_ndacs) { + FILE_LOG(logERROR, ("GetDACName index out of range, %d invalid.\n",dac_num)); return 0; } strcpy(s,Module_dac_names[dac_num]); return 1; } -int Feb_Control_GetDACNumber(char* s, unsigned int* n){ +int Feb_Control_GetDACNumber(char* s, unsigned int* n) { unsigned int i; - for(i=0;i15){ - cprintf(RED,"Warning invalid ch for SetDAC.\n"); + if (ch<0||ch>15) { + FILE_LOG(logERROR, ("invalid ch for SetDAC.\n")); return 0; } - //if(voltage<0) return PowerDownDAC(socket_num,ch); + //if (voltage<0) return PowerDownDAC(socket_num,ch); *value&=0xfff; unsigned int dac_ic = (ch<8) ? 1:2; @@ -878,73 +882,72 @@ int Feb_Control_SendDACValue(unsigned int dst_num, unsigned int ch, unsigned int unsigned int r = dac_ic<<30 | 3<<16 | dac_ch<<12 | *value; //3 write and power up - if(Feb_Control_activated){ - if(!Feb_Interface_WriteRegister(dst_num,0,r,1,0)){ - cprintf(RED,"Warning: trouble setting dac %d voltage.\n",ch); + if (Feb_Control_activated) { + if (!Feb_Interface_WriteRegister(dst_num,0,r,1,0)) { + FILE_LOG(logERROR, ("trouble setting dac %d voltage.\n",ch)); return 0; } } float voltage=Feb_Control_DACToVoltage(*value,4096,0,2048); - printf("\tDac number %d (%s) of dst %d set to %d (%f mV).\n",ch,Module_dac_names[ch],dst_num,*value,voltage); + FILE_LOG(logINFO, ("%s set to %d (%.2fmV)\n", Module_dac_names[ch],*value,voltage)); + FILE_LOG(logDEBUG1, ("Dac number %d (%s) of dst %d set to %d (%f mV)\n",ch,Module_dac_names[ch],dst_num,*value,voltage)); return 1; } -int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int *trimbits){ - printf("Setting Trimbits\n"); +int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int *trimbits) { + FILE_LOG(logINFO, ("Setting Trimbits\n")); //for (int iy=10000;iy<20020;++iy)//263681 //for (int iy=263670;iy<263680;++iy)//263681 - // printf("%d:%c\t\t",iy,trimbits[iy]); + // FILE_LOG(logINFO, ("%d:%c\t\t",iy,trimbits[iy])); unsigned int trimbits_to_load_l[1024]; unsigned int trimbits_to_load_r[1024]; unsigned int module_index=0; - if(!Feb_Control_GetModuleIndex(module_num,&module_index)){ - cprintf(RED,"Warning could not set trimbits, bad module number.\n"); + if (!Feb_Control_GetModuleIndex(module_num,&module_index)) { + FILE_LOG(logERROR, ("could not set trimbits, bad module number.\n")); return 0; } - if(Feb_Control_Reset() == STATUS_ERROR) cprintf(RED,"Warning could not reset DAQ.\n"); - int l_r; //printf("222\n"); - for(l_r=0;l_r<2;l_r++){ // l_r loop - //printf("\nl_r:%d\t\t",l_r); + if (Feb_Control_Reset() == STATUS_ERROR) { + FILE_LOG(logERROR, ("could not reset DAQ.\n")); + } + int l_r; + for(l_r=0;l_r<2;l_r++) { // l_r loop unsigned int disable_chip_mask = l_r ? DAQ_CS_BAR_LEFT : DAQ_CS_BAR_RIGHT; - if(Feb_Control_activated){ - if(!(Feb_Interface_WriteRegister(0xfff,DAQ_REG_STATIC_BITS,disable_chip_mask|DAQ_STATIC_BIT_PROGRAM|DAQ_STATIC_BIT_M8,0,0) + if (Feb_Control_activated) { + if (!(Feb_Interface_WriteRegister(0xfff,DAQ_REG_STATIC_BITS,disable_chip_mask|DAQ_STATIC_BIT_PROGRAM|DAQ_STATIC_BIT_M8,0,0) &&Feb_Control_SetCommandRegister(DAQ_SET_STATIC_BIT) - &&(Feb_Control_StartDAQOnlyNWaitForFinish(5000) == STATUS_IDLE))){ - printf("Could not select chips\n"); + &&(Feb_Control_StartDAQOnlyNWaitForFinish(5000) == STATUS_IDLE))) { + FILE_LOG(logERROR, ("Could not select chips\n")); return 0; } } int row_set; - for(row_set=0;row_set<16;row_set++){ //16 rows at a time - //printf("row_set:%d\t\t",row_set); - if(row_set==0){ - if(!Feb_Control_SetCommandRegister(DAQ_RESET_COMPLETELY|DAQ_SEND_A_TOKEN_IN|DAQ_LOAD_16ROWS_OF_TRIMBITS)){ - cprintf(RED,"Warning: Could not Feb_Control_SetCommandRegister for loading trim bits.\n"); + for(row_set=0;row_set<16;row_set++) { //16 rows at a time + if (row_set==0) { + if (!Feb_Control_SetCommandRegister(DAQ_RESET_COMPLETELY|DAQ_SEND_A_TOKEN_IN|DAQ_LOAD_16ROWS_OF_TRIMBITS)) { + FILE_LOG(logERROR, ("Could not Feb_Control_SetCommandRegister for loading trim bits.\n")); return 0; } - }else{ - if(!Feb_Control_SetCommandRegister(DAQ_LOAD_16ROWS_OF_TRIMBITS)){ - cprintf(RED,"Warning: Could not Feb_Control_SetCommandRegister for loading trim bits.\n"); + } else { + if (!Feb_Control_SetCommandRegister(DAQ_LOAD_16ROWS_OF_TRIMBITS)) { + FILE_LOG(logERROR, ("Could not Feb_Control_SetCommandRegister for loading trim bits.\n")); return 0; } } int row; - for(row=0;row<16;row++){ //row loop - //printf("row:%d\t\t",row); + for(row=0;row<16;row++) { //row loop int offset = 2*32*row; int sc; - for(sc=0;sc<32;sc++){ //supercolumn loop sc - //printf("sc:%d\t\t",sc); + for(sc=0;sc<32;sc++) { //supercolumn loop sc int super_column_start_position_l = 1030*row + l_r *258 + sc*8; int super_column_start_position_r = 1030*row + 516 + l_r *258 + sc*8; @@ -958,15 +961,14 @@ int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int *trimbits){ trimbits_to_load_l[offset+chip_sc+32] = 0; trimbits_to_load_r[offset+chip_sc+32] = 0; int i; - for(i=0;i<8;i++){ // column loop i - //printf("i:%d\t\t",i); + for(i=0;i<8;i++) { // column loop i - if(Module_TopAddressIsValid(&modules[1])){ + if (Module_TopAddressIsValid(&modules[1])) { trimbits_to_load_l[offset+chip_sc] |= ( 0x7 & trimbits[row_set*16480+super_column_start_position_l+i])<<((7-i)*4);//low trimbits_to_load_l[offset+chip_sc+32] |= ((0x38 & trimbits[row_set*16480+super_column_start_position_l+i])>>3)<<((7-i)*4);//upper trimbits_to_load_r[offset+chip_sc] |= ( 0x7 & trimbits[row_set*16480+super_column_start_position_r+i])<<((7-i)*4);//low trimbits_to_load_r[offset+chip_sc+32] |= ((0x38 & trimbits[row_set*16480+super_column_start_position_r+i])>>3)<<((7-i)*4);//upper - }else{ + } else { trimbits_to_load_l[offset+chip_sc] |= ( 0x7 & trimbits[263679 - (row_set*16480+super_column_start_position_l+i)])<<((7-i)*4);//low trimbits_to_load_l[offset+chip_sc+32] |= ((0x38 & trimbits[263679 - (row_set*16480+super_column_start_position_l+i)])>>3)<<((7-i)*4);//upper trimbits_to_load_r[offset+chip_sc] |= ( 0x7 & trimbits[263679 - (row_set*16480+super_column_start_position_r+i)])<<((7-i)*4);//low @@ -977,25 +979,25 @@ int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int *trimbits){ } //end supercolumn loop sc } //end row loop - if(Module_TopAddressIsValid(&modules[1])){ - if(Feb_Control_activated){ - if(!Feb_Interface_WriteMemoryInLoops(Module_GetTopLeftAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_l)|| + if (Module_TopAddressIsValid(&modules[1])) { + if (Feb_Control_activated) { + if (!Feb_Interface_WriteMemoryInLoops(Module_GetTopLeftAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_l)|| !Feb_Interface_WriteMemoryInLoops(Module_GetTopRightAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_r)|| - //if(!Feb_Interface_WriteMemory(Module_GetTopLeftAddress(&modules[0]),0,0,1023,trimbits_to_load_r)|| + //if (!Feb_Interface_WriteMemory(Module_GetTopLeftAddress(&modules[0]),0,0,1023,trimbits_to_load_r)|| // !Feb_Interface_WriteMemory(Module_GetTopRightAddress(&modules[0]),0,0,1023,trimbits_to_load_l)|| - (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - printf(" some errror!\n"); + (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, (" some errror!\n")); return 0; } } - }else{ - if(Feb_Control_activated){ - if(!Feb_Interface_WriteMemoryInLoops(Module_GetBottomLeftAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_l)|| + } else { + if (Feb_Control_activated) { + if (!Feb_Interface_WriteMemoryInLoops(Module_GetBottomLeftAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_l)|| !Feb_Interface_WriteMemoryInLoops(Module_GetBottomRightAddress(&modules[Feb_Control_current_index]),0,0,1024,trimbits_to_load_r)|| - //if(!Feb_Interface_WriteMemory(Module_GetTopLeftAddress(&modules[0]),0,0,1023,trimbits_to_load_r)|| + //if (!Feb_Interface_WriteMemory(Module_GetTopLeftAddress(&modules[0]),0,0,1023,trimbits_to_load_r)|| // !Feb_Interface_WriteMemory(Module_GetTopRightAddress(&modules[0]),0,0,1023,trimbits_to_load_l)|| - (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - printf(" some errror!\n"); + (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, (" some errror!\n")); return 0; } } @@ -1010,47 +1012,46 @@ int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int *trimbits){ } -unsigned int* Feb_Control_GetTrimbits(){ +unsigned int* Feb_Control_GetTrimbits() { return Feb_Control_last_downloaded_trimbits; } -unsigned int Feb_Control_AddressToAll(){printf("in Feb_Control_AddressToAll()\n"); +unsigned int Feb_Control_AddressToAll() { + FILE_LOG(logDEBUG1, ("in Feb_Control_AddressToAll()\n")); -if(moduleSize==0) return 0; + if (moduleSize==0) return 0; -if(Module_BottomAddressIsValid(&modules[1])){ - //printf("************* bottom\n"); - //if(Feb_Control_am_i_master) - return Module_GetBottomLeftAddress(&modules[1])|Module_GetBottomRightAddress(&modules[1]); - // else return 0; -} -// printf("************* top\n"); + if (Module_BottomAddressIsValid(&modules[1])) { + //if (Feb_Control_am_i_master) + return Module_GetBottomLeftAddress(&modules[1])|Module_GetBottomRightAddress(&modules[1]); + // else return 0; + } -return Module_GetTopLeftAddress(&modules[1])|Module_GetTopRightAddress(&modules[1]); -//return Module_GetTopLeftAddress(&modules[0])|Module_GetTopRightAddress(&modules[0]); + return Module_GetTopLeftAddress(&modules[1])|Module_GetTopRightAddress(&modules[1]); + //return Module_GetTopLeftAddress(&modules[0])|Module_GetTopRightAddress(&modules[0]); } -int Feb_Control_SetCommandRegister(unsigned int cmd){ - if(Feb_Control_activated) +int Feb_Control_SetCommandRegister(unsigned int cmd) { + if (Feb_Control_activated) return Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CHIP_CMDS,cmd,0,0); else return 1; } -int Feb_Control_GetDAQStatusRegister(unsigned int dst_address, unsigned int* ret_status){ +int Feb_Control_GetDAQStatusRegister(unsigned int dst_address, unsigned int* ret_status) { //if deactivated, should be handled earlier and should not get into this function - if(Feb_Control_activated){ - if(!Feb_Interface_ReadRegister(dst_address,DAQ_REG_STATUS,ret_status)){ - cprintf(RED,"Error: reading status register.\n"); + if (Feb_Control_activated) { + if (!Feb_Interface_ReadRegister(dst_address,DAQ_REG_STATUS,ret_status)) { + FILE_LOG(logERROR, ("Error: reading status register.\n")); return 0; } } @@ -1060,10 +1061,10 @@ int Feb_Control_GetDAQStatusRegister(unsigned int dst_address, unsigned int* ret } -int Feb_Control_StartDAQOnlyNWaitForFinish(int sleep_time_us){ - if(Feb_Control_activated){ - if(!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0)||!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,DAQ_CTRL_START,0,0)){ - cprintf(RED,"Warning: could not start.\n"); +int Feb_Control_StartDAQOnlyNWaitForFinish(int sleep_time_us) { + if (Feb_Control_activated) { + if (!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0)||!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,DAQ_CTRL_START,0,0)) { + FILE_LOG(logERROR, ("could not start.\n")); return 0; } } @@ -1071,30 +1072,31 @@ int Feb_Control_StartDAQOnlyNWaitForFinish(int sleep_time_us){ } -int Feb_Control_AcquisitionInProgress(){ +int Feb_Control_AcquisitionInProgress() { unsigned int status_reg_r=0,status_reg_l=0; //deactivated should return end of acquisition - if(!Feb_Control_activated) + if (!Feb_Control_activated) return STATUS_IDLE; int ind = Feb_Control_current_index; - if(Module_BottomAddressIsValid(&modules[ind])){ + if (Module_BottomAddressIsValid(&modules[ind])) { - if(!(Feb_Control_GetDAQStatusRegister(Module_GetBottomRightAddress(&modules[ind]),&status_reg_r))) - {cprintf(RED,"Error: Trouble reading Status register. bottom right address\n");return STATUS_ERROR;} - if(!(Feb_Control_GetDAQStatusRegister(Module_GetBottomLeftAddress(&modules[ind]),&status_reg_l))) - {cprintf(RED,"Error: Trouble reading Status register. bottom left address\n");return STATUS_ERROR;} + if (!(Feb_Control_GetDAQStatusRegister(Module_GetBottomRightAddress(&modules[ind]),&status_reg_r))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. bottom right address\n"));return STATUS_ERROR;} + if (!(Feb_Control_GetDAQStatusRegister(Module_GetBottomLeftAddress(&modules[ind]),&status_reg_l))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. bottom left address\n"));return STATUS_ERROR;} - }else{ - if(!(Feb_Control_GetDAQStatusRegister(Module_GetTopRightAddress(&modules[ind]),&status_reg_r))) - {cprintf(RED,"Error: Trouble reading Status register. top right address\n");return STATUS_ERROR;} - if(!(Feb_Control_GetDAQStatusRegister(Module_GetTopLeftAddress(&modules[ind]),&status_reg_l))) - {cprintf(RED,"Error: Trouble reading Status register. top left address\n");return STATUS_ERROR;} + } else { + if (!(Feb_Control_GetDAQStatusRegister(Module_GetTopRightAddress(&modules[ind]),&status_reg_r))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. top right address\n"));return STATUS_ERROR;} + if (!(Feb_Control_GetDAQStatusRegister(Module_GetTopLeftAddress(&modules[ind]),&status_reg_l))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. top left address\n"));return STATUS_ERROR;} } //running - if((status_reg_r|status_reg_l)&DAQ_STATUS_DAQ_RUNNING) {/*printf("**runningggg\n");*/ + if ((status_reg_r|status_reg_l)&DAQ_STATUS_DAQ_RUNNING) { + FILE_LOG(logDEBUG1, ("**runningggg\n")); return STATUS_RUNNING; } //idle @@ -1102,30 +1104,30 @@ int Feb_Control_AcquisitionInProgress(){ } -int Feb_Control_AcquisitionStartedBit(){ +int Feb_Control_AcquisitionStartedBit() { unsigned int status_reg_r=0,status_reg_l=0; //deactivated should return acquisition started/ready - if(!Feb_Control_activated) + if (!Feb_Control_activated) return 1; int ind = Feb_Control_current_index; - if(Module_BottomAddressIsValid(&modules[ind])){ + if (Module_BottomAddressIsValid(&modules[ind])) { - if(!(Feb_Control_GetDAQStatusRegister(Module_GetBottomRightAddress(&modules[ind]),&status_reg_r))) - {cprintf(RED,"Error: Trouble reading Status register. bottom right address\n");return -1;} - if(!(Feb_Control_GetDAQStatusRegister(Module_GetBottomLeftAddress(&modules[ind]),&status_reg_l))) - {cprintf(RED,"Error: Trouble reading Status register. bottom left address\n");return -1;} + if (!(Feb_Control_GetDAQStatusRegister(Module_GetBottomRightAddress(&modules[ind]),&status_reg_r))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. bottom right address\n"));return -1;} + if (!(Feb_Control_GetDAQStatusRegister(Module_GetBottomLeftAddress(&modules[ind]),&status_reg_l))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. bottom left address\n"));return -1;} - }else{ - if(!(Feb_Control_GetDAQStatusRegister(Module_GetTopRightAddress(&modules[ind]),&status_reg_r))) - {cprintf(RED,"Error: Trouble reading Status register. top right address\n"); return -1;} - if(!(Feb_Control_GetDAQStatusRegister(Module_GetTopLeftAddress(&modules[ind]),&status_reg_l))) - {cprintf(RED,"Error: Trouble reading Status register. top left address\n");return -1;} + } else { + if (!(Feb_Control_GetDAQStatusRegister(Module_GetTopRightAddress(&modules[ind]),&status_reg_r))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. top right address\n")); return -1;} + if (!(Feb_Control_GetDAQStatusRegister(Module_GetTopLeftAddress(&modules[ind]),&status_reg_l))) + {FILE_LOG(logERROR, ("Error: Trouble reading Status register. top left address\n"));return -1;} } //doesnt mean it started, just the bit - if((status_reg_r|status_reg_l)&DAQ_STATUS_DAQ_RUN_TOGGLE) + if ((status_reg_r|status_reg_l)&DAQ_STATUS_DAQ_RUN_TOGGLE) return 1; return 0; @@ -1133,13 +1135,13 @@ int Feb_Control_AcquisitionStartedBit(){ -int Feb_Control_WaitForFinishedFlag(int sleep_time_us){ +int Feb_Control_WaitForFinishedFlag(int sleep_time_us) { int is_running = Feb_Control_AcquisitionInProgress(); int check_error = 0; // it will break out if it is idle or if check_error is more than 5 times - while(is_running != STATUS_IDLE){ + while(is_running != STATUS_IDLE) { usleep(sleep_time_us); is_running = Feb_Control_AcquisitionInProgress(); @@ -1157,35 +1159,35 @@ int Feb_Control_WaitForFinishedFlag(int sleep_time_us){ } -int Feb_Control_WaitForStartedFlag(int sleep_time_us, int prev_flag){ +int Feb_Control_WaitForStartedFlag(int sleep_time_us, int prev_flag) { //deactivated dont wait (otherwise give a toggle value back) - if(!Feb_Control_activated) + if (!Feb_Control_activated) return 1; //did not start - if(prev_flag == -1) + if (prev_flag == -1) return 0; int value = prev_flag; - while(value == prev_flag){ + while(value == prev_flag) { usleep(sleep_time_us); value = Feb_Control_AcquisitionStartedBit(); } //did not start - if(value == -1) + if (value == -1) return 0; return 1; } -int Feb_Control_Reset(){ - printf("Reset daq\n"); - if(Feb_Control_activated){ - if(!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0) || !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,DAQ_CTRL_RESET,0,0) || !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0)){ - cprintf(RED,"Warning: Could not reset daq, no response.\n"); +int Feb_Control_Reset() { + FILE_LOG(logINFO, ("Reset daq\n")); + if (Feb_Control_activated) { + if (!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0) || !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,DAQ_CTRL_RESET,0,0) || !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CTRL,0,0,0)) { + FILE_LOG(logERROR, ("Could not reset daq, no response.\n")); return 0; } } @@ -1196,278 +1198,283 @@ int Feb_Control_Reset(){ -int Feb_Control_SetStaticBits(){ - if(Feb_Control_activated){ +int Feb_Control_SetStaticBits() { + if (Feb_Control_activated) { //program=1,m4=2,m8=4,test=8,rotest=16,cs_bar_left=32,cs_bar_right=64 - if(!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_STATIC_BITS,Feb_Control_staticBits,0,0) || + if (!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_STATIC_BITS,Feb_Control_staticBits,0,0) || !Feb_Control_SetCommandRegister(DAQ_SET_STATIC_BIT) || - (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - cprintf(RED,"Warning: Could not set static bits\n"); + (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, ("Could not set static bits\n")); return 0; } } return 1; } -int Feb_Control_SetStaticBits1(unsigned int the_static_bits){ +int Feb_Control_SetStaticBits1(unsigned int the_static_bits) { Feb_Control_staticBits = the_static_bits; return Feb_Control_SetStaticBits(); } -int Feb_Control_SetInTestModeVariable(int on){ - if(on) Feb_Control_staticBits |= DAQ_STATIC_BIT_CHIP_TEST; //setting test bit to high +int Feb_Control_SetInTestModeVariable(int on) { + if (on) Feb_Control_staticBits |= DAQ_STATIC_BIT_CHIP_TEST; //setting test bit to high else Feb_Control_staticBits &= (~DAQ_STATIC_BIT_CHIP_TEST); //setting test bit to low return 1; } -int Feb_Control_GetTestModeVariable(){ +int Feb_Control_GetTestModeVariable() { return Feb_Control_staticBits&DAQ_STATIC_BIT_CHIP_TEST; } -int Feb_Control_SetDynamicRange(unsigned int four_eight_sixteen_or_thirtytwo){ +int Feb_Control_SetDynamicRange(unsigned int four_eight_sixteen_or_thirtytwo) { static unsigned int everything_but_bit_mode = DAQ_STATIC_BIT_PROGRAM|DAQ_STATIC_BIT_CHIP_TEST|DAQ_STATIC_BIT_ROTEST; - if(four_eight_sixteen_or_thirtytwo==4){ + if (four_eight_sixteen_or_thirtytwo==4) { Feb_Control_staticBits = DAQ_STATIC_BIT_M4 | (Feb_Control_staticBits&everything_but_bit_mode); //leave test bits in currernt state Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING; - }else if(four_eight_sixteen_or_thirtytwo==8){ + } else if (four_eight_sixteen_or_thirtytwo==8) { Feb_Control_staticBits = DAQ_STATIC_BIT_M8 | (Feb_Control_staticBits&everything_but_bit_mode); Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING; - }else if(four_eight_sixteen_or_thirtytwo==16){ + } else if (four_eight_sixteen_or_thirtytwo==16) { Feb_Control_staticBits = DAQ_STATIC_BIT_M12 | (Feb_Control_staticBits&everything_but_bit_mode); Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING; - }else if(four_eight_sixteen_or_thirtytwo==32){ + } else if (four_eight_sixteen_or_thirtytwo==32) { Feb_Control_staticBits = DAQ_STATIC_BIT_M12 | (Feb_Control_staticBits&everything_but_bit_mode); Feb_Control_subFrameMode |= DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING; - }else{ - cprintf(RED,"Warning: dynamic range (%d) not valid, not setting bit mode.\n",four_eight_sixteen_or_thirtytwo); - printf("Set dynamic range int must equal 4,8 16, or 32.\n"); + } else { + FILE_LOG(logERROR, ("dynamic range (%d) not valid, not setting bit mode.\n",four_eight_sixteen_or_thirtytwo)); + FILE_LOG(logINFO, ("Set dynamic range int must equal 4,8 16, or 32.\n")); return 0; } - printf("Dynamic range set to: %d\n",four_eight_sixteen_or_thirtytwo); + FILE_LOG(logINFO, ("Dynamic range set to %d\n",four_eight_sixteen_or_thirtytwo)); return 1; } -unsigned int Feb_Control_GetDynamicRange(){ - if(Feb_Control_subFrameMode&DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING) return 32; - else if(DAQ_STATIC_BIT_M4&Feb_Control_staticBits) return 4; - else if(DAQ_STATIC_BIT_M8&Feb_Control_staticBits) return 8; +unsigned int Feb_Control_GetDynamicRange() { + if (Feb_Control_subFrameMode&DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING) return 32; + else if (DAQ_STATIC_BIT_M4&Feb_Control_staticBits) return 4; + else if (DAQ_STATIC_BIT_M8&Feb_Control_staticBits) return 8; return 16; } -int Feb_Control_SetReadoutSpeed(unsigned int readout_speed){ //0->full,1->half,2->quarter or 3->super_slow +int Feb_Control_SetReadoutSpeed(unsigned int readout_speed) { //0->full,1->half,2->quarter or 3->super_slow Feb_Control_acquireNReadoutMode &= (~DAQ_CHIP_CONTROLLER_SUPER_SLOW_SPEED); - if(readout_speed==1){ + if (readout_speed==1) { Feb_Control_acquireNReadoutMode |= DAQ_CHIP_CONTROLLER_HALF_SPEED; - printf("Everything at half speed, ie. reading with 50 MHz main clk (half speed) ....\n"); - }else if(readout_speed==2){ + FILE_LOG(logINFO, ("Speed set to half speed (50 MHz)\n")); + } else if (readout_speed==2) { Feb_Control_acquireNReadoutMode |= DAQ_CHIP_CONTROLLER_QUARTER_SPEED; - printf("Everything at quarter speed, ie. reading with 25 MHz main clk (quarter speed) ....\n"); - }else if(readout_speed==3){ + FILE_LOG(logINFO, ("Speed set to quarter speed (25 MHz)\n")); + } else if (readout_speed==3) { Feb_Control_acquireNReadoutMode |= DAQ_CHIP_CONTROLLER_SUPER_SLOW_SPEED; - printf("Everything at super slow speed, ie. reading with ~0.200 MHz main clk (super slow speed) ....\n"); - }else{ - if(readout_speed){ - cprintf(RED,"Warning readout speed %d unknown, defaulting to full speed.\n",readout_speed); - printf("Everything at full speed, ie. reading with 100 MHz main clk (full speed) ....\n"); + FILE_LOG(logINFO, ("Speed set to super slow speed (~0.200 MHz)\n")); + } else { + if (readout_speed) { + FILE_LOG(logERROR, ("readout speed %d unknown, defaulting to full speed.\n",readout_speed)); + FILE_LOG(logINFO, ("full speed, (100 MHz)\n")); return 0; } - printf("Everything at full speed, ie. reading with 100 MHz main clk (full speed) ....\n"); + FILE_LOG(logINFO, ("Speed set to full speed (100 MHz)\n")); } return 1; } -int Feb_Control_SetReadoutMode(unsigned int readout_mode){ //0->parallel,1->non-parallel,2-> safe_mode +int Feb_Control_SetReadoutMode(unsigned int readout_mode) { //0->parallel,1->non-parallel,2-> safe_mode Feb_Control_acquireNReadoutMode &= (~DAQ_NEXPOSURERS_PARALLEL_MODE); - if(readout_mode==1){ + if (readout_mode==1) { Feb_Control_acquireNReadoutMode |= DAQ_NEXPOSURERS_NORMAL_NONPARALLEL_MODE; - printf("Readout mode set to normal non-parallel readout mode ... \n");; - }else if(readout_mode==2){ + FILE_LOG(logINFO, ("Readout mode set to Non Parallel\n")); + } else if (readout_mode==2) { Feb_Control_acquireNReadoutMode |= DAQ_NEXPOSURERS_SAFEST_MODE_ROW_CLK_BEFORE_MODE; - printf("Readout mode set to safest mode, row clk before main clk readout sequence .... \n");; - }else{ + FILE_LOG(logINFO, ("Readout mode set to Safe (row clk before main clk readout sequence)\n")); + } else { Feb_Control_acquireNReadoutMode |= DAQ_NEXPOSURERS_PARALLEL_MODE; - if(readout_mode){ - cprintf(RED,"Warning readout mode %d) unknown, defaulting to full speed.\n",readout_mode); - printf("Readout mode set to parrallel acquire/read mode .... \n");; + if (readout_mode) { + FILE_LOG(logERROR, ("readout mode %d) unknown, defaulting to parallel readout.\n",readout_mode)); + FILE_LOG(logINFO, ("Readout mode set to Parallel\n")); return 0; } - printf("Readout mode set to parrallel acquire/read mode .... \n");; + FILE_LOG(logINFO, ("Readout mode set to Parallel\n")); } return 1; } -int Feb_Control_SetTriggerMode(unsigned int trigger_mode,int polarity){ +int Feb_Control_SetTriggerMode(unsigned int trigger_mode,int polarity) { //"00"-> internal exposure time and period, //"01"-> external acquistion start and internal exposure time and period, //"10"-> external start trigger and internal exposure time, //"11"-> external triggered start and stop of exposures Feb_Control_triggerMode = (~DAQ_NEXPOSURERS_EXTERNAL_IMAGE_START_AND_STOP); - if(trigger_mode == 1){ + if (trigger_mode == 1) { Feb_Control_triggerMode = DAQ_NEXPOSURERS_EXTERNAL_ACQUISITION_START; - printf("Trigger mode: external start of acquisition sequence, internal exposure length and period.\n");; - }else if(trigger_mode == 2){ + FILE_LOG(logINFO, ("Trigger mode set to Burst Trigger\n")); + } else if (trigger_mode == 2) { Feb_Control_triggerMode = DAQ_NEXPOSURERS_EXTERNAL_IMAGE_START; - printf("Trigger mode: external image start, internal exposure time.\n");; - }else if(trigger_mode == 3){ + FILE_LOG(logINFO, ("Trigger mode set to Trigger Exposure\n")); + } else if (trigger_mode == 3) { Feb_Control_triggerMode = DAQ_NEXPOSURERS_EXTERNAL_IMAGE_START_AND_STOP; - printf("Trigger mode: externally controlled, external image window (start and stop).\n");; - }else{ + FILE_LOG(logINFO, ("Trigger mode set to Gated\n")); + } else { Feb_Control_triggerMode = DAQ_NEXPOSURERS_INTERNAL_ACQUISITION; - if(trigger_mode) cprintf(RED,"Warning trigger %d) unknown, defaulting to internal triggering.\n",trigger_mode);; + if (trigger_mode) { + FILE_LOG(logERROR, ("trigger %d) unknown, defaulting to Auto\n",trigger_mode)); + } - printf("Trigger mode: acquisition internally controlled exposure length and period.\n");; + FILE_LOG(logINFO, ("Trigger mode set to Auto\n")); return trigger_mode==0; } - if(polarity){ + if (polarity) { Feb_Control_triggerMode |= DAQ_NEXPOSURERS_EXTERNAL_TRIGGER_POLARITY; - printf("External trigger polarity set to positive.\n");; - }else{ + FILE_LOG(logINFO, ("External trigger polarity set to positive\n")); + } else { Feb_Control_triggerMode &= (~DAQ_NEXPOSURERS_EXTERNAL_TRIGGER_POLARITY); - printf("External trigger polarity set to negitive.\n");; + FILE_LOG(logINFO, ("External trigger polarity set to negitive\n")); } return 1; } -int Feb_Control_SetExternalEnableMode(int use_external_enable, int polarity){ - if(use_external_enable){ +int Feb_Control_SetExternalEnableMode(int use_external_enable, int polarity) { + if (use_external_enable) { Feb_Control_externalEnableMode |= DAQ_NEXPOSURERS_EXTERNAL_ENABLING; - printf("External enabling enabled, "); - if(polarity){ + if (polarity) { Feb_Control_externalEnableMode |= DAQ_NEXPOSURERS_EXTERNAL_ENABLING_POLARITY; - printf(", polarity set to positive.\n");; - }else{ + } else { Feb_Control_externalEnableMode &= (~DAQ_NEXPOSURERS_EXTERNAL_ENABLING_POLARITY); - printf(", polarity set to negative.\n");; } - }else{ + FILE_LOG(logINFO, ("External enabling enabled, polarity set to %s\n", + (polarity ? "positive" : "negative"))); + + } else { Feb_Control_externalEnableMode = 0; /* changed by Dhanya according to old code &= (~DAQ_NEXPOSURERS_EXTERNAL_ENABLING);*/ - printf("External enabling disabled.\n");; + FILE_LOG(logINFO, ("External enabling disabled\n")); } return 1; } -int Feb_Control_SetNExposures(unsigned int n_images){ - if(!n_images){ - cprintf(RED,"Warning nimages must be greater than zero.%d\n",n_images); +int Feb_Control_SetNExposures(unsigned int n_images) { + if (!n_images) { + FILE_LOG(logERROR, ("nimages must be greater than zero.%d\n",n_images)); return 0; } Feb_Control_nimages = n_images; - printf("Number of images set to: %d\n",Feb_Control_nimages); + FILE_LOG(logINFO, ("Number of images set to %d\n",Feb_Control_nimages)); return 1; } -unsigned int Feb_Control_GetNExposures(){return Feb_Control_nimages;} +unsigned int Feb_Control_GetNExposures() {return Feb_Control_nimages;} -int Feb_Control_SetExposureTime(double the_exposure_time_in_sec){ +int Feb_Control_SetExposureTime(double the_exposure_time_in_sec) { Feb_Control_exposure_time_in_sec = the_exposure_time_in_sec; - printf("Exposure time set to: %fs\n",Feb_Control_exposure_time_in_sec); + FILE_LOG(logINFO, ("Exposure time set to %fs\n",Feb_Control_exposure_time_in_sec)); return 1; } -double Feb_Control_GetExposureTime(){return Feb_Control_exposure_time_in_sec;} -int64_t Feb_Control_GetExposureTime_in_nsec(){return (int64_t)(Feb_Control_exposure_time_in_sec*(1E9));} +double Feb_Control_GetExposureTime() {return Feb_Control_exposure_time_in_sec;} +int64_t Feb_Control_GetExposureTime_in_nsec() {return (int64_t)(Feb_Control_exposure_time_in_sec*(1E9));} -int Feb_Control_SetSubFrameExposureTime(int64_t the_subframe_exposure_time_in_10nsec){ +int Feb_Control_SetSubFrameExposureTime(int64_t the_subframe_exposure_time_in_10nsec) { Feb_Control_subframe_exposure_time_in_10nsec = the_subframe_exposure_time_in_10nsec; - printf("Sub Frame Exposure time set to: %lld\n",(long long int)Feb_Control_subframe_exposure_time_in_10nsec); + FILE_LOG(logINFO, ("Sub Frame Exposure time set to %lldns\n",(long long int)Feb_Control_subframe_exposure_time_in_10nsec * 10)); return 1; } -int64_t Feb_Control_GetSubFrameExposureTime(){return Feb_Control_subframe_exposure_time_in_10nsec*10;} +int64_t Feb_Control_GetSubFrameExposureTime() {return Feb_Control_subframe_exposure_time_in_10nsec*10;} -int Feb_Control_SetSubFramePeriod(int64_t the_subframe_period_in_10nsec){ +int Feb_Control_SetSubFramePeriod(int64_t the_subframe_period_in_10nsec) { Feb_Control_subframe_period_in_10nsec = the_subframe_period_in_10nsec; - printf("Sub Frame Period set to: %lld\n",(long long int)Feb_Control_subframe_period_in_10nsec); + FILE_LOG(logINFO, ("Sub Frame Period set to %lldns\n",(long long int)Feb_Control_subframe_period_in_10nsec * 10)); return 1; } -int64_t Feb_Control_GetSubFramePeriod(){return Feb_Control_subframe_period_in_10nsec*10;} +int64_t Feb_Control_GetSubFramePeriod() {return Feb_Control_subframe_period_in_10nsec*10;} -int Feb_Control_SetExposurePeriod(double the_exposure_period_in_sec){ +int Feb_Control_SetExposurePeriod(double the_exposure_period_in_sec) { Feb_Control_exposure_period_in_sec = the_exposure_period_in_sec; - printf("Exposure period set to: %f\n",Feb_Control_exposure_period_in_sec); + FILE_LOG(logINFO, ("Exposure period set to %fs\n",Feb_Control_exposure_period_in_sec)); return 1; } -double Feb_Control_GetExposurePeriod(){return Feb_Control_exposure_period_in_sec;} +double Feb_Control_GetExposurePeriod() {return Feb_Control_exposure_period_in_sec;} -unsigned int Feb_Control_ConvertTimeToRegister(float time_in_sec){ +unsigned int Feb_Control_ConvertTimeToRegister(float time_in_sec) { float n_clk_cycles = round(time_in_sec/10e-9); //200 MHz ctb clk or 100 MHz feb clk unsigned int decoded_time; - if(n_clk_cycles>(pow(2,29)-1)*pow(10,7)){ + if (n_clk_cycles>(pow(2,29)-1)*pow(10,7)) { float max_time = 10e-9*(pow(2,28)-1)*pow(10,7); - cprintf(RED,"Warning: time exceeds (%f) maximum exposure time of %f sec.\n",time_in_sec,max_time); - printf("\t Setting to maximum %f us.\n",max_time); + FILE_LOG(logERROR, ("time exceeds (%f) maximum exposure time of %f sec.\n",time_in_sec,max_time)); + FILE_LOG(logINFO, ("\t Setting to maximum %f us.\n",max_time)); decoded_time = 0xffffffff; - }else{ + } else { int power_of_ten = 0; - while(n_clk_cycles>pow(2,29)-1){ power_of_ten++; n_clk_cycles = round(n_clk_cycles/10.0);} + while(n_clk_cycles>pow(2,29)-1) { power_of_ten++; n_clk_cycles = round(n_clk_cycles/10.0);} decoded_time = (int)(n_clk_cycles)<<3 | (int)(power_of_ten); } return decoded_time; } -int Feb_Control_ResetChipCompletely(){ - if(!Feb_Control_SetCommandRegister(DAQ_RESET_COMPLETELY) || (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - cprintf(RED,"Warning: could not ResetChipCompletely() with 0x%x.\n",DAQ_RESET_COMPLETELY); +int Feb_Control_ResetChipCompletely() { + if (!Feb_Control_SetCommandRegister(DAQ_RESET_COMPLETELY) || (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, ("could not ResetChipCompletely() with 0x%x.\n",DAQ_RESET_COMPLETELY)); return 0; } - printf("Chip reset completely\n"); + FILE_LOG(logINFO, ("Chip reset completely\n")); return 1; } -int Feb_Control_ResetChipPartially(){ - if(!Feb_Control_SetCommandRegister(DAQ_RESET_PERIPHERY) || (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - cprintf(RED,"Warning: could not ResetChipPartially with periphery\n"); +int Feb_Control_ResetChipPartially() { + if (!Feb_Control_SetCommandRegister(DAQ_RESET_PERIPHERY) || (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, ("could not ResetChipPartially with periphery\n")); return 0; } - printf("Chip reset periphery 0x%x\n",DAQ_RESET_PERIPHERY); + FILE_LOG(logINFO, ("Chip reset periphery 0x%x\n",DAQ_RESET_PERIPHERY)); - if(!Feb_Control_SetCommandRegister(DAQ_RESET_COLUMN_SELECT) || (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - cprintf(RED,"Warning: could not ResetChipPartially with column select\n"); + if (!Feb_Control_SetCommandRegister(DAQ_RESET_COLUMN_SELECT) || (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, ("could not ResetChipPartially with column select\n")); return 0; } - printf("Chip reset column select 0x%x\n",DAQ_RESET_COLUMN_SELECT); + FILE_LOG(logINFO, ("Chip reset column select 0x%x\n",DAQ_RESET_COLUMN_SELECT)); return 1; } -void Feb_Control_PrintAcquisitionSetup(){ +void Feb_Control_PrintAcquisitionSetup() { time_t rawtime; time(&rawtime); struct tm *timeinfo = localtime(&rawtime); - printf("\nStarting an exposure: %s",asctime(timeinfo)); - printf("\t Dynamic range nbits: %d\n",Feb_Control_GetDynamicRange()); - printf("\t Trigger mode: 0x%x\n",Feb_Control_triggerMode); - printf("\t Number of exposures: %d\n",Feb_Control_GetNExposures()); - printf("\t Exsposure time (if used): %f seconds.\n",Feb_Control_exposure_time_in_sec); - printf("\t Exsposure period (if used): %f seconds.\n\n\n",Feb_Control_exposure_period_in_sec); + FILE_LOG(logINFO, ("Starting an exposure: (%s)" + "\t Dynamic range nbits: %d\n" + "\t Trigger mode: 0x%x\n" + "\t Number of exposures: %d\n" + "\t Exsposure time (if used): %f seconds.\n" + "\t Exsposure period (if used): %f seconds.\n\n", + asctime(timeinfo), Feb_Control_GetDynamicRange(), Feb_Control_triggerMode, + Feb_Control_GetNExposures(), Feb_Control_exposure_time_in_sec, + Feb_Control_exposure_period_in_sec)); } -int Feb_Control_SendBitModeToBebServer(){ +int Feb_Control_SendBitModeToBebServer() { unsigned int just_bit_mode = (DAQ_STATIC_BIT_M4|DAQ_STATIC_BIT_M8) & Feb_Control_staticBits; unsigned int bit_mode = 16; //default - if(just_bit_mode == DAQ_STATIC_BIT_M4) bit_mode = 4; - else if(just_bit_mode == DAQ_STATIC_BIT_M8) bit_mode = 8; - else if(Feb_Control_subFrameMode&DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING) bit_mode = 32; + if (just_bit_mode == DAQ_STATIC_BIT_M4) bit_mode = 4; + else if (just_bit_mode == DAQ_STATIC_BIT_M8) bit_mode = 8; + else if (Feb_Control_subFrameMode&DAQ_NEXPOSURERS_ACTIVATE_AUTO_SUBIMAGING) bit_mode = 32; - if(!Beb_SetUpTransferParameters(bit_mode)){ - cprintf(RED,"Error: sending bit mode ...\n"); + if (!Beb_SetUpTransferParameters(bit_mode)) { + FILE_LOG(logERROR, ("Error: sending bit mode ...\n")); return 0; } @@ -1475,35 +1482,36 @@ int Feb_Control_SendBitModeToBebServer(){ } -int Feb_Control_PrepareForAcquisition(){//return 1; +int Feb_Control_PrepareForAcquisition() {//return 1; + FILE_LOG(logINFO, ("Going to Prepare for Acquisition\n\n\n")); static unsigned int reg_nums[20]; static unsigned int reg_vals[20]; Feb_Control_PrintAcquisitionSetup(); - // if(!Reset()||!ResetDataStream()){ - if(Feb_Control_Reset() == STATUS_ERROR){ - printf("Trouble reseting daq or data stream...\n");; + // if (!Reset()||!ResetDataStream()) { + if (Feb_Control_Reset() == STATUS_ERROR) { + FILE_LOG(logERROR, ("Trouble reseting daq or data stream...\n")); return 0; } - if(!Feb_Control_SetStaticBits1(Feb_Control_staticBits&(DAQ_STATIC_BIT_M4|DAQ_STATIC_BIT_M8))){ - printf("Trouble setting static bits ...\n");; + if (!Feb_Control_SetStaticBits1(Feb_Control_staticBits&(DAQ_STATIC_BIT_M4|DAQ_STATIC_BIT_M8))) { + FILE_LOG(logERROR, ("Trouble setting static bits ...\n")); return 0; } - if(!Feb_Control_SendBitModeToBebServer()){ - printf("Trouble sending static bits to server ...\n");; + if (!Feb_Control_SendBitModeToBebServer()) { + FILE_LOG(logERROR, ("Trouble sending static bits to server ...\n")); return 0; } int ret=0; - if(Feb_Control_counter_bit) + if (Feb_Control_counter_bit) ret = Feb_Control_ResetChipCompletely(); else ret = Feb_Control_ResetChipPartially(); - if(!ret){ - printf("Trouble resetting chips ...\n");; + if (!ret) { + FILE_LOG(logERROR, ("Trouble resetting chips ...\n")); return 0; } @@ -1522,10 +1530,10 @@ int Feb_Control_PrepareForAcquisition(){//return 1; reg_vals[5]= Feb_Control_subframe_exposure_time_in_10nsec; //(1 means 10ns, 100 means 1000ns) reg_nums[6]=DAQ_REG_SUBFRAME_PERIOD; reg_vals[6]= Feb_Control_subframe_period_in_10nsec; //(1 means 10ns, 100 means 1000ns) - // if(!Feb_Interface_WriteRegisters((Module_GetTopLeftAddress(&modules[1])|Module_GetTopRightAddress(&modules[1])),20,reg_nums,reg_vals,0,0)){ - if(Feb_Control_activated){ - if(!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),7,reg_nums,reg_vals,0,0)){ - printf("Trouble starting acquisition....\n");; + // if (!Feb_Interface_WriteRegisters((Module_GetTopLeftAddress(&modules[1])|Module_GetTopRightAddress(&modules[1])),20,reg_nums,reg_vals,0,0)) { + if (Feb_Control_activated) { + if (!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),7,reg_nums,reg_vals,0,0)) { + FILE_LOG(logERROR, ("Trouble starting acquisition....\n")); return 0; } } @@ -1535,24 +1543,24 @@ int Feb_Control_PrepareForAcquisition(){//return 1; -int Feb_Control_StartAcquisition(){ - printf("****** starting acquisition********* \n"); +int Feb_Control_StartAcquisition() { + FILE_LOG(logINFOBLUE, ("Starting Acquisition\n")); static unsigned int reg_nums[20]; static unsigned int reg_vals[20]; int i; - for(i=0;i<14;i++){ + for(i=0;i<14;i++) { reg_nums[i]=DAQ_REG_CTRL; reg_vals[i]=0; } reg_nums[14]=DAQ_REG_CTRL; reg_vals[14]=ACQ_CTRL_START; - if(Feb_Control_activated){ - if(!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),15,reg_nums,reg_vals,0,0)){ - cprintf(RED,"Trouble starting acquisition....\n");; + if (Feb_Control_activated) { + if (!Feb_Interface_WriteRegisters(Feb_Control_AddressToAll(),15,reg_nums,reg_vals,0,0)) { + FILE_LOG(logERROR, ("Trouble starting acquisition....\n")); return 0; } } @@ -1561,13 +1569,13 @@ int Feb_Control_StartAcquisition(){ return 1; } -int Feb_Control_StopAcquisition(){ +int Feb_Control_StopAcquisition() { return Feb_Control_Reset(); } -int Feb_Control_SaveAllTrimbitsTo(int value){ +int Feb_Control_SaveAllTrimbitsTo(int value) { unsigned int chanregs[Feb_Control_trimbit_size]; int i; for(i=0;i255||y<0||y>255){ - cprintf(RED,"Warning: Pixel out of range.\n"); + if (x<0||x>255||y<0||y>255) { + FILE_LOG(logERROR, ("Pixel out of range.\n")); return 0; } @@ -1609,17 +1617,17 @@ int Feb_Control_Pulse_Pixel(int npulses, int x, int y){ Feb_Control_SetStaticBits(); Feb_Control_SetCommandRegister(DAQ_RESET_PERIPHERY|DAQ_RESET_COLUMN_SELECT); if (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE) { - cprintf(RED,"Warning: could not pulse pixel as status not idle\n"); + FILE_LOG(logERROR, ("could not pulse pixel as status not idle\n")); return 0; } unsigned int serial_in = 8<<(4*(7-x%8)); - if(!Feb_Control_Shift32InSerialIn(serial_in)){ - cprintf(RED,"Warning ChipController::PulsePixel: could shift in the initail 32.\n"); + if (!Feb_Control_Shift32InSerialIn(serial_in)) { + FILE_LOG(logERROR, ("ChipController::PulsePixel: could shift in the initail 32.\n")); return 0; } - if(!pulse_multiple) + if (!pulse_multiple) serial_in=0; for(i=0;i1023){ - cprintf(RED,"Warning: Clock row clock ntimes (%d) exceeds the maximum value of 1023.\n\t Setting ntimes to 1023.\n",ntimes); +int Feb_Control_ClockRowClock(unsigned int ntimes) { + if (ntimes>1023) { + FILE_LOG(logERROR, ("Clock row clock ntimes (%d) exceeds the maximum value of 1023.\n\t Setting ntimes to 1023.\n",ntimes)); ntimes=1023; } - if(Feb_Control_activated){ - if(!Feb_Control_SetCommandRegister(DAQ_CLK_ROW_CLK_NTIMES) || + if (Feb_Control_activated) { + if (!Feb_Control_SetCommandRegister(DAQ_CLK_ROW_CLK_NTIMES) || !Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CLK_ROW_CLK_NTIMES,ntimes,0,0) || - (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - cprintf(RED,"Warning: could not clock row clock.\n"); + (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, ("could not clock row clock.\n")); return 0; } } @@ -1691,16 +1699,16 @@ int Feb_Control_ClockRowClock(unsigned int ntimes){ } -int Feb_Control_PulseChip(int npulses){ +int Feb_Control_PulseChip(int npulses) { int i; int on = 1; - if(npulses == -1){ + if (npulses == -1) { on = 0; - printf("\nResetting to normal mode\n"); - }else{ - printf("\n\nPulsing Chip.\n");//really just toggles the enable - printf("Vcmp should be set to 2.0 and Vtrim should be 2.\n"); + FILE_LOG(logINFO, ("\nResetting to normal mode\n")); + } else { + FILE_LOG(logINFO, ("\n\nPulsing Chip.\n"));//really just toggles the enable + FILE_LOG(logINFO, ("Vcmp should be set to 2.0 and Vtrim should be 2.\n")); } @@ -1708,145 +1716,149 @@ int Feb_Control_PulseChip(int npulses){ Feb_Control_SetStaticBits(); //toggle the enable 2x times Feb_Control_ResetChipCompletely(); - for(i=0;i ratemax) ratemax= Feb_Control_rate_meas[i]; + for(i=0;i ratemax) ratemax= Feb_Control_rate_meas[i]; } /* b : index/address of block ram/rate correction table b0 : base in vhdl m : slope in vhdl - + Firmware: data_in(11..2) -> memory address --> memory data_in( 1..0) -> lsb - + mem_data_out(13.. 0) -> base mem_data_out(17..14) -> slope - + delta = slope*lsb corr = base+delta - */ - + */ + int next_i=0; double beforemax; b0[0] = 0; m[0] = 1; - + Feb_Control_rate_correction_table[0] = (((int)(m[0]+0.5)&0xf)<<14) | ((int)(b0[0]+0.5)&0x3fff); int b=0; - for(b=1;b<1024;b++){ - if(m[b-1]<15){ + for(b=1;b<1024;b++) { + if (m[b-1]<15) { double s=0,sx=0,sy=0,sxx=0,sxy=0; - for(;;next_i++){ - if(next_i>=np){ - for(; b<1024; b++){ - if(beforemax>ratemax) b0[b] = beforemax; - else b0[b] = ratemax; - m[b] = 15; - Feb_Control_rate_correction_table[b] = (((int)(m[b]+0.5)&0xf)<<14) | ((int)(b0[b]+0.5)&0x3fff); - } - b=1024; - break; - } - - double x = Feb_Control_rate_meas[next_i] - b*4; - double y = next_i; - /*printf("Start Loop x: %f,\t y: %f,\t s: %f,\t sx: %f,\t sy: %f,\t sxx: %f,\t sxy: %f,\t " + for(;;next_i++) { + if (next_i>=np) { + for(; b<1024; b++) { + if (beforemax>ratemax) b0[b] = beforemax; + else b0[b] = ratemax; + m[b] = 15; + Feb_Control_rate_correction_table[b] = (((int)(m[b]+0.5)&0xf)<<14) | ((int)(b0[b]+0.5)&0x3fff); + } + b=1024; + break; + } + + double x = Feb_Control_rate_meas[next_i] - b*4; + double y = next_i; + /*FILE_LOG(logDEBUG1, ("Start Loop x: %f,\t y: %f,\t s: %f,\t sx: %f,\t sy: %f,\t sxx: %f,\t sxy: %f,\t " "next_i: %d,\t b: %d,\t Feb_Control_rate_meas[next_i]: %f\n", - x, y, s, sx, sy, sxx, sxy, next_i, b, Feb_Control_rate_meas[next_i]);*/ - - if(x < -0.5) continue; - if(x > 3.5) break; - s += 1; - sx += x; - sy += y; - sxx += x*x; - sxy += x*y; - /*printf("End Loop x: %f,\t y: %f,\t s: %f,\t sx: %f,\t sy: %f,\t sxx: %f,\t sxy: %f,\t " + x, y, s, sx, sy, sxx, sxy, next_i, b, Feb_Control_rate_meas[next_i]));*/ + + if (x < -0.5) continue; + if (x > 3.5) break; + s += 1; + sx += x; + sy += y; + sxx += x*x; + sxy += x*y; + /*FILE_LOG(logDEBUG1, ("End Loop x: %f,\t y: %f,\t s: %f,\t sx: %f,\t sy: %f,\t sxx: %f,\t sxy: %f,\t " "next_i: %d,\t b: %d,\t Feb_Control_rate_meas[next_i]: %f\n", - x, y, s, sx, sy, sxx, sxy, next_i, b, Feb_Control_rate_meas[next_i]);*/ + x, y, s, sx, sy, sxx, sxy, next_i, b, Feb_Control_rate_meas[next_i]));*/ } double delta = s*sxx - sx*sx; b0[b] = (sxx*sy - sx*sxy)/delta; m[b] = (s*sxy - sx*sy) /delta; beforemax= b0[b]; - if(m[b]<0||m[b]>15){ - m[b]=15; - if(beforemax>ratemax) b0[b] = beforemax; - else b0[b] = ratemax; + if (m[b]<0||m[b]>15) { + m[b]=15; + if (beforemax>ratemax) b0[b] = beforemax; + else b0[b] = ratemax; } - /*printf("After Loop s: %f,\t sx: %f,\t sy: %f,\t sxx: %f,\t sxy: %f,\t " + /*FILE_LOG(logDEBUG1, ("After Loop s: %f,\t sx: %f,\t sy: %f,\t sxx: %f,\t sxy: %f,\t " "next_i: %d,\t b: %d,\t Feb_Control_rate_meas[next_i]: %f\n", - s, sx, sy, sxx, sxy, next_i, b, Feb_Control_rate_meas[next_i]);*/ + s, sx, sy, sxx, sxy, next_i, b, Feb_Control_rate_meas[next_i]));*/ // cout<ratemax) b0[b] = beforemax; - else b0[b] = ratemax; - m[b] = 15; + } else { + if (beforemax>ratemax) b0[b] = beforemax; + else b0[b] = ratemax; + m[b] = 15; } Feb_Control_rate_correction_table[b] = (((int)(m[b]+0.5)&0xf)<<14) | ((int)(b0[b]+0.5)&0x3fff); - /*printf("After Loop 4*b: %d\tbase:%d\tslope:%d\n",4*b, (int)(b0[b]+0.5), (int)(m[b]+0.5) );*/ + /*FILE_LOG(logDEBUG1, ("After Loop 4*b: %d\tbase:%d\tslope:%d\n",4*b, (int)(b0[b]+0.5), (int)(m[b]+0.5) ));*/ } - if(Feb_Control_SetRateCorrectionTable(Feb_Control_rate_correction_table)){ + if (Feb_Control_SetRateCorrectionTable(Feb_Control_rate_correction_table)) { Feb_Control_RateTable_Tau_in_nsec = tau_in_Nsec; Feb_Control_RateTable_Period_in_nsec = period_in_sec*1e9; return 1; - }else{ + } else { Feb_Control_RateTable_Tau_in_nsec = -1; Feb_Control_RateTable_Period_in_nsec = -1; return 0; @@ -1858,75 +1870,75 @@ int Feb_Control_SetRateCorrectionTau(int64_t tau_in_Nsec){ -int Feb_Control_SetRateCorrectionTable(unsigned int *table){ - if(!table){ - printf("Error: could not set rate correction table, point is zero.\n"); - Feb_Control_SetRateCorrectionVariable(0); - return 0; - } +int Feb_Control_SetRateCorrectionTable(unsigned int *table) { + if (!table) { + FILE_LOG(logERROR, ("Error: could not set rate correction table, point is zero.\n")); + Feb_Control_SetRateCorrectionVariable(0); + return 0; + } - printf("Setting rate correction table. %d %d %d %d ....\n", - table[0],table[1],table[2],table[3]); + FILE_LOG(logINFO, ("Setting rate correction table. %d %d %d %d ....\n", + table[0],table[1],table[2],table[3])); - //was added otherwise after an acquire, startdaqonlywatiforfinish waits forever - if(!Feb_Control_SetCommandRegister(DAQ_RESET_COMPLETELY)){ - cprintf(RED,"Warning: Could not Feb_Control_SetCommandRegister for loading trim bits.\n"); - return 0; - } - printf("daq reset completely\n"); + //was added otherwise after an acquire, startdaqonlywatiforfinish waits forever + if (!Feb_Control_SetCommandRegister(DAQ_RESET_COMPLETELY)) { + FILE_LOG(logERROR, ("Could not Feb_Control_SetCommandRegister for loading trim bits.\n")); + return 0; + } + FILE_LOG(logINFO, ("daq reset completely\n")); - if(Module_TopAddressIsValid(&modules[1])){ - if(Feb_Control_activated){ - if(!Feb_Interface_WriteMemoryInLoops(Module_GetTopLeftAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| - !Feb_Interface_WriteMemoryInLoops(Module_GetTopRightAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| - (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - cprintf(BG_RED,"Error in Top Writing to Memory ::Feb_Control_SetRateCorrectionTable\n"); - return 0; - } - } - }else{ - if(Feb_Control_activated){ - if(!Feb_Interface_WriteMemoryInLoops(Module_GetBottomLeftAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| - !Feb_Interface_WriteMemoryInLoops(Module_GetBottomRightAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| - (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)){ - cprintf(BG_RED,"Error in Bottom Writing to Memory ::Feb_Control_SetRateCorrectionTable\n"); - return 0; - } - } - } - return 1; + if (Module_TopAddressIsValid(&modules[1])) { + if (Feb_Control_activated) { + if (!Feb_Interface_WriteMemoryInLoops(Module_GetTopLeftAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| + !Feb_Interface_WriteMemoryInLoops(Module_GetTopRightAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| + (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, ("could not write to memory (top) ::Feb_Control_SetRateCorrectionTable\n")); + return 0; + } + } + } else { + if (Feb_Control_activated) { + if (!Feb_Interface_WriteMemoryInLoops(Module_GetBottomLeftAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| + !Feb_Interface_WriteMemoryInLoops(Module_GetBottomRightAddress(&modules[Feb_Control_current_index]),1,0,1024,Feb_Control_rate_correction_table)|| + (Feb_Control_StartDAQOnlyNWaitForFinish(5000) != STATUS_IDLE)) { + FILE_LOG(logERROR, ("could not write to memory (bottom) ::Feb_Control_SetRateCorrectionTable\n")); + return 0; + } + } + } + return 1; } -int Feb_Control_GetRateCorrectionVariable(){ return (Feb_Control_subFrameMode&DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION);} +int Feb_Control_GetRateCorrectionVariable() { return (Feb_Control_subFrameMode&DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION);} -void Feb_Control_SetRateCorrectionVariable(int activate_rate_correction){ - if(activate_rate_correction){ - Feb_Control_subFrameMode |= DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION; - printf("Rate correction activated.\n"); - }else{ - Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION; - printf("Rate correction deactivated.\n"); - } +void Feb_Control_SetRateCorrectionVariable(int activate_rate_correction) { + if (activate_rate_correction) { + Feb_Control_subFrameMode |= DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION; + FILE_LOG(logINFO, ("Rate correction activated\n")); + } else { + Feb_Control_subFrameMode &= ~DAQ_NEXPOSURERS_ACTIVATE_RATE_CORRECTION; + FILE_LOG(logINFO, ("Rate correction deactivated\n")); + } } -int Feb_Control_PrintCorrectedValues(){ +int Feb_Control_PrintCorrectedValues() { int i; int delta, slope, base, lsb, corr; - for (i=0; i < 4096; i++){ + for (i=0; i < 4096; i++) { lsb = i&3; base = Feb_Control_rate_correction_table[i>>2] & 0x3fff; slope = ((Feb_Control_rate_correction_table[i>>2] & 0x3c000) >> 14); - + delta = slope*lsb; corr = delta+base; - if(slope==15) corr= 3*slope+base; + if (slope==15) corr= 3*slope+base; - printf("Readout Input: %d,\tBase:%d,\tSlope:%d,\tLSB:%d,\tDelta:%d\tResult:%d\tReal:%lf\n", - i, base, slope, lsb, delta, corr, Feb_Control_rate_meas[i]); + FILE_LOG(logDEBUG1, ("Readout Input: %d,\tBase:%d,\tSlope:%d,\tLSB:%d,\tDelta:%d\tResult:%d\tReal:%lf\n", + i, base, slope, lsb, delta, corr, Feb_Control_rate_meas[i])); } return 1; } @@ -1935,9 +1947,9 @@ int Feb_Control_PrintCorrectedValues(){ //So if software says now 40.00 you neeed to convert to mdegrees 40000(call it A1) and then //A1/65536/0.00198421639-273.15 -int Feb_Control_GetLeftFPGATemp(){ +int Feb_Control_GetLeftFPGATemp() { unsigned int temperature=0; - if(Module_TopAddressIsValid(&modules[1])) + if (Module_TopAddressIsValid(&modules[1])) Feb_Interface_ReadRegister(Module_GetTopLeftAddress (&modules[1]),FEB_REG_STATUS, &temperature); else Feb_Interface_ReadRegister(Module_GetBottomLeftAddress (&modules[1]),FEB_REG_STATUS, &temperature); @@ -1947,9 +1959,9 @@ int Feb_Control_GetLeftFPGATemp(){ return (int)temperature; } -int Feb_Control_GetRightFPGATemp(){ +int Feb_Control_GetRightFPGATemp() { unsigned int temperature=0; - if(Module_TopAddressIsValid(&modules[1])) + if (Module_TopAddressIsValid(&modules[1])) Feb_Interface_ReadRegister(Module_GetTopRightAddress (&modules[1]),FEB_REG_STATUS, &temperature); else Feb_Interface_ReadRegister(Module_GetBottomRightAddress (&modules[1]),FEB_REG_STATUS, &temperature); @@ -1986,24 +1998,20 @@ int Feb_Control_SoftwareTrigger() { unsigned int cmd = orig_value | DAQ_REG_CHIP_CMDS_INT_TRIGGER; - if(Feb_Control_activated) { + if (Feb_Control_activated) { // set trigger bit -#ifdef VERBOSE - cprintf(BLUE,"Setting Trigger, Register:0x%x\n",cmd); -#endif + FILE_LOG(logDEBUG1, ("Setting Trigger, Register:0x%x\n",cmd)); if (!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CHIP_CMDS,cmd,0,0)) { - cprintf(RED,"Warning: Could not give software trigger\n"); + FILE_LOG(logERROR, ("Could not give software trigger\n")); return 0; } // unset trigger bit -#ifdef VERBOSE - cprintf(BLUE,"Unsetting Trigger, Register:0x%x\n",orig_value); -#endif + FILE_LOG(logDEBUG1, ("Unsetting Trigger, Register:0x%x\n",orig_value)); if (!Feb_Interface_WriteRegister(Feb_Control_AddressToAll(),DAQ_REG_CHIP_CMDS,orig_value,0,0)) { - cprintf(RED,"Warning: Could not give software trigger\n"); + FILE_LOG(logERROR, ("Could not give software trigger\n")); return 0; } - cprintf(BLUE,"Software Internal Trigger Sent!\n"); + FILE_LOG(logINFO, ("Software Internal Trigger Sent!\n")); } return 1; @@ -2012,26 +2020,24 @@ int Feb_Control_SoftwareTrigger() { uint32_t Feb_Control_WriteRegister(uint32_t offset, uint32_t data) { uint32_t value=0; - if(Module_TopAddressIsValid(&modules[1])){ - if(!Feb_Interface_WriteRegister(Module_GetTopRightAddress (&modules[1]),offset, data,0, 0)) { - cprintf(RED,"Could not read tr value. Value read:%d\n", value); + if (Module_TopAddressIsValid(&modules[1])) { + if (!Feb_Interface_WriteRegister(Module_GetTopRightAddress (&modules[1]),offset, data,0, 0)) { + FILE_LOG(logERROR, ("Could not read tr value. Value read:%d\n", value)); value = 0; } - if(!Feb_Interface_WriteRegister(Module_GetTopLeftAddress (&modules[1]),offset, data,0, 0)) { - cprintf(RED,"Could not read tl value. Value read:%d\n", value); - value = 0; - } - + if(!Feb_Interface_WriteRegister(Module_GetTopLeftAddress (&modules[1]),offset, data,0, 0)) { + cprintf(RED,"Could not read tl value. Value read:%d\n", value); + value = 0; + } } else { - if(!Feb_Interface_WriteRegister(Module_GetBottomRightAddress (&modules[1]),offset, data,0, 0)) { - cprintf(RED,"Could not read br value. Value read:%d\n", value); + if (!Feb_Interface_WriteRegister(Module_GetBottomRightAddress (&modules[1]),offset, data,0, 0)) { + FILE_LOG(logERROR, ("Could not read br value. Value read:%d\n", value)); value = 0; } - if(!Feb_Interface_WriteRegister(Module_GetBottomLeftAddress (&modules[1]),offset, data,0, 0)) { - cprintf(RED,"Could not read bl value. Value read:%d\n", value); - value = 0; - } - + if(!Feb_Interface_WriteRegister(Module_GetBottomLeftAddress (&modules[1]),offset, data,0, 0)) { + cprintf(RED,"Could not read bl value. Value read:%d\n", value); + value = 0; + } } return Feb_Control_ReadRegister(offset); } @@ -2040,33 +2046,32 @@ uint32_t Feb_Control_WriteRegister(uint32_t offset, uint32_t data) { uint32_t Feb_Control_ReadRegister(uint32_t offset) { uint32_t value=0; uint32_t value1=0; - if(Module_TopAddressIsValid(&modules[1])){ - if(!Feb_Interface_ReadRegister(Module_GetTopRightAddress (&modules[1]),offset, &value)) { - cprintf(RED,"Could not read value. Value read:%d\n", value); - value = 0; - } - printf("Read top right addr: 0x%08x\n", value); - if(!Feb_Interface_ReadRegister(Module_GetTopLeftAddress (&modules[1]),offset, &value1)) { - cprintf(RED,"Could not read value. Value read:%d\n", value1); - value1 = 0; - } - printf("Read top left addr: 0x%08x\n", value1); - if (value != value1) - value = -1; - + if (Module_TopAddressIsValid(&modules[1])) { + if (!Feb_Interface_ReadRegister(Module_GetTopRightAddress (&modules[1]),offset, &value)) { + FILE_LOG(logERROR, ("Could not read value. Value read:%d\n", value)); + value = 0; + } + printf("Read top right addr: 0x%08x\n", value); + if(!Feb_Interface_ReadRegister(Module_GetTopLeftAddress (&modules[1]),offset, &value1)) { + cprintf(RED,"Could not read value. Value read:%d\n", value1); + value1 = 0; + } + printf("Read top left addr: 0x%08x\n", value1); + if (value != value1) + value = -1; } else { - if(!Feb_Interface_ReadRegister(Module_GetBottomRightAddress (&modules[1]),offset, &value)) { - cprintf(RED,"Could not read value. Value read:%d\n", value); - value = 0; - } - printf("Read bottom right addr: 0x%08x\n", value); - if(!Feb_Interface_ReadRegister(Module_GetBottomLeftAddress (&modules[1]),offset, &value1)) { - cprintf(RED,"Could not read value. Value read:%d\n", value1); - value1 = 0; - } - printf("Read bottom left addr: 0x%08x\n", value1); - if (value != value1) - value = -1; + if (!Feb_Interface_ReadRegister(Module_GetBottomRightAddress (&modules[1]),offset, &value)) { + FILE_LOG(logERROR, ("Could not read value. Value read:%d\n", value)); + value = 0; + } + printf("Read bottom right addr: 0x%08x\n", value); + if(!Feb_Interface_ReadRegister(Module_GetBottomLeftAddress (&modules[1]),offset, &value1)) { + cprintf(RED,"Could not read value. Value read:%d\n", value1); + value1 = 0; + } + printf("Read bottom left addr: 0x%08x\n", value1); + if (value != value1) + value = -1; } return value; } diff --git a/slsDetectorServers/eigerDetectorServer/FebControl.h b/slsDetectorServers/eigerDetectorServer/FebControl.h new file mode 100755 index 000000000..2e65666fd --- /dev/null +++ b/slsDetectorServers/eigerDetectorServer/FebControl.h @@ -0,0 +1,157 @@ +#pragma once +#include "FebInterface.h" +#include + + +struct Module{ + unsigned int module_number; + int top_address_valid; + unsigned int top_left_address; + unsigned int top_right_address; + int bottom_address_valid; + unsigned int bottom_left_address; + unsigned int bottom_right_address; + + unsigned int idelay_top[4]; //ll,lr,rl,ll + unsigned int idelay_bottom[4]; //ll,lr,rl,ll + float high_voltage; + int* top_dac; + int* bottom_dac; +}; + + +void Module_Module(struct Module* mod,unsigned int number, unsigned int address_top); +void Module_ModuleBottom(struct Module* mod,unsigned int number, unsigned int address_bottom); +void Module_Module1(struct Module* mod,unsigned int number, unsigned int address_top, unsigned int address_bottom); +unsigned int Module_GetModuleNumber(struct Module* mod); +int Module_TopAddressIsValid(struct Module* mod); +unsigned int Module_GetTopBaseAddress(struct Module* mod); +unsigned int Module_GetTopLeftAddress(struct Module* mod) ; +unsigned int Module_GetTopRightAddress(struct Module* mod); +unsigned int Module_GetBottomBaseAddress(struct Module* mod); +int Module_BottomAddressIsValid(struct Module* mod); +unsigned int Module_GetBottomLeftAddress(struct Module* mod); +unsigned int Module_GetBottomRightAddress(struct Module* mod); +unsigned int Module_SetTopIDelay(struct Module* mod,unsigned int chip,unsigned int value); +unsigned int Module_GetTopIDelay(struct Module* mod,unsigned int chip) ; +unsigned int Module_SetBottomIDelay(struct Module* mod,unsigned int chip,unsigned int value); +unsigned int Module_GetBottomIDelay(struct Module* mod,unsigned int chip); + +float Module_SetHighVoltage(struct Module* mod,float value); +float Module_GetHighVoltage(struct Module* mod); + +int Module_SetTopDACValue(struct Module* mod,unsigned int i, int value); +int Module_GetTopDACValue(struct Module* mod,unsigned int i); +int Module_SetBottomDACValue(struct Module* mod,unsigned int i, int value); +int Module_GetBottomDACValue(struct Module* mod,unsigned int i); + + +void Feb_Control_activate(int activate); + +int Feb_Control_IsBottomModule(); +int Feb_Control_GetModuleNumber(); + +void Feb_Control_PrintModuleList(); +int Feb_Control_GetModuleIndex(unsigned int module_number, unsigned int* module_index); +int Feb_Control_CheckModuleAddresses(struct Module* m); +int Feb_Control_AddModule(unsigned int module_number, unsigned int top_address); +int Feb_Control_AddModule1(unsigned int module_number, int top_enable, unsigned int top_address, unsigned int bottom_address, int half_module); +int Feb_Control_GetDACNumber(char* s, unsigned int* n); +int Feb_Control_SendDACValue(unsigned int dst_num, unsigned int ch, unsigned int* value); +int Feb_Control_VoltageToDAC(float value, unsigned int* digital, unsigned int nsteps, float vmin, float vmax); +float Feb_Control_DACToVoltage(unsigned int digital,unsigned int nsteps,float vmin,float vmax); +int Feb_Control_SendIDelays(unsigned int dst_num, int chip_lr, unsigned int channels, unsigned int ndelay_units); +int Feb_Control_SetStaticBits(); +int Feb_Control_SetStaticBits1(unsigned int the_static_bits); +int Feb_Control_SendBitModeToBebServer(); +unsigned int Feb_Control_ConvertTimeToRegister(float time_in_sec); +unsigned int Feb_Control_AddressToAll(); +int Feb_Control_SetCommandRegister(unsigned int cmd); +int Feb_Control_GetDAQStatusRegister(unsigned int dst_address, unsigned int* ret_status); +int Feb_Control_StartDAQOnlyNWaitForFinish(int sleep_time_us); +int Feb_Control_ResetChipCompletely(); +int Feb_Control_ResetChipPartially(); +void Feb_Control_FebControl(); +int Feb_Control_Init(int master, int top, int normal, int module_num); +int Feb_Control_OpenSerialCommunication(); +void Feb_Control_CloseSerialCommunication(); +int Feb_Control_CheckSetup(); +unsigned int Feb_Control_GetNModules(); +unsigned int Feb_Control_GetNHalfModules(); + +int Feb_Control_SetHighVoltage(int value); +int Feb_Control_GetHighVoltage(int* value); + +int Feb_Control_SendHighVoltage(int dacvalue); +int Feb_Control_ReceiveHighVoltage(unsigned int* value); + +int Feb_Control_SetIDelays(unsigned int module_num, unsigned int ndelay_units); +int Feb_Control_SetIDelays1(unsigned int module_num, unsigned int chip_pos, unsigned int ndelay_units); + +int Feb_Control_DecodeDACString(char* dac_str, unsigned int* module_index, int* top, int* bottom, unsigned int* dac_ch); +int Feb_Control_SetDAC(char* s, int value, int is_a_voltage_mv); +int Feb_Control_GetDAC(char* s, int* ret_value, int voltage_mv); +int Feb_Control_GetDACName(unsigned int dac_num,char* s); + +int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int* trimbits); +unsigned int* Feb_Control_GetTrimbits(); +int Feb_Control_SaveAllTrimbitsTo(int value); +int Feb_Control_Reset(); +int Feb_Control_PrepareForAcquisition(); + +int Feb_Control_StartAcquisition(); +int Feb_Control_StopAcquisition(); +int Feb_Control_AcquisitionInProgress(); +int Feb_Control_AcquisitionStartedBit(); +int Feb_Control_WaitForFinishedFlag(int sleep_time_us); +int Feb_Control_WaitForStartedFlag(int sleep_time_us, int prev_flag); +void Feb_Control_PrintAcquisitionSetup(); +int Feb_Control_SetNExposures(unsigned int n_images); +unsigned int Feb_Control_GetNExposures(); +int Feb_Control_SetExposureTime(double the_exposure_time_in_sec); +double Feb_Control_GetExposureTime(); +int64_t Feb_Control_GetExposureTime_in_nsec(); +int Feb_Control_SetSubFrameExposureTime(int64_t the_subframe_exposure_time_in_10nsec); +int64_t Feb_Control_GetSubFrameExposureTime(); +int Feb_Control_SetSubFramePeriod(int64_t the_subframe_period_in_10nsec); +int64_t Feb_Control_GetSubFramePeriod(); +int Feb_Control_SetExposurePeriod(double the_exposure_period_in_sec); +double Feb_Control_GetExposurePeriod(); +int Feb_Control_SetDynamicRange(unsigned int four_eight_sixteen_or_thirtytwo); +unsigned int Feb_Control_GetDynamicRange(); +int Feb_Control_SetReadoutSpeed(unsigned int readout_speed); //0 was default, 0->full,1->half,2->quarter or 3->super_slow +int Feb_Control_SetReadoutMode(unsigned int readout_mode); ///0 was default,0->parallel,1->non-parallel,2-> safe_mode +int Feb_Control_SetTriggerMode(unsigned int trigger_mode, int polarity);//0 and 1 was default, +int Feb_Control_SetExternalEnableMode(int use_external_enable, int polarity);//0 and 1 was default, + +int Feb_Control_SetInTestModeVariable(int on); +int Feb_Control_GetTestModeVariable(); + +void Feb_Control_Set_Counter_Bit(int value); +int Feb_Control_Get_Counter_Bit(); +int Feb_Control_Pulse_Pixel(int npulses,int x, int y); +int Feb_Control_PulsePixelNMove(int npulses, int inc_x_pos, int inc_y_pos); +int Feb_Control_Shift32InSerialIn(unsigned int value_to_shift_in); +int Feb_Control_SendTokenIn(); +int Feb_Control_ClockRowClock(unsigned int ntimes); +int Feb_Control_PulseChip(int npulses); + +int64_t Feb_Control_Get_RateTable_Tau_in_nsec(); +int64_t Feb_Control_Get_RateTable_Period_in_nsec(); +int Feb_Control_SetRateCorrectionTau(int64_t tau_in_Nsec); +int Feb_Control_SetRateCorrectionTable(unsigned int *table); +int Feb_Control_GetRateCorrectionVariable(); +void Feb_Control_SetRateCorrectionVariable(int activate_rate_correction); +int Feb_Control_PrintCorrectedValues(); + +int Feb_Control_GetLeftFPGATemp(); +int Feb_Control_GetRightFPGATemp(); + +int64_t Feb_Control_GetMeasuredPeriod(); +int64_t Feb_Control_GetSubMeasuredPeriod(); + +int Feb_Control_SoftwareTrigger(); + +uint32_t Feb_Control_WriteRegister(uint32_t offset, uint32_t data); +uint32_t Feb_Control_ReadRegister(uint32_t offset); + diff --git a/slsDetectorServers/eigerDetectorServer/FebInterface.c b/slsDetectorServers/eigerDetectorServer/FebInterface.c new file mode 100755 index 000000000..9c7d33051 --- /dev/null +++ b/slsDetectorServers/eigerDetectorServer/FebInterface.c @@ -0,0 +1,195 @@ +#include "FebInterface.h" +#include "LocalLinkInterface.h" +#include "xparameters.h" +#include "logger.h" + +#include + + + +struct LocalLinkInterface ll_local,* ll; + +unsigned int Feb_Interface_nfebs; +unsigned int* Feb_Interface_feb_numb; + +int Feb_Interface_send_ndata; +unsigned int Feb_Interface_send_buffer_size; +unsigned int* Feb_Interface_send_data_raw; +unsigned int* Feb_Interface_send_data; + +int Feb_Interface_recv_ndata; +unsigned int Feb_Interface_recv_buffer_size; +unsigned int* Feb_Interface_recv_data_raw; +unsigned int* Feb_Interface_recv_data; + + +void Feb_Interface_FebInterface() { + ll = &ll_local; + Feb_Interface_nfebs = 0; + Feb_Interface_feb_numb = 0; + + Feb_Interface_send_ndata = 0; + Feb_Interface_send_buffer_size = 1026; + Feb_Interface_send_data_raw = malloc((Feb_Interface_send_buffer_size+1) * sizeof(unsigned int)); + Feb_Interface_send_data = &Feb_Interface_send_data_raw[1]; + + Feb_Interface_recv_ndata = 0; + Feb_Interface_recv_buffer_size = 1026; + Feb_Interface_recv_data_raw = malloc((Feb_Interface_recv_buffer_size+1) * sizeof(unsigned int)); + Feb_Interface_recv_data = &Feb_Interface_recv_data_raw[1]; + + Local_LocalLinkInterface1(ll,XPAR_PLB_LL_FIFO_AURORA_DUAL_CTRL_FEB_RIGHT_BASEADDR); + +} + + + +void Feb_Interface_SendCompleteList(unsigned int n,unsigned int* list) { + unsigned int i; + if (Feb_Interface_feb_numb) free(Feb_Interface_feb_numb); + Feb_Interface_nfebs = n; + Feb_Interface_feb_numb = malloc(n * sizeof(unsigned int)); + for(i=0;i0xfff) return 0; + + FILE_LOG(logDEBUG1, ("FIW ch %d\n", ch)); + +Feb_Interface_send_data_raw[0] = 0x8fff0000; +if (Local_Write(ll,4,Feb_Interface_send_data_raw)!=4) return 0; + +Feb_Interface_send_data_raw[0] = 0x90000000 | (ch<<16); +if (Local_Write(ll,4,Feb_Interface_send_data_raw)!=4) return 0; + +Feb_Interface_send_data_raw[0] = 0xc0000000; +return ((Feb_Interface_send_ndata+1)*4==Local_Write(ll,(Feb_Interface_send_ndata+1)*4,Feb_Interface_send_data_raw)); +} + +int Feb_Interface_ReadFrom(unsigned int ch, unsigned int ntrys) { + unsigned int t; + if (ch>=0xfff) return 0; + + Feb_Interface_recv_data_raw[0] = 0xa0000000 | (ch<<16); + Local_Write(ll,4,Feb_Interface_recv_data_raw); + usleep(20); + + Feb_Interface_recv_ndata=-1; + for(t=0;t0) { + Feb_Interface_recv_ndata--; + break; + } + usleep(1000); + } + + return (Feb_Interface_recv_ndata>=0); +} + + + +int Feb_Interface_SetByteOrder() { + Feb_Interface_send_data_raw[0] = 0x8fff0000; + if (Local_Write(ll,4,Feb_Interface_send_data_raw)!=4) return 0; + Feb_Interface_send_ndata = 2; + Feb_Interface_send_data[0] = 0; + Feb_Interface_send_data[1] = 0; + unsigned int i; + unsigned int dst = 0xff; + for(i=0;iFeb_Interface_send_buffer_size-2) return 0; + + Feb_Interface_send_ndata = nreads+2; + Feb_Interface_send_data[0] = 0x20000000 | nreads << 14; + + for(i=0;iFeb_Interface_send_buffer_size-2) return 0; + + //cout<<"Write register : "<0) { + n_to_send = ndata_countdownFeb_Interface_send_buffer_size-2) { + FILE_LOG(logERROR, ("invalid nwrites:%d\n",nwrites)); + return 0; + }//*d-1026 + + Feb_Interface_send_ndata = nwrites+2;//*d-1026 + Feb_Interface_send_data[0] = 0xc0000000 | mem_num << 24 | nwrites << 14 | start_address; //cmd -> write to memory, nwrites, mem number, start address + Feb_Interface_send_data[nwrites+1] = 0; + for(i=0;i -//#include -//#include -//#include -//#include - #include "HardwareIO.h" xfs_u8 HWIO_xfs_in8(xfs_u32 InAddress) diff --git a/slsDetectorSoftware/eigerDetectorServer/HardwareIO.h b/slsDetectorServers/eigerDetectorServer/HardwareIO.h old mode 100644 new mode 100755 similarity index 86% rename from slsDetectorSoftware/eigerDetectorServer/HardwareIO.h rename to slsDetectorServers/eigerDetectorServer/HardwareIO.h index bc39d4668..92a6259d1 --- a/slsDetectorSoftware/eigerDetectorServer/HardwareIO.h +++ b/slsDetectorServers/eigerDetectorServer/HardwareIO.h @@ -1,9 +1,6 @@ - //Class initially from Gerd and was called mmap_test.c - -#ifndef HARDWAREIO_H -#define HARDWAREIO_H +#pragma once #include "xfs_types.h" @@ -17,10 +14,3 @@ void HWIO_xfs_out16(xfs_u32 OutAddress, xfs_u16 Value); void HWIO_xfs_out32(xfs_u32 OutAddress, xfs_u32 Value); - - - - - - -#endif diff --git a/slsDetectorSoftware/eigerDetectorServer/HardwareMMappingDefs.h b/slsDetectorServers/eigerDetectorServer/HardwareMMappingDefs.h old mode 100644 new mode 100755 similarity index 100% rename from slsDetectorSoftware/eigerDetectorServer/HardwareMMappingDefs.h rename to slsDetectorServers/eigerDetectorServer/HardwareMMappingDefs.h diff --git a/slsDetectorSoftware/eigerDetectorServer/LocalLinkInterface.c b/slsDetectorServers/eigerDetectorServer/LocalLinkInterface.c old mode 100644 new mode 100755 similarity index 64% rename from slsDetectorSoftware/eigerDetectorServer/LocalLinkInterface.c rename to slsDetectorServers/eigerDetectorServer/LocalLinkInterface.c index 8d1b9db1f..3e47cd61a --- a/slsDetectorSoftware/eigerDetectorServer/LocalLinkInterface.c +++ b/slsDetectorServers/eigerDetectorServer/LocalLinkInterface.c @@ -1,44 +1,34 @@ - -//Class initially from Gerd and was called mmap_test.c -//return reversed 1 means good, 0 means failed - - -#include -#include -//#include - - -#include "HardwareMMappingDefs.h" - #include "LocalLinkInterface.h" +#include "HardwareMMappingDefs.h" +#include "logger.h" + +#include +#include +#include - -void Local_LocalLinkInterface1(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr){ - // printf("\n v 1 \n"); - printf("Initialize PLB LL FIFOs\n"); +void Local_LocalLinkInterface1(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr) { + FILE_LOG(logDEBUG1, ("Initialize PLB LL FIFOs\n")); ll->ll_fifo_base=0; ll->ll_fifo_ctrl_reg=0; - if(Local_Init(ll,ll_fifo_badr)){ + if (Local_Init(ll,ll_fifo_badr)) { Local_Reset(ll); - printf("\tFIFO Status : 0x%08x\n",Local_StatusVector(ll)); - }else printf("\tError LocalLink Mappping : 0x%08x\n",ll_fifo_badr); - printf("\n\n"); + FILE_LOG(logDEBUG1, ("\tFIFO Status : 0x%08x\n\n\n", Local_StatusVector(ll))); + } else FILE_LOG(logERROR, ("\tCould not map LocalLink : 0x%08x\n\n\n", ll_fifo_badr)); } -/*~LocalLinkInterface(){};*/ -void Local_LocalLinkInterface(struct LocalLinkInterface* ll){ - printf("Initializing new memory\n"); +void Local_LocalLinkInterface(struct LocalLinkInterface* ll) { + FILE_LOG(logDEBUG1, ("Initializing new memory\n")); } -int Local_Init(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr){ +int Local_Init(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr) { int fd; void *plb_ll_fifo_ptr; - if ((fd=open("/dev/mem", O_RDWR)) < 0){ + if ((fd=open("/dev/mem", O_RDWR)) < 0) { fprintf(stderr, "Could not open /dev/mem\n"); return 0; } @@ -46,7 +36,7 @@ int Local_Init(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr){ plb_ll_fifo_ptr = mmap(0, getpagesize(), PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, fd, ll_fifo_badr); close(fd); - if (plb_ll_fifo_ptr == MAP_FAILED){ + if (plb_ll_fifo_ptr == MAP_FAILED) { perror ("mmap"); return 0; } @@ -59,13 +49,13 @@ int Local_Init(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr){ -int Local_Reset(struct LocalLinkInterface* ll){ +int Local_Reset(struct LocalLinkInterface* ll) { return Local_Reset1(ll,PLB_LL_FIFO_CTRL_RESET_STD); } -int Local_Reset1(struct LocalLinkInterface* ll,unsigned int rst_mask){ +int Local_Reset1(struct LocalLinkInterface* ll,unsigned int rst_mask) { ll->ll_fifo_ctrl_reg |= rst_mask; - printf("\tCTRL Register bits: 0x%08x\n",ll->ll_fifo_ctrl_reg); + FILE_LOG(logDEBUG1, ("\tCTRL Register bits: 0x%08x\n",ll->ll_fifo_ctrl_reg)); HWIO_xfs_out32(ll->ll_fifo_base+4*PLB_LL_FIFO_REG_CTRL,ll->ll_fifo_ctrl_reg); HWIO_xfs_out32(ll->ll_fifo_base+4*PLB_LL_FIFO_REG_CTRL,ll->ll_fifo_ctrl_reg); @@ -75,17 +65,16 @@ int Local_Reset1(struct LocalLinkInterface* ll,unsigned int rst_mask){ ll->ll_fifo_ctrl_reg &= (~rst_mask); HWIO_xfs_out32(ll->ll_fifo_base+4*PLB_LL_FIFO_REG_CTRL,ll->ll_fifo_ctrl_reg); - // printf("FIFO CTRL Address: 0x%08x\n FIFO CTRL Register: 0x%08x\n",PLB_LL_FIFO_REG_CTRL,plb_ll_fifo[PLB_LL_FIFO_REG_CTRL]); return 1; } -unsigned int Local_StatusVector(struct LocalLinkInterface* ll){ +unsigned int Local_StatusVector(struct LocalLinkInterface* ll) { return HWIO_xfs_in32(ll->ll_fifo_base+4*PLB_LL_FIFO_REG_STATUS); } -int Local_Write(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer){ +int Local_Write(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer) { // note: buffer must be word (4 byte) aligned // frame_len in byte int vacancy=0; @@ -101,22 +90,19 @@ int Local_Write(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buf last_word = (buffer_len-1)/4; word_ptr = (unsigned int *)buffer; -#ifdef MARTIN - cprintf(BLUE, "LL Write - Len: %2d - If: %X - Data: ",buffer_len, ll->ll_fifo_base); + FILE_LOG(logDEBUG1, ("LL Write - Len: %2d - If: %X - Data: ",buffer_len, ll->ll_fifo_base)); for (i=0; i < buffer_len/4; i++) - cprintf(BLUE, "%.8X ",*(((unsigned *) buffer)+i)); - printf("\n"); -#endif + FILE_LOG(logDEBUG1, ("%.8X ",*(((unsigned *) buffer)+i))); while (words_send <= last_word) { while (!vacancy)//wait for Fifo to be empty again { status = HWIO_xfs_in32(ll->ll_fifo_base+4*PLB_LL_FIFO_REG_STATUS); - if((status & PLB_LL_FIFO_STATUS_ALMOSTFULL) == 0) vacancy = 1; -#ifdef MARTIN - if (vacancy == 0) cprintf(RED, "Fifo full!\n"); -#endif + if ((status & PLB_LL_FIFO_STATUS_ALMOSTFULL) == 0) vacancy = 1; + if (vacancy == 0) { + FILE_LOG(logERROR, ("Fifo full!\n")); + } } //Just to know: #define PLB_LL_FIFO_ALMOST_FULL_THRESHOLD_WORDS 100 @@ -140,7 +126,7 @@ int Local_Write(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buf } -int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer){ +int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer) { static unsigned int buffer_ptr = 0; // note: buffer must be word (4 byte) aligned // frame_len in byte @@ -150,9 +136,7 @@ int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buff volatile unsigned int fifo_val; int sof = 0; -#ifdef MARTIN - cprintf(CYAN, "LL Read - If: %X - Data: ",ll->ll_fifo_base); -#endif + FILE_LOG(logDEBUG1, ("LL Read - If: %X - Data: ",ll->ll_fifo_base)); word_ptr = (unsigned int *)buffer; do @@ -168,7 +152,6 @@ int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buff buffer_ptr = 0; return -1; // buffer overflow } - // printf(">>>> SOF\n\r"); buffer_ptr = 0; sof = 1; } @@ -179,9 +162,7 @@ int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buff { if ( (buffer_len >> 2) > buffer_ptr) { -#ifdef MARTIN - cprintf(CYAN, "%.8X ", fifo_val); -#endif + FILE_LOG(logDEBUG1, ("%.8X ", fifo_val)); word_ptr[buffer_ptr++] = fifo_val; //write to buffer } else @@ -193,10 +174,7 @@ int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buff if (status & PLB_LL_FIFO_STATUS_LL_EOF) { len = (buffer_ptr << 2) -3 + ( (status & PLB_LL_FIFO_STATUS_LL_REM)>>PLB_LL_FIFO_STATUS_LL_REM_SHIFT ); -#ifdef MARTIN - cprintf(CYAN, "Len: %d\n",len); -#endif - // printf(">>>>status=0x%08x EOF len = %d \n\r\n\r",status, len); + FILE_LOG(logDEBUG1, ("Len: %d\n",len)); buffer_ptr = 0; return len; } @@ -209,19 +187,15 @@ int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buff return 0; } -int Local_ctrl_reg_write_mask(struct LocalLinkInterface* ll,unsigned int mask, unsigned int val){ - // printf("Fifo CTRL Reg(1): 0x%08x\n",plb_ll_fifo_ctrl_reg); +int Local_ctrl_reg_write_mask(struct LocalLinkInterface* ll,unsigned int mask, unsigned int val) { ll->ll_fifo_ctrl_reg &= (~mask); - //printf("Fifo CTRL Reg(2): 0x%08x\n",plb_ll_fifo_ctrl_reg); ll->ll_fifo_ctrl_reg |= ( mask & val); - // printf("Fifo CTRL Reg: 0x%08x\n",plb_ll_fifo_ctrl_reg); HWIO_xfs_out32(ll->ll_fifo_base+4*PLB_LL_FIFO_REG_CTRL,ll->ll_fifo_ctrl_reg); - // printf("Fifo STAT Reg: 0x%08x\n", plb_ll_fifo[PLB_LL_FIFO_REG_STATUS]); return 1; } -int Local_Test(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer){ +int Local_Test(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer) { int len; unsigned int rec_buff_len = 4096; @@ -233,28 +207,14 @@ int Local_Test(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buff do{ len = Local_Read(ll,rec_buff_len,rec_buffer); - printf("receive length: %i\n",len); + FILE_LOG(logDEBUG1, ("receive length: %i\n",len)); - if (len > 0){ + if (len > 0) { rec_buffer[len]=0; - printf((char*) rec_buffer); - printf("\n"); + FILE_LOG(logINFO, ("%s\n", (char*) rec_buffer)); } } while(len > 0); - printf("\n\n\n\n"); return 1; } -void Local_llfifo_print_frame(struct LocalLinkInterface* ll,unsigned char* fbuff, int len){ - int i; - printf("\n\r----Frame of len : %d Byte\n\r",len); - for(i=0;i #include //to gethostname #include #ifdef VIRTUAL @@ -9,28 +15,38 @@ #include #endif -#include "slsDetectorFunctionList.h" -#ifndef VIRTUAL -#include "gitInfoEiger.h" -#include "FebControl.h" -#include "Beb.h" -#include "versionAPI.h" -#endif +// Global variable from slsDetectorServer_funcs +extern int debugflag; -int default_tau_from_file= -1; -#define BEB_NUM 34 +// Global variable from communication_funcs.c +extern int isControlServer; + +int firmware_compatibility = OK; +int firmware_check_done = 0; +char firmware_message[MAX_STR_LENGTH]; + -enum detectorSettings thisSettings; const char* dac_names[16] = {"SvP","Vtr","Vrf","Vrs","SvN","Vtgstv","Vcmp_ll","Vcmp_lr","cal","Vcmp_rl","rxb_rb","rxb_lb","Vcmp_rr","Vcp","Vcn","Vis"}; - -enum{E_PARALLEL, E_NON_PARALLEL, E_SAFE}; - +int default_tau_from_file= -1; +enum detectorSettings thisSettings; sls_detector_module *detectorModules=NULL; -int *detectorChips=NULL; int *detectorChans=NULL; -dacs_t *detectorDacs=NULL; -dacs_t *detectorAdcs=NULL; +int *detectorDacs=NULL; + +int send_to_ten_gig = 0; +int ndsts_in_use=32; +unsigned int nimages_per_request=1; +int on_dst=0; +int dst_requested[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; + +enum masterFlags masterMode=IS_SLAVE; +int top = 0; +int master = 0; +int normal = 0; +#ifndef VIRTUAL +uint32_t detid = 0; +#endif int eiger_highvoltage = 0; int eiger_theo_highvoltage = 0; @@ -44,8 +60,6 @@ int eiger_readoutspeed = 0; int eiger_triggermode = 0; int eiger_extgating = 0; int eiger_extgatingpolarity = 0; - - int eiger_nexposures = 1; int eiger_ncycles = 1; @@ -71,30 +85,6 @@ int eiger_virtual_stop = 0; #endif -int send_to_ten_gig = 0; -int ndsts_in_use=32; -unsigned int nimages_per_request=1; -int on_dst=0; -int dst_requested[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; - - -int default_gain_values[3] = {517000,517000,517000}; -int default_offset_values[3] = {3851000,3851000,3851000}; - - -enum masterFlags masterMode=IS_SLAVE; -int top = 0; -int master = 0; -int normal = 0; -#ifndef VIRTUAL -uint32_t detid = 0; -#endif - -/* basic tests */ - -int firmware_compatibility = OK; -int firmware_check_done = 0; -char firmware_message[MAX_STR_LENGTH]; int isFirmwareCheckDone() { @@ -106,15 +96,12 @@ int getFirmwareCheckResult(char** mess) { return firmware_compatibility; } -void checkFirmwareCompatibility(int flag){ +void basictests() { firmware_compatibility = OK; firmware_check_done = 0; memset(firmware_message, 0, MAX_STR_LENGTH); #ifdef VIRTUAL - cprintf(BLUE,"\n\n" - "********************************************************\n" - "***************** EIGER Virtual Server *****************\n" - "********************************************************\n"); + FILE_LOG(logINFOBLUE, ("************ EIGER Virtual Server *****************\n\n")); firmware_check_done = 1; return; #endif @@ -125,16 +112,12 @@ void checkFirmwareCompatibility(int flag){ int64_t sw_fw_apiversion = getDetectorId(SOFTWARE_FIRMWARE_API_VERSION); int64_t client_sw_apiversion = getDetectorId(CLIENT_SOFTWARE_API_VERSION); - cprintf(BLUE,"\n\n" - "********************************************************\n" - "**********************EIGER Server**********************\n" - "********************************************************\n"); - cprintf(BLUE,"\n" + FILE_LOG(logINFOBLUE, ("**************** EIGER Server *********************\n\n" "Detector IP Addr:\t\t 0x%x\n" "Detector MAC Addr:\t\t 0x%llx\n" "Firmware Version:\t\t %lld\n" - "Software Version:\t\t %llx\n" + "Software Version:\t\t 0x%llx\n" "F/w-S/w API Version:\t\t %lld\n" "Required Firmware Version:\t %d\n" "Client-Software API Version:\t 0x%llx\n" @@ -146,50 +129,47 @@ void checkFirmwareCompatibility(int flag){ (long long int)swversion, (long long int)sw_fw_apiversion, REQUIRED_FIRMWARE_VERSION, - (long long int)client_sw_apiversion); + (long long int)client_sw_apiversion)); - // return if flag is not zero, debug mode - if (flag) { + // return if debugflag is not zero, debug mode + if (debugflag) { firmware_check_done = 1; - return; + return; } //cant read versions - if(!fwversion || !sw_fw_apiversion){ - strcpy(firmware_message, - "FATAL ERROR: Cant read versions from FPGA. Please update firmware.\n"); - cprintf(RED,"%s\n\n", firmware_message); + if (!fwversion || !sw_fw_apiversion) { + strcpy(firmware_message, "Cant read versions from FPGA. Please update firmware.\n"); + FILE_LOG(logERROR, (firmware_message)); firmware_compatibility = FAIL; firmware_check_done = 1; return; } //check for API compatibility - old server - if(sw_fw_apiversion > REQUIRED_FIRMWARE_VERSION){ - sprintf(firmware_message, - "FATAL ERROR: This detector software software version (%lld) is incompatible.\n" + if (sw_fw_apiversion > REQUIRED_FIRMWARE_VERSION) { + sprintf(firmware_message, "This detector software software version (%lld) is incompatible.\n" "Please update detector software (min. %lld) to be compatible with this firmware.\n", (long long int)sw_fw_apiversion, (long long int)REQUIRED_FIRMWARE_VERSION); - cprintf(RED,"%s\n\n", firmware_message); + FILE_LOG(logERROR, (firmware_message)); firmware_compatibility = FAIL; firmware_check_done = 1; return; } //check for firmware compatibility - old firmware - if( REQUIRED_FIRMWARE_VERSION > fwversion){ - sprintf(firmware_message, - "FATAL ERROR: This firmware version (%lld) is incompatible.\n" + if ( REQUIRED_FIRMWARE_VERSION > fwversion) { + sprintf(firmware_message, "This firmware version (%lld) is incompatible.\n" "Please update firmware (min. %lld) to be compatible with this server.\n", (long long int)fwversion, (long long int)REQUIRED_FIRMWARE_VERSION); - cprintf(RED,"%s\n\n", firmware_message); + FILE_LOG(logERROR, (firmware_message)); firmware_compatibility = FAIL; firmware_check_done = 1; return; } - printf("Compatibility - success\n"); + FILE_LOG(logINFO, ("Compatibility - success\n")); firmware_check_done = 1; } @@ -199,22 +179,21 @@ void checkFirmwareCompatibility(int flag){ /* Ids */ -int64_t getDetectorId(enum idMode arg){ +int64_t getDetectorId(enum idMode arg) { #ifdef VIRTUAL return 0; #else int64_t retval = -1; - switch(arg){ + switch(arg) { case DETECTOR_SERIAL_NUMBER: retval = getDetectorNumber();/** to be implemented with mac? */ break; case DETECTOR_FIRMWARE_VERSION: return (int64_t)getFirmwareVersion(); case SOFTWARE_FIRMWARE_API_VERSION: - return (int64_t)Beb_GetFirmwareSoftwareAPIVersion(); + return (int64_t)getFirmwareAPIVersion(); case DETECTOR_SOFTWARE_VERSION: - return (GITDATE & 0xFFFFFF); case CLIENT_SOFTWARE_API_VERSION: return APIEIGER; default: @@ -233,9 +212,17 @@ u_int64_t getFirmwareVersion() { #endif } +u_int64_t getFirmwareAPIVersion() { +#ifdef VIRTUAL + return 0; +#else + return (u_int64_t)Beb_GetFirmwareSoftwareAPIVersion(); +#endif +} -u_int32_t getDetectorNumber(){ + +u_int32_t getDetectorNumber() { #ifdef VIRTUAL return 0; #else @@ -261,22 +248,22 @@ u_int64_t getDetectorMAC() { //getting rid of ":" char * pch; pch = strtok (output,":"); - while (pch != NULL){ + while (pch != NULL) { strcat(mac,pch); pch = strtok (NULL, ":"); } sscanf(mac,"%llx",&res); //increment by 1 for 10g - if(send_to_ten_gig) + if (send_to_ten_gig) res++; - //printf("mac:%llx\n",res); + //FILE_LOG(logINFO, ("mac:%llx\n",res)); return res; #endif } -u_int32_t getDetectorIP(){ +u_int32_t getDetectorIP() { #ifdef VIRTUAL return 0; #endif @@ -297,7 +284,7 @@ u_int32_t getDetectorIP(){ } strcpy(output,temp); sscanf(output, "%x", &res); - //printf("ip:%x\n",res); + //FILE_LOG(logINFO, ("ip:%x\n",res)); return res; } @@ -308,11 +295,10 @@ u_int32_t getDetectorIP(){ /* initialization */ -void initControlServer(){ +void initControlServer() { #ifdef VIRTUAL getModuleConfiguration(); setupDetector(); - printf("\n"); return; #else //Feb and Beb Initializations @@ -321,38 +307,35 @@ void initControlServer(){ Feb_Control_FebControl(); Feb_Control_Init(master,top,normal, getDetectorNumber()); //master of 9M, check high voltage serial communication to blackfin - if(master && !normal){ - if(Feb_Control_OpenSerialCommunication()) - ;// Feb_Control_CloseSerialCommunication(); + if (master && !normal) { + if (Feb_Control_OpenSerialCommunication()) + ;// Feb_Control_CloseSerialCommunication(); } - printf("FEB Initialization done\n"); - Beb_Beb(); + FILE_LOG(logDEBUG1, ("Control server: FEB Initialization done\n")); + Beb_Beb(detid); Beb_SetDetectorNumber(getDetectorNumber()); - printf("BEB Initialization done\n"); + FILE_LOG(logDEBUG1, ("Control server: BEB Initialization done\n")); setupDetector(); #endif - printf("\n"); } -void initStopServer(){ +void initStopServer() { #ifdef VIRTUAL getModuleConfiguration(); - printf("\n"); return; #else getModuleConfiguration(); Feb_Interface_FebInterface(); Feb_Control_FebControl(); Feb_Control_Init(master,top,normal,getDetectorNumber()); - printf("FEB Initialization done\n"); + FILE_LOG(logDEBUG1, ("Stop server: FEB Initialization done\n")); #endif - printf("\n"); } -void getModuleConfiguration(){ +void getModuleConfiguration() { #ifdef VIRTUAL #ifdef VIRTUAL_MASTER master = 1; @@ -366,24 +349,22 @@ void getModuleConfiguration(){ #else normal = 1; #endif - if(top) printf("*************** TOP ***************\n"); - else printf("*************** BOTTOM ***************\n"); - if(master) printf("*************** MASTER ***************\n"); - else printf("*************** SLAVE ***************\n"); - if(normal) printf("*************** NORMAL ***************\n"); - else printf("*************** SPECIAL ***************\n"); + FILE_LOG(logINFOBLUE, ("Module: %s %s %s\n", + (top ? "TOP" : "BOTTOM"), + (master ? "MASTER" : "SLAVE"), + (normal ? "NORMAL" : "SPECIAL"))); return; #else int *m=&master; int *t=⊤ int *n=&normal; Beb_GetModuleConfiguration(m,t,n); - if(top) printf("*************** TOP ***************\n"); - else printf("*************** BOTTOM ***************\n"); - if(master) printf("*************** MASTER ***************\n"); - else printf("*************** SLAVE ***************\n"); - if(normal) printf("*************** NORMAL ***************\n"); - else printf("*************** SPECIAL ***************\n"); + if (isControlServer) { + FILE_LOG(logINFOBLUE, ("Module: %s %s %s\n", + (top ? "TOP" : "BOTTOM"), + (master ? "MASTER" : "SLAVE"), + (normal ? "NORMAL" : "SPECIAL"))); + } // read detector id char output[255]; @@ -391,7 +372,9 @@ void getModuleConfiguration(){ fgets(output, sizeof(output), sysFile); pclose(sysFile); sscanf(output,"%u",&detid); - printf("detector id: %u\n",detid); + if (isControlServer) { + FILE_LOG(logINFOBLUE, ("Detector ID: %u\n\n", detid)); + } #endif } @@ -399,34 +382,25 @@ void getModuleConfiguration(){ /* set up detector */ -void allocateDetectorStructureMemory(){ - printf("This Server is for 1 Eiger half module (250k)\n"); +void allocateDetectorStructureMemory() { + FILE_LOG(logINFO, ("This Server is for 1 Eiger half module (250k)\n\n")); //Allocation of memory - detectorModules=malloc(sizeof(sls_detector_module)); - detectorChips=malloc(NCHIP*sizeof(int)); - detectorChans=malloc(NCHIP*NCHAN*sizeof(int)); - detectorDacs=malloc(NDAC*sizeof(dacs_t)); - detectorAdcs=malloc(NADC*sizeof(dacs_t)); -#ifdef VERBOSE - printf("modules from 0x%x to 0x%x\n",detectorModules, detectorModules+n); - printf("chips from 0x%x to 0x%x\n",detectorChips, detectorChips+n*NCHIP); - printf("chans from 0x%x to 0x%x\n",detectorChans, detectorChans+n*NCHIP*NCHAN); - printf("dacs from 0x%x to 0x%x\n",detectorDacs, detectorDacs+n*NDAC); - printf("adcs from 0x%x to 0x%x\n",detectorAdcs, detectorAdcs+n*NADC); -#endif - (detectorModules)->dacs=detectorDacs; - (detectorModules)->adcs=detectorAdcs; - (detectorModules)->chipregs=detectorChips; - (detectorModules)->chanregs=detectorChans; - (detectorModules)->ndac=NDAC; - (detectorModules)->nadc=NADC; - (detectorModules)->nchip=NCHIP; - (detectorModules)->nchan=NCHIP*NCHAN; - (detectorModules)->module=0; - (detectorModules)->gain=0; - (detectorModules)->offset=0; - (detectorModules)->reg=0; + detectorModules = malloc(sizeof(sls_detector_module)); + detectorChans = malloc(NCHIP*NCHAN*sizeof(int)); + detectorDacs = malloc(NDAC*sizeof(int)); + FILE_LOG(logDEBUG1, ("modules from 0x%x to 0x%x\n",detectorModules, detectorModules)); + FILE_LOG(logDEBUG1, ("chans from 0x%x to 0x%x\n",detectorChans, detectorChans)); + FILE_LOG(logDEBUG1, ("dacs from 0x%x to 0x%x\n",detectorDacs, detectorDacs)); + (detectorModules)->dacs = detectorDacs; + (detectorModules)->chanregs = detectorChans; + (detectorModules)->ndac = NDAC; + (detectorModules)->nchip = NCHIP; + (detectorModules)->nchan = NCHIP * NCHAN; + (detectorModules)->reg = 0; + (detectorModules)->iodelay = 0; + (detectorModules)->tau = 0; + (detectorModules)->eV = 0; thisSettings = UNINITIALIZED; // if trimval requested, should return -1 to acknowledge unknown @@ -442,18 +416,19 @@ void setupDetector() { allocateDetectorStructureMemory(); //set dacs - printf("Setting Default Dac values\n"); + FILE_LOG(logINFOBLUE, ("Setting Default Dac values\n")); { int i = 0; - int retval[2]={-1,-1}; const int defaultvals[NDAC] = DEFAULT_DAC_VALS; for(i = 0; i < NDAC; ++i) { - setDAC((enum DACINDEX)i,defaultvals[i],0,0,retval); - if (retval[0] != defaultvals[i]) - cprintf(RED, "Warning: Setting dac %d failed, wrote %d, read %d\n",i ,defaultvals[i], retval[0]); + setDAC((enum DACINDEX)i,defaultvals[i],0); + if ((detectorModules)->dacs[i] != defaultvals[i]) { + FILE_LOG(logERROR, ("Setting dac %d failed, wrote %d, read %d\n",i ,defaultvals[i], (detectorModules)->dacs[i])); + } } } + FILE_LOG(logINFOBLUE, ("Setting Default Parameters\n")); //setting default measurement parameters setTimer(FRAME_NUMBER, DEFAULT_NUM_FRAMES); setTimer(ACQUISITION_TIME, DEFAULT_EXPTIME); @@ -467,7 +442,7 @@ void setupDetector() { setReadOutFlags(DEFAULT_READOUT_STOREINRAM_MODE); setReadOutFlags(DEFAULT_READOUT_OVERFLOW32_MODE); setSpeed(CLOCK_DIVIDER, DEFAULT_CLK_SPEED);//clk_devider,half speed - setIODelay(DEFAULT_IO_DELAY, DEFAULT_MOD_INDEX); + setIODelay(DEFAULT_IO_DELAY); setTiming(DEFAULT_TIMING_MODE); //SetPhotonEnergyCalibrationParameters(-5.8381e-5,1.838515,5.09948e-7,-4.32390e-11,1.32527e-15); setRateCorrection(DEFAULT_RATE_CORRECTION); @@ -480,6 +455,7 @@ void setupDetector() { #ifndef VIRTUAL Feb_Control_CheckSetup(); #endif + FILE_LOG(logDEBUG1, ("Setup detector done\n\n")); } @@ -503,36 +479,28 @@ uint32_t readRegister(uint32_t offset) { } -/* set parameters - nmod, dr, roi */ - -int setNMod(int nm, enum dimension dim){ - return NMOD; -} +/* set parameters - dr, roi */ -int getNModBoard(enum dimension arg){ - return NMAXMOD; -} - -int setDynamicRange(int dr){ +int setDynamicRange(int dr) { #ifdef VIRTUAL - if(dr > 0){ - printf(" Setting dynamic range: %d\n",dr); + if (dr > 0) { + FILE_LOG(logINFO, ("Setting dynamic range: %d\n", dr)); eiger_dynamicrange = dr; } return eiger_dynamicrange; #else - if(dr > 0){ - printf(" Setting dynamic range: %d\n",dr); - if(Feb_Control_SetDynamicRange(dr)){ + if (dr > 0) { + FILE_LOG(logDEBUG1, ("Setting dynamic range: %d\n", dr)); + if (Feb_Control_SetDynamicRange(dr)) { //EigerSetBitMode(dr); on_dst = 0; int i; for(i=0;i<32;i++) dst_requested[i] = 0; //clear dst requested - if(Beb_SetUpTransferParameters(dr)) + if (Beb_SetUpTransferParameters(dr)) eiger_dynamicrange = dr; - else printf("ERROR:Could not set bit mode in the back end\n"); + else FILE_LOG(logERROR, ("Could not set bit mode in the back end\n")); } } //make sure back end and front end have the same bit mode @@ -547,41 +515,53 @@ int setDynamicRange(int dr){ /* parameters - readout */ -int setSpeed(enum speedVariable arg, int val){ +void setSpeed(enum speedVariable ind, int val) { + if (ind != CLOCK_DIVIDER) + return; - if (arg != CLOCK_DIVIDER) - return -1; - - if(val != -1){ - printf(" Setting Read out Speed: %d\n",val); + if (val != -1) { + FILE_LOG(logDEBUG1, ("Setting Read out Speed: %d\n", val)); #ifndef VIRTUAL - if(Feb_Control_SetReadoutSpeed(val)) + if (Feb_Control_SetReadoutSpeed(val)) #endif eiger_readoutspeed = val; } - return eiger_readoutspeed; +} + +int getSpeed(enum speedVariable ind) { + if (ind != CLOCK_DIVIDER) + return -1; + return eiger_readoutspeed; } -enum readOutFlags setReadOutFlags(enum readOutFlags val){ +enum readOutFlags setReadOutFlags(enum readOutFlags val) { enum readOutFlags retval = GET_READOUT_FLAGS; - if(val!=GET_READOUT_FLAGS){ + if (val!=GET_READOUT_FLAGS) { - if(val&0xF0000){ - switch(val){ - case PARALLEL: val=E_PARALLEL; printf(" Setting Read out Flag: Parallel\n"); break; - case NONPARALLEL: val=E_NON_PARALLEL; printf(" Setting Read out Flag: Non Parallel\n"); break; - case SAFE: val=E_SAFE; printf(" Setting Read out Flag: Safe\n"); break; + if (val&0xF0000) { + switch(val) { + case PARALLEL: + val=E_PARALLEL; + FILE_LOG(logDEBUG1, ("Setting Read out Flag: Parallel\n")); + break; + case NONPARALLEL: + val=E_NON_PARALLEL; + FILE_LOG(logDEBUG1, ("Setting Read out Flag: Non Parallel\n")); + break; + case SAFE: + val=E_SAFE; + FILE_LOG(logDEBUG1, ("Setting Read out Flag: Safe\n")); + break; default: - cprintf(RED,"Cannot set unknown readout flag. 0x%x\n", val); + FILE_LOG(logERROR, ("Cannot set unknown readout flag. 0x%x\n", val)); return -1; } - printf(" Setting Read out Flag: %d\n",val); #ifndef VIRTUAL - if(Feb_Control_SetReadoutMode(val)) + if (Feb_Control_SetReadoutMode(val)) #endif eiger_readoutmode = val; #ifndef VIRTUAL @@ -591,16 +571,21 @@ enum readOutFlags setReadOutFlags(enum readOutFlags val){ } else if (val&0xF00000) { - switch(val){ - case SHOW_OVERFLOW: val=1; printf(" Setting Read out Flag: Overflow in 32 bit mode\n"); break; - case NOOVERFLOW: val=0; printf(" Setting Read out Flag: No overflow in 32 bit mode\n"); break; + switch(val) { + case SHOW_OVERFLOW: + val=1; + FILE_LOG(logDEBUG1, ("Setting Read out Flag: Overflow in 32 bit mode\n")); + break; + case NOOVERFLOW: + val=0; + FILE_LOG(logDEBUG1, ("Setting Read out Flag: No overflow in 32 bit mode\n")); + break; default: - cprintf(RED,"Cannot set unknown readout flag. 0x%x\n", val); + FILE_LOG(logERROR, ("Cannot set unknown readout flag. 0x%x\n", val)); return -1; } - printf(" Setting Read out Flag: %d\n",val); #ifndef VIRTUAL - if(Beb_Set32bitOverflow(val) != -1) + if (Beb_Set32bitOverflow(val) != -1) #endif eiger_overflow32 = val; #ifndef VIRTUAL @@ -609,41 +594,58 @@ enum readOutFlags setReadOutFlags(enum readOutFlags val){ } - else{ - switch(val){ - case STORE_IN_RAM: val=1; printf(" Setting Read out Flag: Store in Ram\n"); break; - case CONTINOUS_RO: val=0; printf(" Setting Read out Flag: Continuous Readout\n"); break; + else { + switch(val) { + case STORE_IN_RAM: + val=1; + FILE_LOG(logDEBUG1, ("Setting Read out Flag: Store in Ram\n")); + break; + case CONTINOUS_RO: + val=0; + FILE_LOG(logDEBUG1, ("Setting Read out Flag: Continuous Readout\n")); + break; default: - cprintf(RED,"Cannot set unknown readout flag. 0x%x\n", val); + FILE_LOG(logERROR, ("Cannot set unknown readout flag. 0x%x\n", val)); return -1; } - printf(" Setting store in ram variable: %d\n",val); eiger_storeinmem = val; } } - switch(eiger_readoutmode){ - case E_PARALLEL: retval=PARALLEL; break; - case E_NON_PARALLEL: retval=NONPARALLEL; break; - case E_SAFE: retval=SAFE; break; + switch(eiger_readoutmode) { + case E_PARALLEL: + retval=PARALLEL; + break; + case E_NON_PARALLEL: + retval=NONPARALLEL; + break; + case E_SAFE: + retval=SAFE; + break; } - switch(eiger_overflow32){ - case 1: retval|=SHOW_OVERFLOW; break; - case 0: retval|=NOOVERFLOW; break; + switch(eiger_overflow32) { + case 1: + retval|=SHOW_OVERFLOW; + break; + case 0: + retval|=NOOVERFLOW; + break; } - switch(eiger_storeinmem){ - case 0: retval|=CONTINOUS_RO; break; - case 1: retval|=STORE_IN_RAM; break; + switch(eiger_storeinmem) { + case 0: + retval|=CONTINOUS_RO; + break; + case 1: + retval|=STORE_IN_RAM; + break; } - - - printf("Read out Flag: 0x%x\n",retval); + FILE_LOG(logDEBUG1, ("Read out Flag: 0x%x\n", retval)); return retval; } @@ -656,17 +658,17 @@ enum readOutFlags setReadOutFlags(enum readOutFlags val){ /* parameters - timer */ -int64_t setTimer(enum timerIndex ind, int64_t val){ +int64_t setTimer(enum timerIndex ind, int64_t val) { #ifndef VIRTUAL int64_t subdeadtime = 0; #endif int64_t subexptime = 0; - switch(ind){ + switch(ind) { case FRAME_NUMBER: - if(val >= 0){ - printf(" Setting number of frames: %d * %d\n",(unsigned int)val,eiger_ncycles); + if (val >= 0) { + FILE_LOG(logDEBUG1, ("Setting number of frames: %d * %d\n", (unsigned int)val, eiger_ncycles)); #ifndef VIRTUAL - if(Feb_Control_SetNExposures((unsigned int)val*eiger_ncycles)){ + if (Feb_Control_SetNExposures((unsigned int)val*eiger_ncycles)) { eiger_nexposures = val; //SetDestinationParameters(EigerGetNumberOfExposures()*EigerGetNumberOfCycles()); on_dst = 0; @@ -682,8 +684,8 @@ int64_t setTimer(enum timerIndex ind, int64_t val){ }return eiger_nexposures; case ACQUISITION_TIME: - if(val >= 0){ - printf(" Setting exp time: %fs\n",val/(1E9)); + if (val >= 0) { + FILE_LOG(logDEBUG1, ("Setting exp time: %fs\n", val/(1E9))); #ifndef VIRTUAL Feb_Control_SetExposureTime(val/(1E9)); #else @@ -697,8 +699,8 @@ int64_t setTimer(enum timerIndex ind, int64_t val){ #endif case SUBFRAME_ACQUISITION_TIME: - if(val >= 0){ - printf(" Setting sub exp time: %lldns\n",(long long int)val); + if (val >= 0) { + FILE_LOG(logDEBUG1, ("Setting sub exp time: %lldns\n", (long long int)val)); #ifndef VIRTUAL // calculate subdeadtime before settings subexptime subdeadtime = Feb_Control_GetSubFramePeriod() - @@ -722,16 +724,16 @@ int64_t setTimer(enum timerIndex ind, int64_t val){ case SUBFRAME_DEADTIME: #ifndef VIRTUAL - // get subexptime - subexptime = Feb_Control_GetSubFrameExposureTime(); + // get subexptime + subexptime = Feb_Control_GetSubFrameExposureTime(); #else - subexptime = eiger_virtual_subexptime*10; + subexptime = eiger_virtual_subexptime*10; #endif - if(val >= 0){ - printf(" Setting sub period: %lldns = subexptime(%lld) + subdeadtime(%lld)\n", - (long long int)(val + subexptime), + if (val >= 0) { + FILE_LOG(logINFO, ("Setting sub period (subdeadtime(%lld)): %lldns\n", (long long int)subexptime, - (long long int)val); + (long long int)val), + (long long int)(val + subexptime)); //calculate subperiod val += subexptime; #ifndef VIRTUAL @@ -747,8 +749,8 @@ int64_t setTimer(enum timerIndex ind, int64_t val){ #endif case FRAME_PERIOD: - if(val >= 0){ - printf(" Setting acq period: %fs\n",val/(1E9)); + if (val >= 0) { + FILE_LOG(logDEBUG1, ("Setting acq period: %fs\n", val/(1E9))); #ifndef VIRTUAL Feb_Control_SetExposurePeriod(val/(1E9)); #else @@ -762,10 +764,11 @@ int64_t setTimer(enum timerIndex ind, int64_t val){ #endif case CYCLES_NUMBER: - if(val >= 0){ - printf(" Setting number of triggers: %d * %d\n",(unsigned int)val,eiger_nexposures); + if (val >= 0) { + FILE_LOG(logDEBUG1, ("Setting number of triggers: %d * %d\n", + (unsigned int)val,eiger_nexposures)); #ifndef VIRTUAL - if(Feb_Control_SetNExposures((unsigned int)val*eiger_nexposures)){ + if (Feb_Control_SetNExposures((unsigned int)val*eiger_nexposures)) { eiger_ncycles = val; //SetDestinationParameters(EigerGetNumberOfExposures()*EigerGetNumberOfCycles()); on_dst = 0; @@ -780,7 +783,7 @@ int64_t setTimer(enum timerIndex ind, int64_t val){ } return eiger_ncycles; default: - cprintf(RED,"Warning: Timer Index not implemented for this detector: %d\n", ind); + FILE_LOG(logERROR, ("Timer Index not implemented for this detector: %d\n", ind)); break; } @@ -792,12 +795,12 @@ int64_t getTimeLeft(enum timerIndex ind) { #ifdef VIRTUAL return 0; #else - switch(ind){ + switch(ind) { case MEASURED_PERIOD: return Feb_Control_GetMeasuredPeriod(); case MEASURED_SUBPERIOD: return Feb_Control_GetSubMeasuredPeriod(); return 0; default: - cprintf(RED,"This timer left index (%d) not defined for Eiger\n",ind); + FILE_LOG(logERROR, ("This timer left index (%d) not defined for Eiger\n", ind)); return -1; } #endif @@ -806,92 +809,140 @@ int64_t getTimeLeft(enum timerIndex ind) { -/* parameters - channel, chip, module, settings */ +/* parameters - channel, module, settings */ -int setModule(sls_detector_module myMod, int delay){ - int retval[2]; - int i; +int setModule(sls_detector_module myMod, char* mess) { - //#ifdef VERBOSE - printf("Setting module with settings %d\n",myMod.reg); - //#endif - //copy module locally (module number, serial number, gain offset, - //dacs (pointless), trimbit values(if needed) - if (detectorModules) - if (copyModule(detectorModules,&myMod) == FAIL) - return FAIL; + FILE_LOG(logINFO, ("Setting module with settings %d\n",myMod.reg)); // settings - setSettings( (enum detectorSettings)myMod.reg,-1); + setSettings( (enum detectorSettings)myMod.reg); + + //copy module locally (module number, serial number + //dacs (pointless), trimbit values(if needed) + if (detectorModules) { + if (copyModule(detectorModules,&myMod) == FAIL) { + sprintf(mess, "Could not copy module\n"); + FILE_LOG(logERROR, (mess)); + setSettings(UNDEFINED); + FILE_LOG(logERROR, ("Settings has been changed to undefined\n")); + return FAIL; + } + } // iodelay - if(setIODelay(delay, -1)!= delay){ - cprintf(RED,"could not set iodelay %d\n",delay); + if (setIODelay(myMod.iodelay)!= myMod.iodelay) { + sprintf(mess, "Could not set module. Could not set iodelay %d\n", myMod.iodelay); + FILE_LOG(logERROR, (mess)); + setSettings(UNDEFINED); + FILE_LOG(logERROR, ("Settings has been changed to undefined\n")); return FAIL; } - // dacs - for(i=0;i= 0) + setThresholdEnergy(myMod.eV); + else { + // (loading a random trim file) (dont return fail) + setSettings(UNDEFINED); + FILE_LOG(logERROR, ("Settings has been changed to undefined (random trim file)\n")); + } + // dacs + { + int i = 0; + for(i = 0; i < NDAC; ++i) { + setDAC((enum DACINDEX)i, myMod.dacs[i] , 0); + if (myMod.dacs[i] != (detectorModules)->dacs[i]) { + sprintf(mess, "Could not set module. Could not set dac %d\n", i); + FILE_LOG(logERROR, (mess)); + setSettings(UNDEFINED); + FILE_LOG(logERROR, ("Settings has been changed to undefined\n")); + return FAIL; + } + } + } // trimbits #ifndef VIRTUAL - if(myMod.nchan==0 && myMod.nchip == 0) - cprintf(BLUE,"Setting module without trimbits\n"); - else{ - printf("Setting module with trimbits\n"); + if (myMod.nchan == 0) { + FILE_LOG(logINFO, ("Setting module without trimbits\n")); + } else { + FILE_LOG(logINFO, ("Setting module with trimbits\n")); //includ gap pixels unsigned int tt[263680]; - int iy,ichip,ix,ip=0,ich=0; - for(iy=0;iy<256;iy++) { - for (ichip=0; ichip<4; ichip++) { - for(ix=0;ix<256;ix++) { - tt[ip++]=myMod.chanregs[ich++]; + int iy, ichip, ix, ip = 0, ich = 0; + for (iy = 0; iy < 256; ++iy) { + for (ichip = 0; ichip < 4; ++ichip) { + for (ix = 0; ix < 256; ++ix) { + tt[ip++] = myMod.chanregs[ich++]; } - if (ichip<3) { - tt[ip++]=0; - tt[ip++]=0; + if (ichip < 3) { + tt[ip++] = 0; + tt[ip++] = 0; } } } //set trimbits - if(!Feb_Control_SetTrimbits(Feb_Control_GetModuleNumber(),tt)){ - cprintf(BG_RED,"Could not set trimbits\n"); + if (!Feb_Control_SetTrimbits(Feb_Control_GetModuleNumber(), tt)) { + sprintf(mess, "Could not set module. Could not set trimbits\n"); + FILE_LOG(logERROR, (mess)); + setSettings(UNDEFINED); + FILE_LOG(logERROR, ("Settings has been changed to undefined (random trim file)\n")); return FAIL; } } + + + //rate correction + //switch off rate correction: no value read from load settings) + if (myMod.tau == -1) { + if (getRateCorrectionEnable()) { + setRateCorrection(0); + sprintf(mess,"Cannot set module. Cannot set Rate correction. " + "No default tau provided. Deactivating Rate Correction\n"); + FILE_LOG(logERROR, (mess)); + setSettings(UNDEFINED); + FILE_LOG(logERROR, ("Settings has been changed to undefined (random trim file)\n")); + return FAIL; + } + } + //normal tau value (only if enabled) + else { + setDefaultSettingsTau_in_nsec(myMod.tau); + if (getRateCorrectionEnable()) { + int64_t retvalTau = setRateCorrection(myMod.tau); + if (myMod.tau != retvalTau) { + sprintf(mess, "Cannot set module. Could not set rate correction\n"); + FILE_LOG(logERROR, (mess)); + setSettings(UNDEFINED); + FILE_LOG(logERROR, ("Settings has been changed to undefined (random trim file)\n")); + return FAIL; + } + } + } #endif - return thisSettings; + return OK; } -int getModule(sls_detector_module *myMod){ +int getModule(sls_detector_module *myMod) { #ifndef VIRTUAL - int i; - int retval[2]; - - //dacs - for(i=0;idacs)+i)); - } - //trimbits unsigned int* tt; tt = Feb_Control_GetTrimbits(); //exclude gap pixels - int iy,ichip,ix,ip=0,ich=0; - for(iy=0;iy<256;iy++) { - for (ichip=0; ichip<4; ichip++) { - for(ix=0;ix<256;ix++) { - myMod->chanregs[ich++]=tt[ip++]; + int iy, ichip, ix, ip = 0, ich = 0; + for (iy = 0; iy < 256; ++iy) { + for (ichip = 0; ichip < 4; ++ichip) { + for (ix = 0; ix < 256; ++iy) { + myMod->chanregs[ich++] = tt[ip++]; } - if (ichip<3) { + if (ichip < 3) { ip++; ip++; } @@ -903,7 +954,7 @@ int getModule(sls_detector_module *myMod){ if (detectorModules) { if (copyModule(myMod, detectorModules) == FAIL) return FAIL; - } + } else return FAIL; return OK; @@ -911,16 +962,16 @@ int getModule(sls_detector_module *myMod){ -enum detectorSettings setSettings(enum detectorSettings sett, int imod){ - if(sett == UNINITIALIZED){ +enum detectorSettings setSettings(enum detectorSettings sett) { + if (sett == UNINITIALIZED) { return thisSettings; - }if(sett != GET_SETTINGS) + }if (sett != GET_SETTINGS) thisSettings = sett; - printf(" Settings: %d\n", thisSettings); + FILE_LOG(logINFO, ("Settings: %d\n", thisSettings)); return thisSettings; } -enum detectorSettings getSettings(){ +enum detectorSettings getSettings() { return thisSettings; } @@ -931,17 +982,17 @@ enum detectorSettings getSettings(){ /* parameters - threshold */ -int getThresholdEnergy(int imod){ - printf(" Getting Threshold energy\n"); +int getThresholdEnergy() { + FILE_LOG(logINFO, ("Getting Threshold energy\n")); return eiger_photonenergy; } -int setThresholdEnergy(int ev, int imod){ - printf(" Setting threshold energy:%d\n",ev); - if(ev >= 0) +int setThresholdEnergy(int ev) { + FILE_LOG(logINFO, ("Setting threshold energy:%d\n",ev)); + if (ev >= 0) eiger_photonenergy = ev; - return getThresholdEnergy(imod); + return getThresholdEnergy(); } @@ -950,75 +1001,88 @@ int setThresholdEnergy(int ev, int imod){ /* parameters - dac, adc, hv */ -void setDAC(enum DACINDEX ind, int val, int imod, int mV, int retval[]){ - printf("Going to set dac %d to %d of imod %d with mv mode %d \n", (int)ind, val, imod, mV); - if(ind == VTHRESHOLD){ - int ret[5]; - setDAC(VCMP_LL,val,imod,mV,retval); - ret[0] = retval[mV]; - setDAC(VCMP_LR,val,imod,mV,retval); - ret[1] = retval[mV]; - setDAC(VCMP_RL,val,imod,mV,retval); - ret[2] = retval[mV]; - setDAC(VCMP_RR,val,imod,mV,retval); - ret[3] = retval[mV]; - setDAC(VCP,val,imod,mV,retval); - ret[4] = retval[mV]; +// uses LTC2620 with 2.048V (implementation different to others not bit banging) +void setDAC(enum DACINDEX ind, int val, int mV) { + if (val < 0) + return; + FILE_LOG(logDEBUG1, ("Setting dac[%d]: %d %s \n", (int)ind, val, (mV ? "mV" : "dac units"))); - if((ret[0]== ret[1])&& - (ret[1]==ret[2])&& - (ret[2]==ret[3]) && - (ret[3]==ret[4])) - cprintf(GREEN,"vthreshold match\n"); - else{ - retval[0] = -1;retval[1] = -1; - cprintf(RED,"vthreshold mismatch 0:%d 1:%d 2:%d 3:%d\n", - ret[0],ret[1],ret[2],ret[3]); - } + if (ind == VTHRESHOLD) { + setDAC(VCMP_LL, val, mV); + setDAC(VCMP_LR, val, mV); + setDAC(VCMP_RL, val, mV); + setDAC(VCMP_RR, val, mV); + setDAC(VCP, val, mV); return; } - char iname[10]; - if(((int)ind>=0)&&((int)ind= 0) - printf("Setting dac %d: %s to %d ",ind, iname,val); - else - printf("Getting dac %d: %s ",ind, iname); - if(mV) - printf("in mV\n"); - else - printf("in dac units\n"); -#endif + // validate index + if (ind < 0 || ind >= NDAC) { + FILE_LOG(logERROR, ("\tDac index %d is out of bounds (0 to %d)\n", ind, NDAC - 1)); + return; + } + #ifdef VIRTUAL - if (mV){ - retval[0] = (int)(((val-0)/(2048-0))*(4096-1) + 0.5); - retval[1] = val; - }else - retval[0] = val; - + if (!mV) { + (detectorModules)->dacs[ind] = val; + } + // convert to dac units + else if (ConvertToDifferentRange(DAC_MIN_MV, DAC_MAX_MV, LTC2620_MIN_VAL, LTC2620_MAX_VAL, + val, &dacval) == OK) { + (detectorModules)->dacs[ind] = dacval; + } #else - if(val >= 0) - Feb_Control_SetDAC(iname,val,mV); - int k; - Feb_Control_GetDAC(iname, &k,0); - retval[0] = k; - Feb_Control_GetDAC(iname,&k,1); - retval[1] = k; + char iname[10]; + strcpy(iname,dac_names[(int)ind]); + if (Feb_Control_SetDAC(iname, val, mV)) { + int dacval = 0; + Feb_Control_GetDAC(iname, &dacval, 0); + (detectorModules)->dacs[ind] = dacval; + } #endif - (detectorModules)->dacs[ind] = retval[0]; +} +int getDAC(enum DACINDEX ind, int mV) { + if (ind == VTHRESHOLD) { + int ret[5] = {0}; + ret[0] = getDAC(VCMP_LL, mV); + ret[1] = getDAC(VCMP_LR, mV); + ret[2] = getDAC(VCMP_RL, mV); + ret[3] = getDAC(VCMP_RR, mV); + ret[4] = getDAC(VCP, mV); + + if ((ret[0]== ret[1])&& + (ret[1]==ret[2])&& + (ret[2]==ret[3]) && + (ret[3]==ret[4])) { + FILE_LOG(logINFO, ("\tvthreshold match\n")); + return ret[0]; + } else { + FILE_LOG(logERROR, ("\tvthreshold mismatch vcmp_ll:%d vcmp_lr:%d vcmp_rl:%d vcmp_rr:%d vcp:%d\n", + ret[0],ret[1],ret[2],ret[3], ret[4])); + return -1; + } + } + + if (!mV) { + FILE_LOG(logDEBUG1, ("Getting DAC %d : %d dac\n",ind, (detectorModules)->dacs[ind])); + return (detectorModules)->dacs[ind]; + } + int voltage = -1; + // dac units to voltage + ConvertToDifferentRange(DAC_MIN_MV, DAC_MAX_MV, LTC2620_MIN_VAL, LTC2620_MAX_VAL, + (detectorModules)->dacs[ind], &voltage); + FILE_LOG(logDEBUG1, ("Getting DAC %d : %d dac (%d mV)\n",ind, (detectorModules)->dacs[ind], voltage)); + return voltage; +} + +int getMaxDacSteps() { + return DAC_MAX_STEPS; } - -int getADC(enum ADCINDEX ind, int imod){ +int getADC(enum ADCINDEX ind) { #ifdef VIRTUAL return 0; #else @@ -1026,43 +1090,43 @@ int getADC(enum ADCINDEX ind, int imod){ char tempnames[6][20]={"FPGA EXT", "10GE","DCDC", "SODL", "SODR", "FPGA"}; char cstore[255]; - switch(ind){ - case TEMP_FPGA: - retval=getBebFPGATemp(); - break; - case TEMP_FPGAFEBL: - retval=Feb_Control_GetLeftFPGATemp(); - break; - case TEMP_FPGAFEBR: - retval=Feb_Control_GetRightFPGATemp(); - break; - case TEMP_FPGAEXT: - case TEMP_10GE: - case TEMP_DCDC: - case TEMP_SODL: - case TEMP_SODR: - sprintf(cstore,"more /sys/class/hwmon/hwmon%d/device/temp1_input",ind); - FILE* sysFile = popen(cstore, "r"); - fgets(cstore, sizeof(cstore), sysFile); - pclose(sysFile); - sscanf(cstore,"%d",&retval); - break; - default: - return -1; + switch(ind) { + case TEMP_FPGA: + retval=getBebFPGATemp(); + break; + case TEMP_FPGAFEBL: + retval=Feb_Control_GetLeftFPGATemp(); + break; + case TEMP_FPGAFEBR: + retval=Feb_Control_GetRightFPGATemp(); + break; + case TEMP_FPGAEXT: + case TEMP_10GE: + case TEMP_DCDC: + case TEMP_SODL: + case TEMP_SODR: + sprintf(cstore,"more /sys/class/hwmon/hwmon%d/device/temp1_input",ind); + FILE* sysFile = popen(cstore, "r"); + fgets(cstore, sizeof(cstore), sysFile); + pclose(sysFile); + sscanf(cstore,"%d",&retval); + break; + default: + return -1; } - printf("Temperature %s: %f°C\n",tempnames[ind],(double)retval/1000.00); + FILE_LOG(logINFO, ("Temperature %s: %f°C\n", tempnames[ind], (double)retval/1000.00)); return retval; #endif } -int setHighVoltage(int val){ +int setHighVoltage(int val) { #ifdef VIRTUAL if (master) { // set - if(val!=-1){ + if (val!=-1) { eiger_theo_highvoltage = val; } return eiger_theo_highvoltage; @@ -1074,10 +1138,10 @@ int setHighVoltage(int val){ if (master) { // set - if(val!=-1){ + if (val!=-1) { eiger_theo_highvoltage = val; int ret = Feb_Control_SetHighVoltage(val); - if(!ret) //could not set + if (!ret) //could not set return -2; else if (ret == -1) //outside range return -1; @@ -1085,13 +1149,13 @@ int setHighVoltage(int val){ // get if (!Feb_Control_GetHighVoltage(&eiger_highvoltage)) { - cprintf(RED,"Warning: Could not read high voltage\n"); + FILE_LOG(logERROR, ("Could not read high voltage\n")); return -3; } // tolerance of 5 if (abs(eiger_theo_highvoltage-eiger_highvoltage) > HIGH_VOLTAGE_TOLERANCE) { - cprintf(BLUE, "High voltage still ramping: %d\n", eiger_highvoltage); + FILE_LOG(logINFO, ("High voltage still ramping: %d\n", eiger_highvoltage)); return eiger_highvoltage; } return eiger_theo_highvoltage; @@ -1109,30 +1173,34 @@ int setHighVoltage(int val){ /* parameters - timing, extsig */ -enum externalCommunicationMode setTiming( enum externalCommunicationMode arg){ +void setTiming( enum externalCommunicationMode arg) { enum externalCommunicationMode ret=GET_EXTERNAL_COMMUNICATION_MODE; - if(arg != GET_EXTERNAL_COMMUNICATION_MODE){ - switch((int)arg){ + if (arg != GET_EXTERNAL_COMMUNICATION_MODE) { + switch((int)arg) { case AUTO_TIMING: ret = 0; break; case TRIGGER_EXPOSURE: ret = 2; break; case BURST_TRIGGER: ret = 1; break; - case GATE_FIX_NUMBER: ret = 3; break; + case GATED: ret = 3; break; } - printf(" Setting Triggering Mode: %d\n",(int)ret); + FILE_LOG(logDEBUG1, ("Setting Triggering Mode: %d\n", (int)ret)); #ifndef VIRTUAL - if(Feb_Control_SetTriggerMode(ret,1)) + if (Feb_Control_SetTriggerMode(ret,1)) #endif eiger_triggermode = ret; } +} + +enum externalCommunicationMode getTiming() { + enum externalCommunicationMode ret = GET_EXTERNAL_COMMUNICATION_MODE; ret = eiger_triggermode; - switch((int)ret){ + switch((int)ret) { case 0: ret = AUTO_TIMING; break; case 2: ret = TRIGGER_EXPOSURE; break; case 1: ret = BURST_TRIGGER; break; - case 3: ret = GATE_FIX_NUMBER; break; + case 3: ret = GATED; break; default: - printf("Unknown trigger mode found %d\n",ret); + FILE_LOG(logERROR, ("Unknown trigger mode found %d\n", ret)); ret = 0; } return ret; @@ -1140,13 +1208,11 @@ enum externalCommunicationMode setTiming( enum externalCommunicationMode arg){ - - - /* configure mac */ -int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport, uint32_t udpport2, int ival) { +int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport, uint32_t udpport2) { #ifndef VIRTUAL + FILE_LOG(logINFO, ("Configuring MAC\n")); char src_mac[50], src_ip[50],dst_mac[50], dst_ip[50]; int src_port = 0xE185; sprintf(src_ip,"%d.%d.%d.%d",(sourceip>>24)&0xff,(sourceip>>16)&0xff,(sourceip>>8)&0xff,(sourceip)&0xff); @@ -1164,40 +1230,49 @@ int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t (unsigned int)((destmac>>8)&0xFF), (unsigned int)((destmac>>0)&0xFF)); - printf("src_port:%d\n",src_port); - printf("src_ip:%s\n",src_ip); - printf("dst_ip:%s\n",dst_ip); - printf("src_mac:%s\n",src_mac); - printf("dst_mac:%s\n",dst_mac); - int beb_num = BEB_NUM;//Feb_Control_GetModuleNumber(); + FILE_LOG(logINFO, ( + "\tSource IP : %s\n" + "\tSource MAC : %s\n" + "\tSource Port : %d\n" + "\tDest IP : %s\n" + "\tDest MAC : %s\n", + src_ip, src_mac, src_port, + dst_ip, dst_mac)); + + + int beb_num = detid; int header_number = 0; int dst_port = udpport; - if(!top) + if (!top) dst_port = udpport2; - printf("dst_port:%d\n\n",dst_port); + FILE_LOG(logINFO, ("\tDest Port : %d\n", dst_port)); int i=0; - /* for(i=0;i<32;i++){ modified for Aldo*/ - if(Beb_SetBebSrcHeaderInfos(beb_num,send_to_ten_gig,src_mac,src_ip,src_port) && - Beb_SetUpUDPHeader(beb_num,send_to_ten_gig,header_number+i,dst_mac,dst_ip, dst_port)) - printf("set up left ok\n"); - else return -1; + /* for(i=0;i<32;i++) { modified for Aldo*/ + if (Beb_SetBebSrcHeaderInfos(beb_num,send_to_ten_gig,src_mac,src_ip,src_port) && + Beb_SetUpUDPHeader(beb_num,send_to_ten_gig,header_number+i,dst_mac,dst_ip, dst_port)) { + FILE_LOG(logDEBUG1, ("\tset up left ok\n")); + } else { + return FAIL; + } /*}*/ header_number = 32; dst_port = udpport2; - if(!top) + if (!top) dst_port = udpport; - printf("dst_port:%d\n\n",dst_port); + FILE_LOG(logINFO, ("\tDest Port : %d\n",dst_port)); - /*for(i=0;i<32;i++){*//** modified for Aldo*/ - if(Beb_SetBebSrcHeaderInfos(beb_num,send_to_ten_gig,src_mac,src_ip,src_port) && - Beb_SetUpUDPHeader(beb_num,send_to_ten_gig,header_number+i,dst_mac,dst_ip, dst_port)) - printf("set up right ok\n\n"); - else return -1; + /*for(i=0;i<32;i++) {*//** modified for Aldo*/ + if (Beb_SetBebSrcHeaderInfos(beb_num,send_to_ten_gig,src_mac,src_ip,src_port) && + Beb_SetUpUDPHeader(beb_num,send_to_ten_gig,header_number+i,dst_mac,dst_ip, dst_port)) { + FILE_LOG(logDEBUG1, (" set up right ok\n")); + } else { + return FAIL; + } /*}*/ on_dst = 0; @@ -1205,7 +1280,7 @@ int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t for(i=0;i<32;i++) dst_requested[i] = 0; //clear dst requested nimages_per_request=eiger_nexposures * eiger_ncycles; #endif - return 0; + return OK; } @@ -1219,16 +1294,27 @@ int setDetectorPosition(int pos[]) { } +int enableTenGigabitEthernet(int val) { + if (val!=-1) { + FILE_LOG(logINFO, ("Setting 10Gbe: %d\n", (val > 0) ? 1 : 0)); + if (val>0) + send_to_ten_gig = 1; + else + send_to_ten_gig = 0; + //configuremac called from client + } + return send_to_ten_gig; +} -/* eiger specific - iodelay, 10g, pulse, rate, temp, activate, delay nw parameter */ +/* eiger specific - iodelay, pulse, rate, temp, activate, delay nw parameter */ -int setIODelay(int val, int imod){ - if(val!=-1){ - printf(" Setting IO Delay: %d\n",val); +int setIODelay(int val) { + if (val!=-1) { + FILE_LOG(logDEBUG1, ("Setting IO Delay: %d\n",val)); #ifndef VIRTUAL - if(Feb_Control_SetIDelays(Feb_Control_GetModuleNumber(),val)) + if (Feb_Control_SetIDelays(Feb_Control_GetModuleNumber(),val)) #endif eiger_iodelay = val; } @@ -1236,30 +1322,13 @@ int setIODelay(int val, int imod){ } -int enableTenGigabitEthernet(int val){ - if(val!=-1){ - if(val>0) - send_to_ten_gig = 1; - else - send_to_ten_gig = 0; - //configuremac called from client - } -#ifdef VERBOSE - printf("10Gbe:%d\n",send_to_ten_gig); -#endif - return send_to_ten_gig; -} - - -int setCounterBit(int val){ - if(val!=-1){ +int setCounterBit(int val) { + if (val!=-1) { + FILE_LOG(logINFO, ("Setting Counter Bit: %d\n",val)); #ifdef VIRTUAL eiger_virtual_counter_bit = val; #else Feb_Control_Set_Counter_Bit(val); -#endif -#ifdef VERBOSE - printf("Counter Bit:%d\n",val); #endif } #ifdef VIRTUAL @@ -1270,45 +1339,45 @@ int setCounterBit(int val){ } -int pulsePixel(int n, int x, int y){ +int pulsePixel(int n, int x, int y) { #ifndef VIRTUAL - if(!Feb_Control_Pulse_Pixel(n,x,y)) + if (!Feb_Control_Pulse_Pixel(n,x,y)) return FAIL; #endif return OK; } -int pulsePixelNMove(int n, int x, int y){ +int pulsePixelNMove(int n, int x, int y) { #ifndef VIRTUAL - if(!Feb_Control_PulsePixelNMove(n,x,y)) + if (!Feb_Control_PulsePixelNMove(n,x,y)) return FAIL; #endif return OK; } -int pulseChip(int n){ +int pulseChip(int n) { #ifndef VIRTUAL - if(!Feb_Control_PulseChip(n)) + if (!Feb_Control_PulseChip(n)) return FAIL; #endif return OK; } -int64_t setRateCorrection(int64_t custom_tau_in_nsec){//in nanosec (will never be -1) +int64_t setRateCorrection(int64_t custom_tau_in_nsec) {//in nanosec (will never be -1) #ifdef VIRTUAL //deactivating rate correction - if(custom_tau_in_nsec==0){ + if (custom_tau_in_nsec==0) { eiger_virtual_ratecorrection_variable = 0; return 0; } //when dynamic range changes, use old tau - else if(custom_tau_in_nsec == -1) + else if (custom_tau_in_nsec == -1) custom_tau_in_nsec = eiger_virtual_ratetable_tau_in_ns; //get period = subexptime if 32bit , else period = exptime if 16 bit int64_t actual_period = eiger_virtual_subexptime*10; //already in nsec - if(eiger_dynamicrange == 16) + if (eiger_dynamicrange == 16) actual_period = eiger_virtual_exptime; int64_t ratetable_period_in_nsec = eiger_virtual_ratetable_period_in_ns; @@ -1317,44 +1386,45 @@ int64_t setRateCorrection(int64_t custom_tau_in_nsec){//in nanosec (will never b //same setting - if((tau_in_nsec == custom_tau_in_nsec) && (ratetable_period_in_nsec == actual_period)){ - if(eiger_dynamicrange == 32) - printf("Rate Table already created before: Same Tau %lldns, Same subexptime %lldns\n", - (long long int)tau_in_nsec,(long long int)ratetable_period_in_nsec); - else - printf("Rate Table already created before: Same Tau %lldns, Same exptime %lldns\n", - (long long int)tau_in_nsec,(long long int)ratetable_period_in_nsec); + if ((tau_in_nsec == custom_tau_in_nsec) && (ratetable_period_in_nsec == actual_period)) { + if (eiger_dynamicrange == 32) { + FILE_LOG(logINFO, ("Rate Table already created before: Same Tau %lldns, Same subexptime %lldns\n", + (long long int)tau_in_nsec,(long long int)ratetable_period_in_nsec)); + } else { + FILE_LOG(logINFO, ("Rate Table already created before: Same Tau %lldns, Same exptime %lldns\n", + (long long int)tau_in_nsec,(long long int)ratetable_period_in_nsec)); + } } //different setting, calculate table - else{ + else { eiger_virtual_ratetable_tau_in_ns = custom_tau_in_nsec; double period_in_sec = (double)(eiger_virtual_subexptime*10)/(double)1e9; - if(eiger_dynamicrange == 16) + if (eiger_dynamicrange == 16) period_in_sec = eiger_virtual_exptime; eiger_virtual_ratetable_period_in_ns = period_in_sec*1e9; } //activating rate correction eiger_virtual_ratecorrection_variable = 1; - printf("Rate Correction Value set to %lld ns\n",(long long int)eiger_virtual_ratetable_tau_in_ns); + FILE_LOG(logINFO, ("Rate Correction Value set to %lld ns\n",(long long int)eiger_virtual_ratetable_tau_in_ns)); return eiger_virtual_ratetable_tau_in_ns; #else //deactivating rate correction - if(custom_tau_in_nsec==0){ + if (custom_tau_in_nsec==0) { Feb_Control_SetRateCorrectionVariable(0); return 0; } //when dynamic range changes, use old tau - else if(custom_tau_in_nsec == -1) + else if (custom_tau_in_nsec == -1) custom_tau_in_nsec = Feb_Control_Get_RateTable_Tau_in_nsec(); int dr = Feb_Control_GetDynamicRange(); //get period = subexptime if 32bit , else period = exptime if 16 bit int64_t actual_period = Feb_Control_GetSubFrameExposureTime(); //already in nsec - if(dr == 16) + if (dr == 16) actual_period = Feb_Control_GetExposureTime_in_nsec(); int64_t ratetable_period_in_nsec = Feb_Control_Get_RateTable_Period_in_nsec(); @@ -1362,35 +1432,34 @@ int64_t setRateCorrection(int64_t custom_tau_in_nsec){//in nanosec (will never b //same setting - if((tau_in_nsec == custom_tau_in_nsec) && (ratetable_period_in_nsec == actual_period)){ - if(dr == 32) - printf("Rate Table already created before: Same Tau %lldns, Same subexptime %lldns\n", - tau_in_nsec,ratetable_period_in_nsec); - else - printf("Rate Table already created before: Same Tau %lldns, Same exptime %lldns\n", - tau_in_nsec,ratetable_period_in_nsec); + if ((tau_in_nsec == custom_tau_in_nsec) && (ratetable_period_in_nsec == actual_period)) { + if (dr == 32) { + FILE_LOG(logINFO, ("Rate Table already created before: Same Tau %lldns, Same subexptime %lldns\n", + tau_in_nsec,ratetable_period_in_nsec)); + } else { + FILE_LOG(logINFO, ("Rate Table already created before: Same Tau %lldns, Same exptime %lldns\n", + tau_in_nsec,ratetable_period_in_nsec)); + } } //different setting, calculate table - else{ + else { int ret = Feb_Control_SetRateCorrectionTau(custom_tau_in_nsec); - if(ret<=0){ - cprintf(RED,"Rate correction failed. Deactivating rate correction\n"); + if (ret<=0) { + FILE_LOG(logERROR, ("Rate correction failed. Deactivating rate correction\n")); Feb_Control_SetRateCorrectionVariable(0); return ret; } } //activating rate correction Feb_Control_SetRateCorrectionVariable(1); - printf("Rate Correction Value set to %lld ns\n",(long long int)Feb_Control_Get_RateTable_Tau_in_nsec()); -#ifdef VERBOSE + FILE_LOG(logINFO, ("Rate Correction Value set to %lld ns\n", (long long int)Feb_Control_Get_RateTable_Tau_in_nsec())); Feb_Control_PrintCorrectedValues(); -#endif return Feb_Control_Get_RateTable_Tau_in_nsec(); #endif } -int getRateCorrectionEnable(){ +int getRateCorrectionEnable() { #ifdef VIRTUAL return eiger_virtual_ratecorrection_variable; #else @@ -1398,28 +1467,28 @@ int getRateCorrectionEnable(){ #endif } -int getDefaultSettingsTau_in_nsec(){ +int getDefaultSettingsTau_in_nsec() { return default_tau_from_file; } -void setDefaultSettingsTau_in_nsec(int t){ +void setDefaultSettingsTau_in_nsec(int t) { default_tau_from_file = t; - printf("Default tau set to %d\n",default_tau_from_file); + FILE_LOG(logINFO, ("Default tau set to %d\n", default_tau_from_file)); } -int64_t getCurrentTau(){ - if(!getRateCorrectionEnable()) +int64_t getCurrentTau() { + if (!getRateCorrectionEnable()) return 0; else #ifndef VIRTUAL return Feb_Control_Get_RateTable_Tau_in_nsec(); #else - return eiger_virtual_ratetable_tau_in_ns; + return eiger_virtual_ratetable_tau_in_ns; #endif } -void setExternalGating(int enable[]){ - if(enable>=0){ +void setExternalGating(int enable[]) { + if (enable>=0) { #ifndef VIRTUAL Feb_Control_SetExternalEnableMode(enable[0], enable[1]);//enable = 0 or 1, polarity = 0 or 1 , where 1 is positive #endif @@ -1430,44 +1499,41 @@ void setExternalGating(int enable[]){ enable[1] = eiger_extgatingpolarity; } -int setAllTrimbits(int val){ +int setAllTrimbits(int val) { #ifndef VIRTUAL - if(!Feb_Control_SaveAllTrimbitsTo(val)){ - cprintf(RED,"error in setting all trimbits to value\n"); + if (!Feb_Control_SaveAllTrimbitsTo(val)) { + FILE_LOG(logERROR, ("Could not set all trimbits\n")); return FAIL; } #endif -#ifdef VERBOSE - printf("Copying register %x value %d\n",destMod->reg,val); -#endif - if (detectorModules){ + if (detectorModules) { int ichan; for (ichan=0; ichan<(detectorModules->nchan); ichan++) { *((detectorModules->chanregs)+ichan)=val; } } - cprintf(GREEN, "All trimbits have been set to %d\n", val); + FILE_LOG(logINFO, ("All trimbits have been set to %d\n", val)); return OK; } -int getAllTrimbits(){ +int getAllTrimbits() { int ichan=0; int value = *((detectorModules->chanregs)); - if (detectorModules){ + if (detectorModules) { for (ichan=0; ichan<(detectorModules->nchan); ichan++) { - if(*((detectorModules->chanregs)+ichan) != value) { + if (*((detectorModules->chanregs)+ichan) != value) { value= -1; break; } } } - printf("Value of all Trimbits: %d\n", value); + FILE_LOG(logINFO, ("Value of all Trimbits: %d\n", value)); return value; } -int getBebFPGATemp(){ +int getBebFPGATemp() { #ifdef VIRTUAL return 0; #else @@ -1475,7 +1541,7 @@ int getBebFPGATemp(){ #endif } -int activate(int enable){ +int activate(int enable) { #ifdef VIRTUAL if (enable >=0) eiger_virtual_activate = enable; @@ -1487,12 +1553,12 @@ int activate(int enable){ #endif } -int setNetworkParameter(enum NETWORKINDEX mode, int value){ +int setNetworkParameter(enum NETWORKINDEX mode, int value) { #ifndef VIRTUAL return Beb_SetNetworkParameter(mode, value); #else if (value>-1) { - switch(mode){ + switch(mode) { case TXN_LEFT: eiger_virtual_transmission_delay_left = value; break; @@ -1504,13 +1570,13 @@ int setNetworkParameter(enum NETWORKINDEX mode, int value){ break; case FLOWCTRL_10G: eiger_virtual_transmission_flowcontrol_10g = value; - if(value>0) value = 1; + if (value>0) value = 1; break; - default: cprintf(BG_RED,"Unrecognized mode in network parameter: %d\n",mode); - return -1; + default: FILE_LOG(logERROR, ("Unrecognized mode in network parameter: %d\n",mode)); + return -1; } } - switch(mode){ + switch(mode) { case TXN_LEFT: return eiger_virtual_transmission_delay_left; case TXN_RIGHT: @@ -1519,8 +1585,8 @@ int setNetworkParameter(enum NETWORKINDEX mode, int value){ return eiger_virtual_transmission_delay_frame; case FLOWCTRL_10G: return eiger_virtual_transmission_flowcontrol_10g; - default: cprintf(BG_RED,"Unrecognized mode in network parameter: %d\n",mode); - return -1; + default: FILE_LOG(logERROR, ("Unrecognized mode in network parameter: %d\n",mode)); + return -1; } #endif } @@ -1534,11 +1600,11 @@ int setNetworkParameter(enum NETWORKINDEX mode, int value){ /* aquisition */ -int prepareAcquisition(){ +int prepareAcquisition() { #ifndef VIRTUAL - printf("Going to prepare for acquisition with counter_bit:%d\n",Feb_Control_Get_Counter_Bit()); + FILE_LOG(logINFO, ("Going to prepare for acquisition with counter_bit:%d\n",Feb_Control_Get_Counter_Bit())); Feb_Control_PrepareForAcquisition(); - printf("Going to reset Frame Number\n"); + FILE_LOG(logINFO, ("Going to reset Frame Number\n")); Beb_ResetFrameNumber(); #endif return OK; @@ -1546,16 +1612,16 @@ int prepareAcquisition(){ } -int startStateMachine(){ +int startStateMachine() { #ifdef VIRTUAL eiger_virtual_status = 1; eiger_virtual_stop = 0; - if(pthread_create(&eiger_virtual_tid, NULL, &start_timer, NULL)) { - cprintf(RED,"Could not start Virtual acquisition thread\n"); + if (pthread_create(&eiger_virtual_tid, NULL, &start_timer, NULL)) { + FILE_LOG(logERROR, ("Could not start Virtual acquisition thread\n")); eiger_virtual_status = 0; return FAIL; } - cprintf(GREEN,"***Virtual Acquisition started\n"); + FILE_LOG(logINFO ,("Virtual Acquisition started\n")); return OK; #else @@ -1563,24 +1629,24 @@ int startStateMachine(){ //get the DAQ toggle bit prev_flag = Feb_Control_AcquisitionStartedBit(); - printf("Going to start acquisition\n"); + FILE_LOG(logINFO, ("Going to start acquisition\n")); Feb_Control_StartAcquisition(); - if(!eiger_storeinmem){ - printf("requesting images right after start\n"); + if (!eiger_storeinmem) { + FILE_LOG(logINFO, ("requesting images right after start\n")); ret = startReadOut(); } //wait for acquisition start - if(ret == OK){ - if(!Feb_Control_WaitForStartedFlag(5000, prev_flag)){ - cprintf(RED,"Error: Acquisition did not start or trouble reading register\n"); + if (ret == OK) { + if (!Feb_Control_WaitForStartedFlag(5000, prev_flag)) { + FILE_LOG(logERROR, ("Acquisition did not FILE_LOG(logERROR ouble reading register\n")); return FAIL; } - cprintf(GREEN,"***Acquisition started\n"); + FILE_LOG(logINFOGREEN, ("Acquisition started\n")); } - /*while(getRunStatus() == IDLE){printf("waiting for being not idle anymore\n");}*/ + /*while(getRunStatus() == IDLE) {FILE_LOG(logINFO, ("waiting for being not idle anymore\n"));}*/ return ret; #endif @@ -1590,12 +1656,12 @@ int startStateMachine(){ void* start_timer(void* arg) { eiger_virtual_status = 1; int wait_in_s = nimages_per_request * eiger_virtual_period; - cprintf(GREEN,"going to wait for %d s\n", wait_in_s); + FILE_LOG(logINFO, ("going to wait for %d s\n", wait_in_s)); while(!eiger_virtual_stop && (wait_in_s >= 0)) { usleep(1000 * 1000); wait_in_s--; } - cprintf(GREEN,"Virtual Timer Done***\n"); + FILE_LOG(logINFO, ("Virtual Timer Done***\n")); eiger_virtual_status = 0; return NULL; @@ -1604,16 +1670,16 @@ void* start_timer(void* arg) { -int stopStateMachine(){ - cprintf(BG_RED,"Going to stop acquisition\n"); +int stopStateMachine() { + FILE_LOG(logINFORED, ("Going to stop acquisition\n")); #ifdef VIRTUAL eiger_virtual_stop = 0; return OK; #else - if((Feb_Control_StopAcquisition() == STATUS_IDLE) & Beb_StopAcquisition()) + if ((Feb_Control_StopAcquisition() == STATUS_IDLE) & Beb_StopAcquisition()) return OK; - cprintf(BG_RED,"failed to stop acquisition\n"); + FILE_LOG(logERROR, ("failed to stop acquisition\n")); return FAIL; #endif } @@ -1629,29 +1695,29 @@ int softwareTrigger() { } -int startReadOut(){ +int startReadOut() { - printf("Requesting images...\n"); + FILE_LOG(logINFO, ("Requesting images...\n")); #ifdef VIRTUAL return OK; #else //RequestImages(); int ret_val = 0; dst_requested[0] = 1; - while(dst_requested[on_dst]){ + while(dst_requested[on_dst]) { //waits on data - int beb_num = BEB_NUM;//Feb_Control_GetModuleNumber(); + int beb_num = detid; if ((ret_val = (!Beb_RequestNImages(beb_num,send_to_ten_gig,on_dst,nimages_per_request,0)))) break; -// for(i=0;imodule>=0) { -#ifdef VERBOSE - printf("Copying module number %d to module number %d\n",srcMod->module,destMod->module); -#endif - destMod->module=srcMod->module; - } - if (srcMod->serialnumber>=0){ + if (srcMod->serialnumber>=0) { destMod->serialnumber=srcMod->serialnumber; } //no trimbit feature - if (destMod->nchip && ((srcMod->nchip)>(destMod->nchip))) { - printf("Number of chip of source is larger than number of chips of destination\n"); - return FAIL; - } - //no trimbit feature if (destMod->nchan && ((srcMod->nchan)>(destMod->nchan))) { - printf("Number of channels of source is larger than number of channels of destination\n"); + FILE_LOG(logINFO, ("Number of channels of source is larger than number of channels of destination\n")); return FAIL; } if ((srcMod->ndac)>(destMod->ndac)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - if ((srcMod->nadc)>(destMod->nadc)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); + FILE_LOG(logINFO, ("Number of dacs of source is larger than number of dacs of destination\n")); return FAIL; } -#ifdef VERBOSE - printf("DACs: src %d, dest %d\n",srcMod->ndac,destMod->ndac); - printf("ADCs: src %d, dest %d\n",srcMod->nadc,destMod->nadc); - printf("Chips: src %d, dest %d\n",srcMod->nchip,destMod->nchip); - printf("Chans: src %d, dest %d\n",srcMod->nchan,destMod->nchan); - -#endif + FILE_LOG(logDEBUG1, ("DACs: src %d, dest %d\n",srcMod->ndac,destMod->ndac)); + FILE_LOG(logDEBUG1, ("Chans: src %d, dest %d\n",srcMod->nchan,destMod->nchan)); destMod->ndac=srcMod->ndac; - destMod->nadc=srcMod->nadc; destMod->nchip=srcMod->nchip; destMod->nchan=srcMod->nchan; if (srcMod->reg>=0) destMod->reg=srcMod->reg; -#ifdef VERBOSE - printf("Copying register %x (%x)\n",destMod->reg,srcMod->reg ); -#endif - if (srcMod->gain>=0) - destMod->gain=srcMod->gain; - if (srcMod->offset>=0) - destMod->offset=srcMod->offset; + if (srcMod->iodelay>=0) + destMod->iodelay=srcMod->iodelay; + if (srcMod->tau>=0) + destMod->tau=srcMod->tau; + if (srcMod->eV>=0) + destMod->eV=srcMod->eV; + FILE_LOG(logDEBUG1, ("Copying register %x (%x)\n",destMod->reg,srcMod->reg )); - if((destMod->nchip!=0) || (destMod->nchan!=0)) { - for (ichip=0; ichip<(srcMod->nchip); ichip++) { - if (*((srcMod->chipregs)+ichip)>=0) - *((destMod->chipregs)+ichip)=*((srcMod->chipregs)+ichip); - } + if (destMod->nchan!=0) { for (ichan=0; ichan<(srcMod->nchan); ichan++) { if (*((srcMod->chanregs)+ichan)>=0) *((destMod->chanregs)+ichan)=*((srcMod->chanregs)+ichan); } } -#ifdef VERBOSE - else printf("Not Copying trimbits\n"); -#endif + else FILE_LOG(logINFO, ("Not Copying trimbits\n")); + for (idac=0; idac<(srcMod->ndac); idac++) { if (*((srcMod->dacs)+idac)>=0) { *((destMod->dacs)+idac)=*((srcMod->dacs)+idac); } } - for (iadc=0; iadc<(srcMod->nadc); iadc++) { - if (*((srcMod->adcs)+iadc)>=0) - *((destMod->adcs)+iadc)=*((srcMod->adcs)+iadc); - } return ret; } -int calculateDataBytes(){ - if(send_to_ten_gig) +int calculateDataBytes() { + if (send_to_ten_gig) return setDynamicRange(-1) * ONE_GIGA_CONSTANT * TEN_GIGA_BUFFER_SIZE; else return setDynamicRange(-1) * TEN_GIGA_CONSTANT * ONE_GIGA_BUFFER_SIZE; } -int getTotalNumberOfChannels(){return ((int)getNumberOfChannelsPerModule() * (int)getTotalNumberOfModules());} -int getTotalNumberOfChips(){return ((int)getNumberOfChipsPerModule() * (int)getTotalNumberOfModules());} -int getTotalNumberOfModules(){return NMOD;} -int getNumberOfChannelsPerModule(){return ((int)getNumberOfChannelsPerChip() * (int)getTotalNumberOfChips());} -int getNumberOfChipsPerModule(){return NCHIP;} -int getNumberOfDACsPerModule(){return NDAC;} -int getNumberOfADCsPerModule(){return NADC;} -int getNumberOfChannelsPerChip(){return NCHAN;} -int getNumberOfGainsPerModule(){return NGAIN;} -int getNumberOfOffsetsPerModule(){return NOFFSET;} - - - - -/* sync */ - -enum masterFlags setMaster(enum masterFlags arg){ - return NO_MASTER; -} - - - -enum synchronizationMode setSynchronization(enum synchronizationMode arg){ - return NO_SYNCHRONIZATION; -} +int getTotalNumberOfChannels() {return ((int)getNumberOfChannelsPerChip() * (int)getNumberOfChips());} +int getNumberOfChips() {return NCHIP;} +int getNumberOfDACs() {return NDAC;} +int getNumberOfChannelsPerChip() {return NCHAN;} + + @@ -1863,4 +1874,3 @@ enum synchronizationMode setSynchronization(enum synchronizationMode arg){ -//#endif diff --git a/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorFunctionList.h b/slsDetectorServers/eigerDetectorServer/slsDetectorFunctionList.h similarity index 100% rename from slsDetectorSoftware/jungfrauDetectorServer/slsDetectorFunctionList.h rename to slsDetectorServers/eigerDetectorServer/slsDetectorFunctionList.h diff --git a/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer.c b/slsDetectorServers/eigerDetectorServer/slsDetectorServer.c similarity index 100% rename from slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer.c rename to slsDetectorServers/eigerDetectorServer/slsDetectorServer.c diff --git a/slsDetectorSoftware/eigerDetectorServer/slsDetectorServer_defs.h b/slsDetectorServers/eigerDetectorServer/slsDetectorServer_defs.h old mode 100644 new mode 100755 similarity index 87% rename from slsDetectorSoftware/eigerDetectorServer/slsDetectorServer_defs.h rename to slsDetectorServers/eigerDetectorServer/slsDetectorServer_defs.h index 5eae871d9..3ab0c42f6 --- a/slsDetectorSoftware/eigerDetectorServer/slsDetectorServer_defs.h +++ b/slsDetectorServers/eigerDetectorServer/slsDetectorServer_defs.h @@ -1,17 +1,6 @@ -/* - * slsDetectorServer_defs.h - * - * Created on: Jan 24, 2013 - * Author: l_maliakal_d - */ - -#ifndef SLSDETECTORSERVER_DEFS_H_ -#define SLSDETECTORSERVER_DEFS_H_ - +#pragma once #include "sls_detector_defs.h" -#include -#define GOODBYE (-200) #define REQUIRED_FIRMWARE_VERSION (22) #define IDFILECOMMAND "more /home/root/executables/detid.txt" @@ -42,17 +31,12 @@ enum DACINDEX {SVP,VTR,VRF,VRS,SVN,VTGSTV,VCMP_LL,VCMP_LR,CAL,VCMP_RL,RX }; enum ADCINDEX {TEMP_FPGAEXT, TEMP_10GE, TEMP_DCDC, TEMP_SODL, TEMP_SODR, TEMP_FPGA, TEMP_FPGAFEBL, TEMP_FPGAFEBR}; enum NETWORKINDEX {TXN_LEFT, TXN_RIGHT, TXN_FRAME,FLOWCTRL_10G}; - +enum {E_PARALLEL, E_NON_PARALLEL, E_SAFE}; /* Hardware Definitions */ -#define NMAXMOD (1) -#define NMOD (1) #define NCHAN (256 * 256) #define NCHIP (4) -#define NADC (0) #define NDAC (16) -#define NGAIN (0) -#define NOFFSET (0) #define TEN_GIGA_BUFFER_SIZE (4112) @@ -65,7 +49,6 @@ enum NETWORKINDEX {TXN_LEFT, TXN_RIGHT, TXN_FRAME,FLOWCTRL_10G}; #define SPECIAL9M_HIGHVOLTAGE_BUFFERSIZE (16) /** Default Parameters */ -#define DEFAULT_MOD_INDEX (0) #define DEFAULT_NUM_FRAMES (1) #define DEFAULT_NUM_CYCLES (1) #define DEFAULT_EXPTIME (1E9) //ns @@ -90,11 +73,14 @@ enum NETWORKINDEX {TXN_LEFT, TXN_RIGHT, TXN_FRAME,FLOWCTRL_10G}; #define DEFAULT_TEST_MODE (0) #define DEFAULT_HIGH_VOLTAGE (0) +#define DAC_MIN_MV (0) +#define DAC_MAX_MV (2048) +#define LTC2620_MIN_VAL (0) // including LTC defines instead of LTC262.h (includes bit banging and blackfin read and write) +#define LTC2620_MAX_VAL (4095) // 12 bits +#define DAC_MAX_STEPS (4096) #define MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS (0x1FFFFFFF) /** 29 bit register for max subframe exposure value */ #define SLAVE_HIGH_VOLTAGE_READ_VAL (-999) #define HIGH_VOLTAGE_TOLERANCE (5) - -#endif /* SLSDETECTORSERVER_DEFS_H_ */ diff --git a/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_funcs.c b/slsDetectorServers/eigerDetectorServer/slsDetectorServer_funcs.c similarity index 100% rename from slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_funcs.c rename to slsDetectorServers/eigerDetectorServer/slsDetectorServer_funcs.c diff --git a/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_funcs.h b/slsDetectorServers/eigerDetectorServer/slsDetectorServer_funcs.h similarity index 100% rename from slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_funcs.h rename to slsDetectorServers/eigerDetectorServer/slsDetectorServer_funcs.h diff --git a/slsDetectorServers/eigerDetectorServer/sls_detector_defs.h b/slsDetectorServers/eigerDetectorServer/sls_detector_defs.h new file mode 120000 index 000000000..2af30d73a --- /dev/null +++ b/slsDetectorServers/eigerDetectorServer/sls_detector_defs.h @@ -0,0 +1 @@ +../../slsSupportLib/include/sls_detector_defs.h \ No newline at end of file diff --git a/slsDetectorServers/eigerDetectorServer/sls_detector_funcs.h b/slsDetectorServers/eigerDetectorServer/sls_detector_funcs.h new file mode 120000 index 000000000..3f48959a9 --- /dev/null +++ b/slsDetectorServers/eigerDetectorServer/sls_detector_funcs.h @@ -0,0 +1 @@ +../../slsSupportLib/include/sls_detector_funcs.h \ No newline at end of file diff --git a/slsDetectorServers/eigerDetectorServer/versionAPI.h b/slsDetectorServers/eigerDetectorServer/versionAPI.h new file mode 120000 index 000000000..5e580d8bb --- /dev/null +++ b/slsDetectorServers/eigerDetectorServer/versionAPI.h @@ -0,0 +1 @@ +../../slsSupportLib/include/versionAPI.h \ No newline at end of file diff --git a/slsDetectorSoftware/eigerDetectorServer/xfs_types.h b/slsDetectorServers/eigerDetectorServer/xfs_types.h old mode 100644 new mode 100755 similarity index 93% rename from slsDetectorSoftware/eigerDetectorServer/xfs_types.h rename to slsDetectorServers/eigerDetectorServer/xfs_types.h index cd092bbd6..792cc1d82 --- a/slsDetectorSoftware/eigerDetectorServer/xfs_types.h +++ b/slsDetectorServers/eigerDetectorServer/xfs_types.h @@ -1,5 +1,4 @@ -#ifndef __XFS_TYPES_H__ -#define __XFS_TYPES_H__ +#pragma once //#include "types.h" #include @@ -47,6 +46,3 @@ struct udp_header_type -#endif // __XFS_TYPES_H__ - - diff --git a/slsDetectorSoftware/eigerDetectorServer/xparameters.h b/slsDetectorServers/eigerDetectorServer/xparameters.h old mode 100644 new mode 100755 similarity index 100% rename from slsDetectorSoftware/eigerDetectorServer/xparameters.h rename to slsDetectorServers/eigerDetectorServer/xparameters.h diff --git a/slsDetectorSoftware/gotthardDetectorServer/.target-makefrag b/slsDetectorServers/gotthardDetectorServer/.target-makefrag similarity index 100% rename from slsDetectorSoftware/gotthardDetectorServer/.target-makefrag rename to slsDetectorServers/gotthardDetectorServer/.target-makefrag diff --git a/slsDetectorServers/gotthardDetectorServer/AD9252.h b/slsDetectorServers/gotthardDetectorServer/AD9252.h new file mode 120000 index 000000000..2ab1ed191 --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/AD9252.h @@ -0,0 +1 @@ +../slsDetectorServer/AD9252.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/AD9257.h b/slsDetectorServers/gotthardDetectorServer/AD9257.h similarity index 100% rename from slsDetectorSoftware/jungfrauDetectorServer/AD9257.h rename to slsDetectorServers/gotthardDetectorServer/AD9257.h diff --git a/slsDetectorServers/gotthardDetectorServer/LTC2620.h b/slsDetectorServers/gotthardDetectorServer/LTC2620.h new file mode 120000 index 000000000..13157cb8b --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/LTC2620.h @@ -0,0 +1 @@ +../slsDetectorServer/LTC2620.h \ No newline at end of file diff --git a/slsDetectorServers/gotthardDetectorServer/Makefile b/slsDetectorServers/gotthardDetectorServer/Makefile new file mode 100755 index 000000000..9d606f0c6 --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/Makefile @@ -0,0 +1,37 @@ +CROSS = bfin-uclinux- +CC = $(CROSS)gcc +CFLAGS += -Wall -DGOTTHARDD -DSTOP_SERVER # -DVERBOSE +LDLIBS += -lm -lstdc++ + +PROGS = gotthardDetectorServer +DESTDIR ?= bin +INSTMODE = 0777 + +SRCS = communication_funcs.c slsDetectorServer.c slsDetectorServer_funcs.c slsDetectorFunctionList.c +OBJS = $(SRCS:%.c=%.o) + + +all: clean versioning $(PROGS) + +boot: $(OBJS) + +version_name=APIGOTTHARD +version_path=slsDetectorServers/gotthardDetectorServer +versioning: + cd ../../ && echo $(PWD) && echo `tput setaf 6; ./updateAPIVersion.sh $(version_name) $(version_path); tput sgr0;` + + +$(PROGS): $(OBJS) +# echo $(OBJS) + mkdir -p $(DESTDIR) + $(CC) -o $@ $^ $(CFLAGS) $(LDLIBS) + mv $(PROGS) $(DESTDIR) + rm *.gdb + +clean: + rm -rf $(DESTDIR)/$(PROGS) *.o *.gdb + + + + + diff --git a/slsDetectorServers/gotthardDetectorServer/Makefile.virtual b/slsDetectorServers/gotthardDetectorServer/Makefile.virtual new file mode 100755 index 000000000..65174a82f --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/Makefile.virtual @@ -0,0 +1,27 @@ +CC = gcc +CFLAGS += -Wall -DGOTTHARDD -DVIRTUAL -DSTOP_SERVER #-DVERBOSEI #-DVERBOSE +LDLIBS += -lm -lstdc++ -pthread + +PROGS = gotthardDetectorServer_virtual +DESTDIR ?= bin +INSTMODE = 0777 + +SRC_CLNT = communication_funcs.c slsDetectorServer.c slsDetectorServer_funcs.c slsDetectorFunctionList.c +OBJS = $(SRC_CLNT:.c=.o) + +all: clean versioning $(PROGS) + +boot: $(OBJS) + +versioning: + @echo `tput setaf 6; ./updateGitVersion.sh; tput sgr0;` + +$(PROGS): $(OBJS) +# echo $(OBJS) + mkdir -p $(DESTDIR) + $(CC) -o $@ $^ $(CFLAGS) $(LDLIBS) + mv $(PROGS) $(DESTDIR) + +clean: + rm -rf $(DESTDIR)/$(PROGS) *.o + \ No newline at end of file diff --git a/slsDetectorServers/gotthardDetectorServer/RegisterDefs.h b/slsDetectorServers/gotthardDetectorServer/RegisterDefs.h new file mode 100755 index 000000000..b4ea94ad1 --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/RegisterDefs.h @@ -0,0 +1,369 @@ +#pragma once + +/* Definitions for FPGA*/ +#define MEM_MAP_SHIFT (11) + +/** Gain register */ +#define GAIN_REG (0x10 << MEM_MAP_SHIFT) + +#define GAIN_CONFGAIN_OFST (0) +#define GAIN_CONFGAIN_MSK (0x000000FF << GAIN_CONFGAIN_OFST) +#define GAIN_CONFGAIN_HGH_GAIN_VAL ((0x0 << GAIN_CONFGAIN_OFST) & GAIN_CONFGAIN_MSK) +#define GAIN_CONFGAIN_DYNMC_GAIN_VAL ((0x8 << GAIN_CONFGAIN_OFST) & GAIN_CONFGAIN_MSK) +#define GAIN_CONFGAIN_LW_GAIN_VAL ((0x6 << GAIN_CONFGAIN_OFST) & GAIN_CONFGAIN_MSK) +#define GAIN_CONFGAIN_MDM_GAIN_VAL ((0x2 << GAIN_CONFGAIN_OFST) & GAIN_CONFGAIN_MSK) +#define GAIN_CONFGAIN_VRY_HGH_GAIN_VAL ((0x1 << GAIN_CONFGAIN_OFST) & GAIN_CONFGAIN_MSK) + +/** Flow Control register */ +//#define FLOW_CONTROL_REG (0x11 << MEM_MAP_SHIFT) + +/** Flow Status register */ +//#define FLOW_STATUS_REG (0x12 << MEM_MAP_SHIFT) + +/** Frame register */ +//#define FRAME_REG (0x13 << MEM_MAP_SHIFT) + +/** Multi Purpose register */ +#define MULTI_PURPOSE_REG (0x14 << MEM_MAP_SHIFT) + +#define PHS_STP_OFST (0) +#define PHS_STP_MSK (0x00000001 << PHS_STP_OFST) +#define RST_CNTR_OFST (2) +#define RST_CNTR_MSK (0x00000001 << RST_CNTR_OFST) +#define SW1_OFST (5) +#define SW1_MSK (0x00000001 << SW1_OFST) +#define WRT_BCK_OFST (6) +#define WRT_BCK_MSK (0x00000001 << WRT_BCK_OFST) +#define RST_OFST (7) +#define RST_MSK (0x00000001 << RST_OFST) +#define PLL_CLK_SL_OFST (8) +#define PLL_CLK_SL_MSK (0x00000007 << PLL_CLK_SL_OFST) +#define PLL_CLK_SL_MSTR_VAL ((0x1 << PLL_CLK_SL_OFST) & PLL_CLK_SL_MSK) +#define PLL_CLK_SL_MSTR_ADC_VAL ((0x2 << PLL_CLK_SL_OFST) & PLL_CLK_SL_MSK) +#define PLL_CLK_SL_SLV_VAL ((0x3 << PLL_CLK_SL_OFST) & PLL_CLK_SL_MSK) +#define PLL_CLK_SL_SLV_ADC_VAL ((0x4 << PLL_CLK_SL_OFST) & PLL_CLK_SL_MSK) +#define ENT_RSTN_OFST (11) +#define ENT_RSTN_MSK (0x00000001 << ENT_RSTN_OFST) +#define INT_RSTN_OFST (12) +#define INT_RSTN_MSK (0x00000001 << INT_RSTN_OFST) +#define DGTL_TST_OFST (14) +#define DGTL_TST_MSK (0x00000001 << DGTL_TST_OFST) +#define CHNG_AT_PWR_ON_OFST (15) // Not used in SW +#define CHNG_AT_PWR_ON_MSK (0x00000001 << CHNG_AT_PWR_ON_OFST) // Not used in SW +#define RST_TO_SW1_DLY_OFST (16) +#define RST_TO_SW1_DLY_MSK (0x0000000F << RST_TO_SW1_DLY_OFST) +#define STRT_ACQ_DLY_OFST (20) +#define STRT_ACQ_DLY_MSK (0x0000000F << STRT_ACQ_DLY_OFST) + +/** DAQ register */ +#define DAQ_REG (0x15 << MEM_MAP_SHIFT) + +#define DAQ_TKN_TMNG_OFST (0) +#define DAQ_TKN_TMNG_MSK (0x0000FFFF << DAQ_TKN_TMNG_OFST) +#define DAQ_TKN_TMNG_BRD_RVSN_1_VAL ((0x1f16 << DAQ_TKN_TMNG_OFST) & DAQ_TKN_TMNG_MSK) +#define DAQ_TKN_TMNG_BRD_RVSN_2_VAL ((0x1f10 << DAQ_TKN_TMNG_OFST) & DAQ_TKN_TMNG_MSK) +#define DAQ_PCKT_LNGTH_OFST (16) +#define DAQ_PCKT_LNGTH_MSK (0x0000FFFF << DAQ_PCKT_LNGTH_OFST) +#define DAQ_PCKT_LNGTH_NO_ROI_VAL ((0x0013f << DAQ_PCKT_LNGTH_OFST) & DAQ_PCKT_LNGTH_MSK) +#define DAQ_PCKT_LNGTH_ROI_VAL ((0x0007f << DAQ_PCKT_LNGTH_OFST) & DAQ_PCKT_LNGTH_MSK) + +/** Time From Start register */ +//#define TIME_FROM_START_REG (0x16 << MEM_MAP_SHIFT) + +/** DAC Control register */ +#define SPI_REG (0x17 << MEM_MAP_SHIFT) + +#define SPI_DAC_SRL_CS_OTPT_OFST (0) +#define SPI_DAC_SRL_CS_OTPT_MSK (0x00000001 << SPI_DAC_SRL_CS_OTPT_OFST) +#define SPI_DAC_SRL_CLK_OTPT_OFST (1) +#define SPI_DAC_SRL_CLK_OTPT_MSK (0x00000001 << SPI_DAC_SRL_CLK_OTPT_OFST) +#define SPI_DAC_SRL_DGTL_OTPT_OFST (2) +#define SPI_DAC_SRL_DGTL_OTPT_MSK (0x00000001 << SPI_DAC_SRL_DGTL_OTPT_OFST) + +/** ADC SPI register */ +#define ADC_SPI_REG (0x18 << MEM_MAP_SHIFT) + +#define ADC_SPI_SRL_CLK_OTPT_OFST (0) +#define ADC_SPI_SRL_CLK_OTPT_MSK (0x00000001 << ADC_SPI_SRL_CLK_OTPT_OFST) +#define ADC_SPI_SRL_DT_OTPT_OFST (1) +#define ADC_SPI_SRL_DT_OTPT_MSK (0x00000001 << ADC_SPI_SRL_DT_OTPT_OFST) +#define ADC_SPI_SRL_CS_OTPT_OFST (2) +#define ADC_SPI_SRL_CS_OTPT_MSK (0x0000001F << ADC_SPI_SRL_CS_OTPT_OFST) + +/** ADC Sync register */ +#define ADC_SYNC_REG (0x19 << MEM_MAP_SHIFT) + +#define ADC_SYNC_ENET_STRT_DLY_OFST (0) +#define ADC_SYNC_ENET_STRT_DLY_MSK (0x0000000F << ADC_SYNC_ENET_STRT_DLY_OFST) +#define ADC_SYNC_ENET_STRT_DLY_VAL ((0x4 << ADC_SYNC_ENET_STRT_DLY_OFST) & ADC_SYNC_ENET_STRT_DLY_MSK) +#define ADC_SYNC_TKN1_HGH_DLY_OFST (4) +#define ADC_SYNC_TKN1_HGH_DLY_MSK (0x0000000F << ADC_SYNC_TKN1_HGH_DLY_OFST) +#define ADC_SYNC_TKN1_HGH_DLY_VAL ((0x1 << ADC_SYNC_TKN1_HGH_DLY_OFST) & ADC_SYNC_TKN1_HGH_DLY_MSK) +#define ADC_SYNC_TKN2_HGH_DLY_OFST (8) +#define ADC_SYNC_TKN2_HGH_DLY_MSK (0x0000000F << ADC_SYNC_TKN2_HGH_DLY_OFST) +#define ADC_SYNC_TKN2_HGH_DLY_VAL ((0x2 << ADC_SYNC_TKN2_HGH_DLY_OFST) & ADC_SYNC_TKN2_HGH_DLY_MSK) +#define ADC_SYNC_TKN1_LOW_DLY_OFST (12) +#define ADC_SYNC_TKN1_LOW_DLY_MSK (0x0000000F << ADC_SYNC_TKN1_LOW_DLY_OFST) +#define ADC_SYNC_TKN1_LOW_DLY_VAL ((0x2 << ADC_SYNC_TKN1_LOW_DLY_OFST) & ADC_SYNC_TKN1_LOW_DLY_MSK) +#define ADC_SYNC_TKN2_LOW_DLY_OFST (16) +#define ADC_SYNC_TKN2_LOW_DLY_MSK (0x0000000F << ADC_SYNC_TKN2_LOW_DLY_OFST) +#define ADC_SYNC_TKN2_LOW_DLY_VAL ((0x3 << ADC_SYNC_TKN2_LOW_DLY_OFST) & ADC_SYNC_TKN2_LOW_DLY_MSK) +//0x32214 +#define ADC_SYNC_TKN_VAL (ADC_SYNC_ENET_STRT_DLY_VAL | ADC_SYNC_TKN1_HGH_DLY_VAL | ADC_SYNC_TKN2_HGH_DLY_VAL | ADC_SYNC_TKN1_LOW_DLY_VAL | ADC_SYNC_TKN2_LOW_DLY_VAL) +#define ADC_SYNC_CLEAN_FIFOS_OFST (20) +#define ADC_SYNC_CLEAN_FIFOS_MSK (0x00000001 << ADC_SYNC_CLEAN_FIFOS_OFST) +#define ADC_SYNC_ENET_DELAY_OFST (24) +#define ADC_SYNC_ENET_DELAY_MSK (0x000000FF << ADC_SYNC_ENET_DELAY_OFST) +#define ADC_SYNC_ENET_DELAY_NO_ROI_VAL ((0x88 << ADC_SYNC_ENET_DELAY_OFST) & ADC_SYNC_ENET_DELAY_MSK) +#define ADC_SYNC_ENET_DELAY_ROI_VAL ((0x1b << ADC_SYNC_ENET_DELAY_OFST) & ADC_SYNC_ENET_DELAY_MSK) + +/** Time From Start register */ +//#define MU_TIME_REG (0x1a << MEM_MAP_SHIFT) + +/** Temperatre SPI In register */ +#define TEMP_SPI_IN_REG (0x1b << MEM_MAP_SHIFT) + +#define TEMP_SPI_IN_T1_CLK_OFST (0) +#define TEMP_SPI_IN_T1_CLK_MSK (0x00000001 << TEMP_SPI_IN_T1_CLK_OFST) +#define TEMP_SPI_IN_T1_CS_OFST (1) +#define TEMP_SPI_IN_T1_CS_MSK (0x00000001 << TEMP_SPI_IN_T1_CS_OFST) +#define TEMP_SPI_IN_T2_CLK_OFST (2) +#define TEMP_SPI_IN_T2_CLK_MSK (0x00000001 << TEMP_SPI_IN_T2_CLK_OFST) +#define TEMP_SPI_IN_T2_CS_OFST (3) +#define TEMP_SPI_IN_T2_CS_MSK (0x00000001 << TEMP_SPI_IN_T2_CS_OFST) +#define TEMP_SPI_IN_IDLE_MSK (TEMP_SPI_IN_T1_CS_MSK | TEMP_SPI_IN_T2_CS_MSK | TEMP_SPI_IN_T1_CLK_MSK | TEMP_SPI_IN_T2_CLK_MSK) + +/** Temperatre SPI Out register */ +#define TEMP_SPI_OUT_REG (0x1c << MEM_MAP_SHIFT) + +#define TEMP_SPI_OUT_T1_DT_OFST (0) +#define TEMP_SPI_OUT_T1_DT_MSK (0x00000001 << TEMP_SPI_OUT_T1_DT_OFST) +#define TEMP_SPI_OUT_T2_DT_OFST (1) +#define TEMP_SPI_OUT_T2_DT_MSK (0x00000001 << TEMP_SPI_OUT_T2_DT_OFST) + +/** TSE Configure register */ +#define TSE_CONF_REG (0x1d << MEM_MAP_SHIFT) + +/** SPI Configure register */ +#define ENET_CONF_REG (0x1e << MEM_MAP_SHIFT) + +/** Write TSE Shadow register */ +//#define WRITE_TSE_SHADOW_REG (0x1f << MEM_MAP_SHIFT) + +/** High Voltage register */ +#define HV_REG (0x20 << MEM_MAP_SHIFT) + +#define HV_ENBL_OFST (0) +#define HV_ENBL_MSK (0x00000001 << HV_ENBL_OFST) +#define HV_SEL_OFST (1) +#define HV_SEL_MSK (0x00000007 << HV_SEL_OFST) +#define HV_SEL_90_VAL ((0x0 << HV_SEL_OFST) & HV_SEL_MSK) +#define HV_SEL_110_VAL ((0x1 << HV_SEL_OFST) & HV_SEL_MSK) +#define HV_SEL_120_VAL ((0x2 << HV_SEL_OFST) & HV_SEL_MSK) +#define HV_SEL_150_VAL ((0x3 << HV_SEL_OFST) & HV_SEL_MSK) +#define HV_SEL_180_VAL ((0x4 << HV_SEL_OFST) & HV_SEL_MSK) +#define HV_SEL_200_VAL ((0x5 << HV_SEL_OFST) & HV_SEL_MSK) + +/** Dummy register */ +#define DUMMY_REG (0x21 << MEM_MAP_SHIFT) + +/** Firmware Version register */ +#define FPGA_VERSION_REG (0x22 << MEM_MAP_SHIFT) + +#define FPGA_VERSION_OFST (0) +#define FPGA_VERSION_MSK (0x00FFFFFF << FPGA_VERSION_OFST) // to get in format yymmdd + +/* Fix Pattern register */ +#define FIX_PATT_REG (0x23 << MEM_MAP_SHIFT) + +#define FIX_PATT_VAL (0xACDC1980) + +/** 16 bit Control register */ +#define CONTROL_REG (0x24 << MEM_MAP_SHIFT) + +#define CONTROL_STRT_ACQ_OFST (0) +#define CONTROL_STRT_ACQ_MSK (0x00000001 << CONTROL_STRT_ACQ_OFST) +#define CONTROL_STP_ACQ_OFST (1) +#define CONTROL_STP_ACQ_MSK (0x00000001 << CONTROL_STP_ACQ_OFST) +#define CONTROL_STRT_FF_TST_OFST (2) // Not used in FW & SW +#define CONTROL_STRT_FF_TST_MSK (0x00000001 << CONTROL_STRT_FF_TST_OFST) +#define CONTROL_STP_FF_TST_OFST (3) // Not used in FW & SW +#define CONTROL_STP_FF_TST_MSK (0x00000001 << CONTROL_STP_FF_TST_OFST) +#define CONTROL_STRT_RDT_OFST (4) +#define CONTROL_STRT_RDT_MSK (0x00000001 << CONTROL_STRT_RDT_OFST) +#define CONTROL_STP_RDT_OFST (5) +#define CONTROL_STP_RDT_MSK (0x00000001 << CONTROL_STP_RDT_OFST) +#define CONTROL_STRT_EXPSR_OFST (6) +#define CONTROL_STRT_EXPSR_MSK (0x00000001 << CONTROL_STRT_EXPSR_OFST) +#define CONTROL_STP_EXPSR_OFST (7) +#define CONTROL_STP_EXPSR_MSK (0x00000001 << CONTROL_STP_EXPSR_OFST) +#define CONTROL_STRT_TRN_OFST (8) +#define CONTROL_STRT_TRN_MSK (0x00000001 << CONTROL_STRT_TRN_OFST) +#define CONTROL_STP_TRN_OFST (9) +#define CONTROL_STP_TRN_MSK (0x00000001 << CONTROL_STP_TRN_OFST) +#define CONTROL_SYNC_RST_OFST (10) +#define CONTROL_SYNC_RST_MSK (0x00000001 << CONTROL_SYNC_RST_OFST) + +/** Status register */ +#define STATUS_REG (0x25 << MEM_MAP_SHIFT) + +#define STATUS_RN_BSY_OFST (0) +#define STATUS_RN_BSY_MSK (0x00000001 << STATUS_RN_BSY_OFST) +#define STATUS_RDT_BSY_OFST (1) +#define STATUS_RDT_BSY_MSK (0x00000001 << STATUS_RDT_BSY_OFST) +#define STATUS_WTNG_FR_TRGGR_OFST (3) +#define STATUS_WTNG_FR_TRGGR_MSK (0x00000001 << STATUS_WTNG_FR_TRGGR_OFST) +#define STATUS_DLY_BFR_OFST (4) +#define STATUS_DLY_BFR_MSK (0x00000001 << STATUS_DLY_BFR_OFST) +#define STATUS_DLY_AFTR_OFST (5) +#define STATUS_DLY_AFTR_MSK (0x00000001 << STATUS_DLY_AFTR_OFST) +#define STATUS_EXPSNG_OFST (6) +#define STATUS_EXPSNG_MSK (0x00000001 << STATUS_EXPSNG_OFST) +#define STATUS_CNT_ENBL_OFST (7) +#define STATUS_CNT_ENBL_MSK (0x00000001 << STATUS_CNT_ENBL_OFST) +#define STATUS_RD_STT_OFST (8) +#define STATUS_RD_STT_MSK (0x00000007 << STATUS_RD_STT_OFST) +#define STATUS_RN_STT_OFST (12) +#define STATUS_RN_STT_MSK (0x00000007 << STATUS_RN_STT_OFST) +#define STATUS_SM_FF_FLL_OFST (15) +#define STATUS_SM_FF_FLL_MSK (0x00000001 << STATUS_SM_FF_FLL_OFST) +#define STATUS_ALL_FF_EMPTY_OFST (11) +#define STATUS_ALL_FF_EMPTY_MSK (0x00000001 << STATUS_ALL_FF_EMPTY_OFST) +#define STATUS_RN_MSHN_BSY_OFST (17) +#define STATUS_RN_MSHN_BSY_MSK (0x00000001 << STATUS_RN_MSHN_BSY_OFST) +#define STATUS_RD_MSHN_BSY_OFST (18) +#define STATUS_RD_MSHN_BSY_MSK (0x00000001 << STATUS_RD_MSHN_BSY_OFST) +#define STATUS_RN_FNSHD_OFST (20) +#define STATUS_RN_FNSHD_MSK (0x00000001 << STATUS_RN_FNSHD_OFST) +#define STATUS_IDLE_MSK (0x0000FFFF << 0) + +/** Config register */ +#define CONFIG_REG (0x26 << MEM_MAP_SHIFT) + +#define CONFIG_SLAVE_OFST (0) // Not used in FW & SW +#define CONFIG_SLAVE_MSK (0x00000001 << CONFIG_SLAVE_OFST) +#define CONFIG_MASTER_OFST (1) // Not used in FW & SW +#define CONFIG_MASTER_MSK (0x00000001 << CONFIG_MASTER_OFST) +#define CONFIG_TM_GT_ENBL_OFST (2) // Not used in FW & SW +#define CONFIG_TM_GT_ENBL_MSK (0x00000001 << CONFIG_TM_GT_ENBL_OFST) +#define CONFIG_CPU_RDT_OFST (12) +#define CONFIG_CPU_RDT_MSK (0x00000001 << CONFIG_CPU_RDT_OFST) +#define CONFIG_CNTNS_RDT_OFST (23) // Not used in FW & SW +#define CONFIG_CNTNS_RDT_MSK (0x00000001 << CONFIG_CNTNS_RDT_OFST) +#define CONFIG_ACCMLT_CNTS_OFST (24) // Not used in FW & SW +#define CONFIG_ACCMLT_CNTS_MSK (0x00000001 << CONFIG_ACCMLT_CNTS_OFST) + +/** External Signal register */ +#define EXT_SIGNAL_REG (0x27 << MEM_MAP_SHIFT) + +#define EXT_SIGNAL_OFST (0) +#define EXT_SIGNAL_MSK (0x00000007 << EXT_SIGNAL_OFST) +#define EXT_SIGNAL_OFF_VAL ((0x0 << EXT_SIGNAL_OFST) & EXT_SIGNAL_MSK) +#define EXT_SIGNAL_TRGGR_IN_RSNG_VAL ((0x3 << EXT_SIGNAL_OFST) & EXT_SIGNAL_MSK) +#define EXT_SIGNAL_TRGGR_IN_FLLNG_VAL ((0x4 << EXT_SIGNAL_OFST) & EXT_SIGNAL_MSK) + +/** Look at me register */ +//#define LOOK_AT_ME_REG (0x28 << MEM_MAP_SHIFT) + +/** FPGA SVN register */ +//#define FPGA_SVN_REG (0x29 << MEM_MAP_SHIFT) + +/** Chip of Interest register */ +#define CHIP_OF_INTRST_REG (0x2a << MEM_MAP_SHIFT) + +#define CHIP_OF_INTRST_ADC_SEL_OFST (0) +#define CHIP_OF_INTRST_ADC_SEL_MSK (0x0000001F << CHIP_OF_INTRST_ADC_SEL_OFST) +#define CHIP_OF_INTRST_NUM_CHNNLS_OFST (16) +#define CHIP_OF_INTRST_NUM_CHNNLS_MSK (0x0000FFFF << CHIP_OF_INTRST_NUM_CHNNLS_OFST) + +/** Out MUX register */ +//#define OUT_MUX_REG (0x2b << MEM_MAP_SHIFT) + +/** Board Version register */ +#define BOARD_REVISION_REG (0x2c << MEM_MAP_SHIFT) + +#define BOARD_REVISION_OFST (0) +#define BOARD_REVISION_MSK (0x0000FFFF << BOARD_REVISION_OFST) +#define DETECTOR_TYPE_OFST (16) +#define DETECTOR_TYPE_MSK (0x0000000F << DETECTOR_TYPE_OFST) +//#define DETECTOR_TYPE_GOTTHARD_VAL (??) +#define DETECTOR_TYPE_MOENCH_VAL (2) + +/** Memory Test register */ +//#define MEMORY_TEST_REG (0x2d << MEM_MAP_SHIFT) + +/** Hit Threshold register */ +//#define HIT_THRESHOLD_REG (0x2e << MEM_MAP_SHIFT) + +/** Hit Count register */ +//#define HIT_COUNT_REG (0x2f << MEM_MAP_SHIFT) + +/* 16 bit Fifo Data register */ +#define FIFO_DATA_REG (0x50 << MEM_MAP_SHIFT) // Not used in FW and SW (16bit) + +/** Dacs Set 1 register */ +//#define DACS_SET_1_REG (0x65 << MEM_MAP_SHIFT) + +/** Dacs Set 2 register */ +//#define DACS_SET_2_REG (0x66 << MEM_MAP_SHIFT) + +/** Dacs Set 3 register */ +//#define DACS_SET_3_REG (0x67 << MEM_MAP_SHIFT) + +/* Set Delay 64 bit register */ +#define SET_DELAY_LSB_REG (0x68 << MEM_MAP_SHIFT) +#define SET_DELAY_MSB_REG (0x69 << MEM_MAP_SHIFT) + +/* Get Delay 64 bit register */ +#define GET_DELAY_LSB_REG (0x6a << MEM_MAP_SHIFT) +#define GET_DELAY_MSB_REG (0x6b << MEM_MAP_SHIFT) + +/* Set Cycles 64 bit register */ +#define SET_TRAINS_LSB_REG (0x6c << MEM_MAP_SHIFT) +#define SET_TRAINS_MSB_REG (0x6d << MEM_MAP_SHIFT) + +/* Get Cycles 64 bit register */ +#define GET_TRAINS_LSB_REG (0x6e << MEM_MAP_SHIFT) +#define GET_TRAINS_MSB_REG (0x6f << MEM_MAP_SHIFT) + +/* Set Frames 64 bit register */ +#define SET_FRAMES_LSB_REG (0x70 << MEM_MAP_SHIFT) +#define SET_FRAMES_MSB_REG (0x71 << MEM_MAP_SHIFT) + +/* Get Frames 64 bit register */ +#define GET_FRAMES_LSB_REG (0x72 << MEM_MAP_SHIFT) +#define GET_FRAMES_MSB_REG (0x73 << MEM_MAP_SHIFT) + +/* Set Period 64 bit register */ +#define SET_PERIOD_LSB_REG (0x74 << MEM_MAP_SHIFT) +#define SET_PERIOD_MSB_REG (0x75 << MEM_MAP_SHIFT) + +/* Get Period 64 bit register */ +#define GET_PERIOD_LSB_REG (0x76 << MEM_MAP_SHIFT) +#define GET_PERIOD_MSB_REG (0x77 << MEM_MAP_SHIFT) + +/* Set Exptime 64 bit register */ +#define SET_EXPTIME_LSB_REG (0x78 << MEM_MAP_SHIFT) +#define SET_EXPTIME_MSB_REG (0x79 << MEM_MAP_SHIFT) + +/* Get Exptime 64 bit register */ +#define GET_EXPTIME_LSB_REG (0x7a << MEM_MAP_SHIFT) +#define GET_EXPTIME_MSB_REG (0x7b << MEM_MAP_SHIFT) + +/* Set Gates 64 bit register */ +//#define SET_GATES_LSB_REG (0x7c << MEM_MAP_SHIFT) +//#define SET_GATES_MSB_REG (0x7d << MEM_MAP_SHIFT) + +/* Set Gates 64 bit register */ +//#define GET_GATES_LSB_REG (0x7e << MEM_MAP_SHIFT) +//#define GET_GATES_MSB_REG (0x7f << MEM_MAP_SHIFT) + +/* Dark Image starting address */ +#define DARK_IMAGE_REG (0x81 << MEM_MAP_SHIFT) + +/* Gain Image starting address */ +#define GAIN_IMAGE_REG (0x82 << MEM_MAP_SHIFT) + +/* Counter Block Memory starting address */ +#define COUNTER_MEMORY_REG (0x85 << MEM_MAP_SHIFT) + diff --git a/slsDetectorServers/gotthardDetectorServer/ansi.h b/slsDetectorServers/gotthardDetectorServer/ansi.h new file mode 120000 index 000000000..4a82d0575 --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/ansi.h @@ -0,0 +1 @@ +../../slsSupportLib/include/ansi.h \ No newline at end of file diff --git a/slsDetectorServers/gotthardDetectorServer/bin/gotthardDetectorServer_refactor b/slsDetectorServers/gotthardDetectorServer/bin/gotthardDetectorServer_refactor new file mode 100755 index 000000000..b1a6f14ba Binary files /dev/null and b/slsDetectorServers/gotthardDetectorServer/bin/gotthardDetectorServer_refactor differ diff --git a/slsDetectorServers/gotthardDetectorServer/blackfin.h b/slsDetectorServers/gotthardDetectorServer/blackfin.h new file mode 120000 index 000000000..2873c7dc6 --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/blackfin.h @@ -0,0 +1 @@ +../slsDetectorServer/blackfin.h \ No newline at end of file diff --git a/slsDetectorServers/gotthardDetectorServer/common.h b/slsDetectorServers/gotthardDetectorServer/common.h new file mode 120000 index 000000000..6776eb607 --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/common.h @@ -0,0 +1 @@ +../slsDetectorServer/common.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/commonServerFunctions.h b/slsDetectorServers/gotthardDetectorServer/commonServerFunctions.h similarity index 100% rename from slsDetectorSoftware/jungfrauDetectorServer/commonServerFunctions.h rename to slsDetectorServers/gotthardDetectorServer/commonServerFunctions.h diff --git a/slsDetectorServers/gotthardDetectorServer/communication_funcs.c b/slsDetectorServers/gotthardDetectorServer/communication_funcs.c new file mode 120000 index 000000000..30435fdc4 --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/communication_funcs.c @@ -0,0 +1 @@ +../slsDetectorServer/communication_funcs.c \ No newline at end of file diff --git a/slsDetectorServers/gotthardDetectorServer/communication_funcs.h b/slsDetectorServers/gotthardDetectorServer/communication_funcs.h new file mode 120000 index 000000000..c0c144994 --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/communication_funcs.h @@ -0,0 +1 @@ +../slsDetectorServer/communication_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/gotthardDetectorServer/config.txt b/slsDetectorServers/gotthardDetectorServer/config.txt old mode 100644 new mode 100755 similarity index 100% rename from slsDetectorSoftware/gotthardDetectorServer/config.txt rename to slsDetectorServers/gotthardDetectorServer/config.txt diff --git a/slsDetectorServers/gotthardDetectorServer/logger.h b/slsDetectorServers/gotthardDetectorServer/logger.h new file mode 120000 index 000000000..ff1930ce3 --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/logger.h @@ -0,0 +1 @@ +../slsDetectorServer/logger.h \ No newline at end of file diff --git a/slsDetectorServers/gotthardDetectorServer/slsDetectorFunctionList.c b/slsDetectorServers/gotthardDetectorServer/slsDetectorFunctionList.c new file mode 100755 index 000000000..0c1c7ae38 --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/slsDetectorFunctionList.c @@ -0,0 +1,1865 @@ +#include "slsDetectorFunctionList.h" +#include "versionAPI.h" +#include "logger.h" +#include "RegisterDefs.h" + +#ifndef VIRTUAL +#include "AD9257.h" // commonServerFunctions.h, blackfin.h, ansi.h +#include "AD9252.h" // old board compatibility +#include "LTC2620.h" // dacs +#else +#include "blackfin.h" +#include +#include +#endif + +#include "string.h" + +// Variables that will be exported +int phaseShift = DEFAULT_PHASE_SHIFT; + +int firmware_compatibility = OK; +int firmware_check_done = 0; +char firmware_message[MAX_STR_LENGTH]; + +#ifdef VIRTUAL +pthread_t pthread_virtual_tid; +int virtual_status = 0; +int virtual_stop = 0; +int highvoltage = 0; +#endif + +int detectorFirstServer = 1; +int dacValues[NDAC] = {0}; +enum detectorSettings thisSettings = UNINITIALIZED; +enum externalSignalFlag signalMode = 0; +int digitalTestBit = 0; + +// roi configuration +int adcConfigured = -1; +ROI rois[MAX_ROIS]; +int nROI = 0; +int ipPacketSize = 0; +int udpPacketSize = 0; + +// master slave configuration (for 25um) +int masterflags = NO_MASTER; +int masterdefaultdelay = 62; +int patternphase = 0; +int adcphase = 0; +int slavepatternphase = 0; +int slaveadcphase = 0; +int rsttosw1delay = 2; +int startacqdelay = 1; + +int isFirmwareCheckDone() { + return firmware_check_done; +} + +int getFirmwareCheckResult(char** mess) { + *mess = firmware_message; + return firmware_compatibility; +} + +void basictests() { + firmware_compatibility = OK; + firmware_check_done = 0; + memset(firmware_message, 0, MAX_STR_LENGTH); +#ifdef VIRTUAL + FILE_LOG(logINFOBLUE, ("******** Gotthard Virtual Server *****************\n")); + if (mapCSP0() == FAIL) { + strcpy(firmware_message, + "Could not map to memory. Dangerous to continue.\n"); + FILE_LOG(logERROR, (firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + firmware_check_done = 1; + return; +#else + if (mapCSP0() == FAIL) { + strcpy(firmware_message, + "Could not map to memory. Dangerous to continue.\n"); + FILE_LOG(logERROR, ("%s\n\n", firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + + // does check only if flag is 0 (by default), set by command line + if (((checkType() == FAIL) || (testFpga() == FAIL) || (testBus() == FAIL))) { + strcpy(firmware_message, + "Could not pass basic tests of FPGA and bus. Dangerous to continue.\n"); + FILE_LOG(logERROR, ("%s\n\n", firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + + uint32_t boardrev = getBoardRevision(); + uint32_t ipadd = getDetectorIP(); + uint64_t macadd = getDetectorMAC(); + int64_t fwversion = getDetectorId(DETECTOR_FIRMWARE_VERSION); + int64_t swversion = getDetectorId(DETECTOR_SOFTWARE_VERSION); + int64_t client_sw_apiversion = getDetectorId(CLIENT_SOFTWARE_API_VERSION); + + FILE_LOG(logINFOBLUE, ("************ Gotthard Server *********************\n" + "Board Revision : 0x%x\n" + + "Detector IP Addr : 0x%x\n" + "Detector MAC Addr : 0x%llx\n\n" + + "Firmware Version : 0x%llx\n" + "Software Version : 0x%llx\n" + "Client-S/w API Version : 0x%llx\n" + "********************************************************\n", + boardrev, + + ipadd, + (long long unsigned int)macadd, + + (long long int)fwversion, + (long long int)swversion, + (long long int)client_sw_apiversion + )); + + FILE_LOG(logINFO, ("Basic Tests - success\n")); + firmware_check_done = 1; +#endif +} + +int checkType() { +#ifdef VIRTUAL + return OK; +#endif + volatile u_int32_t type = ((bus_r(BOARD_REVISION_REG) & DETECTOR_TYPE_MSK) >> DETECTOR_TYPE_OFST); + if (type == DETECTOR_TYPE_MOENCH_VAL){ + FILE_LOG(logERROR, ("This is not a Gotthard Server (read %d, expected ?)\n", type)); + return FAIL; + } + return OK; +} + +int testFpga() { +#ifdef VIRTUAL + return OK; +#endif + FILE_LOG(logINFO, ("Testing FPGA:\n")); + + //fixed pattern + int ret = OK; + u_int32_t val = bus_r(FIX_PATT_REG); + if (val == FIX_PATT_VAL) { + FILE_LOG(logINFO, ("Fixed pattern: successful match (0x%08x)\n",val)); + } else { + FILE_LOG(logERROR, ("Fixed pattern does not match! Read 0x%08x, expected 0x%08x\n", val, FIX_PATT_VAL)); + ret = FAIL; + } + + if (ret == OK) { + // dummy reg + FILE_LOG(logINFO, ("\tTesting Dummy Register:\n")); + u_int32_t addr = DUMMY_REG; + volatile u_int32_t val = 0, readval = 0; + int times = 1000 * 1000; + int i = 0; + for (i = 0; i < times; ++i) { + val = 0x5A5A5A5A - i; + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("1:Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + break; + } + val = (i + (i << 10) + (i << 20)); + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("2:Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + break; + } + val = 0x0F0F0F0F; + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("3:Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + break; + } + val = 0xF0F0F0F0; + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("4:Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + break; + } + } + bus_w(addr, 0); + if (ret == OK) { + FILE_LOG(logINFO, ("Successfully tested FPGA Dummy Register %d times\n", times)); + } + } + + return ret; +} + +int testBus() { +#ifdef VIRTUAL + return OK; +#endif + FILE_LOG(logINFO, ("Testing Bus:\n")); + + int ret = OK; + u_int32_t addr = DUMMY_REG; + volatile u_int32_t val = 0, readval = 0; + int times = 1000 * 1000; + int i = 0; + + for (i = 0; i < times; ++i) { + val += 0xbbbbb; + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + } + } + + bus_w(addr, 0); + + if (ret == OK) { + FILE_LOG(logINFO, ("Successfully tested bus %d times\n", times)); + } + return ret; +} + +int detectorTest( enum digitalTestMode arg, int ival) { +#ifdef VIRTUAL + return OK; +#endif + switch(arg){ + case DIGITAL_BIT_TEST: + if (ival > -1) { + digitalTestBit = (ival == 0) ? 0 : 1; + FILE_LOG(logINFO, ("Digital Test bit set: %d\n", digitalTestBit)); + } + return digitalTestBit; + case DETECTOR_FIRMWARE_TEST: return testFpga(); + case DETECTOR_BUS_TEST: return testBus(); + default: + FILE_LOG(logERROR, ("Test not implemented for this detector %d\n", (int)arg)); + break; + } + return OK; +} + + +/* Ids */ + +int64_t getDetectorId(enum idMode arg){ + int64_t retval = -1; + + switch(arg){ + case DETECTOR_SERIAL_NUMBER: + return getDetectorNumber(); + case DETECTOR_FIRMWARE_VERSION: + return getFirmwareVersion(); + case DETECTOR_SOFTWARE_VERSION: + case CLIENT_SOFTWARE_API_VERSION: + return APIGOTTHARD; + default: + return retval; + } +} + +u_int64_t getFirmwareVersion() { +#ifdef VIRTUAL + return 0; +#endif + return ((bus_r(FPGA_VERSION_REG) & FPGA_VERSION_MSK) >> FPGA_VERSION_OFST); +} + +u_int32_t getDetectorNumber(){ +#ifdef VIRTUAL + return 0; +#endif + return 0; +} + +u_int64_t getDetectorMAC() { +#ifdef VIRTUAL + return 0; +#else + char output[255],mac[255]=""; + u_int64_t res=0; + FILE* sysFile = popen("ifconfig eth0 | grep HWaddr | cut -d \" \" -f 11", "r"); + fgets(output, sizeof(output), sysFile); + pclose(sysFile); + //getting rid of ":" + char * pch; + pch = strtok (output,":"); + while (pch != NULL){ + strcat(mac,pch); + pch = strtok (NULL, ":"); + } + sscanf(mac,"%llx",&res); + return res; +#endif +} + +u_int32_t getDetectorIP(){ +#ifdef VIRTUAL + return 0; +#endif + char temp[50]=""; + u_int32_t res=0; + //execute and get address + char output[255]; + FILE* sysFile = popen("ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2", "r"); + fgets(output, sizeof(output), sysFile); + pclose(sysFile); + + //converting IPaddress to hex. + char* pcword = strtok (output,"."); + while (pcword != NULL) { + sprintf(output,"%02x",atoi(pcword)); + strcat(temp,output); + pcword = strtok (NULL, "."); + } + strcpy(output,temp); + sscanf(output, "%x", &res); + //FILE_LOG(logINFO, ("ip:%x\n",res); + + return res; +} + +u_int32_t getBoardRevision() { +#ifdef VIRTUAL + return 0; +#endif + return ((bus_r(BOARD_REVISION_REG) & BOARD_REVISION_MSK) >> BOARD_REVISION_OFST); +} + + +/* initialization */ + +void initControlServer(){ + setupDetector(); +} + +void initStopServer() { + if (mapCSP0() == FAIL) { + FILE_LOG(logERROR, ("Stop Server: Map Fail. Dangerous to continue. Goodbye!\n")); + exit(EXIT_FAILURE); + } +} + + +/* set up detector */ + +void setupDetector() { + FILE_LOG(logINFO, ("This Server is for 1 Gotthard module (1280 channels)\n")); + + // Initialization + setPhaseShiftOnce(); + + // hv + setHighVoltage(DEFAULT_HIGH_VOLTAGE); + + // adc + if (getBoardRevision() == 1) { + AD9252_SetDefines(ADC_SPI_REG, ADC_SPI_SRL_CS_OTPT_MSK, ADC_SPI_SRL_CLK_OTPT_MSK, ADC_SPI_SRL_DT_OTPT_MSK, ADC_SPI_SRL_DT_OTPT_OFST); + AD9252_Disable(); + AD9252_Configure(); + } else { + AD9257_SetDefines(ADC_SPI_REG, ADC_SPI_SRL_CS_OTPT_MSK, ADC_SPI_SRL_CLK_OTPT_MSK, ADC_SPI_SRL_DT_OTPT_MSK, ADC_SPI_SRL_DT_OTPT_OFST); + AD9257_Disable(); + AD9257_Configure(); + } + + // dac + LTC2620_SetDefines(SPI_REG, SPI_DAC_SRL_CS_OTPT_MSK, SPI_DAC_SRL_CLK_OTPT_MSK, SPI_DAC_SRL_DGTL_OTPT_MSK, SPI_DAC_SRL_DGTL_OTPT_OFST, NDAC, DAC_MIN_MV, DAC_MAX_MV); + LTC2620_Disable(); + LTC2620_Configure(); + setDefaultDacs(); + + // temp + bus_w(TEMP_SPI_IN_REG, TEMP_SPI_IN_IDLE_MSK); + bus_w(TEMP_SPI_OUT_REG, 0x0); + + // roi, gbit readout + setROIADC(-1); // set adcsyncreg, daqreg, chipofinterestreg, cleanfifos, + setGbitReadout(); + + // master, slave (25um) + setMasterSlaveConfiguration(); + + // Default Parameters + FILE_LOG(logINFOBLUE, ("Setting Default parameters\n")); + + setSettings(DEFAULT_SETTINGS); + setExtSignal(DEFAULT_TRIGGER_MODE); + setTiming(DEFAULT_TIMING_MODE); + setTimer(FRAME_NUMBER, DEFAULT_NUM_FRAMES); + setTimer(CYCLES_NUMBER, DEFAULT_NUM_CYCLES); + setTimer(ACQUISITION_TIME, DEFAULT_EXPTIME); + setTimer(FRAME_PERIOD, DEFAULT_PERIOD); + setTimer(DELAY_AFTER_TRIGGER, DEFAULT_DELAY); + +} + +int setDefaultDacs() { + int ret = OK; + FILE_LOG(logINFOBLUE, ("Setting Default Dac values\n")); + { + int i = 0; + const int defaultvals[NDAC] = DEFAULT_DAC_VALS; + for(i = 0; i < NDAC; ++i) { + // if not already default, set it to default + if (dacValues[i] != defaultvals[i]) { + setDAC((enum DACINDEX)i, defaultvals[i], 0); + } + } + } + return ret; +} + +uint32_t writeRegister16And32(uint32_t offset, uint32_t data) { + if (((offset << MEM_MAP_SHIFT) == CONTROL_REG) || + ((offset << MEM_MAP_SHIFT) == FIFO_DATA_REG)) { + return writeRegister16(offset, data); + } else + return writeRegister(offset, data); + +} + +uint32_t readRegister16And32(uint32_t offset) { + if (((offset << MEM_MAP_SHIFT) == CONTROL_REG) || + ((offset << MEM_MAP_SHIFT) == FIFO_DATA_REG)) { + return readRegister16(offset); + } else + return readRegister(offset); +} + +/* firmware functions (resets) */ + +void setPhaseShiftOnce() { + u_int32_t addr = MULTI_PURPOSE_REG; + volatile u_int32_t val = bus_r(addr); + FILE_LOG(logDEBUG1, ("Multipurpose reg: 0x%x\n", val)); + + // first time detector has switched on + if (!val) { + detectorFirstServer = 1; + FILE_LOG(logINFO, ("Implementing the first phase shift of %d\n", phaseShift)); + int times = 0; + for (times = 1; times < phaseShift; ++times) { + bus_w(addr,(INT_RSTN_MSK | ENT_RSTN_MSK | SW1_MSK | PHS_STP_MSK)); //0x1821 + bus_w(addr,(INT_RSTN_MSK | ENT_RSTN_MSK | (SW1_MSK &~ PHS_STP_MSK))); //0x1820 + } + FILE_LOG(logDEBUG1, ("Multipurpose reg: 0x%x\n", val)); + } else + detectorFirstServer = 0; +} + +void setPhaseShift(int numphaseshift) { + FILE_LOG(logINFO, ("Implementing phase shift of %d\n", numphaseshift)); + u_int32_t addr = MULTI_PURPOSE_REG; + + volatile u_int32_t val = bus_r(addr); + FILE_LOG(logDEBUG1, ("Multipurpose reg: 0x%x\n", val)); + int times = 0; + for (times = 1; times < numphaseshift; ++times) { + bus_w(addr, val | PHS_STP_MSK); + bus_w(addr, val & (~PHS_STP_MSK)); + } + FILE_LOG(logDEBUG1, ("Multipurpose reg: 0x%x\n", val)); +} + +void cleanFifos() { + FILE_LOG(logINFO, ("Cleaning FIFOs\n")); + bus_w(ADC_SYNC_REG, bus_r(ADC_SYNC_REG) | ADC_SYNC_CLEAN_FIFOS_MSK); + bus_w(ADC_SYNC_REG, bus_r(ADC_SYNC_REG) & ~ADC_SYNC_CLEAN_FIFOS_MSK); +} + +void setADCSyncRegister() { + FILE_LOG(logINFO, ("\tSetting ADC Sync and Token Delays:\n")); + u_int32_t addr = ADC_SYNC_REG; + + // 0x88(no roi), 0x1b(roi) (MSB) + u_int32_t tokenDelay = ((adcConfigured == -1) ? + ADC_SYNC_ENET_DELAY_NO_ROI_VAL : ADC_SYNC_ENET_DELAY_ROI_VAL); + + // 0x88032214(no roi), 0x1b032214(with roi) + u_int32_t val = (ADC_SYNC_TKN_VAL | tokenDelay); + + bus_w(addr, val); + FILE_LOG(logINFO, ("\tADC Sync Reg: 0x%x\n", bus_r(addr))); +} + +void setDAQRegister() { + FILE_LOG(logINFO, ("\tSetting Packet Length and DAQ Token Timing:\n")); + u_int32_t addr = DAQ_REG; + + // 0x1f16(board rev 1) 0x1f0f(board rev 2) + u_int32_t tokenTiming = ((getBoardRevision() == 1) ? + DAQ_TKN_TMNG_BRD_RVSN_1_VAL : DAQ_TKN_TMNG_BRD_RVSN_2_VAL); + + // 0x13f(no roi), 0x7f(roi) + u_int32_t packetLength = ((adcConfigured == -1) ? + DAQ_PCKT_LNGTH_NO_ROI_VAL : DAQ_PCKT_LNGTH_ROI_VAL); + + // MSB: packetLength LSB: tokenTiming + u_int32_t val = (tokenTiming | packetLength); + + bus_w(addr, val); + FILE_LOG(logINFO, ("\tDAQ Reg: 0x%x\n", bus_r(addr))); +} + +void setChipOfInterestRegister(int adc) { + FILE_LOG(logINFO, ("\tSelecting Chips of Interst:\n")); + u_int32_t addr = CHIP_OF_INTRST_REG; + + // 0x1f(no roi), 0xXX(roi) + u_int32_t adcSelect = ((adcConfigured == -1) ? + CHIP_OF_INTRST_ADC_SEL_MSK : + (((1 << adc) << CHIP_OF_INTRST_ADC_SEL_OFST) & CHIP_OF_INTRST_ADC_SEL_MSK)); + + // 0x0500(no roi), 0x0100(roi) + u_int32_t numChannels = (adcConfigured == -1) ? (NCHIP * NCHAN) : (NCHIPS_PER_ADC * NCHAN); + numChannels = ((numChannels << CHIP_OF_INTRST_NUM_CHNNLS_OFST) & CHIP_OF_INTRST_NUM_CHNNLS_MSK); + + // 0x500001f(no roi), 0x10000xx(roi) MSB:num channels, LSB: selected ADC + u_int32_t val = (numChannels | adcSelect); + + bus_w(addr, val); + FILE_LOG(logINFO, ("\tChip Of Interest Reg: 0x%x\n", bus_r(addr))); +} + +void setROIADC(int adc) { + FILE_LOG(logINFO, ("\tSetting ROI ADC: %d\n", adc)); + adcConfigured = adc; + + setADCSyncRegister(); // adc sync & token delays + setDAQRegister(); // packet length & token timing + cleanFifos(); // clean fifos + setChipOfInterestRegister(adc); // num channels & select adc + + ipPacketSize = ((adcConfigured == -1) ? IP_PACKET_SIZE_NO_ROI : IP_PACKET_SIZE_ROI); + udpPacketSize = ((adcConfigured == -1) ? UDP_PACKETSIZE_NO_ROI : UDP_PACKETSIZE_ROI); +} + +void setGbitReadout() { + FILE_LOG(logINFO, ("Setting Gbit Readout\n")); + u_int32_t addr = CONFIG_REG; + bus_w(addr, bus_r(addr) & ~CONFIG_CPU_RDT_MSK); + FILE_LOG(logINFO, ("\tConfig Reg 0x%x\n", bus_r(addr))); +} + +int readConfigFile() { + // open config file + FILE* fd = fopen(CONFIG_FILE, "r"); + if(fd == NULL) { + FILE_LOG(logWARNING, ("\tCould not find config file %s\n", CONFIG_FILE)); + return FAIL; + } + FILE_LOG(logINFO, ("\tConfig file %s opened\n", CONFIG_FILE)); + + // Initialization + const size_t lineSize = 256; + char line[lineSize]; + memset(line, 0, lineSize); + const size_t keySize = lineSize / 2; + char key[keySize]; + memset(key, 0, keySize); + char value[keySize]; + memset(value, 0, keySize); + int scan = OK; + + // keep reading a line + while (fgets(line, lineSize, fd)) { + // ignore comments + if (line[0] == '#') + continue; + // read key & value + sscanf(line, "%s %s\n", key, value); + + // key is master/ slave flag + if (!strcasecmp(key,"masterflags")) { + if (!strcasecmp(value,"is_master")) { + masterflags = IS_MASTER; + FILE_LOG(logINFOBLUE, ("\tMaster\n")); + } else if (!strcasecmp(value,"is_slave")) { + masterflags = IS_SLAVE; + FILE_LOG(logINFOBLUE, ("\tSlave\n")); + } else if (!strcasecmp(value,"no_master")){ + masterflags = NO_MASTER; + FILE_LOG(logINFOBLUE, ("\tNo Master\n")); + } else { + FILE_LOG(logERROR, ("\tCould not scan masterflags %s value from config file\n", value)); + scan = FAIL; + break; + } + + // not first server since detector power on + if (!detectorFirstServer) { + FILE_LOG(logINFOBLUE, ("\tServer has been started up before. Ignoring rest of config file\n")); + fclose(fd); + return FAIL; + } + } + + // key is not master/ slave flag + else { + // convert value to int + int ival = 0; + if(sscanf(value, "%d", &ival) <= 0) { + FILE_LOG(logERROR, ("\tCould not scan parameter %s value %s from config file\n", key, value)); + scan = FAIL; + break; + } + // set value + if (!strcasecmp(key, "masterdefaultdelay")) + masterdefaultdelay = ival; + else if (!strcasecmp(key, "patternphase")) + patternphase = ival; + else if (!strcasecmp(key, "adcphase")) + adcphase = ival; + else if (!strcasecmp(key, "slavepatternphase")) + slavepatternphase = ival; + else if (!strcasecmp(key, "slaveadcphase")) + slaveadcphase = ival; + else if (!strcasecmp(key, "rsttosw1delay")) + rsttosw1delay = ival; + else if (!strcasecmp(key, "startacqdelay")) + startacqdelay = ival; + else { + FILE_LOG(logERROR, ("\tCould not scan parameter %s from config file\n", key)); + scan = FAIL; + break; + } + } + } + fclose(fd); + if (scan == FAIL) + exit(EXIT_FAILURE); + + FILE_LOG(logINFOBLUE, ( + "\tmasterdefaultdelay:%d\n" + "\tpatternphase:%d\n" + "\tadcphase:%d\n" + "\tslavepatternphase:%d\n" + "\tslaveadcphase:%d\n" + "\trsttosw1delay:%d\n" + "\tstartacqdelay:%d\n", + masterdefaultdelay, + patternphase, + adcphase, + slavepatternphase, + slaveadcphase, + rsttosw1delay, + startacqdelay)); + return OK; +} + +void setMasterSlaveConfiguration() { + FILE_LOG(logINFO, ("Reading Master Slave Configuration\n")); + + // no config file or not first time server + if (readConfigFile() == FAIL) + return; + + // master configuration + if (masterflags == IS_MASTER) { + // master default delay set, so reset delay + setTimer(DELAY_AFTER_TRIGGER, 0); + + // Set pattern phase for the master module + u_int32_t val = (bus_r(MULTI_PURPOSE_REG) & (~(PLL_CLK_SL_MSK))); // unset mask + bus_w(MULTI_PURPOSE_REG, val | PLL_CLK_SL_MSTR_VAL); + setPhaseShift(patternphase); + + // Set adc phase for the master module + val = (bus_r(MULTI_PURPOSE_REG) & (~(PLL_CLK_SL_MSK))); // unset mask + bus_w(MULTI_PURPOSE_REG, val | PLL_CLK_SL_MSTR_ADC_VAL); + setPhaseShift(adcphase); + + // Set pattern phase for the slave module + val = (bus_r(MULTI_PURPOSE_REG) & (~(PLL_CLK_SL_MSK))); // unset mask + bus_w(MULTI_PURPOSE_REG, val | PLL_CLK_SL_SLV_VAL); + setPhaseShift(slavepatternphase); + + // Set adc phase for the slave module + val = (bus_r(MULTI_PURPOSE_REG) & (~(PLL_CLK_SL_MSK))); // unset mask + bus_w(MULTI_PURPOSE_REG, val | PLL_CLK_SL_SLV_ADC_VAL); + setPhaseShift(slaveadcphase); + + // Set start acq delay + val = (bus_r(MULTI_PURPOSE_REG) & (~(STRT_ACQ_DLY_MSK))); // unset mask + val = val | ((startacqdelay << STRT_ACQ_DLY_OFST) & STRT_ACQ_DLY_MSK); // set val + bus_w(MULTI_PURPOSE_REG, val); + FILE_LOG(logDEBUG1, ("\tMultipurpose reg: 0x%x\n", val)); + } + + // all configuration - Set RST to SW1 delay + u_int32_t val = (bus_r(MULTI_PURPOSE_REG) & (~(RST_TO_SW1_DLY_MSK))); // unset mask + val = val | ((rsttosw1delay << RST_TO_SW1_DLY_OFST) & RST_TO_SW1_DLY_MSK); // set val + bus_w(MULTI_PURPOSE_REG, val); + FILE_LOG(logDEBUG1, ("\tMultipurpose reg: 0x%x\n", val)); + + FILE_LOG(logINFO, ("\tMaster Slave Configuration has been set up\n")); +} + + +/* set parameters - dr, roi */ + +int setDynamicRange(int dr){ + return DYNAMIC_RANGE; +} + +ROI* setROI(int n, ROI arg[], int *retvalsize, int *ret) { + + // set ROI + if(n >= 0){ + // print + if (!n) { + FILE_LOG(logINFO, ("Clearing ROI\n")); + } else { + FILE_LOG(logINFO, ("Setting ROI:\n")); + int i = 0; + for (i = 0; i < n; ++i) { + FILE_LOG(logINFO, ("\t(%d, %d)\n", arg[i].xmin, arg[i].xmax)); + } + } + // only one ROI allowed per module + if (n > 1) { + FILE_LOG(logERROR, ("\tCannot set more than 1 ROI per module\n")); + *ret = FAIL; + *retvalsize = nROI; + return rois; + } + + //clear all rois + nROI = 0; + + // find adc number and recorrect channel limits + int adc = -1; + if (n) { + // all channels + if ((arg[0].xmin <= 0) && (arg[0].xmax >= NCHIP * NCHAN)) + adc = -1; + // single adc + else { + //adc = mid value/numchans + adc = ((((arg[0].xmax) + (arg[0].xmin))/2) / (NCHAN * NCHIPS_PER_ADC)); + // incorrect adc + if((adc < 0) || (adc > 4)) { + FILE_LOG(logERROR, ("\tadc value greater than 5. deleting roi\n")); + adc = -1; + } + // recorrect roi values + else { + rois[0].xmin = adc * (NCHAN * NCHIPS_PER_ADC); + rois[0].xmax = (adc + 1) * (NCHAN * NCHIPS_PER_ADC) - 1; + rois[0].ymin = -1; + rois[0].ymax = -1; + nROI = 1; + } + } + } + + if (adc == -1) + nROI = 0; + + FILE_LOG(logINFO, ("\tAdc to be configured: %d\n", adc)); + FILE_LOG(logINFO, ("\tROI to be configured: (%d, %d)\n", + (adc == -1) ? 0 : (rois[0].xmin), + (adc == -1) ? (NCHIP * NCHAN - 1) : (rois[0].xmax))); + + // could not set roi + if((n != 0) && ((arg[0].xmin != rois[0].xmin)|| + (arg[0].xmax != rois[0].xmax)|| + (arg[0].ymin != rois[0].ymin)|| + (arg[0].ymax != rois[0].ymax))) { + *ret = FAIL; + FILE_LOG(logERROR, ("\tCould not set given ROI\n")); + } + if(n != nROI) { + *ret = FAIL; + FILE_LOG(logERROR, ("\tCould not set or clear ROIs\n")); + } + + //set adc of interest + setROIADC(adc); + } else FILE_LOG(logINFO, ("Getting ROI:\n")); + + // print + if (!nROI) { + FILE_LOG(logINFO, ("\tROI: None\n")); + } else { + FILE_LOG(logINFO, ("ROI:\n")); + int i = 0; + for (i = 0; i < nROI; ++i) { + FILE_LOG(logINFO, ("\t(%d, %d)\n", rois[i].xmin, rois[i].xmax)); + + } + } + + *retvalsize = nROI; + return rois; +} + +// parameters - readout +void setSpeed(enum speedVariable ind, int val) { + switch(ind) { + case ADC_PHASE: + setPhaseShift(val); + break; + default: + return; + } +} + +int getSpeed(enum speedVariable ind) { + // cannot get phase shift + return -1; +} + +/* parameters - timer */ + +int64_t setTimer(enum timerIndex ind, int64_t val) { + + int64_t retval = -1; + switch(ind){ + + case FRAME_NUMBER: + if(val >= 0) { + FILE_LOG(logINFO, ("Setting Frames: %lld\n",(long long int)val)); + } + retval = set64BitReg(val, SET_FRAMES_LSB_REG, SET_FRAMES_MSB_REG); + FILE_LOG(logDEBUG1, ("\tGetting Frames: %lld\n", (long long int)retval)); + break; + + case ACQUISITION_TIME: + if(val >= 0){ + FILE_LOG(logINFO, ("Setting Exptime: %lld ns\n", (long long int)val)); + val = (val * 1E-3 * CLK_FREQ) + 0.5; + } + retval = (set64BitReg(val, SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG) / + (1E-3 * CLK_FREQ)) + 0.5; + FILE_LOG(logINFO, ("\tGetting Exptime: %lld ns\n", (long long int)retval)); + break; + + case FRAME_PERIOD: + if(val >= 0){ + FILE_LOG(logINFO, ("Setting Period: %lld ns\n",(long long int)val)); + val = (val * 1E-3 * CLK_FREQ) + 0.5; + } + retval = (set64BitReg(val, SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG) / + (1E-3 * CLK_FREQ)) + 0.5; + FILE_LOG(logINFO, ("\tGetting Period: %lld ns\n", (long long int)retval)); + break; + + case DELAY_AFTER_TRIGGER: + if(val >= 0){ + FILE_LOG(logINFO, ("Setting Delay: %lld ns\n", (long long int)val)); + if (masterflags == IS_MASTER) { + val += masterdefaultdelay; + FILE_LOG(logINFO, ("\tActual Delay (master): %lld\n", (long long int) val)); + } + val = (val * 1E-3 * CLK_FREQ) + 0.5; + } + retval = (set64BitReg(val, SET_DELAY_LSB_REG, SET_DELAY_MSB_REG) / + (1E-3 * CLK_FREQ)) + 0.5; + FILE_LOG(logINFO, ("\tGetting Delay: %lld ns\n", (long long int)retval)); + if (masterflags == IS_MASTER) { + FILE_LOG(logDEBUG1, ("\tActual Delay read (master): %lld\n", (long long int) retval)); + retval -= masterdefaultdelay; + } + break; + + case CYCLES_NUMBER: + if(val >= 0) { + FILE_LOG(logINFO, ("Setting Cycles: %lld\n", (long long int)val)); + } + retval = set64BitReg(val, SET_TRAINS_LSB_REG, SET_TRAINS_MSB_REG); + FILE_LOG(logDEBUG1, ("\tGetting Cycles: %lld\n", (long long int)retval)); + break; + + default: + FILE_LOG(logERROR, ("Timer Index not implemented for this detector: %d\n", ind)); + break; + } + + return retval; + +} + + + +int64_t getTimeLeft(enum timerIndex ind){ +#ifdef VIRTUAL + return 0; +#endif + int64_t retval = -1; + switch(ind){ + + case FRAME_NUMBER: + retval = get64BitReg(GET_FRAMES_LSB_REG, GET_FRAMES_MSB_REG); + FILE_LOG(logINFO, ("Getting number of frames left: %lld\n",(long long int)retval)); + break; + + case ACQUISITION_TIME: + retval = (get64BitReg(GET_EXPTIME_LSB_REG, GET_EXPTIME_MSB_REG) / + (1E-3 * CLK_FREQ)) + 0.5; + FILE_LOG(logINFO, ("Getting exptime left: %lldns\n", (long long int)retval)); + break; + + case FRAME_PERIOD: + retval = (get64BitReg(GET_PERIOD_LSB_REG, GET_PERIOD_MSB_REG) / + (1E-3 * CLK_FREQ)) + 0.5; + FILE_LOG(logINFO, ("Getting period left: %lldns\n", (long long int)retval)); + break; + + case DELAY_AFTER_TRIGGER: + retval = (get64BitReg(GET_DELAY_LSB_REG, GET_DELAY_MSB_REG) / + (1E-3 * CLK_FREQ)) + 0.5; + FILE_LOG(logINFO, ("Getting delay left: %lldns\n", (long long int)retval)); + if (masterflags == IS_MASTER) { + FILE_LOG(logDEBUG1, ("\tGetting Actual delay (master): %lld\n", (long long int) retval)); + retval -= masterdefaultdelay; + } + break; + + case CYCLES_NUMBER: + retval = get64BitReg(GET_TRAINS_LSB_REG, GET_TRAINS_MSB_REG); + FILE_LOG(logINFO, ("Getting number of cycles left: %lld\n", (long long int)retval)); + break; + + default: + FILE_LOG(logERROR, ("Remaining Timer index not implemented for this detector: %d\n", ind)); + break; + } + + return retval; +} + +int validateTimer(enum timerIndex ind, int64_t val, int64_t retval) { + if (val < 0) + return OK; + switch(ind) { + case ACQUISITION_TIME: + case FRAME_PERIOD: + val = (val * 1E-3 * CLK_FREQ) + 0.5; // convert to freq + val = (val / (1E-3 * CLK_FREQ)) + 0.5; // convert back to timer + if (val != retval) + return FAIL; + break; + case DELAY_AFTER_TRIGGER: + if (masterflags == IS_MASTER) { + val += masterdefaultdelay; + } + val = (val * 1E-3 * CLK_FREQ) + 0.5; // convert to freq + val = (val / (1E-3 * CLK_FREQ)) + 0.5; // convert back to timer + if (masterflags == IS_MASTER) { + val -= masterdefaultdelay; + } + if (val != retval) + return FAIL; + break; + default: + break; + } + return OK; +} + + +/* parameters - channel, chip, module, settings */ + +int setModule(sls_detector_module myMod, char* mess){ + + FILE_LOG(logINFO, ("Setting module with settings %d\n",myMod.reg)); + + // settings + setSettings( (enum detectorSettings)myMod.reg); + + //set dac values + { + int i = 0; + for(i = 0; i < NDAC; ++i) + setDAC((enum DACINDEX)i, myMod.dacs[i], 0); + } + return OK; +} + +int getModule(sls_detector_module *myMod){ + int idac = 0; + for (idac = 0; idac < NDAC; ++idac) { + if (dacValues[idac] >= 0) + *((myMod->dacs) + idac) = dacValues[idac]; + } + // check if all of them are not initialized + int initialized = 0; + for (idac = 0; idac < NDAC; ++idac) { + if (dacValues[idac] >= 0) + initialized = 1; + } + if (initialized) + return OK; + return FAIL; +} + +enum detectorSettings setSettings(enum detectorSettings sett){ + if(sett == UNINITIALIZED) + return thisSettings; + + // set settings + if(sett != GET_SETTINGS) { + u_int32_t addr = GAIN_REG; + + // find conf gain value + uint32_t confgain = 0x0; + switch (sett) { + case DYNAMICGAIN: + FILE_LOG(logINFO, ("Set settings - Dyanmic Gain\n")); + confgain = GAIN_CONFGAIN_DYNMC_GAIN_VAL; + break; + case HIGHGAIN: + FILE_LOG(logINFO, ("Set settings - High Gain\n")); + confgain = GAIN_CONFGAIN_HGH_GAIN_VAL; + break; + case LOWGAIN: + FILE_LOG(logINFO, ("Set settings - Low Gain\n")); + confgain = GAIN_CONFGAIN_LW_GAIN_VAL; + break; + case MEDIUMGAIN: + FILE_LOG(logINFO, ("Set settings - Medium Gain\n")); + confgain = GAIN_CONFGAIN_MDM_GAIN_VAL; + break; + case VERYHIGHGAIN: + FILE_LOG(logINFO, ("Set settings - Very High Gain\n")); + confgain = GAIN_CONFGAIN_VRY_HGH_GAIN_VAL; + break; + default: + FILE_LOG(logERROR, ("This settings is not defined for this detector %d\n", (int)sett)); + return -1; + } + // set conf gain + bus_w(addr, bus_r(addr) & ~GAIN_CONFGAIN_MSK); + bus_w(addr, bus_r(addr) | confgain); + FILE_LOG(logINFO, ("\tGain Reg: 0x%x\n", bus_r(addr))); + thisSettings = sett; + } + + return getSettings(); +} + +enum detectorSettings getSettings(){ + uint32_t regval = bus_r(GAIN_REG); + uint32_t val = regval & GAIN_CONFGAIN_MSK; + switch(val) { + case GAIN_CONFGAIN_DYNMC_GAIN_VAL: + FILE_LOG(logDEBUG1, ("Settings read: Dynamic Gain. Gain Reg: 0x%x\n", regval)); + thisSettings = DYNAMICGAIN; + break; + case GAIN_CONFGAIN_HGH_GAIN_VAL: + FILE_LOG(logDEBUG1, ("Settings read: High Gain. Gain Reg: 0x%x\n", regval)); + thisSettings = HIGHGAIN; + break; + case GAIN_CONFGAIN_LW_GAIN_VAL: + FILE_LOG(logDEBUG1, ("Settings read: Low Gain. Gain Reg: 0x%x\n", regval)); + thisSettings = LOWGAIN; + break; + case GAIN_CONFGAIN_MDM_GAIN_VAL: + FILE_LOG(logDEBUG1, ("Settings read: Medium Gain. Gain Reg: 0x%x\n", regval)); + thisSettings = MEDIUMGAIN; + break; + case GAIN_CONFGAIN_VRY_HGH_GAIN_VAL: + FILE_LOG(logDEBUG1, ("Settings read: Very High Gain. Gain Reg: 0x%x\n", regval)); + thisSettings = VERYHIGHGAIN; + break; + default: + thisSettings = UNDEFINED; + FILE_LOG(logERROR, ("Settings read: Undefined. Gain Reg: 0x%x\n", regval)); + } + + return thisSettings; +} + + +/* parameters - dac, adc, hv */ + +void setDAC(enum DACINDEX ind, int val, int mV) { + if (val < 0) + return; + + FILE_LOG(logDEBUG1, ("Setting dac[%d]: %d %s \n", (int)ind, val, (mV ? "mV" : "dac units"))); + int dacval = val; +#ifdef VIRTUAL + if (!mV) { + dacValues[ind] = val; + } + // convert to dac units + else if (LTC2620_VoltageToDac(val, &dacval) == OK) { + dacValues[ind] = dacval; + } +#else + if (LTC2620_SetDACValue((int)ind, val, mV, &dacval) == OK) + dacValues[ind] = dacval; +#endif +} + +int getDAC(enum DACINDEX ind, int mV) { + if (!mV) { + FILE_LOG(logDEBUG1, ("Getting DAC %d : %d dac\n",ind, dacValues[ind])); + return dacValues[ind]; + } + int voltage = -1; + LTC2620_DacToVoltage(dacValues[ind], &voltage); + FILE_LOG(logDEBUG1, ("Getting DAC %d : %d dac (%d mV)\n",ind, dacValues[ind], voltage)); + return voltage; +} + +int getMaxDacSteps() { + return LTC2620_MAX_STEPS; +} + + +int getADC(enum ADCINDEX ind){ +#ifdef VIRTUAL + return 0; +#endif + char tempnames[2][40]={"VRs/FPGAs Temperature", "ADCs/ASICs Temperature"}; + FILE_LOG(logDEBUG1, ("Getting Temperature for %s\n", tempnames[ind])); + + u_int32_t addr = TEMP_SPI_IN_REG; + uint32_t addrout = TEMP_SPI_OUT_REG; + const int repeats = 6; // number of register writes for delay + const int reads = 20; + u_int32_t value = 0; + + // standby, high clk, high cs + bus_w(addr, (TEMP_SPI_IN_T1_CLK_MSK | TEMP_SPI_IN_T1_CS_MSK | TEMP_SPI_IN_T2_CLK_MSK | TEMP_SPI_IN_T2_CS_MSK)); + + // high clk low cs + bus_w(addr, (TEMP_SPI_IN_T1_CLK_MSK | TEMP_SPI_IN_T2_CLK_MSK)); + + { + int i = 0; + for (i = 0; i < reads; ++i) { + + int j = 0; + // low clk low cs + for (j = 0; j < repeats; ++j) + bus_w(addr, 0x0); + //high clk low cs + for (j = 0; j < repeats; ++j) + bus_w(addr, (TEMP_SPI_IN_T1_CLK_MSK | TEMP_SPI_IN_T2_CLK_MSK)); + + // only the first time + if (i <= 10) { + if (ind == TEMP_ADC) + value = (value << 1) + (bus_r(addrout) & TEMP_SPI_OUT_T1_DT_MSK); + else + value = (value << 1) + (bus_r(addrout) & TEMP_SPI_OUT_T2_DT_MSK); + } + } + } + + // standby high clk, high cs + bus_w(addr, (TEMP_SPI_IN_T1_CLK_MSK | TEMP_SPI_IN_T1_CS_MSK | TEMP_SPI_IN_T2_CLK_MSK | TEMP_SPI_IN_T2_CS_MSK)); + + FILE_LOG(logDEBUG1, ("\tInitial Temperature value: %u\n", value)); + // conversion + value = value/4.0; + FILE_LOG(logINFO, ("\tTemperature %s: %f °C\n",tempnames[ind], value)); + return value; +} + +int setHighVoltage(int val){ +#ifdef VIRTUAL + if (val >= 0) + highvoltage = val; + return highvoltage; +#endif + u_int32_t addr = HV_REG; + u_int32_t sel = 0x0; + + // set + if (val >= 0) { + FILE_LOG(logINFO, ("Setting High Voltage to %d\n", val)); + switch (val) { + case 0: + break; + case 90: + sel = HV_SEL_90_VAL; + break; + case 110: + sel = HV_SEL_110_VAL; + break; + case 120: + sel = HV_SEL_120_VAL; + break; + case 150: + sel = HV_SEL_150_VAL; + break; + case 180: + sel = HV_SEL_180_VAL; + break; + case 200: + sel = HV_SEL_200_VAL; + break; + default: + FILE_LOG(logERROR, ("%d high voltage is not defined for this detector\n", val)); + return setHighVoltage(-1); + } + FILE_LOG(logDEBUG1, ("\tHigh voltage value to be sent: 0x%x\n", sel)); + + // switch off high voltage + bus_w(addr, (bus_r(addr) & ~HV_ENBL_MSK)); + + // unset mask and set value + bus_w(addr, (bus_r(addr) & ~HV_SEL_MSK) | sel); + + // switch on high voltage + if (val > 0) + bus_w(addr, bus_r(addr) | HV_ENBL_MSK); + } + + // get + u_int32_t retval = 0; + u_int32_t regval = bus_r(addr); + FILE_LOG(logDEBUG1, ("\tHigh voltage value read: 0x%x\n", regval)); + + // if high voltage was enabled, find value + if (regval & HV_ENBL_MSK) { + switch (regval & HV_SEL_MSK) { + case HV_SEL_90_VAL: + retval = 90; + break; + case HV_SEL_110_VAL: + retval = 110; + break; + case HV_SEL_120_VAL: + retval = 120; + break; + case HV_SEL_150_VAL: + retval = 150; + break; + case HV_SEL_180_VAL: + retval = 180; + break; + default: + retval = 200; + break; + } + } + FILE_LOG(logDEBUG1, ("\tHigh Voltage: %d\n", retval)); + return retval; +} + + +/* parameters - timing, extsig */ + + +void setTiming( enum externalCommunicationMode arg){ + u_int32_t addr = EXT_SIGNAL_REG; + + if (arg != GET_EXTERNAL_COMMUNICATION_MODE){ + switch((int)arg){ + case AUTO_TIMING: + FILE_LOG(logINFO, ("Set Timing: Auto\n")); + bus_w(addr, EXT_SIGNAL_OFF_VAL); + break; + case TRIGGER_EXPOSURE: + if (signalMode == TRIGGER_IN_FALLING_EDGE) { + FILE_LOG(logINFO, ("Set Timing: Trigger (Falling Edge)\n")); + bus_w(addr, EXT_SIGNAL_TRGGR_IN_FLLNG_VAL); + } else { + FILE_LOG(logINFO, ("Set Timing: Trigger (Rising Edge)\n")); + bus_w(addr, EXT_SIGNAL_TRGGR_IN_RSNG_VAL); + } + break; + default: + FILE_LOG(logERROR, ("Unknown timing mode %d for this detector\n", (int)arg)); + return; + } + } +} + +enum externalCommunicationMode getTiming() { + u_int32_t regval = bus_r(EXT_SIGNAL_REG); + switch (regval) { + case EXT_SIGNAL_TRGGR_IN_RSNG_VAL: + case EXT_SIGNAL_TRGGR_IN_FLLNG_VAL: + return TRIGGER_EXPOSURE; + default: + return AUTO_TIMING; + } +} + +void setExtSignal(enum externalSignalFlag mode) { + switch (mode) { + case TRIGGER_IN_RISING_EDGE: + FILE_LOG(logINFO, ("Setting External Signal flag: Trigger in Rising Edge\n")); + break; + case TRIGGER_IN_FALLING_EDGE: + FILE_LOG(logINFO, ("Setting External Signal flag: Trigger in Falling Edge\n")); + break; + default: + FILE_LOG(logERROR, ("Extsig (signal mode) %d not defined for this detector\n", mode)); + return; + } + signalMode = mode; + setTiming(getTiming()); +} + +int getExtSignal() { + return signalMode; +} + + +/* configure mac */ + +void calcChecksum(mac_conf* mac, int sourceip, int destip) { + mac->ip.ip_ver = 0x4; + mac->ip.ip_ihl = 0x5; + mac->ip.ip_tos = 0x0; + mac->ip.ip_len = ipPacketSize; + mac->ip.ip_ident = 0x0000; + mac->ip.ip_flag = 0x2; //not nibble aligned (flag& offset + mac->ip.ip_offset = 0x00; + mac->ip.ip_ttl = 0x70; + mac->ip.ip_protocol = 0x11; + mac->ip.ip_chksum = 0x0000 ; // pseudo + mac->ip.ip_sourceip = sourceip; + mac->ip.ip_destip = destip; + FILE_LOG(logDEBUG1, ("\tIP TTL: 0x%x\n", mac->ip.ip_ttl)); + + int count = sizeof(mac->ip); + unsigned short *addr; + addr = (unsigned short*)(&(mac->ip)); /* warning: assignment from incompatible pointer type */ + + long int sum = 0; + while( count > 1 ) { + sum += *addr++; + count -= 2; + } + if (count > 0) + sum += *addr; // Add left-over byte, if any + while (sum>>16) + sum = (sum & 0xffff) + (sum >> 16);// Fold 32-bit sum to 16 bits + long int checksum = (~sum) & 0xffff; + FILE_LOG(logINFO, ("\tIP checksum : 0x%lx\n", checksum)); + mac->ip.ip_chksum = checksum; +} + +int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport) { +#ifdef VIRTUAL + return OK; +#endif + FILE_LOG(logINFOBLUE, ("Configuring MAC\n")); + u_int32_t addr = MULTI_PURPOSE_REG; + + FILE_LOG(logDEBUG1, ("\tRoi: %d, Ip Packet size: %d UDP Packet size: %d\n", + adcConfigured, ipPacketSize, udpPacketSize)); + + uint32_t sourceport = DEFAULT_TX_UDP_PORT; + FILE_LOG(logINFO, ("\tSource IP : %d.%d.%d.%d (0x%08x)\n", + (sourceip>>24)&0xff,(sourceip>>16)&0xff,(sourceip>>8)&0xff,(sourceip)&0xff, sourceip)); + FILE_LOG(logINFO, ("\tSource MAC : %02x:%02x:%02x:%02x:%02x:%02x (0x%010llx)\n", + (unsigned int)((sourcemac>>40)&0xFF), + (unsigned int)((sourcemac>>32)&0xFF), + (unsigned int)((sourcemac>>24)&0xFF), + (unsigned int)((sourcemac>>16)&0xFF), + (unsigned int)((sourcemac>>8)&0xFF), + (unsigned int)((sourcemac>>0)&0xFF), + (long long unsigned int)sourcemac)); + FILE_LOG(logINFO, ("\tSource Port : %d (0x%08x)\n",sourceport, sourceport)); + FILE_LOG(logINFO, ("\tDest. IP : %d.%d.%d.%d (0x%08x)\n", + (destip>>24)&0xff,(destip>>16)&0xff,(destip>>8)&0xff,(destip)&0xff, destip)); + FILE_LOG(logINFO, ("\tDest. MAC : %02x:%02x:%02x:%02x:%02x:%02x (0x%010llx)\n", + (unsigned int)((destmac>>40)&0xFF), + (unsigned int)((destmac>>32)&0xFF), + (unsigned int)((destmac>>24)&0xFF), + (unsigned int)((destmac>>16)&0xFF), + (unsigned int)((destmac>>8)&0xFF), + (unsigned int)((destmac>>0)&0xFF), + (long long unsigned int)destmac)); + FILE_LOG(logINFO, ("\tDest. Port : %d (0x%08x)\n",udpport, udpport)); + + // set/ unset the digital test bit + if (digitalTestBit) + bus_w (addr, bus_r(addr) | DGTL_TST_MSK); + else + bus_w (addr, bus_r(addr) & ~DGTL_TST_MSK); + FILE_LOG(logDEBUG1, ("\tDigital Test Bit. MultiPurpose reg: 0x%x\n", bus_r(addr))); + + //reset mac + bus_w (addr, bus_r(addr) | RST_MSK); + FILE_LOG(logDEBUG1, ("\tReset Mac. MultiPurpose reg: 0x%x\n", bus_r(addr))); + + usleep(500000); + + // release reset + bus_w(addr, bus_r(addr) &(~ RST_MSK)); + FILE_LOG(logDEBUG1, ("\tReset released. MultiPurpose reg: 0x%x\n", bus_r(addr))); + + // write shadow regs + bus_w(addr, bus_r(addr) | (ENT_RSTN_MSK | WRT_BCK_MSK)); + FILE_LOG(logDEBUG1, ("\tWrite shadow regs. MultiPurpose reg: 0x%x\n", bus_r(addr))); + + // release write back + bus_w(addr, bus_r(addr) &(~WRT_BCK_MSK)); + FILE_LOG(logDEBUG1, ("\tWrite back released. MultiPurpose reg: 0x%x\n", bus_r(addr))); + + FILE_LOG(logDEBUG1, ("\tConfiguring MAC CONF\n")); + mac_conf *mac_conf_regs = (mac_conf*)(CSP0BASE + ENET_CONF_REG * 2); // direct write + mac_conf_regs->mac.mac_dest_mac1 = ((destmac >> (8 * 5)) & 0xFF); + mac_conf_regs->mac.mac_dest_mac2 = ((destmac >> (8 * 4)) & 0xFF); + mac_conf_regs->mac.mac_dest_mac3 = ((destmac >> (8 * 3)) & 0xFF); + mac_conf_regs->mac.mac_dest_mac4 = ((destmac >> (8 * 2)) & 0xFF); + mac_conf_regs->mac.mac_dest_mac5 = ((destmac >> (8 * 1)) & 0xFF); + mac_conf_regs->mac.mac_dest_mac6 = ((destmac >> (8 * 0)) & 0xFF); + FILE_LOG(logDEBUG1, ("\tDestination Mac: %llx %x:%x:%x:%x:%x:%x\n", + destmac, + mac_conf_regs->mac.mac_dest_mac1, + mac_conf_regs->mac.mac_dest_mac2, + mac_conf_regs->mac.mac_dest_mac3, + mac_conf_regs->mac.mac_dest_mac4, + mac_conf_regs->mac.mac_dest_mac5, + mac_conf_regs->mac.mac_dest_mac6)); + mac_conf_regs->mac.mac_src_mac1 = ((sourcemac >> (8 * 5)) & 0xFF); + mac_conf_regs->mac.mac_src_mac2 = ((sourcemac >> (8 * 4)) & 0xFF); + mac_conf_regs->mac.mac_src_mac3 = ((sourcemac >> (8 * 3)) & 0xFF); + mac_conf_regs->mac.mac_src_mac4 = ((sourcemac >> (8 * 2)) & 0xFF); + mac_conf_regs->mac.mac_src_mac5 = ((sourcemac >> (8 * 1)) & 0xFF); + mac_conf_regs->mac.mac_src_mac6 = ((sourcemac >> (8 * 0)) & 0xFF); + FILE_LOG(logDEBUG1, ("\tSource Mac: %llx %x:%x:%x:%x:%x:%x\n", + sourcemac, + mac_conf_regs->mac.mac_src_mac1, + mac_conf_regs->mac.mac_src_mac2, + mac_conf_regs->mac.mac_src_mac3, + mac_conf_regs->mac.mac_src_mac4, + mac_conf_regs->mac.mac_src_mac5, + mac_conf_regs->mac.mac_src_mac6)); + mac_conf_regs->mac.mac_ether_type = 0x0800; //ipv4 + + calcChecksum(mac_conf_regs, sourceip, destip); + mac_conf_regs->udp.udp_srcport = sourceport; + mac_conf_regs->udp.udp_destport = udpport; + mac_conf_regs->udp.udp_len = udpPacketSize; + mac_conf_regs->udp.udp_chksum = 0x0000; + + FILE_LOG(logDEBUG1, ("\tConfiguring TSE\n")); + tse_conf *tse_conf_regs = (tse_conf*)(CSP0BASE + TSE_CONF_REG * 2); // direct write + tse_conf_regs->rev = 0xA00; + tse_conf_regs->scratch = 0xCCCCCCCC; + tse_conf_regs->command_config = 0xB; + tse_conf_regs->mac_0 = 0x17231C00; + tse_conf_regs->mac_1 = 0xCB4A; + tse_conf_regs->frm_length = 0x5DC; //max frame length (1500 bytes) (was 0x41C) + tse_conf_regs->pause_quant = 0x0; + tse_conf_regs->rx_section_empty = 0x7F0; + tse_conf_regs->rx_section_full = 0x10; + tse_conf_regs->tx_section_empty = 0x3F8; //was 0x7F0; + tse_conf_regs->tx_section_full = 0x16; + tse_conf_regs->rx_almost_empty = 0x8; + tse_conf_regs->rx_almost_full = 0x8; + tse_conf_regs->tx_almost_empty = 0x8; + tse_conf_regs->tx_almost_full = 0x3; + tse_conf_regs->mdio_addr0 = 0x12; + tse_conf_regs->mdio_addr1 = 0x0; + mac_conf_regs->cdone = 0xFFFFFFFF; + + bus_w(addr, bus_r(addr) | (INT_RSTN_MSK | WRT_BCK_MSK)); + FILE_LOG(logDEBUG1, ("\tWrite shadow regs with int reset. MultiPurpose reg: 0x%x\n", bus_r(addr))); + + usleep(100000); + + // release write back + bus_w(addr, bus_r(addr) &(~WRT_BCK_MSK)); + FILE_LOG(logDEBUG1, ("\tWrite back released. MultiPurpose reg: 0x%x\n", bus_r(addr))); + + bus_w(addr, bus_r(addr) | SW1_MSK); + FILE_LOG(logDEBUG1, ("\tSw1. MultiPurpose reg: 0x%x\n", bus_r(addr))); + + usleep(1000 * 1000); + FILE_LOG(logDEBUG1, ("\tConfigure Mac Done\n")); + { + /** send out first image as first packet does not give 0xcacacaca (needed to know if first image + * when switching back and forth between roi and no roi + */ + FILE_LOG(logINFOBLUE, ("Sending an image to counter the packet numbers\n")); + // remember old parameters + enum externalCommunicationMode oldtiming = getTiming(); + uint64_t oldframes = setTimer(FRAME_NUMBER, -1); + uint64_t oldcycles = setTimer(CYCLES_NUMBER, -1); + uint64_t oldPeriod = setTimer(FRAME_PERIOD, -1); + uint64_t oldExptime = setTimer(ACQUISITION_TIME, -1); + + // set to basic parameters + FILE_LOG(logINFO, ("\tSetting basic parameters\n" + "\tTiming: auto\n" + "\tframes: 1\n" + "\tcycles: 1\n" + "\tperiod: 1s\n" + "\texptime: 900ms\n")); + setTiming(AUTO_TIMING); + setTimer(FRAME_NUMBER, 1); + setTimer(CYCLES_NUMBER, 1); + setTimer(FRAME_PERIOD, 1e9); // important to keep this until we have to wait for acquisition to start + setTimer(ACQUISITION_TIME, 900 * 1000); + + // take an image + if (masterflags == IS_MASTER) + usleep(1 * 1000 * 1000); // required to ensure master starts acquisition only after slave has changed to basic parameters and is waiting + + int loop = 0; + startStateMachine(); + // wait for acquisition to start (trigger from master) + FILE_LOG(logINFO, ("\tWaiting for acquisition to start\n")); + while(!runBusy()) { + usleep(0); + ++loop; + } + + FILE_LOG(logINFO, ("\twaited %d loops to start\n", loop)); + FILE_LOG(logINFO, ("\tWaiting for acquisition to end (frames left: %lld)\n", (long long int)getTimeLeft(FRAME_NUMBER))); + // wait for status to be done + while(runBusy()){ + usleep(500); + } + + // set to previous parameters + FILE_LOG(logINFO, ("\tSetting previous parameters:\n" + "\tTiming: %d\n" + "\tframes: %lld\n" + "\tcycles: %lld\n" + "\tperiod: %lld ns\n" + "\texptime:%lld ns\n", + (int)oldtiming, (long long int)oldframes, (long long int)oldcycles, + (long long int)oldPeriod, (long long int)oldExptime)); + setTiming(oldtiming); + setTimer(FRAME_NUMBER, oldframes); + setTimer(CYCLES_NUMBER, oldcycles); + setTimer(FRAME_PERIOD, oldPeriod); + setTimer(ACQUISITION_TIME, oldExptime); + FILE_LOG(logINFOBLUE, ("Done sending a frame at configuration\n")); + } + return OK; +} + +int getAdcConfigured(){ + return adcConfigured; +} + + +/* gotthard specific - loadimage, read/reset counter block */ + +void loadImage(enum imageType index, short int imageVals[]){ + u_int32_t addr = DARK_IMAGE_REG; + if (index == GAIN_IMAGE) + addr = GAIN_IMAGE_REG; + int dataBytes = calculateDataBytes(); + + volatile u_int16_t *ptr = (u_int16_t*)(CSP0BASE + addr * 2); + memcpy((char*)ptr, (char*)imageVals, dataBytes); + + FILE_LOG(logINFO, ("Loaded %s image at 0x%p\n", + (index == GAIN_IMAGE) ? "Gain" : "Dark", (void*) ptr)); +} + +int readCounterBlock(int startACQ, short int counterVals[]){ + FILE_LOG(logINFO, ("Reading Counter Block with start Acq :%d\n", startACQ)); + + // stop any current acquisition + if (runBusy()) { + if (stopStateMachine() == FAIL) + return FAIL; + // waiting for the last frame read to be done + while(runBusy()) + usleep(500); + FILE_LOG(logDEBUG1, ("State machine stopped\n")); + } + + // copy memory + u_int32_t addr = COUNTER_MEMORY_REG; + volatile u_int16_t *ptr = (u_int16_t*)(CSP0BASE + addr * 2); + int dataBytes = calculateDataBytes(); + memcpy((char*)counterVals, (char*)ptr, dataBytes); + + // unreset counter + addr = MULTI_PURPOSE_REG; + bus_w(addr, (bus_r(addr) &~ RST_CNTR_MSK)); + FILE_LOG(logDEBUG1, ("\tUnsetting reset Counter. Multi Purpose Reg: 0x%x\n", bus_r(addr))); + + // start state machine + if (startACQ == 1){ + startStateMachine(); + if (runBusy()) { + FILE_LOG(logINFO, ("State machine RUNNING\n")); + } else { + FILE_LOG(logINFO, ("State machine IDLE\n")); + } + } + return OK; +} + +int resetCounterBlock(int startACQ){ + FILE_LOG(logINFO, ("Resetting Counter Block with start Acq :%d\n", startACQ)); + + // stop any current acquisition + if (runBusy()) { + if (stopStateMachine() == FAIL) + return FAIL; + // waiting for the last frame read to be done + while(runBusy()) + usleep(500); + FILE_LOG(logDEBUG1, ("State machine stopped\n")); + } + + // reset counter + u_int32_t addr = MULTI_PURPOSE_REG; + bus_w(addr, (bus_r(addr) | RST_CNTR_MSK)); + FILE_LOG(logDEBUG1, ("\tResetting Counter. Multi Purpose Reg: 0x%x\n", bus_r(addr))); + + // copy memory + addr = COUNTER_MEMORY_REG; + volatile u_int16_t *ptr = (u_int16_t*)(CSP0BASE + addr * 2); + int dataBytes = calculateDataBytes(); + char *counterVals = NULL; + counterVals = realloc(counterVals, dataBytes); + memcpy((char*)counterVals, (char*)ptr, dataBytes); + + // unreset counter + addr = MULTI_PURPOSE_REG; + bus_w(addr, (bus_r(addr) &~ RST_CNTR_MSK)); + FILE_LOG(logDEBUG1, ("\tUnsetting reset Counter. Multi Purpose Reg: 0x%x\n", bus_r(addr))); + + // start state machine + if (startACQ == 1){ + startStateMachine(); + if (runBusy()) { + FILE_LOG(logINFO, ("State machine RUNNING\n")); + } else { + FILE_LOG(logINFO, ("State machine IDLE\n")); + } + } + + if (sizeof(counterVals) <= 0){ + FILE_LOG(logERROR, ("\tSize of counterVals: %d\n", (int)sizeof(counterVals))); + return FAIL; + } + + return OK; +} + + +/* aquisition */ + +int startStateMachine(){ +#ifdef VIRTUAL + virtual_status = 1; + virtual_stop = 0; + if(pthread_create(&pthread_virtual_tid, NULL, &start_timer, NULL)) { + virtual_status = 0; + FILE_LOG(logERROR, ("Could not start Virtual acquisition thread\n")); + return FAIL; + } + FILE_LOG(logINFOGREEN, ("Virtual Acquisition started\n")); + return OK; +#endif + FILE_LOG(logINFOBLUE, ("Starting State Machine\n")); + FILE_LOG(logINFO, ("#frames to acquire:%lld\n", (long long int)setTimer(FRAME_NUMBER, -1))); + + cleanFifos(); + + //start state machine + bus_w16(CONTROL_REG, CONTROL_STRT_ACQ_MSK | CONTROL_STRT_EXPSR_MSK); + bus_w16(CONTROL_REG, 0x0); + runState(logINFO); + return OK; +} + +#ifdef VIRTUAL +void* start_timer(void* arg) { + int wait_in_s = (setTimer(FRAME_NUMBER, -1) * + setTimer(CYCLES_NUMBER, -1) * + (setTimer(FRAME_PERIOD, -1)/(1E9))); + FILE_LOG(logDEBUG1, ("going to wait for %d s\n", wait_in_s)); + while(!virtual_stop && (wait_in_s >= 0)) { + usleep(1000 * 1000); + wait_in_s--; + } + FILE_LOG(logINFOGREEN, ("Virtual Timer Done\n")); + + virtual_status = 0; + return NULL; +} +#endif + +int stopStateMachine(){ + FILE_LOG(logINFORED, ("Stopping State Machine\n")); +#ifdef VIRTUAL + virtual_stop = 0; + return OK; +#endif + //stop state machine + bus_w16(CONTROL_REG, CONTROL_STP_ACQ_MSK); + usleep(100); + bus_w16(CONTROL_REG, 0x0); + + // check + usleep(500); + if ((runState(logDEBUG1) & STATUS_RN_MSHN_BSY_MSK)) { + FILE_LOG(logERROR, ("\tFailed to stop state machine.\n")); + runState(logINFORED); + return FAIL; + } + + runState(logINFO); + return OK; +} + +enum runStatus getRunStatus(){ +#ifdef VIRTUAL + if(virtual_status == 0){ + FILE_LOG(logINFOBLUE, ("Status: IDLE\n")); + return IDLE; + }else{ + FILE_LOG(logINFOBLUE, ("Status: RUNNING\n")); + return RUNNING; + } +#endif + FILE_LOG(logDEBUG1, ("Getting status\n")); + + enum runStatus s = IDLE; + u_int32_t retval = runState(logINFO); + + // finished (external stop or fifo full) + if (retval & STATUS_RN_FNSHD_MSK) { + FILE_LOG(logINFORED, ("Status: Stopped\n")); + s = STOPPED; + + FILE_LOG(logINFO, ("\t Reading status reg again\n")); + retval = runState(logINFO); + // fifo full + if (runState(logDEBUG1) & STATUS_RN_FNSHD_MSK) { + FILE_LOG(logINFORED, ("Status: Error\n")); + runState(logINFORED); + s = ERROR; + } + } + + // error (fifo full) + else if (retval & STATUS_SM_FF_FLL_MSK) { + FILE_LOG(logINFORED, ("Status: Error\n")); + s = ERROR; + } + + // not running + else if (!(retval & STATUS_RN_BSY_MSK)) { + // read last frames + if (retval & STATUS_RD_MSHN_BSY_MSK) { + FILE_LOG(logINFOBLUE, ("Status: Read Machine Busy\n")); + s = TRANSMITTING; + } + // ??? + else if (retval & STATUS_ALL_FF_EMPTY_MSK) { + FILE_LOG(logINFOBLUE, ("Status: Data in Fifo\n")); + s = TRANSMITTING; + } + // idle, unknown + else if (!(retval & STATUS_IDLE_MSK)) { + FILE_LOG(logINFOBLUE, ("Status: IDLE\n")); + s = IDLE; + } else { + FILE_LOG(logINFORED, ("Status: Unknown Status: 0x%x. Trying again.\n", retval)); + int iloop = 0; + for (iloop = 0; iloop < 10; ++iloop) { + usleep(1000 * 1000); + if (runState(logDEBUG1) != retval) + return getRunStatus(); + } + s = ERROR; + } + } + + // running + else { + if (retval & STATUS_WTNG_FR_TRGGR_MSK){ + FILE_LOG(logINFOBLUE, ("Status: Waiting\n")); + s = WAITING; + } + else{ + FILE_LOG(logINFOBLUE, ("Status: Running\n")); + s = RUNNING; + } + } + + return s; +} + +void readFrame(int *ret, char *mess){ +#ifdef VIRTUAL + while(virtual_status) { + //FILE_LOG(logERROR, ("Waiting for finished flag\n"); + usleep(5000); + } + return; +#endif + // wait for status to be done + while(runBusy()){ + usleep(500); + } + + // frames left to give status + int64_t retval = getTimeLeft(FRAME_NUMBER) + 1; + if ( retval > -1) { + *ret = (int)FAIL; + sprintf(mess,"No data and run stopped: %lld frames left\n",(long long int)retval); + FILE_LOG(logERROR, (mess)); + } else { + *ret = (int)OK; + FILE_LOG(logINFOGREEN, ("Acquisition successfully finished\n")); + } +} + +u_int32_t runBusy() { +#ifdef VIRTUAL + return virtual_status; +#endif + return runState(logDEBUG1) & STATUS_RN_BSY_MSK; +} + +u_int32_t runState(enum TLogLevel lev) { +#ifdef VIRTUAL + return virtual_status; +#endif + u_int32_t s = bus_r(STATUS_REG); + FILE_LOG(lev, ("Status Register: 0x%08x\n", s)); + return s; +} + +/* common */ + +int calculateDataBytes(){ + return DATA_BYTES; +} + +int getTotalNumberOfChannels(){return ((int)getNumberOfChannelsPerChip() * (int)getNumberOfChips());} +int getNumberOfChips(){return NCHIP;} +int getNumberOfDACs(){return NDAC;} +int getNumberOfChannelsPerChip(){return NCHAN;} + + diff --git a/slsDetectorSoftware/mythen3DetectorServer/slsDetectorFunctionList.h b/slsDetectorServers/gotthardDetectorServer/slsDetectorFunctionList.h similarity index 100% rename from slsDetectorSoftware/mythen3DetectorServer/slsDetectorFunctionList.h rename to slsDetectorServers/gotthardDetectorServer/slsDetectorFunctionList.h diff --git a/slsDetectorSoftware/mythen3DetectorServer/slsDetectorServer.c b/slsDetectorServers/gotthardDetectorServer/slsDetectorServer.c similarity index 100% rename from slsDetectorSoftware/mythen3DetectorServer/slsDetectorServer.c rename to slsDetectorServers/gotthardDetectorServer/slsDetectorServer.c diff --git a/slsDetectorServers/gotthardDetectorServer/slsDetectorServer_defs.h b/slsDetectorServers/gotthardDetectorServer/slsDetectorServer_defs.h new file mode 100755 index 000000000..6c037e852 --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/slsDetectorServer_defs.h @@ -0,0 +1,123 @@ +#pragma once +#include "sls_detector_defs.h" +#include + +/* Enums */ +enum ADCINDEX {TEMP_FPGA, TEMP_ADC}; +enum DACINDEX {VREF_DS, VCASCN_PB, VCASCP_PB, VOUT_CM, VCASC_OUT, VIN_CM, VREF_COMP, IB_TESTC}; +#define DEFAULT_DAC_VALS { \ + 660, /* VREF_DS */ \ + 650, /* VCASCN_PB */ \ + 1480, /* VCASCP_PB */ \ + 1520, /* VOUT_CM */ \ + 1320, /* VCASC_OUT */ \ + 1350, /* VIN_CM */ \ + 350, /* VREF_COMP */ \ + 2001 /* IB_TESTC */ \ + }; + +/* for 25 um */ +#define CONFIG_FILE "config.txt" + +/* Hardware Definitions */ +#define NCHAN (128) +#define NCHIP (10) +#define NDAC (8) +#define NCHIPS_PER_ADC (2) +#define DYNAMIC_RANGE (16) +#define NUM_BITS_PER_PIXEL (DYNAMIC_RANGE / 8) +#define DATA_BYTES (NCHIP * NCHAN * NUM_BITS_PER_PIXEL) +#define CLK_FREQ (32.007729) /* MHz */ + +/** Firmware Definitions */ +#define IP_PACKET_SIZE_NO_ROI (NCHIP * (NCHAN / 2) * 2 + 14 + 20) // 2 packets, so divide by 2 +#define IP_PACKET_SIZE_ROI (NCHIPS_PER_ADC * NCHAN * 2 + 14 + 20) + +#define UDP_PACKETSIZE_NO_ROI (NCHIP * (NCHAN / 2) * 2 + 4 + 8 + 2) // 2 packets, so divide by 2 +#define UDP_PACKETSIZE_ROI (NCHIPS_PER_ADC * NCHAN * 2 + 4 + 8 + 2) + +/** Default Parameters */ +#define DEFAULT_NUM_FRAMES (1) +#define DEFAULT_NUM_CYCLES (1) +#define DEFAULT_EXPTIME (1 * 1000 * 1000) // 1 ms +#define DEFAULT_PERIOD (1 * 1000 * 1000 * 1000) // 1 s +#define DEFAULT_DELAY (0) +#define DEFAULT_SETTINGS (DYNAMICGAIN) +#define DEFAULT_TIMING_MODE (AUTO_TIMING) +#define DEFAULT_TRIGGER_MODE (TRIGGER_IN_RISING_EDGE) +#define DEFAULT_HIGH_VOLTAGE (0) +#define DEFAULT_PHASE_SHIFT (120) +#define DEFAULT_TX_UDP_PORT (0xE185) + +#define DAC_MIN_MV (0) +#define DAC_MAX_MV (2500) + +/** ENEt conf structs */ +typedef struct mac_header_struct{ + u_int8_t mac_dest_mac2; + u_int8_t mac_dest_mac1; + u_int8_t mac_dummy1; + u_int8_t mac_dummy2; + u_int8_t mac_dest_mac6; + u_int8_t mac_dest_mac5; + u_int8_t mac_dest_mac4; + u_int8_t mac_dest_mac3; + u_int8_t mac_src_mac4; + u_int8_t mac_src_mac3; + u_int8_t mac_src_mac2; + u_int8_t mac_src_mac1; + u_int16_t mac_ether_type; + u_int8_t mac_src_mac6; + u_int8_t mac_src_mac5; +} mac_header; + +typedef struct ip_header_struct { + u_int16_t ip_len; + u_int8_t ip_tos; + u_int8_t ip_ihl:4 ,ip_ver:4; + u_int16_t ip_offset:13,ip_flag:3; + u_int16_t ip_ident; + u_int16_t ip_chksum; + u_int8_t ip_protocol; + u_int8_t ip_ttl; + u_int32_t ip_sourceip; + u_int32_t ip_destip; +} ip_header; + +typedef struct udp_header_struct{ + u_int16_t udp_destport; + u_int16_t udp_srcport; + u_int16_t udp_chksum; + u_int16_t udp_len; +} udp_header; + +typedef struct mac_conf_struct{ + mac_header mac; + ip_header ip; + udp_header udp; + u_int32_t npack; + u_int32_t lpack; + u_int32_t npad; + u_int32_t cdone; +} mac_conf; + +typedef struct tse_conf_struct{ + u_int32_t rev; //0x0 + u_int32_t scratch; + u_int32_t command_config; + u_int32_t mac_0; //0x3 + u_int32_t mac_1; + u_int32_t frm_length; + u_int32_t pause_quant; + u_int32_t rx_section_empty; //0x7 + u_int32_t rx_section_full; + u_int32_t tx_section_empty; + u_int32_t tx_section_full; + u_int32_t rx_almost_empty; //0xB + u_int32_t rx_almost_full; + u_int32_t tx_almost_empty; + u_int32_t tx_almost_full; + u_int32_t mdio_addr0; //0xF + u_int32_t mdio_addr1; +}tse_conf; + diff --git a/slsDetectorSoftware/mythen3DetectorServer/slsDetectorServer_funcs.c b/slsDetectorServers/gotthardDetectorServer/slsDetectorServer_funcs.c similarity index 100% rename from slsDetectorSoftware/mythen3DetectorServer/slsDetectorServer_funcs.c rename to slsDetectorServers/gotthardDetectorServer/slsDetectorServer_funcs.c diff --git a/slsDetectorSoftware/mythen3DetectorServer/slsDetectorServer_funcs.h b/slsDetectorServers/gotthardDetectorServer/slsDetectorServer_funcs.h similarity index 100% rename from slsDetectorSoftware/mythen3DetectorServer/slsDetectorServer_funcs.h rename to slsDetectorServers/gotthardDetectorServer/slsDetectorServer_funcs.h diff --git a/slsDetectorServers/gotthardDetectorServer/sls_detector_defs.h b/slsDetectorServers/gotthardDetectorServer/sls_detector_defs.h new file mode 120000 index 000000000..2af30d73a --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/sls_detector_defs.h @@ -0,0 +1 @@ +../../slsSupportLib/include/sls_detector_defs.h \ No newline at end of file diff --git a/slsDetectorServers/gotthardDetectorServer/sls_detector_funcs.h b/slsDetectorServers/gotthardDetectorServer/sls_detector_funcs.h new file mode 120000 index 000000000..3f48959a9 --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/sls_detector_funcs.h @@ -0,0 +1 @@ +../../slsSupportLib/include/sls_detector_funcs.h \ No newline at end of file diff --git a/slsDetectorServers/gotthardDetectorServer/versionAPI.h b/slsDetectorServers/gotthardDetectorServer/versionAPI.h new file mode 120000 index 000000000..5e580d8bb --- /dev/null +++ b/slsDetectorServers/gotthardDetectorServer/versionAPI.h @@ -0,0 +1 @@ +../../slsSupportLib/include/versionAPI.h \ No newline at end of file diff --git a/slsDetectorSoftware/mythen3DetectorServer/AD9257.h b/slsDetectorServers/jungfrauDetectorServer/AD9257.h similarity index 100% rename from slsDetectorSoftware/mythen3DetectorServer/AD9257.h rename to slsDetectorServers/jungfrauDetectorServer/AD9257.h diff --git a/slsDetectorServers/jungfrauDetectorServer/ALTERA_PLL.h b/slsDetectorServers/jungfrauDetectorServer/ALTERA_PLL.h new file mode 120000 index 000000000..e665f009d --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/ALTERA_PLL.h @@ -0,0 +1 @@ +../slsDetectorServer/ALTERA_PLL.h \ No newline at end of file diff --git a/slsDetectorServers/jungfrauDetectorServer/LTC2620.h b/slsDetectorServers/jungfrauDetectorServer/LTC2620.h new file mode 120000 index 000000000..13157cb8b --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/LTC2620.h @@ -0,0 +1 @@ +../slsDetectorServer/LTC2620.h \ No newline at end of file diff --git a/slsDetectorServers/jungfrauDetectorServer/MAX1932.h b/slsDetectorServers/jungfrauDetectorServer/MAX1932.h new file mode 120000 index 000000000..8f7b239ea --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/MAX1932.h @@ -0,0 +1 @@ +../slsDetectorServer/MAX1932.h \ No newline at end of file diff --git a/slsDetectorServers/jungfrauDetectorServer/Makefile b/slsDetectorServers/jungfrauDetectorServer/Makefile new file mode 100755 index 000000000..f197d60dd --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/Makefile @@ -0,0 +1,34 @@ +CROSS = bfin-uclinux- +CC = $(CROSS)gcc +CFLAGS += -Wall -DJUNGFRAUD -DSTOP_SERVER #-DVERBOSEI #-DVERBOSE +LDLIBS += -lm -lstdc++ + +PROGS = jungfrauDetectorServer +DESTDIR ?= bin +INSTMODE = 0777 + +SRC_CLNT = communication_funcs.c slsDetectorServer.c slsDetectorServer_funcs.c slsDetectorFunctionList.c +OBJS = $(SRC_CLNT:.c=.o) + +all: clean versioning $(PROGS) + +boot: $(OBJS) + +version_name=APIJUNGFRAU +version_path=slsDetectorServers/jungfrauDetectorServer +versioning: + cd ../../ && echo $(PWD) && echo `tput setaf 6; ./updateAPIVersion.sh $(version_name) $(version_path); tput sgr0;` + + +$(PROGS): $(OBJS) +# echo $(OBJS) + mkdir -p $(DESTDIR) + $(CC) -o $@ $^ $(CFLAGS) $(LDLIBS) + mv $(PROGS) $(DESTDIR) + rm *.gdb + +clean: + rm -rf $(DESTDIR)/$(PROGS) *.o *.gdb + + + \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/Makefile.virtual b/slsDetectorServers/jungfrauDetectorServer/Makefile.virtual old mode 100644 new mode 100755 similarity index 82% rename from slsDetectorSoftware/jungfrauDetectorServer/Makefile.virtual rename to slsDetectorServers/jungfrauDetectorServer/Makefile.virtual index 97b4812d6..e38c85ca0 --- a/slsDetectorSoftware/jungfrauDetectorServer/Makefile.virtual +++ b/slsDetectorServers/jungfrauDetectorServer/Makefile.virtual @@ -1,5 +1,5 @@ CC = gcc -CFLAGS += -Wall -DJUNGFRAUD -DVIRTUAL -DSLS_DETECTOR_FUNCTION_LIST -DDACS_INT -DSTOP_SERVER #-DVERBOSEI #-DVERBOSE +CFLAGS += -Wall -DJUNGFRAUD -DVIRTUAL -DSTOP_SERVER #-DVERBOSEI #-DVERBOSE LDLIBS += -lm -lstdc++ -pthread PROGS = jungfrauDetectorServer_virtual diff --git a/slsDetectorSoftware/jungfrauDetectorServer/RegisterDefs.h b/slsDetectorServers/jungfrauDetectorServer/RegisterDefs.h old mode 100644 new mode 100755 similarity index 85% rename from slsDetectorSoftware/jungfrauDetectorServer/RegisterDefs.h rename to slsDetectorServers/jungfrauDetectorServer/RegisterDefs.h index 1c7742e86..0129d8be9 --- a/slsDetectorSoftware/jungfrauDetectorServer/RegisterDefs.h +++ b/slsDetectorServers/jungfrauDetectorServer/RegisterDefs.h @@ -1,7 +1,7 @@ -#ifndef REGISTER_DEFS_H -#define REGISTER_DEFS_H +#pragma once /* Definitions for FPGA*/ +#define MEM_MAP_SHIFT 1 /* FPGA Version register */ #define FPGA_VERSION_REG (0x00 << MEM_MAP_SHIFT) @@ -11,6 +11,8 @@ #define DETECTOR_TYPE_OFST (24) #define DETECTOR_TYPE_MSK (0x000000FF << DETECTOR_TYPE_OFST) + + /* Fix pattern register */ #define FIX_PATT_REG (0x01 << MEM_MAP_SHIFT) @@ -32,6 +34,7 @@ #define RUNMACHINE_BUSY_OFST (17) #define RUNMACHINE_BUSY_MSK (0x00000001 << RUNMACHINE_BUSY_OFST) + /* Look at me register */ #define LOOK_AT_ME_REG (0x03 << MEM_MAP_SHIFT) //Not used in firmware or software @@ -92,12 +95,14 @@ /** Get Temperature Carlos, incorrectl as get gates */ #define GET_TEMPERATURE_TMP112_REG (0x1c << MEM_MAP_SHIFT) // (after multiplying by 625) in 10ths of millidegrees of TMP112 -#define TEMPERATURE_VALUE_BIT (0) -#define TEMPERATURE_VALUE_MSK (0x000007FF << TEMPERATURE_VALUE_BIT) -#define TEMPERATURE_POLARITY_BIT (11) -#define TEMPERATURE_POLARITY_MSK (0x00000001 << TEMPERATURE_POLARITY_BIT) +#define TEMPERATURE_VALUE_BIT (0) +#define TEMPERATURE_VALUE_MSK (0x000007FF << TEMPERATURE_VALUE_BIT) +#define TEMPERATURE_POLARITY_BIT (11) +#define TEMPERATURE_POLARITY_MSK (0x00000001 << TEMPERATURE_POLARITY_BIT) -/* Get Frames from Start 64 bit register (frames from last reset using CONTROL_CRST) */ + + +/* Get Frames from Start 64 bit register (frames from last reset using CONTROL_CRST) */ #define FRAMES_FROM_START_PG_LSB_REG (0x24 << MEM_MAP_SHIFT) #define FRAMES_FROM_START_PG_MSB_REG (0x25 << MEM_MAP_SHIFT) @@ -108,29 +113,28 @@ /* SPI (Serial Peripheral Interface) Register */ #define SPI_REG (0x40 << MEM_MAP_SHIFT) -#define DAC_SERIAL_DIGITAL_OUT_OFST (0) -#define DAC_SERIAL_DIGITAL_OUT_MSK (0x00000001 << DAC_SERIAL_DIGITAL_OUT_OFST) -#define DAC_SERIAL_CLK_OUT_OFST (1) -#define DAC_SERIAL_CLK_OUT_MSK (0x00000001 << DAC_SERIAL_CLK_OUT_OFST) -#define DAC_SERIAL_CS_OUT_OFST (2) -#define DAC_SERIAL_CS_OUT_MSK (0x00000001 << DAC_SERIAL_CS_OUT_OFST) -#define HV_SERIAL_DIGITAL_OUT_OFST (8) -#define HV_SERIAL_DIGITAL_OUT_MSK (0x00000001 << HV_SERIAL_DIGITAL_OUT_OFST) -#define HV_SERIAL_CLK_OUT_OFST (9) -#define HV_SERIAL_CLK_OUT_MSK (0x00000001 << HV_SERIAL_CLK_OUT_OFST) -#define HV_SERIAL_CS_OUT_OFST (10) -#define HV_SERIAL_CS_OUT_MSK (0x00000001 << HV_SERIAL_CS_OUT_OFST) - +#define SPI_DAC_SRL_DGTL_OTPT_OFST (0) +#define SPI_DAC_SRL_DGTL_OTPT_MSK (0x00000001 << SPI_DAC_SRL_DGTL_OTPT_OFST) +#define SPI_DAC_SRL_CLK_OTPT_OFST (1) +#define SPI_DAC_SRL_CLK_OTPT_MSK (0x00000001 << SPI_DAC_SRL_CLK_OTPT_OFST) +#define SPI_DAC_SRL_CS_OTPT_OFST (2) +#define SPI_DAC_SRL_CS_OTPT_MSK (0x00000001 << SPI_DAC_SRL_CS_OTPT_OFST) +#define SPI_HV_SRL_DGTL_OTPT_OFST (8) +#define SPI_HV_SRL_DGTL_OTPT_MSK (0x00000001 << SPI_HV_SRL_DGTL_OTPT_OFST) +#define SPI_HV_SRL_CLK_OTPT_OFST (9) +#define SPI_HV_SRL_CLK_OTPT_MSK (0x00000001 << SPI_HV_SRL_CLK_OTPT_OFST) +#define SPI_HV_SRL_CS_OTPT_OFST (10) +#define SPI_HV_SRL_CS_OTPT_MSK (0x00000001 << SPI_HV_SRL_CS_OTPT_OFST) /* ADC SPI (Serial Peripheral Interface) Register */ #define ADC_SPI_REG (0x41 << MEM_MAP_SHIFT) -#define ADC_SERIAL_CLK_OUT_OFST (0) -#define ADC_SERIAL_CLK_OUT_MSK (0x00000001 << ADC_SERIAL_CLK_OUT_OFST) -#define ADC_SERIAL_DATA_OUT_OFST (1) -#define ADC_SERIAL_DATA_OUT_MSK (0x00000001 << ADC_SERIAL_DATA_OUT_OFST) -#define ADC_SERIAL_CS_OUT_OFST (2) -#define ADC_SERIAL_CS_OUT_MSK (0x0000000F << ADC_SERIAL_CS_OUT_OFST) +#define ADC_SPI_SRL_CLK_OTPT_OFST (0) +#define ADC_SPI_SRL_CLK_OTPT_MSK (0x00000001 << ADC_SPI_SRL_CLK_OTPT_OFST) +#define ADC_SPI_SRL_DT_OTPT_OFST (1) +#define ADC_SPI_SRL_DT_OTPT_MSK (0x00000001 << ADC_SPI_SRL_DT_OTPT_OFST) +#define ADC_SPI_SRL_CS_OTPT_OFST (2) +#define ADC_SPI_SRL_CS_OTPT_MSK (0x0000000F << ADC_SPI_SRL_CS_OTPT_OFST) /* ADC offset Register */ #define ADC_OFST_REG (0x42 << MEM_MAP_SHIFT) @@ -191,8 +195,8 @@ // readout timer (from chip) to stabilize (esp in burst acquisition mode) tRDT = (RDT + 1) * 25ns #define CONFIG_RDT_TMR_OFST (0) #define CONFIG_RDT_TMR_MSK (0x0000FFFF << CONFIG_RDT_TMR_OFST) -#define CONFIG_OPRTN_MDE_2_X_10GbE_OFST (16) -#define CONFIG_OPRTN_MDE_2_X_10GbE_MSK (0x00000001 << CONFIG_OPRTN_MDE_2_X_10GbE_OFST) +#define CONFIG_OPRTN_MDE_2_X_10GbE_OFST (16) +#define CONFIG_OPRTN_MDE_2_X_10GbE_MSK (0x00000001 << CONFIG_OPRTN_MDE_2_X_10GbE_OFST) #define CONFIG_OPRTN_MDE_1_X_10GBE_VAL ((0x0 << CONFIG_OPRTN_MDE_2_X_10GbE_OFST) & CONFIG_OPRTN_MDE_2_X_10GbE_MSK) #define CONFIG_READOUT_SPEED_OFST (20) #define CONFIG_READOUT_SPEED_MSK (0x00000003 << CONFIG_READOUT_SPEED_OFST) @@ -202,7 +206,7 @@ #define CONFIG_TDMA_OFST (24) #define CONFIG_TDMA_MSK (0x00000001 << CONFIG_TDMA_OFST) #define CONFIG_TDMA_DISABLE_VAL ((0x0 << CONFIG_TDMA_OFST) & CONFIG_TDMA_MSK) -#define CONFIG_TDMA_TIMESLOT_OFST (25) // 1ms +#define CONFIG_TDMA_TIMESLOT_OFST (25) // 1ms #define CONFIG_TDMA_TIMESLOT_MSK (0x0000001F << CONFIG_TDMA_TIMESLOT_OFST) #define CONFIG_ETHRNT_FLW_CNTRL_OFST (31) #define CONFIG_ETHRNT_FLW_CNTRL_MSK (0x00000001 << CONFIG_ETHRNT_FLW_CNTRL_OFST) @@ -235,18 +239,18 @@ #define PLL_PARAM_REG (0x50 << MEM_MAP_SHIFT) /* Reconfiguratble PLL Control Regiser */ -#define PLL_CONTROL_REG (0x51 << MEM_MAP_SHIFT) +#define PLL_CNTRL_REG (0x51 << MEM_MAP_SHIFT) -#define PLL_CTRL_RECONFIG_RST_OFST (0) //parameter reset -#define PLL_CTRL_RECONFIG_RST_MSK (0x00000001 << PLL_CTRL_RECONFIG_RST_OFST) //parameter reset -#define PLL_CTRL_WR_PARAMETER_OFST (2) -#define PLL_CTRL_WR_PARAMETER_MSK (0x00000001 << PLL_CTRL_WR_PARAMETER_OFST) -#define PLL_CTRL_RST_OFST (3) -#define PLL_CTRL_RST_MSK (0x00000001 << PLL_CTRL_RST_OFST) -#define PLL_CTRL_ADDR_OFST (16) -#define PLL_CTRL_ADDR_MSK (0x0000003F << PLL_CTRL_ADDR_OFST) +#define PLL_CNTRL_RCNFG_PRMTR_RST_OFST (0) //parameter reset +#define PLL_CNTRL_RCNFG_PRMTR_RST_MSK (0x00000001 << PLL_CNTRL_RCNFG_PRMTR_RST_OFST) //parameter reset +#define PLL_CNTRL_WR_PRMTR_OFST (2) +#define PLL_CNTRL_WR_PRMTR_MSK (0x00000001 << PLL_CNTRL_WR_PRMTR_OFST) +#define PLL_CNTRL_PLL_RST_OFST (3) +#define PLL_CNTRL_PLL_RST_MSK (0x00000001 << PLL_CNTRL_PLL_RST_OFST) +#define PLL_CNTRL_ADDR_OFST (16) +#define PLL_CNTRL_ADDR_MSK (0x0000003F << PLL_CNTRL_ADDR_OFST) -/* Sample Register (Obsolete) */ +/* Sample Register */ #define SAMPLE_REG (0x59 << MEM_MAP_SHIFT) #define SAMPLE_ADC_SAMPLE_SEL_OFST (0) @@ -357,6 +361,7 @@ #define TEMP_CTRL_OVR_TMP_EVNT_OFST (31) #define TEMP_CTRL_OVR_TMP_EVNT_MSK (0x00000001 << TEMP_CTRL_OVR_TMP_EVNT_OFST) + /* Set Delay 64 bit register */ #define SET_DELAY_LSB_REG (0x60 << MEM_MAP_SHIFT) // different kind of delay #define SET_DELAY_MSB_REG (0x61 << MEM_MAP_SHIFT) // different kind of delay @@ -373,7 +378,7 @@ #define SET_PERIOD_LSB_REG (0x66 << MEM_MAP_SHIFT) #define SET_PERIOD_MSB_REG (0x67 << MEM_MAP_SHIFT) -/* Set Exposure Time 64 bit register eEXP = Exp x 25 ns */ +/* Set Exptime 64 bit register eEXP = Exp x 25 ns */ #define SET_EXPTIME_LSB_REG (0x68 << MEM_MAP_SHIFT) #define SET_EXPTIME_MSB_REG (0x69 << MEM_MAP_SHIFT) @@ -406,18 +411,31 @@ #define ASIC_CTRL_DS_TMR_MSK (0x000000FF << ASIC_CTRL_DS_TMR_OFST) #define ASIC_CTRL_DS_TMR_VAL ((0x1F << ASIC_CTRL_DS_TMR_OFST) & ASIC_CTRL_DS_TMR_MSK) // tET = (ET + 1) * 25ns (increase timeout range between 2 consecutive storage cells) +#define ASIC_CTRL_EXPSRE_TMR_STEPS (25) #define ASIC_CTRL_EXPSRE_TMR_OFST (16) #define ASIC_CTRL_EXPSRE_TMR_MSK (0x0000FFFF << ASIC_CTRL_EXPSRE_TMR_OFST) -#endif //REGISTERS_G_H - - - - - - - + +/* ADC 0 Deserializer Control */ +#define ADC_DSRLZR_0_REG (0xF0 << MEM_MAP_SHIFT) +#define ADC_DSRLZR_0_RFRSH_ALGNMNT_OFST (31) /* Refresh alignment */ +#define ADC_DSRLZR_0_RFRSH_ALGNMNT_MSK (0x00000001 << ADC_DSRLZR_0_RFRSH_ALGNMNT_OFST) + +/* ADC 0 Deserializer Control */ +#define ADC_DSRLZR_1_REG (0xF1 << MEM_MAP_SHIFT) +#define ADC_DSRLZR_1_RFRSH_ALGNMNT_OFST (31) +#define ADC_DSRLZR_1_RFRSH_ALGNMNT_MSK (0x00000001 << ADC_DSRLZR_1_RFRSH_ALGNMNT_OFST) + +/* ADC 0 Deserializer Control */ +#define ADC_DSRLZR_2_REG (0xF2 << MEM_MAP_SHIFT) +#define ADC_DSRLZR_2_RFRSH_ALGNMNT_OFST (31) +#define ADC_DSRLZR_2_RFRSH_ALGNMNT_MSK (0x00000001 << ADC_DSRLZR_2_RFRSH_ALGNMNT_OFST) + +/* ADC 0 Deserializer Control */ +#define ADC_DSRLZR_3_REG (0xF3 << MEM_MAP_SHIFT) +#define ADC_DSRLZR_3_RFRSH_ALGNMNT_OFST (31) +#define ADC_DSRLZR_3_RFRSH_ALGNMNT_MSK (0x00000001 << ADC_DSRLZR_3_RFRSH_ALGNMNT_OFST) diff --git a/slsDetectorServers/jungfrauDetectorServer/ansi.h b/slsDetectorServers/jungfrauDetectorServer/ansi.h new file mode 120000 index 000000000..4a82d0575 --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/ansi.h @@ -0,0 +1 @@ +../../slsSupportLib/include/ansi.h \ No newline at end of file diff --git a/slsDetectorServers/jungfrauDetectorServer/bin/jungfrauDetectorServer_refactor b/slsDetectorServers/jungfrauDetectorServer/bin/jungfrauDetectorServer_refactor new file mode 100755 index 000000000..ab33ee121 Binary files /dev/null and b/slsDetectorServers/jungfrauDetectorServer/bin/jungfrauDetectorServer_refactor differ diff --git a/slsDetectorServers/jungfrauDetectorServer/bin/jungfrauDetectorServer_virtual b/slsDetectorServers/jungfrauDetectorServer/bin/jungfrauDetectorServer_virtual new file mode 100755 index 000000000..4c211698f Binary files /dev/null and b/slsDetectorServers/jungfrauDetectorServer/bin/jungfrauDetectorServer_virtual differ diff --git a/slsDetectorServers/jungfrauDetectorServer/blackfin.h b/slsDetectorServers/jungfrauDetectorServer/blackfin.h new file mode 120000 index 000000000..2873c7dc6 --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/blackfin.h @@ -0,0 +1 @@ +../slsDetectorServer/blackfin.h \ No newline at end of file diff --git a/slsDetectorServers/jungfrauDetectorServer/common.h b/slsDetectorServers/jungfrauDetectorServer/common.h new file mode 120000 index 000000000..6776eb607 --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/common.h @@ -0,0 +1 @@ +../slsDetectorServer/common.h \ No newline at end of file diff --git a/slsDetectorSoftware/mythen3DetectorServer/commonServerFunctions.h b/slsDetectorServers/jungfrauDetectorServer/commonServerFunctions.h similarity index 100% rename from slsDetectorSoftware/mythen3DetectorServer/commonServerFunctions.h rename to slsDetectorServers/jungfrauDetectorServer/commonServerFunctions.h diff --git a/slsDetectorServers/jungfrauDetectorServer/communication_funcs.c b/slsDetectorServers/jungfrauDetectorServer/communication_funcs.c new file mode 120000 index 000000000..30435fdc4 --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/communication_funcs.c @@ -0,0 +1 @@ +../slsDetectorServer/communication_funcs.c \ No newline at end of file diff --git a/slsDetectorServers/jungfrauDetectorServer/communication_funcs.h b/slsDetectorServers/jungfrauDetectorServer/communication_funcs.h new file mode 120000 index 000000000..c0c144994 --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/communication_funcs.h @@ -0,0 +1 @@ +../slsDetectorServer/communication_funcs.h \ No newline at end of file diff --git a/slsDetectorServers/jungfrauDetectorServer/logger.h b/slsDetectorServers/jungfrauDetectorServer/logger.h new file mode 120000 index 000000000..ff1930ce3 --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/logger.h @@ -0,0 +1 @@ +../slsDetectorServer/logger.h \ No newline at end of file diff --git a/slsDetectorSoftware/mythen3DetectorServer/programfpga.h b/slsDetectorServers/jungfrauDetectorServer/programfpga.h similarity index 100% rename from slsDetectorSoftware/mythen3DetectorServer/programfpga.h rename to slsDetectorServers/jungfrauDetectorServer/programfpga.h diff --git a/slsDetectorServers/jungfrauDetectorServer/slsDetectorFunctionList.c b/slsDetectorServers/jungfrauDetectorServer/slsDetectorFunctionList.c new file mode 100755 index 000000000..bf6721e63 --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/slsDetectorFunctionList.c @@ -0,0 +1,1604 @@ +#include "slsDetectorFunctionList.h" +#include "versionAPI.h" +#include "logger.h" + +#include "AD9257.h" // commonServerFunctions.h, blackfin.h, ansi.h +#include "LTC2620.h" // dacs +#include "MAX1932.h" // hv +#include "ALTERA_PLL.h" // pll +#ifndef VIRTUAL +#include "programfpga.h" +#else +#include "blackfin.h" +#include +#include // usleep +#include +#include +#endif + +// Global variable from slsDetectorServer_funcs +extern int debugflag; + +int firmware_compatibility = OK; +int firmware_check_done = 0; +char firmware_message[MAX_STR_LENGTH]; + +#ifdef VIRTUAL +pthread_t pthread_virtual_tid; +int virtual_status = 0; +int virtual_stop = 0; +#endif + +enum detectorSettings thisSettings = UNINITIALIZED; +int highvoltage = 0; +int dacValues[NDAC] = {0}; +int adcPhase = 0; + + +int isFirmwareCheckDone() { + return firmware_check_done; +} + +int getFirmwareCheckResult(char** mess) { + *mess = firmware_message; + return firmware_compatibility; +} + +void basictests() { + firmware_compatibility = OK; + firmware_check_done = 0; + memset(firmware_message, 0, MAX_STR_LENGTH); +#ifdef VIRTUAL + FILE_LOG(logINFOBLUE, ("******** Jungfrau Virtual Server *****************\n")); + if (mapCSP0() == FAIL) { + strcpy(firmware_message, + "Could not map to memory. Dangerous to continue.\n"); + FILE_LOG(logERROR, (firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + firmware_check_done = 1; + return; +#else + + defineGPIOpins(); + resetFPGA(); + if (mapCSP0() == FAIL) { + strcpy(firmware_message, + "Could not map to memory. Dangerous to continue.\n"); + FILE_LOG(logERROR, ("%s\n\n", firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + + // does check only if flag is 0 (by default), set by command line + if ((!debugflag) && ((checkType() == FAIL) || (testFpga() == FAIL) || (testBus() == FAIL))) { + strcpy(firmware_message, + "Could not pass basic tests of FPGA and bus. Dangerous to continue.\n"); + FILE_LOG(logERROR, ("%s\n\n", firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + + uint16_t hversion = getHardwareVersionNumber(); + uint16_t hsnumber = getHardwareSerialNumber(); + uint32_t ipadd = getDetectorIP(); + uint64_t macadd = getDetectorMAC(); + int64_t fwversion = getDetectorId(DETECTOR_FIRMWARE_VERSION); + int64_t swversion = getDetectorId(DETECTOR_SOFTWARE_VERSION); + int64_t sw_fw_apiversion = 0; + int64_t client_sw_apiversion = getDetectorId(CLIENT_SOFTWARE_API_VERSION); + + + if (fwversion >= MIN_REQRD_VRSN_T_RD_API) + sw_fw_apiversion = getDetectorId(SOFTWARE_FIRMWARE_API_VERSION); + FILE_LOG(logINFOBLUE, ("************ Jungfrau Server *********************\n" + "Hardware Version:\t\t 0x%x\n" + "Hardware Serial Nr:\t\t 0x%x\n" + + "Detector IP Addr:\t\t 0x%x\n" + "Detector MAC Addr:\t\t 0x%llx\n\n" + + "Firmware Version:\t\t 0x%llx\n" + "Software Version:\t\t 0x%llx\n" + "F/w-S/w API Version:\t\t 0x%llx\n" + "Required Firmware Version:\t 0x%x\n" + "Client-Software API Version:\t 0x%llx\n" + "********************************************************\n", + hversion, hsnumber, + ipadd, + (long long unsigned int)macadd, + (long long int)fwversion, + (long long int)swversion, + (long long int)sw_fw_apiversion, + REQRD_FRMWR_VRSN, + (long long int)client_sw_apiversion + )); + + // return if flag is not zero, debug mode + if (debugflag) { + firmware_check_done = 1; + return; + } + + + //cant read versions + FILE_LOG(logINFO, ("Testing Firmware-software compatibility:\n")); + if(!fwversion || !sw_fw_apiversion){ + strcpy(firmware_message, + "Cant read versions from FPGA. Please update firmware.\n"); + FILE_LOG(logERROR, (firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + + //check for API compatibility - old server + if(sw_fw_apiversion > REQRD_FRMWR_VRSN){ + sprintf(firmware_message, + "This detector software software version (0x%llx) is incompatible.\n" + "Please update detector software (min. 0x%llx) to be compatible with this firmware.\n", + (long long int)sw_fw_apiversion, + (long long int)REQRD_FRMWR_VRSN); + FILE_LOG(logERROR, (firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + + //check for firmware compatibility - old firmware + if( REQRD_FRMWR_VRSN > fwversion) { + sprintf(firmware_message, + "This firmware version (0x%llx) is incompatible.\n" + "Please update firmware (min. 0x%llx) to be compatible with this server.\n", + (long long int)fwversion, + (long long int)REQRD_FRMWR_VRSN); + FILE_LOG(logERROR, (firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + FILE_LOG(logINFO, ("Compatibility - success\n")); + firmware_check_done = 1; +#endif +} + + +int checkType() { +#ifdef VIRTUAL + return OK; +#endif + volatile u_int32_t type = ((bus_r(FPGA_VERSION_REG) & DETECTOR_TYPE_MSK) >> DETECTOR_TYPE_OFST); + if (type != BOARD_JUNGFRAU_TYPE){ + FILE_LOG(logERROR, ("This is not a Jungfrau Server (read %d, expected %d)\n", type, BOARD_JUNGFRAU_TYPE)); + return FAIL; + } + + return OK; +} + + + +int testFpga() { +#ifdef VIRTUAL + return OK; +#endif + FILE_LOG(logINFO, ("Testing FPGA:\n")); + + //fixed pattern + int ret = OK; + volatile u_int32_t val = bus_r(FIX_PATT_REG); + if (val == FIX_PATT_VAL) { + FILE_LOG(logINFO, ("Fixed pattern: successful match 0x%08x\n",val)); + } else { + FILE_LOG(logERROR, ("Fixed pattern does not match! Read 0x%08x, expected 0x%08x\n", val, FIX_PATT_VAL)); + ret = FAIL; + } + return ret; +} + + +int testBus() { +#ifdef VIRTUAL + return OK; +#endif + FILE_LOG(logINFO, ("Testing Bus:\n")); + + int ret = OK; + u_int32_t addr = SET_TRIGGER_DELAY_LSB_REG; + int times = 1000 * 1000; + int i = 0; + + for (i = 0; i < times; ++i) { + bus_w(addr, i * 100); + if (i * 100 != bus_r(addr)) { + FILE_LOG(logERROR, ("Mismatch! Wrote 0x%x, read 0x%x\n", + i * 100, bus_r(addr))); + ret = FAIL; + } + } + + bus_w(addr, 0); + + if (ret == OK) { + FILE_LOG(logINFO, ("Successfully tested bus %d times\n", times)); + } + return ret; +} + + + +int detectorTest( enum digitalTestMode arg){ +#ifdef VIRTUAL + return OK; +#endif + switch(arg){ + case DETECTOR_FIRMWARE_TEST: return testFpga(); + case DETECTOR_BUS_TEST: return testBus(); + //DETECTOR_MEMORY_TEST:testRAM + //DETECTOR_SOFTWARE_TEST: + default: + FILE_LOG(logERROR, ("Test %s not implemented for this detector\n", (int)arg)); + break; + } + return OK; +} + + + + + +/* Ids */ + +int64_t getDetectorId(enum idMode arg){ + int64_t retval = -1; + + switch(arg){ + case DETECTOR_SERIAL_NUMBER: + return getDetectorNumber();// or getDetectorMAC() + case DETECTOR_FIRMWARE_VERSION: + return getFirmwareVersion(); + case SOFTWARE_FIRMWARE_API_VERSION: + return getFirmwareAPIVersion(); + case DETECTOR_SOFTWARE_VERSION: + case CLIENT_SOFTWARE_API_VERSION: + return APIJUNGFRAU; + default: + return retval; + } +} + +u_int64_t getFirmwareVersion() { +#ifdef VIRTUAL + return 0; +#endif + return ((bus_r(FPGA_VERSION_REG) & BOARD_REVISION_MSK) >> BOARD_REVISION_OFST); +} + +u_int64_t getFirmwareAPIVersion() { +#ifdef VIRTUAL + return 0; +#endif + return ((bus_r(API_VERSION_REG) & API_VERSION_MSK) >> API_VERSION_OFST); +} + +u_int16_t getHardwareVersionNumber() { +#ifdef VIRTUAL + return 0; +#endif + return ((bus_r(MOD_SERIAL_NUM_REG) & HARDWARE_VERSION_NUM_MSK) >> HARDWARE_VERSION_NUM_OFST); +} + +u_int16_t getHardwareSerialNumber() { +#ifdef VIRTUAL + return 0; +#endif + return ((bus_r(MOD_SERIAL_NUM_REG) & HARDWARE_SERIAL_NUM_MSK) >> HARDWARE_SERIAL_NUM_OFST); +} + +u_int32_t getDetectorNumber(){ +#ifdef VIRTUAL + return 0; +#endif + return bus_r(MOD_SERIAL_NUM_REG); +} + +u_int64_t getDetectorMAC() { +#ifdef VIRTUAL + return 0; +#else + char output[255],mac[255]=""; + u_int64_t res=0; + FILE* sysFile = popen("ifconfig eth0 | grep HWaddr | cut -d \" \" -f 11", "r"); + fgets(output, sizeof(output), sysFile); + pclose(sysFile); + //getting rid of ":" + char * pch; + pch = strtok (output,":"); + while (pch != NULL){ + strcat(mac,pch); + pch = strtok (NULL, ":"); + } + sscanf(mac,"%llx",&res); + return res; +#endif +} + +u_int32_t getDetectorIP(){ +#ifdef VIRTUAL + return 0; +#endif + char temp[50]=""; + u_int32_t res=0; + //execute and get address + char output[255]; + FILE* sysFile = popen("ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2", "r"); + fgets(output, sizeof(output), sysFile); + pclose(sysFile); + + //converting IPaddress to hex. + char* pcword = strtok (output,"."); + while (pcword != NULL) { + sprintf(output,"%02x",atoi(pcword)); + strcat(temp,output); + pcword = strtok (NULL, "."); + } + strcpy(output,temp); + sscanf(output, "%x", &res); + //FILE_LOG(logINFO, ("ip:%x\n",res); + + return res; +} + + + + + + + + +/* initialization */ + +void initControlServer(){ + setupDetector(); +} + + + +void initStopServer() { + + usleep(CTRL_SRVR_INIT_TIME_US); + if (mapCSP0() == FAIL) { + FILE_LOG(logERROR, ("Stop Server: Map Fail. Dangerous to continue. Goodbye!\n")); + exit(EXIT_FAILURE); + } +} + + + + + + +/* set up detector */ + + + + +void setupDetector() { + FILE_LOG(logINFO, ("This Server is for 1 Jungfrau module (500k)\n")); + + adcPhase = 0; + ALTERA_PLL_ResetPLL(); + resetCore(); + resetPeripheral(); + cleanFifos(); + + // hv + MAX1932_SetDefines(SPI_REG, SPI_HV_SRL_CS_OTPT_MSK, SPI_HV_SRL_CLK_OTPT_MSK, SPI_HV_SRL_DGTL_OTPT_MSK, SPI_HV_SRL_DGTL_OTPT_OFST, HIGHVOLTAGE_MIN, HIGHVOLTAGE_MAX); + MAX1932_Disable(); + setHighVoltage(DEFAULT_HIGH_VOLTAGE); + + // adc + AD9257_SetDefines(ADC_SPI_REG, ADC_SPI_SRL_CS_OTPT_MSK, ADC_SPI_SRL_CLK_OTPT_MSK, ADC_SPI_SRL_DT_OTPT_MSK, ADC_SPI_SRL_DT_OTPT_OFST); + AD9257_Disable(); + AD9257_Configure(); + + //dac + LTC2620_SetDefines(SPI_REG, SPI_DAC_SRL_CS_OTPT_MSK, SPI_DAC_SRL_CLK_OTPT_MSK, SPI_DAC_SRL_DGTL_OTPT_MSK, SPI_DAC_SRL_DGTL_OTPT_OFST, NDAC, DAC_MIN_MV, DAC_MAX_MV); + LTC2620_Disable(); + LTC2620_Configure(); + setDefaultDacs(); + + // altera pll + ALTERA_PLL_SetDefines(PLL_CNTRL_REG, PLL_PARAM_REG, PLL_CNTRL_RCNFG_PRMTR_RST_MSK, PLL_CNTRL_WR_PRMTR_MSK, PLL_CNTRL_PLL_RST_MSK, PLL_CNTRL_ADDR_MSK, PLL_CNTRL_ADDR_OFST); + + bus_w(DAQ_REG, 0x0); /* Only once at server startup */ + + FILE_LOG(logINFOBLUE, ("Setting Default parameters\n")); + setClockDivider(HALF_SPEED); + cleanFifos(); + resetCore(); + + alignDeserializer(); + + + configureASICTimer(); + bus_w(ADC_PORT_INVERT_REG, ADC_PORT_INVERT_VAL); + + //Initialization of acquistion parameters + setSettings(DEFAULT_SETTINGS); + + setTimer(FRAME_NUMBER, DEFAULT_NUM_FRAMES); + setTimer(CYCLES_NUMBER, DEFAULT_NUM_CYCLES); + setTimer(ACQUISITION_TIME, DEFAULT_EXPTIME); + setTimer(FRAME_PERIOD, DEFAULT_PERIOD); + setTimer(DELAY_AFTER_TRIGGER, DEFAULT_DELAY); + setTimer(STORAGE_CELL_NUMBER, DEFAULT_NUM_STRG_CLLS); + setTimer(STORAGE_CELL_DELAY, DEFAULT_STRG_CLL_DLY); + selectStoragecellStart(DEFAULT_STRG_CLL_STRT); + /*setClockDivider(HALF_SPEED); depends if all the previous stuff works*/ + setTiming(DEFAULT_TIMING_MODE); + + + // temp threshold and reset event + setThresholdTemperature(DEFAULT_TMP_THRSHLD); + setTemperatureEvent(0); +} + + +int setDefaultDacs() { + int ret = OK; + FILE_LOG(logINFOBLUE, ("Setting Default Dac values\n")); + { + int i = 0; + const int defaultvals[NDAC] = DEFAULT_DAC_VALS; + for(i = 0; i < NDAC; ++i) { + // if not already default, set it to default + if (dacValues[i] != defaultvals[i]) { + setDAC((enum DACINDEX)i,defaultvals[i],0); + } + } + } + return ret; +} + + + + +/* firmware functions (resets) */ + + +void cleanFifos() { +#ifdef VIRTUAL + return; +#endif + FILE_LOG(logINFO, ("Clearing Acquisition Fifos\n")); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_ACQ_FIFO_CLR_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_ACQ_FIFO_CLR_MSK); +} + +void resetCore() { +#ifdef VIRTUAL + return; +#endif + FILE_LOG(logINFO, ("Resetting Core\n")); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_CORE_RST_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_CORE_RST_MSK); + usleep(1000 * 1000); +} + +void resetPeripheral() { +#ifdef VIRTUAL + return; +#endif + FILE_LOG(logINFO, ("Resetting Peripheral\n")); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_PERIPHERAL_RST_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_PERIPHERAL_RST_MSK); +} + + + + + +/* set parameters - dr, roi */ + + + +int setDynamicRange(int dr){ + return DYNAMIC_RANGE; +} + + + + +/* parameters - speed, readout */ + +void setSpeed(enum speedVariable ind, int val, int mode) { + switch(ind) { + case CLOCK_DIVIDER: + setClockDivider(val); + case ADC_PHASE: + setAdcPhase(val, mode); + default: + return; + } +} + +int getSpeed(enum speedVariable ind, int mode) { + switch(ind) { + case CLOCK_DIVIDER: + return getClockDivider(); + case ADC_PHASE: + return getPhase(mode); + case MAX_ADC_PHASE_SHIFT: + return getMaxPhaseShift(); + default: + return -1; + } +} + + + + +/* parameters - timer */ +int selectStoragecellStart(int pos) { + if (pos >= 0) { + FILE_LOG(logINFO, ("Setting storage cell start: %d\n", pos)); + bus_w(DAQ_REG, bus_r(DAQ_REG) & ~DAQ_STRG_CELL_SLCT_MSK); + bus_w(DAQ_REG, bus_r(DAQ_REG) | ((pos << DAQ_STRG_CELL_SLCT_OFST) & DAQ_STRG_CELL_SLCT_MSK)); + } + return ((bus_r(DAQ_REG) & DAQ_STRG_CELL_SLCT_MSK) >> DAQ_STRG_CELL_SLCT_OFST); +} + + + +int64_t setTimer(enum timerIndex ind, int64_t val) { + + int64_t retval = -1; + switch(ind){ + + case FRAME_NUMBER: + if(val >= 0) { + FILE_LOG(logINFO, ("Setting #frames: %lld\n",(long long int)val)); + } + retval = set64BitReg(val, SET_FRAMES_LSB_REG, SET_FRAMES_MSB_REG); + FILE_LOG(logDEBUG1, ("Getting #frames: %lld\n", (long long int)retval)); + break; + + case ACQUISITION_TIME: + if(val >= 0){ + FILE_LOG(logINFO, ("Setting exptime: %lldns\n", (long long int)val)); + val *= (1E-3 * CLK_RUN); + val -= ACQ_TIME_MIN_CLOCK; + if(val < 0) val = 0; + } + retval = (set64BitReg(val, SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG) + ACQ_TIME_MIN_CLOCK) / (1E-3 * CLK_RUN); + FILE_LOG(logDEBUG1, ("Getting exptime: %lldns\n", (long long int)retval)); + break; + + case FRAME_PERIOD: + if(val >= 0){ + FILE_LOG(logINFO, ("Setting period: %lldns\n",(long long int)val)); + val *= (1E-3 * CLK_SYNC); + } + retval = set64BitReg(val, SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG )/ (1E-3 * CLK_SYNC); + FILE_LOG(logDEBUG1, ("Getting period: %lldns\n", (long long int)retval)); + break; + + case DELAY_AFTER_TRIGGER: + if(val >= 0){ + FILE_LOG(logINFO, ("Setting delay: %lldns\n", (long long int)val)); + val *= (1E-3 * CLK_SYNC); + } + retval = set64BitReg(val, SET_TRIGGER_DELAY_LSB_REG, SET_TRIGGER_DELAY_MSB_REG) / (1E-3 * CLK_SYNC); + FILE_LOG(logDEBUG1, ("Getting delay: %lldns\n", (long long int)retval)); + break; + + case CYCLES_NUMBER: + if(val >= 0) { + FILE_LOG(logINFO, ("Setting #cycles: %lld\n", (long long int)val)); + } + retval = set64BitReg(val, SET_CYCLES_LSB_REG, SET_CYCLES_MSB_REG); + FILE_LOG(logDEBUG1, ("Getting #cycles: %lld\n", (long long int)retval)); + break; + + case STORAGE_CELL_NUMBER: + if(val >= 0) { + FILE_LOG(logINFO, ("Setting #storage cells: %lld\n", (long long int)val)); + bus_w(CONTROL_REG, (bus_r(CONTROL_REG) & ~CONTROL_STORAGE_CELL_NUM_MSK) | + ((val << CONTROL_STORAGE_CELL_NUM_OFST) & CONTROL_STORAGE_CELL_NUM_MSK)); + } + retval = ((bus_r(CONTROL_REG) & CONTROL_STORAGE_CELL_NUM_MSK) >> CONTROL_STORAGE_CELL_NUM_OFST); + FILE_LOG(logDEBUG1, ("Getting #storage cells: %lld\n", (long long int)retval)); + break; + + case STORAGE_CELL_DELAY: + if(val >= 0){ + FILE_LOG(logINFO, ("Setting storage cell delay: %lldns\n", (long long int)val)); + val *= (1E-3 * CLK_RUN); + bus_w(ASIC_CTRL_REG, (bus_r(ASIC_CTRL_REG) & ~ASIC_CTRL_EXPSRE_TMR_MSK) | + ((val << ASIC_CTRL_EXPSRE_TMR_OFST) & ASIC_CTRL_EXPSRE_TMR_MSK)); + } + + retval = ((bus_r(ASIC_CTRL_REG) & ASIC_CTRL_EXPSRE_TMR_MSK) >> ASIC_CTRL_EXPSRE_TMR_OFST); + FILE_LOG(logDEBUG1, ("Getting storage cell delay: %lldns\n", (long long int)retval)); + break; + + default: + FILE_LOG(logERROR, ("Timer Index not implemented for this detector: %d\n", ind)); + break; + } + + return retval; + +} + + + +int64_t getTimeLeft(enum timerIndex ind){ +#ifdef VIRTUAL + return 0; +#endif + int64_t retval = -1; + switch(ind){ + + case FRAME_NUMBER: + retval = get64BitReg(GET_FRAMES_LSB_REG, GET_FRAMES_MSB_REG); + FILE_LOG(logINFO, ("Getting number of frames left: %lld\n",(long long int)retval)); + break; + + case FRAME_PERIOD: + retval = get64BitReg(GET_PERIOD_LSB_REG, GET_PERIOD_MSB_REG) / (1E-3 * CLK_SYNC); + FILE_LOG(logINFO, ("Getting period left: %lldns\n", (long long int)retval)); + break; +/* + case DELAY_AFTER_TRIGGER: + retval = get64BitReg(xxx) / (1E-3 * CLK_SYNC); + FILE_LOG(logINFO, ("Getting delay left: %lldns\n", (long long int)retval)); + break; +*/ + case CYCLES_NUMBER: + retval = get64BitReg(GET_CYCLES_LSB_REG, GET_CYCLES_MSB_REG); + FILE_LOG(logINFO, ("Getting number of cycles left: %lld\n", (long long int)retval)); + break; + + case ACTUAL_TIME: + retval = get64BitReg(TIME_FROM_START_LSB_REG, TIME_FROM_START_MSB_REG) / (1E-3 * CLK_SYNC); + FILE_LOG(logINFO, ("Getting actual time (time from start): %lld\n", (long long int)retval)); + break; + + case MEASUREMENT_TIME: + retval = get64BitReg(START_FRAME_TIME_LSB_REG, START_FRAME_TIME_MSB_REG) / (1E-3 * CLK_SYNC); + FILE_LOG(logINFO, ("Getting measurement time (timestamp/ start frame time): %lld\n", (long long int)retval)); + break; + + case FRAMES_FROM_START: + case FRAMES_FROM_START_PG: + retval = get64BitReg(FRAMES_FROM_START_PG_LSB_REG, FRAMES_FROM_START_PG_MSB_REG); + FILE_LOG(logINFO, ("Getting frames from start run control %lld\n", (long long int)retval)); + break; + + default: + FILE_LOG(logERROR, ("Remaining Timer index not implemented for this detector: %d\n", ind)); + break; + } + + return retval; +} + + +int validateTimer(enum timerIndex ind, int64_t val, int64_t retval) { + if (val < 0) + return OK; + switch(ind) { + case ACQUISITION_TIME: + // convert to freq + val *= (1E-3 * CLK_RUN); + val -= ACQ_TIME_MIN_CLOCK; + if(val < 0) val = 0; + // convert back to timer + val = (val + ACQ_TIME_MIN_CLOCK) / (1E-3 * CLK_RUN); + if (val != retval) + return FAIL; + break; + case STORAGE_CELL_DELAY: + // convert to freq + val *= (1E-3 * CLK_RUN); + if(val < 0) val = 0; + // convert back to timer + val = val / (1E-3 * CLK_RUN); + if (val != retval) + return FAIL; + break; + case FRAME_PERIOD: + case DELAY_AFTER_TRIGGER: + // convert to freq + val *= (1E-3 * CLK_SYNC); + // convert back to timer + val = (val) / (1E-3 * CLK_SYNC); + if (val != retval) + return FAIL; + break; + default: + break; + } + return OK; +} + + + +/* parameters - channel, chip, module, settings */ + + +int setModule(sls_detector_module myMod, char* mess){ + + FILE_LOG(logINFO, ("Setting module with settings %d\n",myMod.reg)); + + // settings + setSettings( (enum detectorSettings)myMod.reg); + + //set dac values + { + int i = 0; + for(i = 0; i < NDAC; ++i) + setDAC((enum DACINDEX)i, myMod.dacs[i], 0); + } + return OK; +} + + +int getModule(sls_detector_module *myMod){ + int idac = 0; + for (idac = 0; idac < NDAC; ++idac) { + if (dacValues[idac] >= 0) + *((myMod->dacs) + idac) = dacValues[idac]; + } + // check if all of them are not initialized + int initialized = 0; + for (idac = 0; idac < NDAC; ++idac) { + if (dacValues[idac] >= 0) + initialized = 1; + } + if (initialized) + return OK; + return FAIL; +} + + + +enum detectorSettings setSettings(enum detectorSettings sett){ + if(sett == UNINITIALIZED) + return thisSettings; + + // set settings + if(sett != GET_SETTINGS) { + switch (sett) { + case DYNAMICGAIN: + bus_w(DAQ_REG, bus_r(DAQ_REG) & ~DAQ_SETTINGS_MSK); + FILE_LOG(logINFO, ("Set settings - Dyanmic Gain, DAQ Reg: 0x%x\n", bus_r(DAQ_REG))); + break; + case DYNAMICHG0: + bus_w(DAQ_REG, bus_r(DAQ_REG) & ~DAQ_SETTINGS_MSK); + bus_w(DAQ_REG, bus_r(DAQ_REG) | DAQ_FIX_GAIN_HIGHGAIN_VAL); + FILE_LOG(logINFO, ("Set settings - Dyanmic High Gain 0, DAQ Reg: 0x%x\n", bus_r(DAQ_REG))); + break; + case FIXGAIN1: + bus_w(DAQ_REG, bus_r(DAQ_REG) & ~DAQ_SETTINGS_MSK); + bus_w(DAQ_REG, bus_r(DAQ_REG) | DAQ_FIX_GAIN_STG_1_VAL); + FILE_LOG(logINFO, ("Set settings - Fix Gain 1, DAQ Reg: 0x%x\n", bus_r(DAQ_REG))); + break; + case FIXGAIN2: + bus_w(DAQ_REG, bus_r(DAQ_REG) & ~DAQ_SETTINGS_MSK); + bus_w(DAQ_REG, bus_r(DAQ_REG) | DAQ_FIX_GAIN_STG_2_VAL); + FILE_LOG(logINFO, ("Set settings - Fix Gain 2, DAQ Reg: 0x%x\n", bus_r(DAQ_REG))); + break; + case FORCESWITCHG1: + bus_w(DAQ_REG, bus_r(DAQ_REG) & ~DAQ_SETTINGS_MSK); + bus_w(DAQ_REG, bus_r(DAQ_REG) | DAQ_FRCE_GAIN_STG_1_VAL); + FILE_LOG(logINFO, ("Set settings - Force Switch Gain 1, DAQ Reg: 0x%x\n", bus_r(DAQ_REG))); + break; + case FORCESWITCHG2: + bus_w(DAQ_REG, bus_r(DAQ_REG) & ~DAQ_SETTINGS_MSK); + bus_w(DAQ_REG, bus_r(DAQ_REG) | DAQ_FRCE_GAIN_STG_2_VAL); + FILE_LOG(logINFO, ("Set settings - Force Switch Gain 2, DAQ Reg: 0x%x\n", bus_r(DAQ_REG))); + break; + default: + FILE_LOG(logERROR, ("This settings is not defined for this detector %d\n", (int)sett)); + return -1; + } + + thisSettings = sett; + } + + return getSettings(); + +} + + +enum detectorSettings getSettings(){ + + uint32_t regval = bus_r(DAQ_REG); + uint32_t val = regval & DAQ_SETTINGS_MSK; + FILE_LOG(logDEBUG1, ("Getting Settings\n Reading DAQ Register :0x%x\n", val)); + + switch(val) { + case DAQ_FIX_GAIN_DYNMC_VAL: + thisSettings = DYNAMICGAIN; + FILE_LOG(logDEBUG1, ("Settings read: Dynamic Gain. DAQ Reg: 0x%x\n", regval)); + break; + case DAQ_FIX_GAIN_HIGHGAIN_VAL: + thisSettings = DYNAMICHG0; + FILE_LOG(logDEBUG1, ("Settings read: Dynamig High Gain. DAQ Reg: 0x%x\n", regval)); + break; + case DAQ_FIX_GAIN_STG_1_VAL: + thisSettings = FIXGAIN1; + FILE_LOG(logDEBUG1, ("Settings read: Fix Gain 1. DAQ Reg: 0x%x\n", regval)); + break; + case DAQ_FIX_GAIN_STG_2_VAL: + thisSettings = FIXGAIN2; + FILE_LOG(logDEBUG1, ("Settings read: Fix Gain 2. DAQ Reg: 0x%x\n", regval)); + break; + case DAQ_FRCE_GAIN_STG_1_VAL: + thisSettings = FORCESWITCHG1; + FILE_LOG(logDEBUG1, ("Settings read: Force Switch Gain 1. DAQ Reg: 0x%x\n", regval)); + break; + case DAQ_FRCE_GAIN_STG_2_VAL: + thisSettings = FORCESWITCHG2; + FILE_LOG(logDEBUG1, ("Settings read: Force Switch Gain 2. DAQ Reg: 0x%x\n", regval)); + break; + default: + thisSettings = UNDEFINED; + FILE_LOG(logERROR, ("Settings read: Undefined. DAQ Reg: 0x%x\n", regval)); + } + + return thisSettings; +} + + + + + +/* parameters - dac, adc, hv */ +void setDAC(enum DACINDEX ind, int val, int mV) { + if (val < 0) + return; + + FILE_LOG(logDEBUG1, ("Setting dac[%d]: %d %s \n", (int)ind, val, (mV ? "mV" : "dac units"))); + int dacval = val; +#ifdef VIRTUAL + if (!mV) { + dacValues[ind] = val; + } + // convert to dac units + else if (LTC2620_VoltageToDac(val, &dacval) == OK) { + dacValues[ind] = dacval; + } +#else + if (LTC2620_SetDACValue((int)ind, val, mV, &dacval) == OK) { + dacValues[ind] = dacval; + if (ind == VREF_COMP && (val >= 0)) {//FIXME: if val == pwr down value, write 0? + bus_w (VREF_COMP_MOD_REG, (bus_r(VREF_COMP_MOD_REG) &~ (VREF_COMP_MOD_MSK)) // reset + | ((val << VREF_COMP_MOD_OFST) & VREF_COMP_MOD_MSK)); // or it with value + } + } +#endif +} + +int getDAC(enum DACINDEX ind, int mV) { + if (!mV) { + FILE_LOG(logDEBUG1, ("Getting DAC %d : %d dac\n",ind, dacValues[ind])); + return dacValues[ind]; + } + int voltage = -1; + LTC2620_DacToVoltage(dacValues[ind], &voltage); + FILE_LOG(logDEBUG1, ("Getting DAC %d : %d dac (%d mV)\n",ind, dacValues[ind], voltage)); + return voltage; +} + +int getMaxDacSteps() { + return LTC2620_MAX_STEPS; +} + +int getADC(enum ADCINDEX ind){ +#ifdef VIRTUAL + return 0; +#endif + char tempnames[2][40]={"VRs/FPGAs Temperature", "ADCs/ASICs Temperature"}; + FILE_LOG(logDEBUG1, ("Getting Temperature for %s\n", tempnames[ind])); + u_int32_t addr = GET_TEMPERATURE_TMP112_REG; + uint32_t regvalue = bus_r(addr); + uint32_t value = regvalue & TEMPERATURE_VALUE_MSK; + double retval = value; + + // negative + if (regvalue & TEMPERATURE_POLARITY_MSK) { + // 2s complement + int ret = (~value) + 1; + // attach negative sign + ret = 0 - value; + retval = ret; + } + + // conversion + retval *= 625.0/10.0; + FILE_LOG(logINFO, ("Temperature %s: %f °C\n",tempnames[ind],retval/1000.00)); + return retval; +} + + + +int setHighVoltage(int val){ +#ifdef VIRTUAL + if (val >= 0) + highvoltage = val; + return highvoltage; +#endif + + // setting hv + if (val >= 0) { + FILE_LOG(logINFO, ("Setting High voltage: %d V", val)); + MAX1932_Set(val); + highvoltage = val; + } + return highvoltage; +} + + + + + + +/* parameters - timing, extsig */ + + +void setTiming( enum externalCommunicationMode arg){ + + if(arg != GET_EXTERNAL_COMMUNICATION_MODE){ + switch((int)arg){ + case AUTO_TIMING: + FILE_LOG(logINFO, ("Set Timing: Auto\n")); + bus_w(EXT_SIGNAL_REG, bus_r(EXT_SIGNAL_REG) & ~EXT_SIGNAL_MSK); + break; + case TRIGGER_EXPOSURE: + FILE_LOG(logINFO, ("Set Timing: Trigger\n")); + bus_w(EXT_SIGNAL_REG, bus_r(EXT_SIGNAL_REG) | EXT_SIGNAL_MSK); + break; + default: + FILE_LOG(logERROR, ("Unknown timing mode %d\n", arg)); + return; + } + } +} + + +enum externalCommunicationMode getTiming() { + if (bus_r(EXT_SIGNAL_REG) == EXT_SIGNAL_MSK) + return TRIGGER_EXPOSURE; + return AUTO_TIMING; +} + + + +/* configure mac */ + + +long int calcChecksum(int sourceip, int destip) { + ip_header ip; + ip.ip_ver = 0x4; + ip.ip_ihl = 0x5; + ip.ip_tos = 0x0; + ip.ip_len = IP_PACKETSIZE; + ip.ip_ident = 0x0000; + ip.ip_flag = 0x2; //not nibble aligned (flag& offset + ip.ip_offset = 0x000; + ip.ip_ttl = 0x40; + ip.ip_protocol = 0x11; + ip.ip_chksum = 0x0000 ; // pseudo + ip.ip_sourceip = sourceip; + ip.ip_destip = destip; + + int count = sizeof(ip); + + unsigned short *addr; + addr = (unsigned short*) &(ip); /* warning: assignment from incompatible pointer type */ + + long int sum = 0; + while( count > 1 ) { + sum += *addr++; + count -= 2; + } + if (count > 0) + sum += *addr; // Add left-over byte, if any + while (sum>>16) + sum = (sum & 0xffff) + (sum >> 16);// Fold 32-bit sum to 16 bits + long int checksum = (~sum) & 0xffff; + FILE_LOG(logINFO, ("IP checksum is 0x%lx\n",checksum)); + return checksum; +} + + + +int configureMAC(int numInterfaces, int selInterface, + uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport, + uint32_t destip2, uint64_t destmac2, uint64_t sourcemac2, uint32_t sourceip2, uint32_t udpport2) { +#ifdef VIRTUAL + return OK; +#endif + FILE_LOG(logINFOBLUE, ("Configuring MAC\n")); + + uint32_t sourceport = DEFAULT_TX_UDP_PORT; + + FILE_LOG(logINFO, ("\t#Interfaces : %d\n", numInterfaces)); + FILE_LOG(logINFO, ("\tInterface : %d\n\n", selInterface)); + + FILE_LOG(logINFO, ("\tSource IP : %d.%d.%d.%d \t\t(0x%08x)\n", + (sourceip>>24)&0xff,(sourceip>>16)&0xff,(sourceip>>8)&0xff,(sourceip)&0xff, sourceip)); + FILE_LOG(logINFO, ("\tSource MAC : %02x:%02x:%02x:%02x:%02x:%02x \t(0x%010llx)\n", + (unsigned int)((sourcemac>>40)&0xFF), + (unsigned int)((sourcemac>>32)&0xFF), + (unsigned int)((sourcemac>>24)&0xFF), + (unsigned int)((sourcemac>>16)&0xFF), + (unsigned int)((sourcemac>>8)&0xFF), + (unsigned int)((sourcemac>>0)&0xFF), + (long long unsigned int)sourcemac)); + FILE_LOG(logINFO, ("\tSource Port : %d \t\t\t(0x%08x)\n",sourceport, sourceport)); + + FILE_LOG(logINFO, ("\tDest. IP : %d.%d.%d.%d \t\t\t(0x%08x)\n", + (destip>>24)&0xff,(destip>>16)&0xff,(destip>>8)&0xff,(destip)&0xff, destip)); + FILE_LOG(logINFO, ("\tDest. MAC : %02x:%02x:%02x:%02x:%02x:%02x \t(0x%010llx)\n", + (unsigned int)((destmac>>40)&0xFF), + (unsigned int)((destmac>>32)&0xFF), + (unsigned int)((destmac>>24)&0xFF), + (unsigned int)((destmac>>16)&0xFF), + (unsigned int)((destmac>>8)&0xFF), + (unsigned int)((destmac>>0)&0xFF), + (long long unsigned int)destmac)); + FILE_LOG(logINFO, ("\tDest. Port : %d \t\t\t(0x%08x)\n\n",udpport, udpport)); + + uint32_t sourceport2 = DEFAULT_TX_UDP_PORT + 1; + FILE_LOG(logINFO, ("\tSource IP2 : %d.%d.%d.%d \t\t(0x%08x)\n", + (sourceip2>>24)&0xff,(sourceip2>>16)&0xff,(sourceip2>>8)&0xff,(sourceip2)&0xff, sourceip2)); + FILE_LOG(logINFO, ("\tSource MAC2 : %02x:%02x:%02x:%02x:%02x:%02x \t(0x%010llx)\n", + (unsigned int)((sourcemac2>>40)&0xFF), + (unsigned int)((sourcemac2>>32)&0xFF), + (unsigned int)((sourcemac2>>24)&0xFF), + (unsigned int)((sourcemac2>>16)&0xFF), + (unsigned int)((sourcemac2>>8)&0xFF), + (unsigned int)((sourcemac2>>0)&0xFF), + (long long unsigned int)sourcemac2)); + FILE_LOG(logINFO, ("\tSource Port2: %d \t\t\t(0x%08x)\n",sourceport2, sourceport2)); + + FILE_LOG(logINFO, ("\tDest. IP2 : %d.%d.%d.%d \t\t\t(0x%08x)\n", + (destip2>>24)&0xff,(destip2>>16)&0xff,(destip2>>8)&0xff,(destip2)&0xff, destip2)); + FILE_LOG(logINFO, ("\tDest. MAC2 : %02x:%02x:%02x:%02x:%02x:%02x \t(0x%010llx)\n", + (unsigned int)((destmac2>>40)&0xFF), + (unsigned int)((destmac2>>32)&0xFF), + (unsigned int)((destmac2>>24)&0xFF), + (unsigned int)((destmac2>>16)&0xFF), + (unsigned int)((destmac2>>8)&0xFF), + (unsigned int)((destmac2>>0)&0xFF), + (long long unsigned int)destmac2)); + FILE_LOG(logINFO, ("\tDest. Port2 : %d \t\t\t(0x%08x)\n",udpport2, udpport2)); + + long int checksum=calcChecksum(sourceip, destip); + bus_w(TX_IP_REG, sourceip); + bus_w(RX_IP_REG, destip); + + uint32_t val = 0; + + val = ((sourcemac >> LSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(TX_MAC_LSB_REG, val); + FILE_LOG(logDEBUG1, ("Read from TX_MAC_LSB_REG: 0x%08x\n", bus_r(TX_MAC_LSB_REG))); + + val = ((sourcemac >> MSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(TX_MAC_MSB_REG,val); + FILE_LOG(logDEBUG1, ("Read from TX_MAC_MSB_REG: 0x%08x\n", bus_r(TX_MAC_MSB_REG))); + + val = ((destmac >> LSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(RX_MAC_LSB_REG, val); + FILE_LOG(logDEBUG1, ("Read from RX_MAC_LSB_REG: 0x%08x\n", bus_r(RX_MAC_LSB_REG))); + + val = ((destmac >> MSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(RX_MAC_MSB_REG, val); + FILE_LOG(logDEBUG1, ("Read from RX_MAC_MSB_REG: 0x%08x\n", bus_r(RX_MAC_MSB_REG))); + + val = (((sourceport << UDP_PORT_TX_OFST) & UDP_PORT_TX_MSK) | + ((udpport << UDP_PORT_RX_OFST) & UDP_PORT_RX_MSK)); + bus_w(UDP_PORT_REG, val); + FILE_LOG(logDEBUG1, ("Read from UDP_PORT_REG: 0x%08x\n", bus_r(UDP_PORT_REG))); + + bus_w(TX_IP_CHECKSUM_REG,(checksum << TX_IP_CHECKSUM_OFST) & TX_IP_CHECKSUM_MSK); + FILE_LOG(logDEBUG1, ("Read from TX_IP_CHECKSUM_REG: 0x%08x\n", bus_r(TX_IP_CHECKSUM_REG))); + cleanFifos(); + resetCore(); + alignDeserializer(); + return OK; +} + + +int setDetectorPosition(int pos[]) { + int ret = OK; + FILE_LOG(logDEBUG1, ("Setting detector position: (%d, %d)\n", pos[0], pos[1])); + + bus_w(COORD_0_REG, bus_r(COORD_0_REG) & (~(COORD_0_X_MSK))); + bus_w(COORD_0_REG, bus_r(COORD_0_REG) | ((pos[0] << COORD_0_X_OFST) & COORD_0_X_MSK)); + if ((bus_r(COORD_0_REG) & COORD_0_X_MSK) != ((pos[0] << COORD_0_X_OFST) & COORD_0_X_MSK)) + ret = FAIL; + + bus_w(COORD_0_REG, bus_r(COORD_0_REG) & (~(COORD_0_Y_MSK))); + bus_w(COORD_0_REG, bus_r(COORD_0_REG) | ((pos[1] << COORD_0_Y_OFST) & COORD_0_Y_MSK)); + if ((bus_r(COORD_0_REG) & COORD_0_Y_MSK) != ((pos[1] << COORD_0_Y_OFST) & COORD_0_Y_MSK)) + ret = FAIL; + + if (ret == OK) { + FILE_LOG(logINFO, ("Position set to [%d, %d]\n", pos[0], pos[1])); + } + return ret; +} + + + +/* jungfrau specific - powerchip, autocompdisable, asictimer, clockdiv, pll, flashing fpga */ + + + +int powerChip (int on){ + if(on != -1){ + if(on){ + FILE_LOG(logINFO, ("Powering chip: on\n")); + bus_w(CHIP_POWER_REG, bus_r(CHIP_POWER_REG) | CHIP_POWER_ENABLE_MSK); + } + else{ + FILE_LOG(logINFO, ("Powering chip: off\n")); + bus_w(CHIP_POWER_REG, bus_r(CHIP_POWER_REG) & ~CHIP_POWER_ENABLE_MSK); + } + } + + return ((bus_r(CHIP_POWER_REG) & CHIP_POWER_STATUS_MSK) >> CHIP_POWER_STATUS_OFST); +} + + + +int autoCompDisable(int on) { + if(on != -1){ + if(on){ + FILE_LOG(logINFO, ("Auto comp disable mode: on\n")); + bus_w(VREF_COMP_MOD_REG, bus_r(VREF_COMP_MOD_REG) | VREF_COMP_MOD_ENABLE_MSK); + } + else{ + FILE_LOG(logINFO, ("Auto comp disable mode: off\n")); + bus_w(VREF_COMP_MOD_REG, bus_r(VREF_COMP_MOD_REG) & ~VREF_COMP_MOD_ENABLE_MSK); + } + } + + return (bus_r(VREF_COMP_MOD_REG) & VREF_COMP_MOD_ENABLE_MSK); +} + +void configureASICTimer() { + FILE_LOG(logINFO, ("Configuring ASIC Timer\n")); + bus_w(ASIC_CTRL_REG, (bus_r(ASIC_CTRL_REG) & ~ASIC_CTRL_PRCHRG_TMR_MSK) | ASIC_CTRL_PRCHRG_TMR_VAL); + bus_w(ASIC_CTRL_REG, (bus_r(ASIC_CTRL_REG) & ~ASIC_CTRL_DS_TMR_MSK) | ASIC_CTRL_DS_TMR_VAL); +} + +void setClockDivider(int val) { + // setting + if(val >= 0) { + + // stop state machine if running + if(runBusy()) + stopStateMachine(); + + uint32_t txndelay_msk = 0; + + switch(val){ + + // todo in firmware, for now setting half speed + case FULL_SPEED://40 + FILE_LOG(logINFO, ("Setting Half Speed (20 MHz):\n")); + + FILE_LOG(logINFO, ("\tSetting Sample Reg to 0x%x\n", SAMPLE_ADC_HALF_SPEED)); + bus_w(SAMPLE_REG, SAMPLE_ADC_HALF_SPEED); + + txndelay_msk = (bus_r(CONFIG_REG) & CONFIG_TDMA_TIMESLOT_MSK); // read config tdma timeslot value + FILE_LOG(logINFO, ("\tSetting Config Reg to 0x%x\n", CONFIG_HALF_SPEED | txndelay_msk)); + bus_w(CONFIG_REG, CONFIG_HALF_SPEED | txndelay_msk); + + FILE_LOG(logINFO, ("\tSetting ADC Ofst Reg to 0x%x\n", ADC_OFST_HALF_SPEED_VAL)); + bus_w(ADC_OFST_REG, ADC_OFST_HALF_SPEED_VAL); + + FILE_LOG(logINFO, ("\tSetting ADC Phase Reg to 0x%x\n", ADC_PHASE_HALF_SPEED)); + setAdcPhase(ADC_PHASE_HALF_SPEED, 0); + + break; + case HALF_SPEED: + FILE_LOG(logINFO, ("Setting Half Speed (20 MHz):\n")); + + FILE_LOG(logINFO, ("\tSetting Sample Reg to 0x%x\n", SAMPLE_ADC_HALF_SPEED)); + bus_w(SAMPLE_REG, SAMPLE_ADC_HALF_SPEED); + + txndelay_msk = (bus_r(CONFIG_REG) & CONFIG_TDMA_TIMESLOT_MSK); // read config tdma timeslot value + FILE_LOG(logINFO, ("\tSetting Config Reg to 0x%x\n", CONFIG_HALF_SPEED | txndelay_msk)); + bus_w(CONFIG_REG, CONFIG_HALF_SPEED | txndelay_msk); + + FILE_LOG(logINFO, ("\tSetting ADC Ofst Reg to 0x%x\n", ADC_OFST_HALF_SPEED_VAL)); + bus_w(ADC_OFST_REG, ADC_OFST_HALF_SPEED_VAL); + + FILE_LOG(logINFO, ("\tSetting ADC Phase Reg to 0x%x\n", ADC_PHASE_HALF_SPEED)); + setAdcPhase(ADC_PHASE_HALF_SPEED, 0); + + break; + case QUARTER_SPEED: + FILE_LOG(logINFO, ("Setting Half Speed (10 MHz):\n")); + + FILE_LOG(logINFO, ("\tSetting Sample Reg to 0x%x\n", SAMPLE_ADC_QUARTER_SPEED)); + bus_w(SAMPLE_REG, SAMPLE_ADC_QUARTER_SPEED); + + txndelay_msk = (bus_r(CONFIG_REG) & CONFIG_TDMA_TIMESLOT_MSK); // read config tdma timeslot value + FILE_LOG(logINFO, ("\tSetting Config Reg to 0x%x\n", CONFIG_QUARTER_SPEED | txndelay_msk)); + bus_w(CONFIG_REG, CONFIG_QUARTER_SPEED | txndelay_msk); + + FILE_LOG(logINFO, ("\tSetting ADC Ofst Reg to 0x%x\n", ADC_OFST_QUARTER_SPEED_VAL)); + bus_w(ADC_OFST_REG, ADC_OFST_QUARTER_SPEED_VAL); + + FILE_LOG(logINFO, ("\tSetting ADC Phase Reg to 0x%x\n", ADC_PHASE_QUARTER_SPEED)); + setAdcPhase(ADC_PHASE_QUARTER_SPEED, 0); + + break; + } + } +} + +int getClockDivider() { + u_int32_t speed = bus_r(CONFIG_REG) & CONFIG_READOUT_SPEED_MSK; + switch(speed){ + case CONFIG_FULL_SPEED_40MHZ_VAL: + return FULL_SPEED; + case CONFIG_HALF_SPEED_20MHZ_VAL: + return HALF_SPEED; + case CONFIG_QUARTER_SPEED_10MHZ_VAL: + return QUARTER_SPEED; + default: + return -1; + } +} + +void setAdcPhase(int val, int degrees){ + int maxShift = MAX_PHASE_SHIFTS; + + // validation + if (degrees && (val < 0 || val > 359)) { + FILE_LOG(logERROR, ("\tPhase provided outside limits (0 - 359°C)\n")); + return; + } + if (!degrees && (val < 0 || val > MAX_PHASE_SHIFTS - 1)) { + FILE_LOG(logERROR, ("\tPhase provided outside limits (0 - %d phase shifts)\n", maxShift - 1)); + return; + } + + FILE_LOG(logINFO, ("Setting ADC Phase to %d (degree mode: %d)\n", val, degrees)); + int valShift = val; + // convert to phase shift + if (degrees) { + ConvertToDifferentRange(0, 359, 0, maxShift - 1, val, &valShift); + } + FILE_LOG(logDEBUG1, ("phase shift: %d (degrees/shift: %d)\n", valShift, val)); + + int relativePhase = valShift - adcPhase; + FILE_LOG(logDEBUG1, ("relative phase shift: %d (Current phase: %d)\n", relativePhase, adcPhase)); + + // same phase + if (!relativePhase) { + FILE_LOG(logINFO, ("Nothing to do in Phase Shift\n")); + return; + } + + int phase = 0; + if (relativePhase > 0) { + phase = (maxShift - relativePhase); + } else { + phase = (-1) * relativePhase; + } + FILE_LOG(logDEBUG1, ("[Single Direction] Phase:%d (0x%x). Max Phase shifts:%d\n", phase, phase, maxShift)); + + ALTERA_PLL_SetPhaseShift(phase, 1, 0); + + adcPhase = valShift; +} + +int getPhase(degrees) { + if (!degrees) + return adcPhase; + // convert back to degrees + int val = 0; + ConvertToDifferentRange(0, MAX_PHASE_SHIFTS - 1, 0, 359, adcPhase, &val); + return val; +} + +int getMaxPhaseShift() { + return MAX_PHASE_SHIFTS; +} + +int validatePhaseinDegrees(int val, int retval) { + if (val == -1) + return OK; + FILE_LOG(logDEBUG1, ("validating phase in degrees\n")); + int maxShift = MAX_PHASE_SHIFTS; + // convert degrees to shift + int valShift = 0; + ConvertToDifferentRange(0, 359, 0, maxShift - 1, val, &valShift); + // convert back to degrees + ConvertToDifferentRange(0, maxShift - 1, 0, 359, valShift, &val); + + if (val == retval) + return OK; + return FAIL; +} + + +int setThresholdTemperature(int val) { + + if (val >= 0) { + FILE_LOG(logINFO, ("Setting Threshold Temperature: %f °C\n", val/1000.00)); + val *= (10.0/625.0); + FILE_LOG(logDEBUG1, ("Converted Threshold Temperature: %d\n", val)); + bus_w(TEMP_CTRL_REG, (bus_r(TEMP_CTRL_REG) &~(TEMP_CTRL_PROTCT_THRSHLD_MSK) &~(TEMP_CTRL_OVR_TMP_EVNT_MSK)) + | (((val << TEMP_CTRL_PROTCT_THRSHLD_OFST) & TEMP_CTRL_PROTCT_THRSHLD_MSK))); + FILE_LOG(logDEBUG1, ("Converted Threshold Temperature set to %d\n", + ((bus_r(TEMP_CTRL_REG) & TEMP_CTRL_PROTCT_THRSHLD_MSK) >> TEMP_CTRL_PROTCT_THRSHLD_OFST))); + } + uint32_t temp = ((bus_r(TEMP_CTRL_REG) & TEMP_CTRL_PROTCT_THRSHLD_MSK) >> TEMP_CTRL_PROTCT_THRSHLD_OFST); + + // conversion + temp = (temp * (625.0/10.0)); + + float ftemp = (double)temp/1000.00; + FILE_LOG(logDEBUG1, ("Threshold Temperature read %f °C\n",ftemp)); + + return temp; + +} + + +int setTemperatureControl(int val) { + if (val >= 0) { + // binary value + if (val > 0 ) val = 1; + FILE_LOG(logINFO, ("Setting Temperature control: %d\n", val)); + bus_w(TEMP_CTRL_REG, (bus_r(TEMP_CTRL_REG) &~(TEMP_CTRL_PROTCT_ENABLE_MSK) &~(TEMP_CTRL_OVR_TMP_EVNT_MSK)) + | (((val << TEMP_CTRL_PROTCT_ENABLE_OFST) & TEMP_CTRL_PROTCT_ENABLE_MSK))); + FILE_LOG(logDEBUG1, ("Temperature control read: %d\n", + ((bus_r(TEMP_CTRL_REG) & TEMP_CTRL_PROTCT_ENABLE_MSK) >> TEMP_CTRL_PROTCT_ENABLE_OFST))); + } + return ((bus_r(TEMP_CTRL_REG) & TEMP_CTRL_PROTCT_ENABLE_MSK) >> TEMP_CTRL_PROTCT_ENABLE_OFST); +} + + +int setTemperatureEvent(int val) { +#ifdef VIRTUAL + return 0; +#endif + if (val >= 0) { + // set bit to clear it + val = 1; + FILE_LOG(logINFO, ("Setting Temperature Event (clearing): %d\n", val)); + bus_w(TEMP_CTRL_REG, (bus_r(TEMP_CTRL_REG) &~TEMP_CTRL_OVR_TMP_EVNT_MSK) + | (((val << TEMP_CTRL_OVR_TMP_EVNT_OFST) & TEMP_CTRL_OVR_TMP_EVNT_MSK))); + FILE_LOG(logDEBUG1, ("Temperature Event read %d\n", + ((bus_r(TEMP_CTRL_REG) & TEMP_CTRL_OVR_TMP_EVNT_MSK) >> TEMP_CTRL_OVR_TMP_EVNT_OFST))); + } + return ((bus_r(TEMP_CTRL_REG) & TEMP_CTRL_OVR_TMP_EVNT_MSK) >> TEMP_CTRL_OVR_TMP_EVNT_OFST); +} + +void alignDeserializer() { + // refresh alignment + bus_w(ADC_DSRLZR_0_REG, bus_r(ADC_DSRLZR_0_REG) | ADC_DSRLZR_0_RFRSH_ALGNMNT_MSK); + bus_w(ADC_DSRLZR_1_REG, bus_r(ADC_DSRLZR_1_REG) | ADC_DSRLZR_1_RFRSH_ALGNMNT_MSK); + bus_w(ADC_DSRLZR_2_REG, bus_r(ADC_DSRLZR_2_REG) | ADC_DSRLZR_2_RFRSH_ALGNMNT_MSK); + bus_w(ADC_DSRLZR_3_REG, bus_r(ADC_DSRLZR_3_REG) | ADC_DSRLZR_3_RFRSH_ALGNMNT_MSK); + + usleep(1 * 1000 * 1000); + + // disable the refresh + bus_w(ADC_DSRLZR_0_REG, bus_r(ADC_DSRLZR_0_REG) & (~(ADC_DSRLZR_0_RFRSH_ALGNMNT_MSK))); + bus_w(ADC_DSRLZR_1_REG, bus_r(ADC_DSRLZR_1_REG) & (~(ADC_DSRLZR_1_RFRSH_ALGNMNT_MSK))); + bus_w(ADC_DSRLZR_2_REG, bus_r(ADC_DSRLZR_2_REG) & (~(ADC_DSRLZR_2_RFRSH_ALGNMNT_MSK))); + bus_w(ADC_DSRLZR_3_REG, bus_r(ADC_DSRLZR_3_REG) & (~(ADC_DSRLZR_3_RFRSH_ALGNMNT_MSK))); +} + + +int setNetworkParameter(enum NETWORKINDEX mode, int value) { + if (mode != TXN_FRAME) + return -1; + + if (value >= 0) { + FILE_LOG(logINFO, ("Setting transmission delay: %d\n", value)); + bus_w(CONFIG_REG, (bus_r(CONFIG_REG) &~CONFIG_TDMA_TIMESLOT_MSK) + | (((value << CONFIG_TDMA_TIMESLOT_OFST) & CONFIG_TDMA_TIMESLOT_MSK))); + if (value == 0) + bus_w(CONFIG_REG, bus_r(CONFIG_REG) &~ CONFIG_TDMA_MSK); + else + bus_w(CONFIG_REG, bus_r(CONFIG_REG) | CONFIG_TDMA_MSK); + FILE_LOG(logDEBUG1, ("Transmission delay read %d\n", + ((bus_r(CONFIG_REG) & CONFIG_TDMA_TIMESLOT_MSK) >> CONFIG_TDMA_TIMESLOT_OFST))); + } + + return ((bus_r(CONFIG_REG) & CONFIG_TDMA_TIMESLOT_MSK) >> CONFIG_TDMA_TIMESLOT_OFST); +} + + + + + +/* aquisition */ + +int startStateMachine(){ +#ifdef VIRTUAL + virtual_status = 1; + virtual_stop = 0; + if(pthread_create(&pthread_virtual_tid, NULL, &start_timer, NULL)) { + virtual_status = 0; + FILE_LOG(logERROR, ("Could not start Virtual acquisition thread\n")); + return FAIL; + } + FILE_LOG(logINFOGREEN, ("Virtual Acquisition started\n")); + return OK; +#endif + FILE_LOG(logINFOBLUE, ("Starting State Machine\n")); + + cleanFifos(); + + //start state machine + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_START_ACQ_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_START_ACQ_MSK); + + FILE_LOG(logINFO, ("Status Register: %08x\n",bus_r(STATUS_REG))); + return OK; +} + + +#ifdef VIRTUAL +void* start_timer(void* arg) { + int wait_in_s = (setTimer(FRAME_NUMBER, -1) * + setTimer(CYCLES_NUMBER, -1) * + (setTimer(STORAGE_CELL_NUMBER, -1) + 1) * + (setTimer(FRAME_PERIOD, -1)/(1E9))); + FILE_LOG(logDEBUG1, ("going to wait for %d s\n", wait_in_s)); + while(!virtual_stop && (wait_in_s >= 0)) { + usleep(1000 * 1000); + wait_in_s--; + } + FILE_LOG(logINFOGREEN, ("Virtual Timer Done\n")); + + virtual_status = 0; + return NULL; +} +#endif + +int stopStateMachine(){ + FILE_LOG(logINFORED, ("Stopping State Machine\n")); +#ifdef VIRTUAL + virtual_stop = 0; + return OK; +#endif + //stop state machine + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_STOP_ACQ_MSK); + usleep(100); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_STOP_ACQ_MSK); + + FILE_LOG(logINFO, ("Status Register: %08x\n",bus_r(STATUS_REG))); + return OK; +} + + + + + +enum runStatus getRunStatus(){ +#ifdef VIRTUAL + if(virtual_status == 0){ + FILE_LOG(logINFOBLUE, ("Status: IDLE\n")); + return IDLE; + }else{ + FILE_LOG(logINFOBLUE, ("Status: RUNNING\n")); + return RUNNING; + } +#endif + FILE_LOG(logDEBUG1, ("Getting status\n")); + + enum runStatus s; + u_int32_t retval = bus_r(STATUS_REG); + FILE_LOG(logINFO, ("Status Register: %08x\n",retval)); + + //running + if (retval & RUN_BUSY_MSK) { + if (retval & WAITING_FOR_TRIGGER_MSK) { + FILE_LOG(logINFOBLUE, ("Status: WAITING\n")); + s = WAITING; + } + else{ + FILE_LOG(logINFOBLUE, ("Status: RUNNING\n")); + s = RUNNING; + } + } + + //not running + else { + // stopped or error + if (retval & STOPPED_MSK) { + FILE_LOG(logINFOBLUE, ("Status: STOPPED\n")); + s = STOPPED; + } else if (retval & RUNMACHINE_BUSY_MSK) { + FILE_LOG(logINFOBLUE, ("Status: READ MACHINE BUSY\n")); + s = TRANSMITTING; + } else if (!retval) { + FILE_LOG(logINFOBLUE, ("Status: IDLE\n")); + s = IDLE; + } else { + FILE_LOG(logERROR, ("Status: Unknown status %08x\n", retval)); + s = ERROR; + } + } + + return s; +} + + + +void readFrame(int *ret, char *mess){ +#ifdef VIRTUAL + while(virtual_status) { + //FILE_LOG(logERROR, ("Waiting for finished flag\n"); + usleep(5000); + } + return; +#endif + // wait for status to be done + while(runBusy()){ + usleep(500); + } + + // frames left to give status + int64_t retval = getTimeLeft(FRAME_NUMBER) + 1; + if ( retval > 0) { + *ret = (int)FAIL; + sprintf(mess,"No data and run stopped: %lld frames left\n",(long long int)retval); + FILE_LOG(logERROR, (mess)); + } else { + *ret = (int)OK; + FILE_LOG(logINFOGREEN, ("Acquisition successfully finished\n")); + } +} + + + +u_int32_t runBusy() { +#ifdef VIRTUAL + return virtual_status; +#endif + u_int32_t s = (bus_r(STATUS_REG) & RUN_BUSY_MSK); + FILE_LOG(logDEBUG1, ("Status Register: %08x\n", s)); + return s; +} + + + + + + + + +/* common */ + +int calculateDataBytes(){ + return DATA_BYTES; +} + +int getTotalNumberOfChannels(){return ((int)getNumberOfChannelsPerChip() * (int)getNumberOfChips());} +int getNumberOfChips(){return NCHIP;} +int getNumberOfDACs(){return NDAC;} +int getNumberOfChannelsPerChip(){return NCHAN;} + + diff --git a/slsDetectorServers/jungfrauDetectorServer/slsDetectorFunctionList.h b/slsDetectorServers/jungfrauDetectorServer/slsDetectorFunctionList.h new file mode 120000 index 000000000..345b8c029 --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/slsDetectorFunctionList.h @@ -0,0 +1 @@ +../slsDetectorServer/slsDetectorFunctionList.h \ No newline at end of file diff --git a/slsDetectorServers/jungfrauDetectorServer/slsDetectorServer.c b/slsDetectorServers/jungfrauDetectorServer/slsDetectorServer.c new file mode 120000 index 000000000..a7eb59acb --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/slsDetectorServer.c @@ -0,0 +1 @@ +../slsDetectorServer/slsDetectorServer.c \ No newline at end of file diff --git a/slsDetectorServers/jungfrauDetectorServer/slsDetectorServer_defs.h b/slsDetectorServers/jungfrauDetectorServer/slsDetectorServer_defs.h new file mode 100755 index 000000000..f90873e5e --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/slsDetectorServer_defs.h @@ -0,0 +1,95 @@ +#pragma once +#include "sls_detector_defs.h" +#include "RegisterDefs.h" + + +#define MIN_REQRD_VRSN_T_RD_API 0x171220 +#define REQRD_FRMWR_VRSN 0x181206 // temp bug fix from last version, timing mode is backwards compatible + +#define BOARD_JUNGFRAU_TYPE (8) +#define CTRL_SRVR_INIT_TIME_US (300 * 1000) + +/* Struct Definitions */ +typedef struct ip_header_struct { + uint16_t ip_len; + uint8_t ip_tos; + uint8_t ip_ihl:4 ,ip_ver:4; + uint16_t ip_offset:13,ip_flag:3; + uint16_t ip_ident; + uint16_t ip_chksum; + uint8_t ip_protocol; + uint8_t ip_ttl; + uint32_t ip_sourceip; + uint32_t ip_destip; +} ip_header; + +/* Enums */ +enum CLK_SPEED_INDEX {FULL_SPEED, HALF_SPEED, QUARTER_SPEED}; +enum ADCINDEX {TEMP_FPGA, TEMP_ADC}; +enum DACINDEX {VB_COMP, VDD_PROT, VIN_COM, VREF_PRECH, VB_PIXBUF, VB_DS, VREF_DS, VREF_COMP }; +#define DEFAULT_DAC_VALS { 1220, /* VB_COMP */ \ + 3000, /* VDD_PROT */ \ + 1053, /* VIN_COM */ \ + 1450, /* VREF_PRECH */ \ + 750, /* VB_PIXBUF */ \ + 1000, /* VB_DS */ \ + 480, /* VREF_DS */ \ + 420 /* VREF_COMP */ \ + }; +enum NETWORKINDEX { TXN_FRAME }; + +/* Hardware Definitions */ +#define NCHAN (256 * 256) +#define NCHIP (8) +#define NDAC (8) +#define NDAC_OLDBOARD (16) +#define DYNAMIC_RANGE (16) +#define NUM_BYTES_PER_PIXEL (DYNAMIC_RANGE / 8) +#define DATA_BYTES (NCHIP * NCHAN * NUM_BYTES_PER_PIXEL) +#define IP_PACKETSIZE (0x2052) +#define CLK_RUN (40) /* MHz */ +#define CLK_SYNC (20) /* MHz */ + +/** Default Parameters */ +#define DEFAULT_NUM_FRAMES (100*1000*1000) +#define DEFAULT_NUM_CYCLES (1) +#define DEFAULT_EXPTIME (10*1000) //ns +#define DEFAULT_PERIOD (2*1000*1000) //ns +#define DEFAULT_DELAY (0) +#define DEFAULT_HIGH_VOLTAGE (0) +#define DEFAULT_TIMING_MODE (AUTO_TIMING) +#define DEFAULT_SETTINGS (DYNAMICGAIN) +#define DEFAULT_TX_UDP_PORT (0x7e9a) +#define DEFAULT_TMP_THRSHLD (65*1000) //milli degree Celsius +#define DEFAULT_NUM_STRG_CLLS (0) +#define DEFAULT_STRG_CLL_STRT (0xf) +#define DEFAULT_STRG_CLL_DLY (0) + +#define HIGHVOLTAGE_MIN (60) +#define HIGHVOLTAGE_MAX (200) +#define DAC_MIN_MV (0) +#define DAC_MAX_MV (2500) + +/* Defines in the Firmware */ +#define MAX_TIMESLOT_VAL (0x1F) +#define MAX_THRESHOLD_TEMP_VAL (127999) //millidegrees +#define MAX_STORAGE_CELL_VAL (15) //0xF +#define MAX_STORAGE_CELL_DLY_NS_VAL ((ASIC_CTRL_EXPSRE_TMR_MSK >> ASIC_CTRL_EXPSRE_TMR_OFST) * ASIC_CTRL_EXPSRE_TMR_STEPS) +#define ACQ_TIME_MIN_CLOCK (2) + +#define SAMPLE_ADC_HALF_SPEED (SAMPLE_DECMT_FACTOR_2_VAL + SAMPLE_DGTL_SAMPLE_0_VAL + SAMPLE_ADC_DECMT_FACTOR_0_VAL + SAMPLE_ADC_SAMPLE_0_VAL) /* 0x1000 */ +#define SAMPLE_ADC_QUARTER_SPEED (SAMPLE_DECMT_FACTOR_4_VAL + SAMPLE_DGTL_SAMPLE_8_VAL + SAMPLE_ADC_DECMT_FACTOR_1_VAL + SAMPLE_ADC_SAMPLE_0_VAL) /* 0x2810 */ +#define CONFIG_HALF_SPEED (CONFIG_TDMA_DISABLE_VAL + CONFIG_HALF_SPEED_20MHZ_VAL + CONFIG_OPRTN_MDE_1_X_10GBE_VAL) /**0x100000 */ +#define CONFIG_QUARTER_SPEED (CONFIG_TDMA_DISABLE_VAL + CONFIG_QUARTER_SPEED_10MHZ_VAL + CONFIG_OPRTN_MDE_1_X_10GBE_VAL) +#define ADC_OFST_HALF_SPEED_VAL (0x20)//(0x1f) //(0x20) +#define ADC_OFST_QUARTER_SPEED_VAL (0x0f) //(0x0f) +#define ADC_PHASE_HALF_SPEED (0x2D) //45 +#define ADC_PHASE_QUARTER_SPEED (0x2D) //45 +#define ADC_PORT_INVERT_VAL (0x5A5A5A5A)//(0x453b2a9c) +#define MAX_PHASE_SHIFTS (160) + +/* MSB & LSB DEFINES */ +#define MSB_OF_64_BIT_REG_OFST (32) +#define LSB_OF_64_BIT_REG_OFST (0) +#define BIT_32_MSK (0xFFFFFFFF) + diff --git a/slsDetectorServers/jungfrauDetectorServer/slsDetectorServer_funcs.c b/slsDetectorServers/jungfrauDetectorServer/slsDetectorServer_funcs.c new file mode 120000 index 000000000..a7532ccd4 --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/slsDetectorServer_funcs.c @@ -0,0 +1 @@ +../slsDetectorServer/slsDetectorServer_funcs.c \ No newline at end of file diff --git a/slsDetectorServers/jungfrauDetectorServer/slsDetectorServer_funcs.h b/slsDetectorServers/jungfrauDetectorServer/slsDetectorServer_funcs.h new file mode 120000 index 000000000..7569daf47 --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/slsDetectorServer_funcs.h @@ -0,0 +1 @@ +../slsDetectorServer/slsDetectorServer_funcs.h \ No newline at end of file diff --git a/slsDetectorServers/jungfrauDetectorServer/sls_detector_defs.h b/slsDetectorServers/jungfrauDetectorServer/sls_detector_defs.h new file mode 120000 index 000000000..2af30d73a --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/sls_detector_defs.h @@ -0,0 +1 @@ +../../slsSupportLib/include/sls_detector_defs.h \ No newline at end of file diff --git a/slsDetectorServers/jungfrauDetectorServer/sls_detector_funcs.h b/slsDetectorServers/jungfrauDetectorServer/sls_detector_funcs.h new file mode 120000 index 000000000..3f48959a9 --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/sls_detector_funcs.h @@ -0,0 +1 @@ +../../slsSupportLib/include/sls_detector_funcs.h \ No newline at end of file diff --git a/slsDetectorServers/jungfrauDetectorServer/versionAPI.h b/slsDetectorServers/jungfrauDetectorServer/versionAPI.h new file mode 120000 index 000000000..5e580d8bb --- /dev/null +++ b/slsDetectorServers/jungfrauDetectorServer/versionAPI.h @@ -0,0 +1 @@ +../../slsSupportLib/include/versionAPI.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/AD9257.h b/slsDetectorServers/moenchDetectorServer/AD9257.h new file mode 120000 index 000000000..87b70e097 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/AD9257.h @@ -0,0 +1 @@ +../slsDetectorServer/AD9257.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/ALTERA_PLL.h b/slsDetectorServers/moenchDetectorServer/ALTERA_PLL.h new file mode 120000 index 000000000..e665f009d --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/ALTERA_PLL.h @@ -0,0 +1 @@ +../slsDetectorServer/ALTERA_PLL.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/LTC2620.h b/slsDetectorServers/moenchDetectorServer/LTC2620.h new file mode 120000 index 000000000..13157cb8b --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/LTC2620.h @@ -0,0 +1 @@ +../slsDetectorServer/LTC2620.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/MAX1932.h b/slsDetectorServers/moenchDetectorServer/MAX1932.h new file mode 120000 index 000000000..8f7b239ea --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/MAX1932.h @@ -0,0 +1 @@ +../slsDetectorServer/MAX1932.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/Makefile b/slsDetectorServers/moenchDetectorServer/Makefile new file mode 100755 index 000000000..65960a021 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/Makefile @@ -0,0 +1,34 @@ +CROSS = bfin-uclinux- +CC = $(CROSS)gcc +CFLAGS += -Wall -DMOENCHD -DSTOP_SERVER -DDEBUG1# -DVERBOSEI #-DVERBOSE +LDLIBS += -lm -lstdc++ + +PROGS = moenchDetectorServer +DESTDIR ?= bin +INSTMODE = 0777 + +SRC_CLNT = communication_funcs.c slsDetectorServer.c slsDetectorServer_funcs.c slsDetectorFunctionList.c +OBJS = $(SRC_CLNT:.c=.o) + +all: clean versioning $(PROGS) + +boot: $(OBJS) + +version_name=APIMOENCH +version_path=slsDetectorServers/moenchDetectorServer +versioning: + cd ../../ && echo $(PWD) && echo `tput setaf 6; ./updateAPIVersion.sh $(version_name) $(version_path); tput sgr0;` + + +$(PROGS): $(OBJS) +# echo $(OBJS) + mkdir -p $(DESTDIR) + $(CC) -o $@ $^ $(CFLAGS) $(LDLIBS) + mv $(PROGS) $(DESTDIR) + rm *.gdb + +clean: + rm -rf $(DESTDIR)/$(PROGS) *.o *.gdb + + + \ No newline at end of file diff --git a/slsDetectorSoftware/mythen3DetectorServer/Makefile b/slsDetectorServers/moenchDetectorServer/Makefile.virtual old mode 100644 new mode 100755 similarity index 57% rename from slsDetectorSoftware/mythen3DetectorServer/Makefile rename to slsDetectorServers/moenchDetectorServer/Makefile.virtual index ba8ffe5f1..f502da862 --- a/slsDetectorSoftware/mythen3DetectorServer/Makefile +++ b/slsDetectorServers/moenchDetectorServer/Makefile.virtual @@ -1,33 +1,27 @@ -CROSS = bfin-uclinux- -CC = $(CROSS)gcc -#CC = gcc -CLAGS += -Wall -DMYTHEN3D -DSLS_DETECTOR_FUNCTION_LIST -DDACS_INT -DSTOP_SERVER #-DVERBOSEI #-DVERBOSE -LDLIBS += -lm -lstdc++ +CC = gcc +CFLAGS += -Wall -DMOENCHD -DVIRTUAL -DSTOP_SERVER #-DVERBOSEI #-DVERBOSE +LDLIBS += -lm -lstdc++ -pthread - -PROGS = mythen3DetectorServer +PROGS = moenchDetectorServer_virtual DESTDIR ?= bin INSTMODE = 0777 -SRC_CLNT = communication_funcs.c slsDetectorServer.c slsDetectorServer_funcs.c slsDetectorFunctionList.c +SRC_CLNT = communication_funcs.c slsDetectorServer.c slsDetectorServer_funcs.c slsDetectorFunctionList.c OBJS = $(SRC_CLNT:.c=.o) - - - + all: clean versioning $(PROGS) -boot: $(OBJS) +boot: $(OBJS) versioning: @echo `tput setaf 6; ./updateGitVersion.sh; tput sgr0;` - + $(PROGS): $(OBJS) # echo $(OBJS) mkdir -p $(DESTDIR) $(CC) -o $@ $^ $(CFLAGS) $(LDLIBS) mv $(PROGS) $(DESTDIR) - rm *.gdb clean: rm -rf $(DESTDIR)/$(PROGS) *.o - + diff --git a/slsDetectorServers/moenchDetectorServer/RegisterDefs.h b/slsDetectorServers/moenchDetectorServer/RegisterDefs.h new file mode 100755 index 000000000..a946a0a47 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/RegisterDefs.h @@ -0,0 +1,539 @@ +#pragma once + +/* Definitions for FPGA */ +#define MEM_MAP_SHIFT 1 + + +/* FPGA Version RO register */ +#define FPGA_VERSION_REG (0x00 << MEM_MAP_SHIFT) + +#define FPGA_VERSION_BRD_RVSN_OFST (0) +#define FPGA_VERSION_BRD_RVSN_MSK (0x00FFFFFF << FPGA_VERSION_BRD_RVSN_OFST) +#define FPGA_VERSION_DTCTR_TYP_OFST (24) +#define FPGA_VERSION_DTCTR_TYP_MSK (0x000000FF << FPGA_VERSION_DTCTR_TYP_OFST) +#define FPGA_VERSION_DTCTR_TYP_MOENCH_VAL ((0x5 << FPGA_VERSION_DTCTR_TYP_OFST) & FPGA_VERSION_DTCTR_TYP_MSK) + +/* Fix pattern RO register */ +#define FIX_PATT_REG (0x01 << MEM_MAP_SHIFT) + +#define FIX_PATT_VAL (0xACDC2014) + +/* Status RO register */ +#define STATUS_REG (0x02 << MEM_MAP_SHIFT) + +#define STATUS_RN_BSY_OFST (0) +#define STATUS_RN_BSY_MSK (0x00000001 << STATUS_RN_BSY_OFST) +#define STATUS_RDT_BSY_OFST (1) +#define STATUS_RDT_BSY_MSK (0x00000001 << STATUS_RDT_BSY_OFST) +#define STATUS_ANY_FF_FLL_OFST (2) +#define STATUS_ANY_FF_FLL_MSK (0x00000001 << STATUS_ANY_FF_FLL_OFST) +#define STATUS_WTNG_FR_TRGGR_OFST (3) +#define STATUS_WTNG_FR_TRGGR_MSK (0x00000001 << STATUS_WTNG_FR_TRGGR_OFST) +#define STATUS_DLY_BFR_OFST (4) +#define STATUS_DLY_BFR_MSK (0x00000001 << STATUS_DLY_BFR_OFST) +#define STATUS_DLY_AFTR_OFST (5) +#define STATUS_DLY_AFTR_MSK (0x00000001 << STATUS_DLY_AFTR_OFST) +#define STATUS_EXPSNG_OFST (6) +#define STATUS_EXPSNG_MSK (0x00000001 << STATUS_EXPSNG_OFST) +#define STATUS_CNT_ENBL_OFST (7) +#define STATUS_CNT_ENBL_MSK (0x00000001 << STATUS_CNT_ENBL_OFST) +#define STATUS_SM_FF_FLL_OFST (11) +#define STATUS_SM_FF_FLL_MSK (0x00000001 << STATUS_SM_FF_FLL_OFST) +#define STATUS_STPPD_OFST (15) +#define STATUS_STPPD_MSK (0x00000001 << STATUS_STPPD_OFST) +#define STATUS_ALL_FF_EMPTY_OFST (16) +#define STATUS_ALL_FF_EMPTY_MSK (0x00000001 << STATUS_ALL_FF_EMPTY_OFST) +#define STATUS_CYCL_RN_BSY_OFST (17) +#define STATUS_CYCL_RN_BSY_MSK (0x00000001 << STATUS_CYCL_RN_BSY_OFST) +#define STATUS_FRM_RN_BSY_OFST (18) +#define STATUS_FRM_RN_BSY_MSK (0x00000001 << STATUS_FRM_RN_BSY_OFST) +#define STATUS_ADC_DESERON_OFST (19) +#define STATUS_ADC_DESERON_MSK (0x00000001 << STATUS_ADC_DESERON_OFST) +#define STATUS_PLL_RCNFG_BSY_OFST (20) +#define STATUS_PLL_RCNFG_BSY_MSK (0x00000001 << STATUS_PLL_RCNFG_BSY_OFST) +#define STATUS_DT_STRMNG_BSY_OFST (21) +#define STATUS_DT_STRMNG_BSY_MSK (0x00000001 << STATUS_DT_STRMNG_BSY_OFST) +#define STATUS_FRM_PCKR_BSY_OFST (22) +#define STATUS_FRM_PCKR_BSY_MSK (0x00000001 << STATUS_FRM_PCKR_BSY_OFST) +#define STATUS_PLL_PHS_DN_OFST (23) +#define STATUS_PLL_PHS_DN_MSK (0x00000001 << STATUS_PLL_PHS_DN_OFST) +#define STATUS_PT_CNTRL_STTS_OFF_OFST (24) +#define STATUS_PT_CNTRL_STTS_OFF_MSK (0x000000FF << STATUS_PT_CNTRL_STTS_OFF_OFST) +#define STATUS_IDLE_MSK (0x677FF) + +/* Look at me RO register TODO */ +#define LOOK_AT_ME_REG (0x03 << MEM_MAP_SHIFT) + +/* System Status RO register */ +#define SYSTEM_STATUS_REG (0x04 << MEM_MAP_SHIFT) + +#define SYSTEM_STATUS_DDR3_CLBRTN_OK_OFST (0) +#define SYSTEM_STATUS_DDR3_CLBRTN_OK_MSK (0x00000001 << SYSTEM_STATUS_DDR3_CLBRTN_OK_OFST) +#define SYSTEM_STATUS_DDR3_CLBRTN_FL_OFST (1) +#define SYSTEM_STATUS_DDR3_CLBRTN_FL_MSK (0x00000001 << SYSTEM_STATUS_DDR3_CLBRTN_FL_OFST) +#define SYSTEM_STATUS_DDR3_INT_DN_OFST (2) +#define SYSTEM_STATUS_DDR3_INT_DN_MSK (0x00000001 << SYSTEM_STATUS_DDR3_INT_DN_OFST) +#define SYSTEM_STATUS_RCNFG_PLL_LCK_OFST (3) +#define SYSTEM_STATUS_RCNFG_PLL_LCK_MSK (0x00000001 << SYSTEM_STATUS_RCNFG_PLL_LCK_OFST) +#define SYSTEM_STATUS_PLL_A_LCK_OFST (4) +#define SYSTEM_STATUS_PLL_A_LCK_MSK (0x00000001 << SYSTEM_STATUS_PLL_A_LCK_OFST) + +/* PLL Param (Reconfiguratble PLL Parameter) RO register TODO FIXME: Same as PLL_PARAM_REG 0x50 */ +//#define PLL_PARAM_REG (0x05 << MEM_MAP_SHIFT) + +/* FIFO Data RO register TODO */ +#define FIFO_DATA_REG (0x06 << MEM_MAP_SHIFT) + +#define FIFO_DATA_HRDWR_SRL_NMBR_OFST (0) +#define FIFO_DATA_HRDWR_SRL_NMBR_MSK (0x0000FFFF << FIFO_DATA_HRDWR_SRL_NMBR_OFST) +//#define FIFO_DATA_WRD_OFST (16) +//#define FIFO_DATA_WRD_MSK (0x0000FFFF << FIFO_DATA_WRD_OFST) + +/* FIFO Status RO register TODO */ +#define FIFO_STATUS_REG (0x07 << MEM_MAP_SHIFT) + +/* FIFO Empty RO register TODO */ +#define FIFO_EMPTY_REG (0x08 << MEM_MAP_SHIFT) +#define FIFO_EMPTY_ALL_EMPTY_MSK (0xFFFFFFFF) + +/* FIFO Full RO register TODO */ +#define FIFO_FULL_REG (0x09 << MEM_MAP_SHIFT) + +/* MCB Serial Number RO register */ +#define MOD_SERIAL_NUMBER_REG (0x0A << MEM_MAP_SHIFT) + +#define MOD_SERIAL_NUMBER_OFST (0) +#define MOD_SERIAL_NUMBER_MSK (0x000000FF << MOD_SERIAL_NUMBER_OFST) +#define MOD_SERIAL_NUMBER_VRSN_OFST (16) +#define MOD_SERIAL_NUMBER_VRSN_MSK (0x0000003F << MOD_SERIAL_NUMBER_VRSN_OFST) + +/* API Version RO register */ +#define API_VERSION_REG (0x0F << MEM_MAP_SHIFT) + +#define API_VERSION_OFST (0) +#define API_VERSION_MSK (0x00FFFFFF << API_VERSION_OFST) +#define API_VERSION_DTCTR_TYP_OFST (24) +#define API_VERSION_DTCTR_TYP_MSK (0x000000FF << API_VERSION_DTCTR_TYP_OFST) + +/* Time from Start 64 bit RO register. t = GCLK x 50 ns. Reset using CONTROL_CRST. TODO */ +#define TIME_FROM_START_LSB_REG (0x10 << MEM_MAP_SHIFT) +#define TIME_FROM_START_MSB_REG (0x11 << MEM_MAP_SHIFT) + +/* Delay Left 64 bit RO register. t = DLY x 50 ns. TODO */ +#define DELAY_LEFT_LSB_REG (0x12 << MEM_MAP_SHIFT) +#define DELAY_LEFT_MSB_REG (0x13 << MEM_MAP_SHIFT) + +/* Cycles Left 64 bit RO register TODO */ +#define CYCLES_LEFT_LSB_REG (0x14 << MEM_MAP_SHIFT) +#define CYCLES_LEFT_MSB_REG (0x15 << MEM_MAP_SHIFT) + +/* Frames Left 64 bit RO register TODO */ +#define FRAMES_LEFT_LSB_REG (0x16 << MEM_MAP_SHIFT) +#define FRAMES_LEFT_MSB_REG (0x17 << MEM_MAP_SHIFT) + +/* Period Left 64 bit RO register. t = T x 50 ns. TODO */ +#define PERIOD_LEFT_LSB_REG (0x18 << MEM_MAP_SHIFT) +#define PERIOD_LEFT_MSB_REG (0x19 << MEM_MAP_SHIFT) + +/* Exposure Time Left 64 bit RO register */ +//#define EXPTIME_LEFT_LSB_REG (0x1A << MEM_MAP_SHIFT) // Not used in FW +//#define EXPTIME_LEFT_MSB_REG (0x1B << MEM_MAP_SHIFT) // Not used in FW + +/* Gates Left 64 bit RO register */ +//#define GATES_LEFT_LSB_REG (0x1C << MEM_MAP_SHIFT) // Not used in FW +//#define GATES_LEFT_MSB_REG (0x1D << MEM_MAP_SHIFT) // Not used in FW + +/* Data In 64 bit RO register TODO */ +#define DATA_IN_LSB_REG (0x1E << MEM_MAP_SHIFT) +#define DATA_IN_MSB_REG (0x1F << MEM_MAP_SHIFT) + +/* Pattern Out 64 bit RO register */ +#define PATTERN_OUT_LSB_REG (0x20 << MEM_MAP_SHIFT) +#define PATTERN_OUT_MSB_REG (0x21 << MEM_MAP_SHIFT) + +/* Frames From Start 64 bit RO register TODO */ +//#define FRAMES_FROM_START_LSB_REG (0x22 << MEM_MAP_SHIFT) // Not used in FW +//#define FRAMES_FROM_START_MSB_REG (0x23 << MEM_MAP_SHIFT) // Not used in FW + +/* Frames From Start PG 64 bit RO register. Reset using CONTROL_CRST. TODO */ +#define FRAMES_FROM_START_PG_LSB_REG (0x24 << MEM_MAP_SHIFT) +#define FRAMES_FROM_START_PG_MSB_REG (0x25 << MEM_MAP_SHIFT) + +/* Start Frame Time (Measurement Time) 64 bit register (timestamp at a frame start until reset) TODO */ +#define START_FRAME_TIME_LSB_REG (0x26 << MEM_MAP_SHIFT) +#define START_FRAME_TIME_MSB_REG (0x27 << MEM_MAP_SHIFT) + +/* Power Status RO register */ +#define POWER_STATUS_REG (0x29 << MEM_MAP_SHIFT) + +#define POWER_STATUS_ALRT_OFST (27) +#define POWER_STATUS_ALRT_MSK (0x0000001F << POWER_STATUS_ALRT_OFST) + +/* DAC Value Out RO register */ +//#define DAC_VAL_OUT_REG (0x2A << MEM_MAP_SHIFT) + +/* Slow ADC SPI Value RO register */ +#define ADC_SPI_SLOW_VAL_REG (0x2B << MEM_MAP_SHIFT) + +/* FIFO Digital In Status RO register */ +#define FIFO_DIN_STATUS_REG (0x3B << MEM_MAP_SHIFT) +#define FIFO_DIN_STATUS_FIFO_FULL_OFST (30) +#define FIFO_DIN_STATUS_FIFO_FULL_MSK (0x00000001 << FIFO_DIN_STATUS_FIFO_FULL_OFST) +#define FIFO_DIN_STATUS_FIFO_EMPTY_OFST (31) +#define FIFO_DIN_STATUS_FIFO_EMPTY_MSK (0x00000001 << FIFO_DIN_STATUS_FIFO_EMPTY_OFST) + +/* FIFO Digital In 64 bit RO register */ +#define FIFO_DIN_LSB_REG (0x3C << MEM_MAP_SHIFT) +#define FIFO_DIN_MSB_REG (0x3D << MEM_MAP_SHIFT) + +/* SPI (Serial Peripheral Interface) DAC, HV RW register */ +#define SPI_REG (0x40 << MEM_MAP_SHIFT) + +#define SPI_DAC_SRL_DGTL_OTPT_OFST (0) +#define SPI_DAC_SRL_DGTL_OTPT_MSK (0x00000001 << SPI_DAC_SRL_DGTL_OTPT_OFST) +#define SPI_DAC_SRL_CLK_OTPT_OFST (1) +#define SPI_DAC_SRL_CLK_OTPT_MSK (0x00000001 << SPI_DAC_SRL_CLK_OTPT_OFST) +#define SPI_DAC_SRL_CS_OTPT_OFST (2) +#define SPI_DAC_SRL_CS_OTPT_MSK (0x00000001 << SPI_DAC_SRL_CS_OTPT_OFST) +#define SPI_HV_SRL_DGTL_OTPT_OFST (8) +#define SPI_HV_SRL_DGTL_OTPT_MSK (0x00000001 << SPI_HV_SRL_DGTL_OTPT_OFST) +#define SPI_HV_SRL_CLK_OTPT_OFST (9) +#define SPI_HV_SRL_CLK_OTPT_MSK (0x00000001 << SPI_HV_SRL_CLK_OTPT_OFST) +#define SPI_HV_SRL_CS_OTPT_OFST (10) +#define SPI_HV_SRL_CS_OTPT_MSK (0x00000001 << SPI_HV_SRL_CS_OTPT_OFST) + +/* ADC SPI (Serial Peripheral Interface) RW register */ +#define ADC_SPI_REG (0x41 << MEM_MAP_SHIFT) + +#define ADC_SPI_SRL_CLK_OTPT_OFST (0) +#define ADC_SPI_SRL_CLK_OTPT_MSK (0x00000001 << ADC_SPI_SRL_CLK_OTPT_OFST) +#define ADC_SPI_SRL_DT_OTPT_OFST (1) +#define ADC_SPI_SRL_DT_OTPT_MSK (0x00000001 << ADC_SPI_SRL_DT_OTPT_OFST) +#define ADC_SPI_SRL_CS_OTPT_OFST (2) +#define ADC_SPI_SRL_CS_OTPT_MSK (0x0000000F << ADC_SPI_SRL_CS_OTPT_OFST) +#define ADC_SPI_SLOW_SRL_DT_OFST (8) +#define ADC_SPI_SLOW_SRL_DT_MSK (0x00000001 << ADC_SPI_SLOW_SRL_DT_OFST) +#define ADC_SPI_SLOW_SRL_CLK_OFST (9) +#define ADC_SPI_SLOW_SRL_CLK_MSK (0x00000001 << ADC_SPI_SLOW_SRL_CLK_OFST) +#define ADC_SPI_SLOW_SRL_CNV_OFST (10) +#define ADC_SPI_SLOW_SRL_CNV_MSK (0x00000001 << ADC_SPI_SLOW_SRL_CNV_OFST) + +/* ADC Offset RW register */ +#define ADC_OFFSET_REG (0x42 << MEM_MAP_SHIFT) + +#define ADC_OFFSET_ADC_PPLN_OFST (0) +#define ADC_OFFSET_ADC_PPLN_MSK (0x000000FF << ADC_OFFSET_ADC_PPLN_OFST) +#define ADC_OFFSET_DBT_PPLN_OFST (16) +#define ADC_OFFSET_DBT_PPLN_MSK (0x000000FF << ADC_OFFSET_DBT_PPLN_OFST) + +/* ADC Port Invert RW register */ +#define ADC_PORT_INVERT_REG (0x43 << MEM_MAP_SHIFT) + +#define ADC_PORT_INVERT_0_INPT_OFST (0) +#define ADC_PORT_INVERT_0_INPT_MSK (0x000000FF << ADC_PORT_INVERT_0_INPT_OFST) +#define ADC_PORT_INVERT_1_INPT_OFST (8) +#define ADC_PORT_INVERT_1_INPT_MSK (0x000000FF << ADC_PORT_INVERT_1_INPT_OFST) +#define ADC_PORT_INVERT_2_INPT_OFST (16) +#define ADC_PORT_INVERT_2_INPT_MSK (0x000000FF << ADC_PORT_INVERT_2_INPT_OFST) +#define ADC_PORT_INVERT_3_INPT_OFST (24) +#define ADC_PORT_INVERT_3_INPT_MSK (0x000000FF << ADC_PORT_INVERT_3_INPT_OFST) + +/* Dummy RW register */ +#define DUMMY_REG (0x44 << MEM_MAP_SHIFT) + +#define DUMMY_FIFO_CHNNL_SLCT_OFST (0) +#define DUMMY_FIFO_CHNNL_SLCT_MSK (0x0000003F << DUMMY_FIFO_CHNNL_SLCT_OFST) +#define DUMMY_ANLG_FIFO_RD_STRBE_OFST (8) +#define DUMMY_ANLG_FIFO_RD_STRBE_MSK (0x00000001 << DUMMY_ANLG_FIFO_RD_STRBE_OFST) +#define DUMMY_DGTL_FIFO_RD_STRBE_OFST (9) +#define DUMMY_DGTL_FIFO_RD_STRBE_MSK (0x00000001 << DUMMY_DGTL_FIFO_RD_STRBE_OFST) + +/* Receiver IP Address RW register */ +#define RX_IP_REG (0x45 << MEM_MAP_SHIFT) + +/* UDP Port RW register */ +#define UDP_PORT_REG (0x46 << MEM_MAP_SHIFT) + +#define UDP_PORT_RX_OFST (0) +#define UDP_PORT_RX_MSK (0x0000FFFF << UDP_PORT_RX_OFST) +#define UDP_PORT_TX_OFST (16) +#define UDP_PORT_TX_MSK (0x0000FFFF << UDP_PORT_TX_OFST) + +/* Receiver Mac Address 64 bit RW register */ +#define RX_MAC_LSB_REG (0x47 << MEM_MAP_SHIFT) +#define RX_MAC_MSB_REG (0x48 << MEM_MAP_SHIFT) + +#define RX_MAC_LSB_OFST (0) +#define RX_MAC_LSB_MSK (0xFFFFFFFF << RX_MAC_LSB_OFST) +#define RX_MAC_MSB_OFST (0) +#define RX_MAC_MSB_MSK (0x0000FFFF << RX_MAC_MSB_OFST) + +/* Detector/ Transmitter Mac Address 64 bit RW register */ +#define TX_MAC_LSB_REG (0x49 << MEM_MAP_SHIFT) +#define TX_MAC_MSB_REG (0x4A << MEM_MAP_SHIFT) + +#define TX_MAC_LSB_OFST (0) +#define TX_MAC_LSB_MSK (0xFFFFFFFF << TX_MAC_LSB_OFST) +#define TX_MAC_MSB_OFST (0) +#define TX_MAC_MSB_MSK (0x0000FFFF << TX_MAC_MSB_OFST) + +/* Detector/ Transmitter IP Address RW register */ +#define TX_IP_REG (0x4B << MEM_MAP_SHIFT) + +/* Detector/ Transmitter IP Checksum RW register */ +#define TX_IP_CHECKSUM_REG (0x4C << MEM_MAP_SHIFT) + +#define TX_IP_CHECKSUM_OFST (0) +#define TX_IP_CHECKSUM_MSK (0x0000FFFF << TX_IP_CHECKSUM_OFST) + +/* Configuration RW register */ +#define CONFIG_REG (0x4D << MEM_MAP_SHIFT) + +#define CONFIG_LED_DSBL_OFST (0) +#define CONFIG_LED_DSBL_MSK (0x00000001 << CONFIG_LED_DSBL_OFST) +#define CONFIG_DSBL_ANLG_OTPT_OFST (8) +#define CONFIG_DSBL_ANLG_OTPT_MSK (0x00000001 << CONFIG_DSBL_ANLG_OTPT_OFST) +#define CONFIG_ENBLE_DGTL_OTPT_OFST (9) +#define CONFIG_ENBLE_DGTL_OTPT_MSK (0x00000001 << CONFIG_ENBLE_DGTL_OTPT_OFST) +#define CONFIG_GB10_SND_UDP_OFST (12) +#define CONFIG_GB10_SND_UDP_MSK (0x00000001 << CONFIG_GB10_SND_UDP_OFST) + +/* External Signal RW register */ +#define EXT_SIGNAL_REG (0x4E << MEM_MAP_SHIFT) + +#define EXT_SIGNAL_OFST (0) +#define EXT_SIGNAL_MSK (0x00000001 << EXT_SIGNAL_OFST) +#define EXT_SIGNAL_AUTO_VAL ((0x0 << EXT_SIGNAL_OFST) & EXT_SIGNAL_MSK) +#define EXT_SIGNAL_TRGGR_VAL ((0x1 << EXT_SIGNAL_OFST) & EXT_SIGNAL_MSK) + +/* Control RW register */ +#define CONTROL_REG (0x4F << MEM_MAP_SHIFT) + +#define CONTROL_STRT_ACQSTN_OFST (0) +#define CONTROL_STRT_ACQSTN_MSK (0x00000001 << CONTROL_STRT_ACQSTN_OFST) +#define CONTROL_STP_ACQSTN_OFST (1) +#define CONTROL_STP_ACQSTN_MSK (0x00000001 << CONTROL_STP_ACQSTN_OFST) +//#define CONTROL_STRT_FF_TST_OFST (2) +//#define CONTROL_STRT_FF_TST_MSK (0x00000001 << CONTROL_STRT_FF_TST_OFST) +//#define CONTROL_STP_FF_TST_OFST (3) +//#define CONTROL_STP_FF_TST_MSK (0x00000001 << CONTROL_STP_FF_TST_OFST) +//#define CONTROL_STRT_RDT_OFST (4) +//#define CONTROL_STRT_RDT_MSK (0x00000001 << CONTROL_STRT_RDT_OFST) +//#define CONTROL_STP_RDT_OFST (5) +//#define CONTROL_STP_RDT_MSK (0x00000001 << CONTROL_STP_RDT_OFST) +#define CONTROL_STRT_EXPSR_OFST (6) +#define CONTROL_STRT_EXPSR_MSK (0x00000001 << CONTROL_STRT_EXPSR_OFST) +//#define CONTROL_STP_EXPSR_OFST (7) +//#define CONTROL_STP_EXPSR_MSK (0x00000001 << CONTROL_STP_RDT_OFST) +//#define CONTROL_STRT_TRN_OFST (8) +//#define CONTROL_STRT_TRN_MSK (0x00000001 << CONTROL_STRT_RDT_OFST) +//#define CONTROL_STP_TRN_OFST (9) +//#define CONTROL_STP_TRN_MSK (0x00000001 << CONTROL_STP_RDT_OFST) +#define CONTROL_CRE_RST_OFST (10) +#define CONTROL_CRE_RST_MSK (0x00000001 << CONTROL_CRE_RST_OFST) +#define CONTROL_PRPHRL_RST_OFST (11) // Only GBE10? +#define CONTROL_PRPHRL_RST_MSK (0x00000001 << CONTROL_PRPHRL_RST_OFST) +#define CONTROL_MMRY_RST_OFST (12) +#define CONTROL_MMRY_RST_MSK (0x00000001 << CONTROL_MMRY_RST_OFST) +//#define CONTROL_PLL_RCNFG_WR_OFST (13) +//#define CONTROL_PLL_RCNFG_WR_MSK (0x00000001 << CONTROL_PLL_RCNFG_WR_OFST) +#define CONTROL_SND_10GB_PCKT_OFST (14) +#define CONTROL_SND_10GB_PCKT_MSK (0x00000001 << CONTROL_SND_10GB_PCKT_OFST) +#define CONTROL_CLR_ACQSTN_FIFO_OFST (15) +#define CONTROL_CLR_ACQSTN_FIFO_MSK (0x00000001 << CONTROL_CLR_ACQSTN_FIFO_OFST) + +/* Reconfiguratble PLL Paramater RW register */ +#define PLL_PARAM_REG (0x50 << MEM_MAP_SHIFT) + +/* Reconfiguratble PLL Control RW regiser */ +#define PLL_CNTRL_REG (0x51 << MEM_MAP_SHIFT) + +#define PLL_CNTRL_RCNFG_PRMTR_RST_OFST (0) +#define PLL_CNTRL_RCNFG_PRMTR_RST_MSK (0x00000001 << PLL_CNTRL_RCNFG_PRMTR_RST_OFST) +#define PLL_CNTRL_WR_PRMTR_OFST (2) +#define PLL_CNTRL_WR_PRMTR_MSK (0x00000001 << PLL_CNTRL_WR_PRMTR_OFST) +#define PLL_CNTRL_PLL_RST_OFST (3) +#define PLL_CNTRL_PLL_RST_MSK (0x00000001 << PLL_CNTRL_PLL_RST_OFST) +#define PLL_CNTRL_ADDR_OFST (16) +#define PLL_CNTRL_ADDR_MSK (0x0000003F << PLL_CNTRL_ADDR_OFST) + +/* Pattern Control RW register */ +#define PATTERN_CNTRL_REG (0x52 << MEM_MAP_SHIFT) + +#define PATTERN_CNTRL_WR_OFST (0) +#define PATTERN_CNTRL_WR_MSK (0x00000001 << PATTERN_CNTRL_WR_OFST) +#define PATTERN_CNTRL_RD_OFST (1) +#define PATTERN_CNTRL_RD_MSK (0x00000001 << PATTERN_CNTRL_RD_OFST) +#define PATTERN_CNTRL_ADDR_OFST (16) +#define PATTERN_CNTRL_ADDR_MSK (0x0000FFFF << PATTERN_CNTRL_ADDR_OFST) + +/* Pattern Limit RW regiser */ +#define PATTERN_LIMIT_REG (0x53 << MEM_MAP_SHIFT) + +#define PATTERN_LIMIT_STRT_OFST (0) +#define PATTERN_LIMIT_STRT_MSK (0x0000FFFF << PATTERN_LIMIT_STRT_OFST) +#define PATTERN_LIMIT_STP_OFST (16) +#define PATTERN_LIMIT_STP_MSK (0x0000FFFF << PATTERN_LIMIT_STP_OFST) + +/* Pattern Loop 0 Address RW regiser */ +#define PATTERN_LOOP_0_ADDR_REG (0x54 << MEM_MAP_SHIFT) + +#define PATTERN_LOOP_0_ADDR_STRT_OFST (0) +#define PATTERN_LOOP_0_ADDR_STRT_MSK (0x0000FFFF << PATTERN_LOOP_0_ADDR_STRT_OFST) +#define PATTERN_LOOP_0_ADDR_STP_OFST (16) +#define PATTERN_LOOP_0_ADDR_STP_MSK (0x0000FFFF << PATTERN_LOOP_0_ADDR_STP_OFST) + +/* Pattern Loop 0 Iteration RW regiser */ +#define PATTERN_LOOP_0_ITERATION_REG (0x55 << MEM_MAP_SHIFT) + +/* Pattern Loop 1 Address RW regiser */ +#define PATTERN_LOOP_1_ADDR_REG (0x56 << MEM_MAP_SHIFT) + +#define PATTERN_LOOP_1_ADDR_STRT_OFST (0) +#define PATTERN_LOOP_1_ADDR_STRT_MSK (0x0000FFFF << PATTERN_LOOP_1_ADDR_STRT_OFST) +#define PATTERN_LOOP_1_ADDR_STP_OFST (16) +#define PATTERN_LOOP_1_ADDR_STP_MSK (0x0000FFFF << PATTERN_LOOP_1_ADDR_STP_OFST) + +/* Pattern Loop 1 Iteration RW regiser */ +#define PATTERN_LOOP_1_ITERATION_REG (0x57 << MEM_MAP_SHIFT) + +/* Pattern Loop 2 Address RW regiser */ +#define PATTERN_LOOP_2_ADDR_REG (0x58 << MEM_MAP_SHIFT) + +#define PATTERN_LOOP_2_ADDR_STRT_OFST (0) +#define PATTERN_LOOP_2_ADDR_STRT_MSK (0x0000FFFF << PATTERN_LOOP_2_ADDR_STRT_OFST) +#define PATTERN_LOOP_2_ADDR_STP_OFST (16) +#define PATTERN_LOOP_2_ADDR_STP_MSK (0x0000FFFF << PATTERN_LOOP_2_ADDR_STP_OFST) + +/* Pattern Loop 2 Iteration RW regiser */ +#define PATTERN_LOOP_2_ITERATION_REG (0x59 << MEM_MAP_SHIFT) + +/* Pattern Wait 0 RW regiser */ +#define PATTERN_WAIT_0_ADDR_REG (0x5A << MEM_MAP_SHIFT) + +#define PATTERN_WAIT_0_ADDR_OFST (0) +#define PATTERN_WAIT_0_ADDR_MSK (0x0000FFFF << PATTERN_WAIT_0_ADDR_OFST) +//FIXME: is mask 3FF + +/* Pattern Wait 1 RW regiser */ +#define PATTERN_WAIT_1_ADDR_REG (0x5B << MEM_MAP_SHIFT) + +#define PATTERN_WAIT_1_ADDR_OFST (0) +#define PATTERN_WAIT_1_ADDR_MSK (0x0000FFFF << PATTERN_WAIT_1_ADDR_OFST) + +/* Pattern Wait 2 RW regiser */ +#define PATTERN_WAIT_2_ADDR_REG (0x5C << MEM_MAP_SHIFT) + +#define PATTERN_WAIT_2_ADDR_OFST (0) +#define PATTERN_WAIT_2_ADDR_MSK (0x0000FFFF << PATTERN_WAIT_2_ADDR_OFST) + +/* Samples RW register */ +#define SAMPLES_REG (0x5D << MEM_MAP_SHIFT) + +/** Power RW register */ +#define POWER_REG (0x5E << MEM_MAP_SHIFT) + +#define POWER_ENBL_VLTG_RGLTR_OFST (16) +#define POWER_ENBL_VLTG_RGLTR_MSK (0x0000001F << POWER_ENBL_VLTG_RGLTR_OFST) +#define POWER_HV_SLCT_OFST (31) +#define POWER_HV_SLCT_MSK (0x00000001 << POWER_HV_SLCT_OFST) + +/* Number of Words RW register TODO */ +#define NUMBER_OF_WORDS_REG (0x5F << MEM_MAP_SHIFT) + + +/* Delay 64 bit RW register. t = DLY x 50 ns. */ +#define DELAY_LSB_REG (0x60 << MEM_MAP_SHIFT) +#define DELAY_MSB_REG (0x61 << MEM_MAP_SHIFT) + +/* Cycles 64 bit RW register */ +#define CYCLES_LSB_REG (0x62 << MEM_MAP_SHIFT) +#define CYCLES_MSB_REG (0x63 << MEM_MAP_SHIFT) + +/* Frames 64 bit RW register */ +#define FRAMES_LSB_REG (0x64 << MEM_MAP_SHIFT) +#define FRAMES_MSB_REG (0x65 << MEM_MAP_SHIFT) + +/* Period 64 bit RW register */ +#define PERIOD_LSB_REG (0x66 << MEM_MAP_SHIFT) +#define PERIOD_MSB_REG (0x67 << MEM_MAP_SHIFT) + +/* Period 64 bit RW register */ +//#define EXPTIME_LSB_REG (0x68 << MEM_MAP_SHIFT) // Not used in FW +//#define EXPTIME_MSB_REG (0x69 << MEM_MAP_SHIFT) // Not used in FW + +/* Gates 64 bit RW register */ +//#define GATES_LSB_REG (0x6A << MEM_MAP_SHIFT) // Not used in FW +//#define GATES_MSB_REG (0x6B << MEM_MAP_SHIFT) // Not used in FW + +/* Pattern IO Control 64 bit RW regiser + * Each bit configured as output(1)/ input(0) */ +#define PATTERN_IO_CNTRL_LSB_REG (0x6C << MEM_MAP_SHIFT) +#define PATTERN_IO_CNTRL_MSB_REG (0x6D << MEM_MAP_SHIFT) + +/* Pattern IO Clock Control 64 bit RW regiser + * When bit n enabled (1), clocked output for DIO[n] (T run clock) + * When bit n disabled (0), Dio[n] driven by its pattern output */ +#define PATTERN_IO_CLK_CNTRL_LSB_REG (0x6E << MEM_MAP_SHIFT) +#define PATTERN_IO_CLK_CNTRL_MSB_REG (0x6F << MEM_MAP_SHIFT) + +/* Pattern In 64 bit RW register */ +#define PATTERN_IN_LSB_REG (0x70 << MEM_MAP_SHIFT) +#define PATTERN_IN_MSB_REG (0x71 << MEM_MAP_SHIFT) + +/* Pattern Wait Timer 0 64 bit RW register. t = PWT1 x T run clock */ +#define PATTERN_WAIT_TIMER_0_LSB_REG (0x72 << MEM_MAP_SHIFT) +#define PATTERN_WAIT_TIMER_0_MSB_REG (0x73 << MEM_MAP_SHIFT) + +/* Pattern Wait Timer 1 64 bit RW register. t = PWT2 x T run clock */ +#define PATTERN_WAIT_TIMER_1_LSB_REG (0x74 << MEM_MAP_SHIFT) +#define PATTERN_WAIT_TIMER_1_MSB_REG (0x75 << MEM_MAP_SHIFT) + +/* Pattern Wait Timer 2 64 bit RW register. t = PWT3 x T run clock */ +#define PATTERN_WAIT_TIMER_2_LSB_REG (0x76 << MEM_MAP_SHIFT) +#define PATTERN_WAIT_TIMER_2_MSB_REG (0x77 << MEM_MAP_SHIFT) + +/* ADC Disable RW register TODO */ +#define ADC_DISABLE_REG (0x78 << MEM_MAP_SHIFT) + +/* DAC Value RW register TODO */ +//#define DAC_VALUE_REG (0x79 << MEM_MAP_SHIFT) + +/* DAC Number RW register TODO */ +//#define DAC_NUMBER_REG (0x7A << MEM_MAP_SHIFT) + +/* Digital Bit External Trigger RW register */ +#define DBIT_EXT_TRG_REG (0x7B << MEM_MAP_SHIFT) + +#define DBIT_EXT_TRG_SRC_OFST (0) +#define DBIT_EXT_TRG_SRC_MSK (0x0000003F << DBIT_EXT_TRG_SRC_OFST) +#define DBIT_EXT_TRG_OPRTN_MD_OFST (16) +#define DBIT_EXT_TRG_OPRTN_MD_MSK (0x00000001 << DBIT_EXT_TRG_OPRTN_MD_OFST) + +/* Pin Delay 0 RW register */ +#define OUTPUT_DELAY_0_REG (0x7C << MEM_MAP_SHIFT) +#define OUTPUT_DELAY_0_OTPT_STTNG_STEPS (25) +#define OUTPUT_DELAY_0_OTPT_STTNG_OFST (0) //t = OTPT_STTNG * 25 ps, max for Cyclone V = 775 ps +#define OUTPUT_DELAY_0_OTPT_STTNG_MSK (0x0000001F << OUTPUT_DELAY_0_OTPT_STTNG_OFST) +// 1: load dynamic output settings, 0: trigger start of dynamic output delay configuration pn falling edge of ODT (output delay trigger) bit +#define OUTPUT_DELAY_0_OTPT_TRGGR_OFST (31) +#define OUTPUT_DELAY_0_OTPT_TRGGR_MSK (0x00000001 << OUTPUT_DELAY_0_OTPT_TRGGR_OFST) +#define OUTPUT_DELAY_0_OTPT_TRGGR_LD_VAL (1) +#define OUTPUT_DELAY_0_OTPT_TRGGR_STRT_VAL (0) + +/* Pin Delay 1 RW register + * Each bit configured as enable for dynamic output delay configuration */ +#define PIN_DELAY_1_REG (0x7D << MEM_MAP_SHIFT) + +/** Pattern Mask 64 bit RW regiser */ +#define PATTERN_MASK_LSB_REG (0x80 << MEM_MAP_SHIFT) +#define PATTERN_MASK_MSB_REG (0x81 << MEM_MAP_SHIFT) + +/** Pattern Set 64 bit RW regiser */ +#define PATTERN_SET_LSB_REG (0x82 << MEM_MAP_SHIFT) +#define PATTERN_SET_MSB_REG (0x83 << MEM_MAP_SHIFT) + + + + + diff --git a/slsDetectorServers/moenchDetectorServer/UDPPacketHeaderGenerator.h b/slsDetectorServers/moenchDetectorServer/UDPPacketHeaderGenerator.h new file mode 120000 index 000000000..eb0223a3e --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/UDPPacketHeaderGenerator.h @@ -0,0 +1 @@ +../slsDetectorServer/UDPPacketHeaderGenerator.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/ansi.h b/slsDetectorServers/moenchDetectorServer/ansi.h new file mode 120000 index 000000000..4a82d0575 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/ansi.h @@ -0,0 +1 @@ +../../slsSupportLib/include/ansi.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/blackfin.h b/slsDetectorServers/moenchDetectorServer/blackfin.h new file mode 120000 index 000000000..2873c7dc6 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/blackfin.h @@ -0,0 +1 @@ +../slsDetectorServer/blackfin.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/common.h b/slsDetectorServers/moenchDetectorServer/common.h new file mode 120000 index 000000000..6776eb607 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/common.h @@ -0,0 +1 @@ +../slsDetectorServer/common.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/commonServerFunctions.h b/slsDetectorServers/moenchDetectorServer/commonServerFunctions.h new file mode 120000 index 000000000..33bdd8d53 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/commonServerFunctions.h @@ -0,0 +1 @@ +../slsDetectorServer/commonServerFunctions.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/communication_funcs.c b/slsDetectorServers/moenchDetectorServer/communication_funcs.c new file mode 120000 index 000000000..30435fdc4 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/communication_funcs.c @@ -0,0 +1 @@ +../slsDetectorServer/communication_funcs.c \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/communication_funcs.h b/slsDetectorServers/moenchDetectorServer/communication_funcs.h new file mode 120000 index 000000000..c0c144994 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/communication_funcs.h @@ -0,0 +1 @@ +../slsDetectorServer/communication_funcs.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/communication_funcs_UDP.h b/slsDetectorServers/moenchDetectorServer/communication_funcs_UDP.h new file mode 120000 index 000000000..0d434a97d --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/communication_funcs_UDP.h @@ -0,0 +1 @@ +../slsDetectorServer/communication_funcs_UDP.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/logger.h b/slsDetectorServers/moenchDetectorServer/logger.h new file mode 120000 index 000000000..ff1930ce3 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/logger.h @@ -0,0 +1 @@ +../slsDetectorServer/logger.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/programfpga.h b/slsDetectorServers/moenchDetectorServer/programfpga.h new file mode 120000 index 000000000..72c54d21d --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/programfpga.h @@ -0,0 +1 @@ +../slsDetectorServer/programfpga.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/slsDetectorFunctionList.c b/slsDetectorServers/moenchDetectorServer/slsDetectorFunctionList.c new file mode 100755 index 000000000..0a87846d6 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/slsDetectorFunctionList.c @@ -0,0 +1,2119 @@ +#include "slsDetectorFunctionList.h" +#include "versionAPI.h" +#include "logger.h" + +#include "communication_funcs_UDP.h" +#include "UDPPacketHeaderGenerator.h" +#include "AD9257.h" // commonServerFunctions.h, blackfin.h, ansi.h +#include "LTC2620.h" // dacs +#include "MAX1932.h" // hv +#include "ALTERA_PLL.h" // pll +#ifndef VIRTUAL +#include "programfpga.h" +#else +#include "blackfin.h" +#include +#include // usleep +#include +#include +#endif + +// Global variable from slsDetectorServer_funcs +extern int debugflag; + +// Global variable from UDPPacketHeaderGenerator +extern uint64_t udpFrameNumber; +extern uint32_t udpPacketNumber; + +int firmware_compatibility = OK; +int firmware_check_done = 0; +char firmware_message[MAX_STR_LENGTH]; + +#ifdef VIRTUAL +pthread_t pthread_virtual_tid; +int virtual_status = 0; +int virtual_stop = 0; +#endif + +int dataBytes = 0; +char* ramValues = 0; +char udpPacketData[UDP_PACKET_DATA_BYTES + sizeof(sls_detector_header)]; + +int32_t clkPhase[NUM_CLOCKS] = {0, 0, 0, 0}; +uint32_t clkDivider[NUM_CLOCKS] = {40, 20, 20, 200}; + +int dacValues[NDAC] = {0}; +// software limit that depends on the current chip on the ctb +int vLimit = 0; + +int highvoltage = 0; +ROI rois[MAX_ROIS]; +int nROI = 0; +uint32_t adcDisableMask = 0; +int nSamples = 1; +char volatile *now_ptr = 0; + +// basic tests +int isFirmwareCheckDone() { + return firmware_check_done; +} + +int getFirmwareCheckResult(char** mess) { + *mess = firmware_message; + return firmware_compatibility; +} + +void basictests() { + firmware_compatibility = OK; + firmware_check_done = 0; + memset(firmware_message, 0, MAX_STR_LENGTH); +#ifdef VIRTUAL + FILE_LOG(logINFOBLUE, ("******** Moench Detector Virtual Server *****************\n")); + if (mapCSP0() == FAIL) { + strcpy(firmware_message, + "Could not map to memory. Dangerous to continue.\n"); + FILE_LOG(logERROR, (firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + firmware_check_done = 1; + return; +#else + + defineGPIOpins(); + resetFPGA(); + if (mapCSP0() == FAIL) { + strcpy(firmware_message, + "Could not map to memory. Dangerous to continue.\n"); + FILE_LOG(logERROR, ("%s\n\n", firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + + // does check only if flag is 0 (by default), set by command line + if ((!debugflag) && ((checkType() == FAIL) || (testFpga() == FAIL) || (testBus() == FAIL))) { + strcpy(firmware_message, + "Could not pass basic tests of FPGA and bus. Dangerous to continue.\n"); + FILE_LOG(logERROR, ("%s\n\n", firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + + uint16_t hversion = getHardwareVersionNumber(); + uint16_t hsnumber = getHardwareSerialNumber(); + uint32_t ipadd = getDetectorIP(); + uint64_t macadd = getDetectorMAC(); + int64_t fwversion = getDetectorId(DETECTOR_FIRMWARE_VERSION); + int64_t swversion = getDetectorId(DETECTOR_SOFTWARE_VERSION); + int64_t sw_fw_apiversion = 0; + int64_t client_sw_apiversion = getDetectorId(CLIENT_SOFTWARE_API_VERSION); + + + if (fwversion >= MIN_REQRD_VRSN_T_RD_API) + sw_fw_apiversion = getDetectorId(SOFTWARE_FIRMWARE_API_VERSION); + FILE_LOG(logINFOBLUE, ("************ Moench Detector Server *********************\n" + "Hardware Version:\t\t 0x%x\n" + "Hardware Serial Nr:\t\t 0x%x\n" + + "Detector IP Addr:\t\t 0x%x\n" + "Detector MAC Addr:\t\t 0x%llx\n\n" + + "Firmware Version:\t\t 0x%llx\n" + "Software Version:\t\t 0x%llx\n" + "F/w-S/w API Version:\t\t 0x%llx\n" + "Required Firmware Version:\t 0x%x\n" + "Client-Software API Version:\t 0x%llx\n" + "********************************************************\n", + hversion, hsnumber, + ipadd, + (long long unsigned int)macadd, + (long long int)fwversion, + (long long int)swversion, + (long long int)sw_fw_apiversion, + REQRD_FRMWR_VRSN, + (long long int)client_sw_apiversion + )); + + // return if flag is not zero, debug mode + if (debugflag) { + firmware_check_done = 1; + return; + } + + + //cant read versions + FILE_LOG(logINFO, ("Testing Firmware-software compatibility:\n")); + if(!fwversion || !sw_fw_apiversion){ + strcpy(firmware_message, + "Cant read versions from FPGA. Please update firmware.\n"); + FILE_LOG(logERROR, (firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + + //check for API compatibility - old server + if(sw_fw_apiversion > REQRD_FRMWR_VRSN){ + sprintf(firmware_message, + "This detector software software version (0x%llx) is incompatible.\n" + "Please update detector software (min. 0x%llx) to be compatible with this firmware.\n", + (long long int)sw_fw_apiversion, + (long long int)REQRD_FRMWR_VRSN); + FILE_LOG(logERROR, (firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + + //check for firmware compatibility - old firmware + if( REQRD_FRMWR_VRSN > fwversion) { + sprintf(firmware_message, + "This firmware version (0x%llx) is incompatible.\n" + "Please update firmware (min. 0x%llx) to be compatible with this server.\n", + (long long int)fwversion, + (long long int)REQRD_FRMWR_VRSN); + FILE_LOG(logERROR, (firmware_message)); + firmware_compatibility = FAIL; + firmware_check_done = 1; + return; + } + FILE_LOG(logINFO, ("\tCompatibility - success\n")); + firmware_check_done = 1; +#endif +} + +int checkType() { +#ifdef VIRTUAL + return OK; +#endif + uint32_t type = ((bus_r(FPGA_VERSION_REG) & FPGA_VERSION_DTCTR_TYP_MSK) >> FPGA_VERSION_DTCTR_TYP_OFST); + uint32_t expectedType = (((FPGA_VERSION_DTCTR_TYP_MOENCH_VAL) & FPGA_VERSION_DTCTR_TYP_MSK) >> FPGA_VERSION_DTCTR_TYP_OFST); + + if (type != expectedType) { + FILE_LOG(logERROR, ("This is not a Moench Detector Server (read %d, expected %d)\n", + type, expectedType)); + return FAIL; + } + return OK; +} + +int testFpga() { +#ifdef VIRTUAL + return OK; +#endif + FILE_LOG(logINFO, ("Testing FPGA:\n")); + + //fixed pattern + int ret = OK; + uint32_t val = bus_r(FIX_PATT_REG); + if (val == FIX_PATT_VAL) { + FILE_LOG(logINFO, ("\tFixed pattern: successful match (0x%08x)\n",val)); + } else { + FILE_LOG(logERROR, ("Fixed pattern does not match! Read 0x%08x, expected 0x%08x\n", val, FIX_PATT_VAL)); + ret = FAIL; + } + + if (ret == OK) { + // Delay LSB reg + FILE_LOG(logINFO, ("\tTesting Delay LSB Register:\n")); + uint32_t addr = DELAY_LSB_REG; + + // store previous delay value + uint32_t previousValue = bus_r(addr); + + volatile uint32_t val = 0, readval = 0; + int times = 1000 * 1000; + int i = 0; + for (i = 0; i < times; ++i) { + val = 0x5A5A5A5A - i; + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("1:Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + break; + } + val = (i + (i << 10) + (i << 20)); + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("2:Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + break; + } + val = 0x0F0F0F0F; + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("3:Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + break; + } + val = 0xF0F0F0F0; + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("4:Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + break; + } + } + // write back previous value + bus_w(addr, previousValue); + if (ret == OK) { + FILE_LOG(logINFO, ("\tSuccessfully tested FPGA Delay LSB Register %d times\n", times)); + } + } + + return ret; +} + +int testBus() { +#ifdef VIRTUAL + return OK; +#endif + FILE_LOG(logINFO, ("Testing Bus:\n")); + + int ret = OK; + uint32_t addr = DELAY_LSB_REG; + + // store previous delay value + uint32_t previousValue = bus_r(addr); + + volatile uint32_t val = 0, readval = 0; + int times = 1000 * 1000; + int i = 0; + + for (i = 0; i < times; ++i) { + val += 0xbbbbb; + bus_w(addr, val); + readval = bus_r(addr); + if (readval != val) { + FILE_LOG(logERROR, ("Mismatch! Loop(%d): Wrote 0x%x, read 0x%x\n", + i, val, readval)); + ret = FAIL; + } + } + + // write back previous value + bus_w(addr, previousValue); + + if (ret == OK) { + FILE_LOG(logINFO, ("\tSuccessfully tested bus %d times\n", times)); + } + return ret; +} + +int detectorTest( enum digitalTestMode arg){ +#ifdef VIRTUAL + return OK; +#endif + switch(arg){ + case DETECTOR_FIRMWARE_TEST: return testFpga(); + case DETECTOR_BUS_TEST: return testBus(); + default: + FILE_LOG(logERROR, ("Test %s not implemented for this detector\n", (int)arg)); + break; + } + return OK; +} + + +/* Ids */ + +int64_t getDetectorId(enum idMode arg){ + int64_t retval = -1; + + switch(arg){ + case DETECTOR_SERIAL_NUMBER: + return getDetectorNumber(); + case DETECTOR_FIRMWARE_VERSION: + return getFirmwareVersion(); + case SOFTWARE_FIRMWARE_API_VERSION: + return getFirmwareAPIVersion(); + case DETECTOR_SOFTWARE_VERSION: + case CLIENT_SOFTWARE_API_VERSION: + return APIMOENCH; + default: + return retval; + } +} + +uint64_t getFirmwareVersion() { +#ifdef VIRTUAL + return 0; +#endif + return ((bus_r(FPGA_VERSION_REG) & FPGA_VERSION_BRD_RVSN_MSK) >> FPGA_VERSION_BRD_RVSN_OFST); +} + +uint64_t getFirmwareAPIVersion() { +#ifdef VIRTUAL + return 0; +#endif + return ((bus_r(API_VERSION_REG) & API_VERSION_MSK) >> API_VERSION_OFST); +} + +uint16_t getHardwareVersionNumber() { +#ifdef VIRTUAL + return 0; +#endif + return ((bus_r(MOD_SERIAL_NUMBER_REG) & MOD_SERIAL_NUMBER_VRSN_MSK) >> MOD_SERIAL_NUMBER_VRSN_OFST); +} + +uint16_t getHardwareSerialNumber() { +#ifdef VIRTUAL + return 0; +#endif + return ((bus_r(MOD_SERIAL_NUMBER_REG) & MOD_SERIAL_NUMBER_MSK) >> MOD_SERIAL_NUMBER_OFST); +} + +uint32_t getDetectorNumber(){ +#ifdef VIRTUAL + return 0; +#endif + return bus_r(MOD_SERIAL_NUMBER_REG); +} + +uint64_t getDetectorMAC() { +#ifdef VIRTUAL + return 0; +#else + char output[255],mac[255]=""; + uint64_t res=0; + FILE* sysFile = popen("ifconfig eth0 | grep HWaddr | cut -d \" \" -f 11", "r"); + fgets(output, sizeof(output), sysFile); + pclose(sysFile); + //getting rid of ":" + char * pch; + pch = strtok (output,":"); + while (pch != NULL){ + strcat(mac,pch); + pch = strtok (NULL, ":"); + } + sscanf(mac,"%llx",&res); + return res; +#endif +} + +uint32_t getDetectorIP(){ +#ifdef VIRTUAL + return 0; +#endif + char temp[50]=""; + uint32_t res=0; + //execute and get address + char output[255]; + FILE* sysFile = popen("ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2", "r"); + fgets(output, sizeof(output), sysFile); + pclose(sysFile); + + //converting IPaddress to hex. + char* pcword = strtok (output,"."); + while (pcword != NULL) { + sprintf(output,"%02x",atoi(pcword)); + strcat(temp,output); + pcword = strtok (NULL, "."); + } + strcpy(output,temp); + sscanf(output, "%x", &res); + //FILE_LOG(logINFO, ("ip:%x\n",res); + + return res; +} + + +/* initialization */ + +void initControlServer(){ + setupDetector(); +} + +void initStopServer() { + + usleep(CTRL_SRVR_INIT_TIME_US); + if (mapCSP0() == FAIL) { + FILE_LOG(logERROR, ("Stop Server: Map Fail. Dangerous to continue. Goodbye!\n")); + exit(EXIT_FAILURE); + } +} + + +/* set up detector */ + +void setupDetector() { + FILE_LOG(logINFO, ("This Server is for 1 moench board\n")); + + // default variables + dataBytes = 0; + if (ramValues) { + free(ramValues); + ramValues = 0; + } + { + int i = 0; + for (i = 0; i < NUM_CLOCKS; ++i) { + clkPhase[i] = 0; + } + clkDivider[RUN_CLK] = DEFAULT_RUN_CLK; + clkDivider[ADC_CLK] = DEFAULT_ADC_CLK; + clkDivider[SYNC_CLK] = DEFAULT_SYNC_CLK; + clkDivider[DBIT_CLK] = DEFAULT_DBIT_CLK; + for (i = 0; i < NDAC; ++i) + dacValues[i] = -1; + } + vLimit = DEFAULT_VLIMIT; + highvoltage = 0; + nROI = 0; + adcDisableMask = 0; + nSamples = 1; + now_ptr = 0; + + + ALTERA_PLL_ResetPLLAndReconfiguration(); + resetCore(); + resetPeripheral(); + cleanFifos(); + + // hv + MAX1932_SetDefines(SPI_REG, SPI_HV_SRL_CS_OTPT_MSK, SPI_HV_SRL_CLK_OTPT_MSK, SPI_HV_SRL_DGTL_OTPT_MSK, SPI_HV_SRL_DGTL_OTPT_OFST, HIGHVOLTAGE_MIN, HIGHVOLTAGE_MAX); + MAX1932_Disable(); + setHighVoltage(DEFAULT_HIGH_VOLTAGE); + + // adc + AD9257_SetDefines(ADC_SPI_REG, ADC_SPI_SRL_CS_OTPT_MSK, ADC_SPI_SRL_CLK_OTPT_MSK, ADC_SPI_SRL_DT_OTPT_MSK, ADC_SPI_SRL_DT_OTPT_OFST); + AD9257_Disable(); + AD9257_Configure(); + + //dac + LTC2620_SetDefines(SPI_REG, SPI_DAC_SRL_CS_OTPT_MSK, SPI_DAC_SRL_CLK_OTPT_MSK, SPI_DAC_SRL_DGTL_OTPT_MSK, SPI_DAC_SRL_DGTL_OTPT_OFST, NDAC, DAC_MIN_MV, DAC_MAX_MV); + LTC2620_Disable(); + LTC2620_Configure(); + //FIXME: + // switch off dacs (power regulators most likely only sets to minimum (if power enable on)) + FILE_LOG(logINFOBLUE, ("Powering down all dacs\n")); + { + int idac = 0; + for (idac = 0; idac < NDAC; ++idac) { + setDAC(idac, LTC2620_PWR_DOWN_VAL, 0); + } + } + + // altera pll + ALTERA_PLL_SetDefines(PLL_CNTRL_REG, PLL_PARAM_REG, PLL_CNTRL_RCNFG_PRMTR_RST_MSK, PLL_CNTRL_WR_PRMTR_MSK, PLL_CNTRL_PLL_RST_MSK, PLL_CNTRL_ADDR_MSK, PLL_CNTRL_ADDR_OFST); + + bus_w(ADC_PORT_INVERT_REG, ADC_PORT_INVERT_VAL);//FIXME: got from moench config file + + FILE_LOG(logINFOBLUE, ("Setting Default parameters\n")); + cleanFifos(); // FIXME: why twice? + resetCore(); + + // 10 G UDP + enableTenGigabitEthernet(1); + + //Initialization of acquistion parameters + setTimer(SAMPLES, DEFAULT_NUM_SAMPLES); // update databytes and allocate ram + setTimer(FRAME_NUMBER, DEFAULT_NUM_FRAMES); + setTimer(ACQUISITION_TIME, DEFAULT_EXPTIME); + setTimer(CYCLES_NUMBER, DEFAULT_NUM_CYCLES); + setTimer(FRAME_PERIOD, DEFAULT_PERIOD); + setTimer(DELAY_AFTER_TRIGGER, DEFAULT_DELAY); + setTiming(DEFAULT_TIMING_MODE); + + // ensuring normal readout (only option for moench) + bus_w(CONFIG_REG, bus_r(CONFIG_REG) & (~CONFIG_DSBL_ANLG_OTPT_MSK) & (~CONFIG_ENBLE_DGTL_OTPT_MSK)); + + // clear roi + { + int ret = OK, retvalsize = 0; + setROI(0, rois, &retvalsize, &ret); + } +} + +int allocateRAM() { + int oldDataBytes = dataBytes; + updateDataBytes(); + + // only allcoate RAM for 1 giga udp (if 10G, return) + if (enableTenGigabitEthernet(-1)) + return OK; + + // update only if change in databytes + if (dataBytes == oldDataBytes) { + FILE_LOG(logDEBUG1, ("RAM of size %d already allocated. Nothing to be done.\n", dataBytes)); + return OK; + } + // Zero databytes + if (dataBytes <= 0) { + FILE_LOG(logERROR, ("Can not allocate RAM for 0 bytes (databytes: 0).\n")); + return FAIL; + } + // clear RAM + if (ramValues) { + free(ramValues); + ramValues = 0; + } + // allocate RAM + ramValues = malloc(dataBytes); + // cannot malloc + if (ramValues == NULL) { + FILE_LOG(logERROR, ("Can not allocate RAM for even 1 frame. " + "Probably cause: Memory Leak.\n")); + return FAIL; + } + + FILE_LOG(logINFO, ("\tRAM allocated to %d bytes\n", dataBytes)); + return OK; +} + +void updateDataBytes() { + int oldDataBytes = dataBytes; + dataBytes = NCHIP * getChannels() * NUM_BYTES_PER_PIXEL * nSamples; + if (dataBytes != oldDataBytes) { + FILE_LOG(logINFO, ("\tUpdating Databytes: %d\n", dataBytes)); + } +} + +int getChannels() { + int nchans = 0; + + nchans += NCHAN; + // remove the channels disabled + int ichan = 0; + for (ichan = 0; ichan < NCHAN; ++ichan) { + if (adcDisableMask & (1 << ichan)) + --nchans; + } + + FILE_LOG(logINFO, ("\tNumber of Channels calculated: %d\n", nchans)) + return nchans; +} + + +/* firmware functions (resets) */ + +void cleanFifos() { +#ifdef VIRTUAL + return; +#endif + FILE_LOG(logINFO, ("Clearing Acquisition Fifos\n")); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_CLR_ACQSTN_FIFO_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_CLR_ACQSTN_FIFO_MSK); +} + +void resetCore() { +#ifdef VIRTUAL + return; +#endif + FILE_LOG(logINFO, ("Resetting Core\n")); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_CRE_RST_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_CRE_RST_MSK); +} + +void resetPeripheral() { +#ifdef VIRTUAL + return; +#endif + FILE_LOG(logINFO, ("Resetting Peripheral\n")); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_PRPHRL_RST_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_PRPHRL_RST_MSK); +} + + +/* set parameters - dr, roi */ + +int setDynamicRange(int dr){ + return DYNAMIC_RANGE; +} + +ROI* setROI(int n, ROI arg[], int *retvalsize, int *ret) { + uint32_t addr = ADC_DISABLE_REG; + + // set ROI + if(n >= 0) { + // clear roi + if (!n) { + FILE_LOG(logINFO, ("Clearing ROI\n")); + adcDisableMask = 0; + } + // set roi + else { + FILE_LOG(logINFO, ("Setting ROI:\n")); + adcDisableMask = 0xffffffff; + int iroi = 0; + // for every roi + for (iroi = 0; iroi < n; ++iroi) { + FILE_LOG(logINFO, ("\t%d: (%d, %d)\n", iroi, arg[iroi].xmin, arg[iroi].xmax)); + // swap if xmin > xmax + if (arg[iroi].xmin > arg[iroi].xmax) { + int temp = arg[iroi].xmin; + arg[iroi].xmin = arg[iroi].xmax; + arg[iroi].xmax = temp; + FILE_LOG(logINFORED, ("\tCorrected %d: (%d, %d)\n", iroi, arg[iroi].xmin, arg[iroi].xmax)); + } + int ich = 0; + // for the roi specified + for (ich = arg[iroi].xmin; ich <= arg[iroi].xmax; ++ich) { + // valid channel (disable) + if (ich >= 0 && ich < NCHAN) + adcDisableMask &= ~(1 << ich); + + FILE_LOG(logDEBUG1, ("%d: ich:%d adcDisableMask:0x%08x\n", + iroi, ich, adcDisableMask)); + } + } + } + FILE_LOG(logINFO, ("\tSetting adcDisableMask to 0x%08x\n", adcDisableMask)); + bus_w(addr, adcDisableMask); + } + + // get roi + adcDisableMask = bus_r(addr); + FILE_LOG(logDEBUG1, ("Getting adcDisableMask: 0x%08x\n", adcDisableMask)); + + nROI = 0; + if (adcDisableMask) { + int ich = 0; + // loop through channels + for (ich = 0; ich < NCHAN; ++ich) { + // channel disabled + if ((~adcDisableMask) & (1 << ich)) { + // first channel + if (ich == 0) { + ++nROI; + rois[nROI - 1].xmin = ich; + rois[nROI - 1].xmax = ich; + rois[nROI - 1].ymin = -1; + rois[nROI - 1].ymax = -1; + } + // not first channel + else { + // previous channel enabled (so increase roi) + if ((adcDisableMask) & (1 << (ich - 1))) { + ++nROI; + // max roi level + if (nROI > MAX_ROIS) { + nROI = -1; + *ret = FAIL; + FILE_LOG(logERROR, ("Max ROI reached!\n")); + break; + } + rois[nROI - 1].xmin = ich; + rois[nROI - 1].ymin = -1; + rois[nROI - 1].ymax = -1; + } + // set max as current one each time + rois[nROI - 1].xmax = ich; + } + } + } + } + + // print + if (!nROI) { + FILE_LOG(logINFO, ("\tROI: None\n")); + } else { + FILE_LOG(logINFO, ("ROI:\n")); + int i = 0; + for (i = 0; i < nROI; ++i) { + FILE_LOG(logINFO, ("\t%d: (%d, %d)\n", i, rois[i].xmin, rois[i].xmax)); + + } + } + + // validate and update databytes + if (n >= 0) { + // validate + if((n != 0) && ((arg[0].xmin != rois[0].xmin)|| + (arg[0].xmax != rois[0].xmax)|| + (arg[0].ymin != rois[0].ymin)|| + (arg[0].ymax != rois[0].ymax))) { + *ret = FAIL; + FILE_LOG(logERROR, ("\tCould not set given ROI\n")); + } + if(n != nROI) { + *ret = FAIL; + FILE_LOG(logERROR, ("\tCould not set or clear ROIs\n")); + } + // update databytes (now that mask is up to date from fpga) and allocate ram + if (allocateRAM() == FAIL) { + *ret = FAIL; + nROI = -2; + } + } + + *retvalsize = nROI; + return rois; +} + + +/* parameters - speed, readout */ + +void setSpeed(enum speedVariable ind, int val, int mode) { + switch(ind) { + case ADC_PHASE: + FILE_LOG(logINFOBLUE, ("Configuring ADC Phase\n")); + configurePhase(ADC_CLK, val, mode); + break; + case DBIT_PHASE: + FILE_LOG(logINFOBLUE, ("Configuring Dbit Phase\n")); + configurePhase(DBIT_CLK, val, mode); + break; + case ADC_CLOCK: + FILE_LOG(logINFOBLUE, ("Configuring ADC Clock\n")); + configureFrequency(ADC_CLK, val); + configureSyncFrequency(ADC_CLK); + break; + case DBIT_CLOCK: + FILE_LOG(logINFOBLUE, ("Configuring Dbit Clock\n")); + configureFrequency(DBIT_CLK, val); + configureSyncFrequency(DBIT_CLK); + break; + case ADC_PIPELINE: + setAdcOffsetRegister(1, val); + break; + case DBIT_PIPELINE: + setAdcOffsetRegister(0, val); + break; + case CLOCK_DIVIDER: + FILE_LOG(logINFOBLUE, ("Configuring Run Clock\n")); + configureFrequency(RUN_CLK, val); + configureSyncFrequency(RUN_CLK); + break; + default: + return; + } +} + +int getSpeed(enum speedVariable ind, int mode) { + switch(ind) { + case ADC_PHASE: + return getPhase(ADC_CLK, mode); + case DBIT_PHASE: + return getPhase(DBIT_CLK, mode); + case MAX_ADC_PHASE_SHIFT: + return getMaxPhase(ADC_CLK); + case MAX_DBIT_PHASE_SHIFT: + return getMaxPhase(DBIT_CLK); + case ADC_CLOCK: + return getFrequency(ADC_CLK); + case DBIT_CLOCK: + return getFrequency(DBIT_CLK); + case CLOCK_DIVIDER: + return getFrequency(RUN_CLK); + case ADC_PIPELINE: + return getAdcOffsetRegister(1); + case DBIT_PIPELINE: + return getAdcOffsetRegister(0); + default: + return -1; + } +} + + + +/* parameters - timer */ +int64_t setTimer(enum timerIndex ind, int64_t val) { + + int64_t retval = -1; + switch(ind){ + + case FRAME_NUMBER: + if(val >= 0) { + FILE_LOG(logINFO, ("Setting #frames: %lld\n",(long long int)val)); + } + retval = set64BitReg(val, FRAMES_LSB_REG, FRAMES_MSB_REG); + FILE_LOG(logINFO, ("\tGetting #frames: %lld\n", (long long int)retval)); + break; + + case ACQUISITION_TIME: + if(val >= 0){ + FILE_LOG(logINFO, ("Setting exptime (pattern wait time level 0): %lldns\n",(long long int)val)); + val *= (1E-3 * clkDivider[RUN_CLK]); + setPatternWaitTime(0, val); + } + retval = setPatternWaitTime(0, -1) / (1E-3 * clkDivider[RUN_CLK]); + FILE_LOG(logINFO, ("\tGetting exptime (pattern wait time level 0): %lldns\n", (long long int)retval)); + break; + + case FRAME_PERIOD: + if(val >= 0){ + FILE_LOG(logINFO, ("Setting period: %lldns\n",(long long int)val)); + val *= (1E-3 * clkDivider[SYNC_CLK]); + } + retval = set64BitReg(val, PERIOD_LSB_REG, PERIOD_MSB_REG )/ (1E-3 * clkDivider[SYNC_CLK]); + FILE_LOG(logINFO, ("\tGetting period: %lldns\n", (long long int)retval)); + break; + + case DELAY_AFTER_TRIGGER: + if(val >= 0){ + FILE_LOG(logINFO, ("Setting delay: %lldns\n", (long long int)val)); + val *= (1E-3 * clkDivider[SYNC_CLK]); + } + retval = set64BitReg(val, DELAY_LSB_REG, DELAY_MSB_REG) / (1E-3 * clkDivider[SYNC_CLK]); + FILE_LOG(logINFO, ("\tGetting delay: %lldns\n", (long long int)retval)); + break; + + case CYCLES_NUMBER: + if(val >= 0) { + FILE_LOG(logINFO, ("Setting #cycles: %lld\n", (long long int)val)); + } + retval = set64BitReg(val, CYCLES_LSB_REG, CYCLES_MSB_REG); + FILE_LOG(logINFO, ("\tGetting #cycles: %lld\n", (long long int)retval)); + break; + + case SAMPLES: + if(val >= 0) { + FILE_LOG(logINFO, ("Setting #samples: %lld\n", (long long int)val)); + nSamples = val; + bus_w(SAMPLES_REG, val); + if (allocateRAM() == FAIL) { + return -1; + } + } + retval = nSamples; + FILE_LOG(logINFO, ("\tGetting #samples: %lld\n", (long long int)retval)); + break; + + default: + FILE_LOG(logERROR, ("Timer Index not implemented for this detector: %d\n", ind)); + break; + } + + return retval; + +} + + + +int64_t getTimeLeft(enum timerIndex ind){ +#ifdef VIRTUAL + return 0; +#endif + int64_t retval = -1; + switch(ind){ + + case FRAME_NUMBER: + retval = get64BitReg(FRAMES_LEFT_LSB_REG, FRAMES_LEFT_MSB_REG); + FILE_LOG(logINFO, ("Getting number of frames left: %lld\n",(long long int)retval)); + break; + + case FRAME_PERIOD: + retval = get64BitReg(PERIOD_LEFT_LSB_REG, PERIOD_LEFT_MSB_REG) / (1E-3 * clkDivider[SYNC_CLK]); + FILE_LOG(logINFO, ("Getting period left: %lldns\n", (long long int)retval)); + break; + + case DELAY_AFTER_TRIGGER: + retval = get64BitReg(DELAY_LEFT_LSB_REG, DELAY_LEFT_MSB_REG) / (1E-3 * clkDivider[SYNC_CLK]); + FILE_LOG(logINFO, ("Getting delay left: %lldns\n", (long long int)retval)); + break; + + case CYCLES_NUMBER: + retval = get64BitReg(CYCLES_LEFT_LSB_REG, CYCLES_LEFT_MSB_REG); + FILE_LOG(logINFO, ("Getting number of cycles left: %lld\n", (long long int)retval)); + break; + + case ACTUAL_TIME: + retval = get64BitReg(TIME_FROM_START_LSB_REG, TIME_FROM_START_MSB_REG) / (1E-3 * CLK_FREQ); + FILE_LOG(logINFO, ("Getting actual time (time from start): %lld\n", (long long int)retval)); + break; + + case MEASUREMENT_TIME: + retval = get64BitReg(START_FRAME_TIME_LSB_REG, START_FRAME_TIME_MSB_REG) / (1E-3 * CLK_FREQ); + FILE_LOG(logINFO, ("Getting measurement time (timestamp/ start frame time): %lld\n", (long long int)retval)); + break; + + case FRAMES_FROM_START: + case FRAMES_FROM_START_PG: + retval = get64BitReg(FRAMES_FROM_START_PG_LSB_REG, FRAMES_FROM_START_PG_MSB_REG); + FILE_LOG(logINFO, ("Getting frames from start run control %lld\n", (long long int)retval)); + break; + + default: + FILE_LOG(logERROR, ("Remaining Timer index not implemented for this detector: %d\n", ind)); + break; + } + + return retval; +} + + +int validateTimer(enum timerIndex ind, int64_t val, int64_t retval) { + if (val < 0) + return OK; + switch(ind) { + case FRAME_PERIOD: + case DELAY_AFTER_TRIGGER: + // convert to freq + val *= (1E-3 * clkDivider[SYNC_CLK]); + // convert back to timer + val = (val) / (1E-3 * clkDivider[SYNC_CLK]); + if (val != retval) { + return FAIL; + } + break; + + case ACQUISITION_TIME: + // convert to freq + val *= (1E-3 * clkDivider[RUN_CLK]); + // convert back to timer + val = (val) / (1E-3 * clkDivider[RUN_CLK]); + if (val != retval) { + return FAIL; + } + break; + default: + break; + } + return OK; +} + + + +/* parameters - settings */ +enum detectorSettings getSettings() { + return UNDEFINED; +} + +/* parameters - dac, adc, hv */ + +void setDAC(enum DACINDEX ind, int val, int mV) { + if (val < 0 && val != LTC2620_PWR_DOWN_VAL) + return; + + FILE_LOG(logDEBUG1, ("Setting dac[%d]: %d %s \n", (int)ind, val, (mV ? "mV" : "dac units"))); + int dacval = val; +#ifdef VIRTUAL + if (!mV) { + dacValues[ind] = val; + } + // convert to dac units + else if (LTC2620_VoltageToDac(val, &dacval) == OK) { + dacValues[ind] = dacval; + } +#else + if (LTC2620_SetDACValue((int)ind, val, mV, &dacval) == OK) + dacValues[ind] = dacval; +#endif +} + +int getDAC(enum DACINDEX ind, int mV) { + if (!mV) { + FILE_LOG(logDEBUG1, ("Getting DAC %d : %d dac\n",ind, dacValues[ind])); + return dacValues[ind]; + } + int voltage = -1; + LTC2620_DacToVoltage(dacValues[ind], &voltage); + FILE_LOG(logDEBUG1, ("Getting DAC %d : %d dac (%d mV)\n",ind, dacValues[ind], voltage)); + return voltage; +} + +int getMaxDacSteps() { + return LTC2620_MAX_STEPS; +} + +int dacToVoltage(int dac) { + int val; + LTC2620_DacToVoltage(dac, &val); + return val; +} + +int checkVLimitCompliant(int mV) { + if (vLimit > 0 && mV > vLimit) + return FAIL; + return OK; +} + +int checkVLimitDacCompliant(int dac) { + if (vLimit > 0) { + int mv = 0; + // could not convert + if (LTC2620_DacToVoltage(dac, &mv) == FAIL) + return FAIL; + if (mv > vLimit) + return FAIL; + } + return OK; +} + +int getVLimit() { + return vLimit; +} + +void setVLimit(int l) { + if (l >= 0) + vLimit = l; +} + + +int setHighVoltage(int val){ +#ifdef VIRTUAL + if (val >= 0) + highvoltage = val; + return highvoltage; +#endif + // setting hv + if (val >= 0) { + FILE_LOG(logINFO, ("Setting High voltage: %d V\n", val)); + MAX1932_Set(val); + highvoltage = val; + } + + return highvoltage; +} + + + + + + +/* parameters - timing, extsig */ + + +void setTiming( enum externalCommunicationMode arg){ + + if(arg != GET_EXTERNAL_COMMUNICATION_MODE){ + switch((int)arg){ + case AUTO_TIMING: + FILE_LOG(logINFO, ("Set Timing: Auto\n")); + bus_w(EXT_SIGNAL_REG, bus_r(EXT_SIGNAL_REG) & ~EXT_SIGNAL_MSK); + break; + case TRIGGER_EXPOSURE: + FILE_LOG(logINFO, ("Set Timing: Trigger\n")); + bus_w(EXT_SIGNAL_REG, bus_r(EXT_SIGNAL_REG) | EXT_SIGNAL_MSK); + break; + default: + FILE_LOG(logERROR, ("Unknown timing mode %d\n", arg)); + return; + } + } +} + + +enum externalCommunicationMode getTiming() { + if (bus_r(EXT_SIGNAL_REG) == EXT_SIGNAL_MSK) + return TRIGGER_EXPOSURE; + return AUTO_TIMING; +} + + + +/* configure mac */ + + +long int calcChecksum(int sourceip, int destip) { + ip_header ip; + ip.ip_ver = 0x4; + ip.ip_ihl = 0x5; + ip.ip_tos = 0x0; + ip.ip_len = IP_PACKETSIZE; + ip.ip_ident = 0x0000; + ip.ip_flag = 0x2; //not nibble aligned (flag& offset + ip.ip_offset = 0x000; + ip.ip_ttl = 0x40; + ip.ip_protocol = 0x11; + ip.ip_chksum = 0x0000 ; // pseudo + ip.ip_sourceip = sourceip; + ip.ip_destip = destip; + + int count = sizeof(ip); + + unsigned short *addr; + addr = (unsigned short*) &(ip); /* warning: assignment from incompatible pointer type */ + + long int sum = 0; + while( count > 1 ) { + sum += *addr++; + count -= 2; + } + if (count > 0) + sum += *addr; // Add left-over byte, if any + while (sum>>16) + sum = (sum & 0xffff) + (sum >> 16);// Fold 32-bit sum to 16 bits + long int checksum = (~sum) & 0xffff; + FILE_LOG(logINFO, ("IP checksum is 0x%lx\n",checksum)); + return checksum; +} + + + +int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport){ +#ifdef VIRTUAL + return OK; +#endif + FILE_LOG(logINFOBLUE, ("Configuring MAC\n")); + // 1 giga udp + if (!enableTenGigabitEthernet(-1)) { + // if it was in 10G mode, it was not allocating RAM + if (allocateRAM() == FAIL) + return -1; + char cDestIp[MAX_STR_LENGTH]; + memset(cDestIp, 0, MAX_STR_LENGTH); + sprintf(cDestIp, "%d.%d.%d.%d", (destip>>24)&0xff,(destip>>16)&0xff,(destip>>8)&0xff,(destip)&0xff); + FILE_LOG(logINFO, ("1G UDP: Destination (IP: %s, port:%d)\n", cDestIp, udpport)); + if (setUDPDestinationDetails(cDestIp, udpport) == FAIL) { + FILE_LOG(logERROR, ("could not set udp 1G destination IP and port\n")); + return FAIL; + } + return OK; + } + + // 10 G + else { + uint32_t sourceport = DEFAULT_TX_UDP_PORT; + + FILE_LOG(logINFO, ("\tSource IP : %d.%d.%d.%d \t\t(0x%08x)\n", + (sourceip>>24)&0xff,(sourceip>>16)&0xff,(sourceip>>8)&0xff,(sourceip)&0xff, sourceip)); + FILE_LOG(logINFO, ("\tSource MAC : %02x:%02x:%02x:%02x:%02x:%02x \t(0x%010llx)\n", + (unsigned int)((sourcemac>>40)&0xFF), + (unsigned int)((sourcemac>>32)&0xFF), + (unsigned int)((sourcemac>>24)&0xFF), + (unsigned int)((sourcemac>>16)&0xFF), + (unsigned int)((sourcemac>>8)&0xFF), + (unsigned int)((sourcemac>>0)&0xFF), + (long long unsigned int)sourcemac)); + FILE_LOG(logINFO, ("\tSource Port : %d \t\t\t(0x%08x)\n",sourceport, sourceport)); + + FILE_LOG(logINFO, ("\tDest. IP : %d.%d.%d.%d \t\t(0x%08x)\n", + (destip>>24)&0xff,(destip>>16)&0xff,(destip>>8)&0xff,(destip)&0xff, destip)); + FILE_LOG(logINFO, ("\tDest. MAC : %02x:%02x:%02x:%02x:%02x:%02x \t(0x%010llx)\n", + (unsigned int)((destmac>>40)&0xFF), + (unsigned int)((destmac>>32)&0xFF), + (unsigned int)((destmac>>24)&0xFF), + (unsigned int)((destmac>>16)&0xFF), + (unsigned int)((destmac>>8)&0xFF), + (unsigned int)((destmac>>0)&0xFF), + (long long unsigned int)destmac)); + FILE_LOG(logINFO, ("\tDest. Port : %d \t\t\t(0x%08x)\n",udpport, udpport)); + + long int checksum=calcChecksum(sourceip, destip); + bus_w(TX_IP_REG, sourceip); + bus_w(RX_IP_REG, destip); + + uint32_t val = 0; + + val = ((sourcemac >> LSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(TX_MAC_LSB_REG, val); + FILE_LOG(logDEBUG1, ("Read from TX_MAC_LSB_REG: 0x%08x\n", bus_r(TX_MAC_LSB_REG))); + + val = ((sourcemac >> MSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(TX_MAC_MSB_REG,val); + FILE_LOG(logDEBUG1, ("Read from TX_MAC_MSB_REG: 0x%08x\n", bus_r(TX_MAC_MSB_REG))); + + val = ((destmac >> LSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(RX_MAC_LSB_REG, val); + FILE_LOG(logDEBUG1, ("Read from RX_MAC_LSB_REG: 0x%08x\n", bus_r(RX_MAC_LSB_REG))); + + val = ((destmac >> MSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); + bus_w(RX_MAC_MSB_REG, val); + FILE_LOG(logDEBUG1, ("Read from RX_MAC_MSB_REG: 0x%08x\n", bus_r(RX_MAC_MSB_REG))); + + val = (((sourceport << UDP_PORT_TX_OFST) & UDP_PORT_TX_MSK) | + ((udpport << UDP_PORT_RX_OFST) & UDP_PORT_RX_MSK)); + bus_w(UDP_PORT_REG, val); + FILE_LOG(logDEBUG1, ("Read from UDP_PORT_REG: 0x%08x\n", bus_r(UDP_PORT_REG))); + + bus_w(TX_IP_CHECKSUM_REG,(checksum << TX_IP_CHECKSUM_OFST) & TX_IP_CHECKSUM_MSK); + FILE_LOG(logDEBUG1, ("Read from TX_IP_CHECKSUM_REG: 0x%08x\n", bus_r(TX_IP_CHECKSUM_REG))); + + cleanFifos();//FIXME: resetPerpheral() for ctb? + resetPeripheral(); + usleep(WAIT_TIME_CONFIGURE_MAC); /* todo maybe without */ + } + + return OK; +} + +int enableTenGigabitEthernet(int val) { + uint32_t addr = CONFIG_REG; + + // set + if (val != -1) { + FILE_LOG(logINFO, ("Setting 10Gbe: %d\n", (val > 0) ? 1 : 0)); + if (val > 0) { + bus_w(addr, bus_r(addr) | CONFIG_GB10_SND_UDP_MSK); + } else { + bus_w(addr, bus_r(addr) & (~CONFIG_GB10_SND_UDP_MSK)); + } + //configuremac called from client + } + return ((bus_r(addr) & CONFIG_GB10_SND_UDP_MSK) >> CONFIG_GB10_SND_UDP_OFST); +} + + + +/* moench specific - configure frequency, phase, pll, */ + +int powerChip(int on) { + uint32_t addr = POWER_REG; + if (on >= 0) { + FILE_LOG(logINFO, ("Powering %s\n", (on > 0 ? "on" : "off"))); + if (on) + bus_w(addr, bus_r(addr) | POWER_ENBL_VLTG_RGLTR_MSK); + else + bus_w(addr, bus_r(addr) & (~POWER_ENBL_VLTG_RGLTR_MSK)); + } + + uint32_t regval = bus_r(addr); + FILE_LOG(logDEBUG1, ("\tPower Register: 0x%08x\n", regval)); + + if (regval & POWER_ENBL_VLTG_RGLTR_MSK) + return 1; + return 0; +} + +// ind can only be ADC_CLK or DBIT_CLK +void configurePhase(enum CLKINDEX ind, int val, int degrees) { + char clock_names[4][10]={"run_clk","adc_clk", "sync_clk", "dbit_clk"}; + int maxShift = getMaxPhase(ind); + + // validation + if (degrees && (val < 0 || val > 359)) { + FILE_LOG(logERROR, ("\tPhase provided for C%d(%s) outside limits (0 - 359°C)\n", ind, clock_names[ind])); + return; + } + if (!degrees && (val < 0 || val > maxShift - 1)) { + FILE_LOG(logERROR, ("\tPhase provided for C%d(%s) outside limits (0 - %d phase shifts)\n", ind, clock_names[ind], maxShift - 1)); + return; + } + + FILE_LOG(logINFO, ("\tConfiguring Phase of C%d(%s) to %d (degree mode: %d)\n", ind, clock_names[ind], val, degrees)); + int valShift = val; + // convert to phase shift + if (degrees) { + ConvertToDifferentRange(0, 359, 0, maxShift - 1, val, &valShift); + } + FILE_LOG(logDEBUG1, ("phase shift: %d (degrees/shift: %d)\n", valShift, val)); + + int relativePhase = valShift - clkPhase[ind]; + FILE_LOG(logDEBUG1, ("relative phase shift: %d (Current phase: %d)\n", relativePhase, clkPhase[ind])); + + // same phase + if (!relativePhase) { + FILE_LOG(logINFO, ("\tNothing to do in Phase Shift\n")); + return; + } + + int phase = 0; + if (relativePhase > 0) { + phase = (maxShift - relativePhase); + } else { + phase = (-1) * relativePhase; + } + FILE_LOG(logDEBUG1, ("[Single Direction] Phase:%d (0x%x). Max Phase shifts:%d\n", phase, phase, maxShift)); + + ALTERA_PLL_SetPhaseShift(phase, (int)ind, 0); + + clkPhase[ind] = valShift; +} + +int getPhase(enum CLKINDEX ind, int degrees) { + if (!degrees) + return clkPhase[ind]; + // convert back to degrees + int val = 0; + ConvertToDifferentRange(0, getMaxPhase(ind) - 1, 0, 359, clkPhase[ind], &val); + return val; +} + +int getMaxPhase(enum CLKINDEX ind) { + int ret = ((double)PLL_VCO_FREQ_MHZ / (double)clkDivider[ind]) * MAX_PHASE_SHIFTS_STEPS; + + char clock_names[4][10]={"run_clk","adc_clk", "sync_clk", "dbit_clk"}; + FILE_LOG(logDEBUG1, ("Max Phase Shift (%s): %d (Clock: %d MHz, VCO:%d MHz)\n", + clock_names[ind], ret, clkDivider[ind], PLL_VCO_FREQ_MHZ)); + + return ret; +} + +int validatePhaseinDegrees(enum speedVariable ind, int val, int retval) { + if (val == -1) + return OK; + enum CLKINDEX clkIndex; + switch(ind) { + case ADC_PHASE: + clkIndex = ADC_CLK; + break; + case DBIT_PHASE: + clkIndex = DBIT_CLK; + break; + default: + FILE_LOG(logERROR, ("Unknown speed enum %d for validating phase in degrees\n", (int)ind)); + } + FILE_LOG(logDEBUG1, ("validating phase in degrees for clk %d\n", clkIndex)); + int maxShift = getMaxPhase(clkIndex); + // convert degrees to shift + int valShift = 0; + ConvertToDifferentRange(0, 359, 0, maxShift - 1, val, &valShift); + // convert back to degrees + ConvertToDifferentRange(0, maxShift - 1, 0, 359, valShift, &val); + + if (val == retval) + return OK; + return FAIL; +} + +void configureFrequency(enum CLKINDEX ind, int val) { + char clock_names[4][10]={"run_clk","adc_clk", "sync_clk", "dbit_clk"}; + if (val <= 0) + return; + + FILE_LOG(logINFO, ("\tConfiguring Frequency of C%d(%s) to %d MHz\n", ind, clock_names[ind], val)); + + // check adc clk too high + if (ind == ADC_CLK && val > MAXIMUM_ADC_CLK) { + FILE_LOG(logERROR, ("Frequency %d MHz too high for ADC\n", val)); + return; + } + + // reset phase + if (ind == ADC_CLK || ind == DBIT_CLK) { + FILE_LOG(logINFO, ("\tReseting phase of %s\n", clock_names[ind])); + configurePhase(ind, 0, 0); + } + + // Calculate and set output frequency + clkDivider[ind] = ALTERA_PLL_SetOuputFrequency (ind, PLL_VCO_FREQ_MHZ, val); + FILE_LOG(logINFO, ("\tC%d(%s): Frequency set to %d MHz\n", ind, clock_names[ind], clkDivider[ind])); +} + +int getFrequency(enum CLKINDEX ind) { + return clkDivider[ind]; +} + +void configureSyncFrequency(enum CLKINDEX ind) { + char clock_names[4][10]={"run_clk","adc_clk", "sync_clk", "dbit_clk"}; + int clka = 0, clkb = 0; + switch(ind) { + case ADC_CLK: + clka = DBIT_CLK; + clkb = RUN_CLK; + break; + case DBIT_CLK: + clka = ADC_CLK; + clkb = RUN_CLK; + break; + case RUN_CLK: + clka = DBIT_CLK; + clkb = ADC_CLK; + break; + default: + return; + } + + int syncFreq = getFrequency(SYNC_CLK); + int retval = getFrequency(ind); + int aFreq = getFrequency(clka); + int bFreq = getFrequency(clkb); + FILE_LOG(logDEBUG1, ("Sync Frequncy:%d, RetvalFreq(%s):%d, aFreq(%s):%d, bFreq(%s):%d\n", + syncFreq, clock_names[ind], retval, clock_names[clka], aFreq, clock_names[clkb], bFreq)); + + int configure = 0; + + // find the smallest frequency + int min = (aFreq < bFreq) ? aFreq : bFreq; + min = (retval < min) ? retval : min; + + // sync is greater than min + if (syncFreq > retval) { + FILE_LOG(logINFO, ("\t--Configuring Sync Clock\n")); + configure = 1; + } + + // sync is smaller than min + else if (syncFreq < min) { + FILE_LOG(logINFO, ("\t++Configuring Sync Clock\n")); + configure = 1; + } + + // configure sync to current + if (configure) + configureFrequency(SYNC_CLK, min); +} + + +void setAdcOffsetRegister(int adc, int val) { + if (val < 0) + return; + + FILE_LOG(logINFO, ("Setting %s Pipeline to %d\n", (adc ? "ADC" : "Dbit"), val)); + uint32_t offset = ADC_OFFSET_ADC_PPLN_OFST; + uint32_t mask = ADC_OFFSET_ADC_PPLN_MSK; + if (!adc) { + offset = ADC_OFFSET_DBT_PPLN_OFST; + mask = ADC_OFFSET_DBT_PPLN_MSK; + } + + uint32_t addr = ADC_OFFSET_REG; + // reset value + bus_w(addr, bus_r(addr) & ~ mask); + // set value + bus_w(addr, bus_r(addr) | ((val << offset) & mask)); + FILE_LOG(logDEBUG1, (" %s Offset: 0x%8x\n", (adc ? "ADC" : "Dbit"), bus_r(addr))); +} + +int getAdcOffsetRegister(int adc) { + if (adc) + return ((bus_r(ADC_OFFSET_REG) & ADC_OFFSET_ADC_PPLN_MSK) >> ADC_OFFSET_ADC_PPLN_OFST); + return ((bus_r(ADC_OFFSET_REG) & ADC_OFFSET_DBT_PPLN_MSK) >> ADC_OFFSET_DBT_PPLN_OFST); +} + + +// patterns +uint64_t writePatternIOControl(uint64_t word) { + if (word != -1) { + FILE_LOG(logINFO, ("Setting Pattern - I/O Control: 0x%llx\n", (long long int) word)); + set64BitReg(word, PATTERN_IO_CNTRL_LSB_REG, PATTERN_IO_CNTRL_MSB_REG); + } + uint64_t retval = get64BitReg(PATTERN_IO_CNTRL_LSB_REG, PATTERN_IO_CNTRL_MSB_REG); + FILE_LOG(logDEBUG1, ("I/O Control: 0x%llx\n", (long long int) retval)); + return retval; +} + +uint64_t writePatternClkControl(uint64_t word) { + if (word != -1) { + FILE_LOG(logINFO, ("Setting Pattern - Clock Control: 0x%llx\n", (long long int) word)); + set64BitReg(word, PATTERN_IO_CLK_CNTRL_LSB_REG, PATTERN_IO_CLK_CNTRL_MSB_REG); + } + uint64_t retval = get64BitReg(PATTERN_IO_CLK_CNTRL_LSB_REG, PATTERN_IO_CLK_CNTRL_MSB_REG); + FILE_LOG(logDEBUG1, ("Clock Control: 0x%llx\n", (long long int) retval)); + return retval; +} + +uint64_t readPatternWord(int addr) { + // error (handled in tcp) + if (addr < 0 || addr > MAX_PATTERN_LENGTH) { + FILE_LOG(logERROR, ("Cannot get Pattern - Word. Invalid addr 0x%x. " + "Should be <= 0x%x\n", addr, MAX_PATTERN_LENGTH)); + return -1; + } + + FILE_LOG(logDEBUG1, (" Reading Pattern - Word (addr:0x%x)\n", addr)); + uint32_t reg = PATTERN_CNTRL_REG; + + // overwrite with only addr + bus_w(reg, ((addr << PATTERN_CNTRL_ADDR_OFST) & PATTERN_CNTRL_ADDR_MSK)); + + // set read strobe + bus_w(reg, bus_r(reg) | PATTERN_CNTRL_RD_MSK); + + // unset read strobe + bus_w(reg, bus_r(reg) & (~PATTERN_CNTRL_RD_MSK)); + usleep(WAIT_TIME_PATTERN_READ); + + // read value + uint64_t retval = get64BitReg(PATTERN_OUT_LSB_REG, PATTERN_OUT_MSB_REG); + FILE_LOG(logDEBUG1, (" Word(addr:0x%x): 0x%llx\n", addr, (long long int) retval)); + + return retval; +} + +uint64_t writePatternWord(int addr, uint64_t word) { + // get + if (word == -1) + return readPatternWord(addr); + + // error (handled in tcp) + if (addr < 0 || addr > MAX_PATTERN_LENGTH) { + FILE_LOG(logERROR, ("Cannot set Pattern - Word. Invalid addr 0x%x. " + "Should be <= 0x%x\n", addr, MAX_PATTERN_LENGTH)); + return -1; + } + + FILE_LOG(logINFO, ("Setting Pattern - Word (addr:0x%x, word:0x%llx)\n", addr, (long long int) word)); + uint32_t reg = PATTERN_CNTRL_REG; + + // write word + set64BitReg(word, PATTERN_IN_LSB_REG, PATTERN_IN_MSB_REG); + FILE_LOG(logDEBUG1, (" Wrote word. PatternIn Reg: 0x%llx\n", get64BitReg(PATTERN_IN_LSB_REG, PATTERN_IN_MSB_REG))); + + // overwrite with only addr + bus_w(reg, ((addr << PATTERN_CNTRL_ADDR_OFST) & PATTERN_CNTRL_ADDR_MSK)); + + // set write strobe + bus_w(reg, bus_r(reg) | PATTERN_CNTRL_WR_MSK); + + // unset write strobe + bus_w(reg, bus_r(reg) & (~PATTERN_CNTRL_WR_MSK)); + + return word; + //return readPatternWord(addr); // will start executing the pattern +} + +int setPatternWaitAddress(int level, int addr) { + + // error (handled in tcp) + if (addr > MAX_PATTERN_LENGTH) { + FILE_LOG(logERROR, ("Cannot set Pattern - Wait Address. Invalid addr 0x%x. " + "Should be <= 0x%x\n", addr, MAX_PATTERN_LENGTH)); + return -1; + } + + uint32_t reg = 0; + uint32_t offset = 0; + uint32_t mask = 0; + + switch (level) { + case 0: + reg = PATTERN_WAIT_0_ADDR_REG; + offset = PATTERN_WAIT_0_ADDR_OFST; + mask = PATTERN_WAIT_0_ADDR_MSK; + break; + case 1: + reg = PATTERN_WAIT_1_ADDR_REG; + offset = PATTERN_WAIT_1_ADDR_OFST; + mask = PATTERN_WAIT_1_ADDR_MSK; + break; + case 2: + reg = PATTERN_WAIT_2_ADDR_REG; + offset = PATTERN_WAIT_2_ADDR_OFST; + mask = PATTERN_WAIT_2_ADDR_MSK; + break; + default: + FILE_LOG(logERROR, ("Cannot set Pattern - Wait Address. Invalid level 0x%x. " + "Should be between 0 and 2.\n", level)); + return -1; + } + + // set + if (addr >= 0) { + FILE_LOG(logINFO, ("Setting Pattern - Wait Address (level:%d, addr:0x%x)\n", level, addr)); + bus_w(reg, ((addr << offset) & mask)); + } + + // get + uint32_t regval = bus_r((reg & mask) >> offset); + FILE_LOG(logDEBUG1, (" Wait Address (level:%d, addr:0x%x)\n", level, regval)); + return regval; +} + +uint64_t setPatternWaitTime(int level, uint64_t t) { + uint32_t regl = 0; + uint32_t regm = 0; + + switch (level) { + case 0: + regl = PATTERN_WAIT_TIMER_0_LSB_REG; + regm = PATTERN_WAIT_TIMER_0_MSB_REG; + break; + case 1: + regl = PATTERN_WAIT_TIMER_1_LSB_REG; + regm = PATTERN_WAIT_TIMER_1_MSB_REG; + break; + case 2: + regl = PATTERN_WAIT_TIMER_2_LSB_REG; + regm = PATTERN_WAIT_TIMER_2_MSB_REG; + break; + default: + FILE_LOG(logERROR, ("Cannot set Pattern - Wait Time. Invalid level %d. " + "Should be between 0 and 2.\n", level)); + return -1; + } + + // set + if (t >= 0) { + FILE_LOG(logINFO, ("Setting Pattern - Wait Time (level:%d, t:%lld)\n", level, (long long int)t)); + set64BitReg(t, regl, regm); + } + + // get + uint64_t regval = get64BitReg(regl, regm); + FILE_LOG(logDEBUG1, (" Wait Time (level:%d, t:%lld)\n", level, (long long int)regval)); + return regval; +} + +void setPatternLoop(int level, int *startAddr, int *stopAddr, int *nLoop) { + + // level 0-2, addr upto patternlength + 1 (checked at tcp) + if ((level != -1) && + (*startAddr > MAX_PATTERN_LENGTH || *stopAddr > MAX_PATTERN_LENGTH)) { + FILE_LOG(logERROR, ("Cannot set Pattern (Pattern Loop, level:%d, startaddr:0x%x, stopaddr:0x%x). " + "Addr must be <= 0x%x\n", + level, *startAddr, *stopAddr, MAX_PATTERN_LENGTH)); + } + + //level -1, addr upto patternlength (checked at tcp) + else if ((level == -1) && + (*startAddr > MAX_PATTERN_LENGTH || *stopAddr > MAX_PATTERN_LENGTH)) { + FILE_LOG(logERROR, ("Cannot set Pattern (Pattern Loop, complete pattern, startaddr:0x%x, stopaddr:0x%x). " + "Addr must be <= 0x%x\n", + *startAddr, *stopAddr, MAX_PATTERN_LENGTH)); + } + + uint32_t addr = 0; + uint32_t nLoopReg = 0; + uint32_t startOffset = 0; + uint32_t startMask = 0; + uint32_t stopOffset = 0; + uint32_t stopMask = 0; + + switch (level) { + case 0: + addr = PATTERN_LOOP_0_ADDR_REG; + nLoopReg = PATTERN_LOOP_0_ITERATION_REG; + startOffset = PATTERN_LOOP_0_ADDR_STRT_OFST; + startMask = PATTERN_LOOP_0_ADDR_STRT_MSK; + stopOffset = PATTERN_LOOP_0_ADDR_STP_OFST; + stopMask = PATTERN_LOOP_0_ADDR_STP_MSK; + break; + case 1: + addr = PATTERN_LOOP_1_ADDR_REG; + nLoopReg = PATTERN_LOOP_1_ITERATION_REG; + startOffset = PATTERN_LOOP_1_ADDR_STRT_OFST; + startMask = PATTERN_LOOP_1_ADDR_STRT_MSK; + stopOffset = PATTERN_LOOP_1_ADDR_STP_OFST; + stopMask = PATTERN_LOOP_1_ADDR_STP_MSK; + break; + case 2: + addr = PATTERN_LOOP_2_ADDR_REG; + nLoopReg = PATTERN_LOOP_2_ITERATION_REG; + startOffset = PATTERN_LOOP_2_ADDR_STRT_OFST; + startMask = PATTERN_LOOP_2_ADDR_STRT_MSK; + stopOffset = PATTERN_LOOP_2_ADDR_STP_OFST; + stopMask = PATTERN_LOOP_2_ADDR_STP_MSK; + break; + case -1: + // complete pattern + addr = PATTERN_LIMIT_REG; + nLoopReg = -1; + startOffset = PATTERN_LIMIT_STRT_OFST; + startMask = PATTERN_LIMIT_STRT_MSK; + stopOffset = PATTERN_LIMIT_STP_OFST; + stopMask = PATTERN_LIMIT_STP_MSK; + break; + default: + // already checked at tcp interface + FILE_LOG(logERROR, ("Cannot set Pattern - Pattern loop. Invalid level %d. " + "Should be between -1 and 2.\n", level)); + *startAddr = 0; + *stopAddr = 0; + *nLoop = 0; + } + + // set iterations + if (level >= 0) { + // set iteration + if (*nLoop >= 0) { + FILE_LOG(logINFO, ("Setting Pattern - Pattern Loop (level:%d, nLoop:%d)\n", + level, *nLoop)); + bus_w(nLoopReg, *nLoop); + } + *nLoop = bus_r(nLoopReg); + } + + // set + if (*startAddr != -1 && *stopAddr != -1) { + // writing start and stop addr + FILE_LOG(logINFO, ("Setting Pattern - Pattern Loop (level:%d, startaddr:0x%x, stopaddr:0x%x)\n", + level, *startAddr, *stopAddr)); + bus_w(addr, ((*startAddr << startOffset) & startMask) | ((*stopAddr << stopOffset) & stopMask)); + FILE_LOG(logDEBUG1, ("Addr:0x%x, val:0x%x\n", addr, bus_r(addr))); + } + + // get + else { + *startAddr = ((bus_r(addr) & startMask) >> startOffset); + FILE_LOG(logDEBUG1, ("Getting Pattern - Pattern Loop Start Address (level:%d, Read startAddr:0x%x)\n", + level, *startAddr)); + + *stopAddr = ((bus_r(addr) & stopMask) >> stopOffset); + FILE_LOG(logDEBUG1, ("Getting Pattern - Pattern Loop Stop Address (level:%d, Read stopAddr:0x%x)\n", + level, *stopAddr)); + } +} + +int setLEDEnable(int enable) { + uint32_t addr = CONFIG_REG; + + // set + if (enable >= 0) { + FILE_LOG(logINFO, ("Switching LED %s\n", (enable > 0) ? "ON" : "OFF")); + // disable + if (enable == 0) { + bus_w(addr, bus_r(addr) | CONFIG_LED_DSBL_MSK); + } + // enable + else { + bus_w(addr, bus_r(addr) & (~CONFIG_LED_DSBL_MSK)); + } + } + // ~ to get the opposite + return (((~bus_r(addr)) & CONFIG_LED_DSBL_MSK) >> CONFIG_LED_DSBL_OFST); +} + +void setDigitalIODelay(uint64_t pinMask, int delay) { + FILE_LOG(logINFO, ("Setings Digital IO Delay (pinMask:0x%llx, delay: %d ps)\n", + (long long unsigned int)pinMask, delay)); + + int delayunit = delay / OUTPUT_DELAY_0_OTPT_STTNG_STEPS; + FILE_LOG(logDEBUG1, ("delay unit: 0x%x (steps of 25ps)\n", delayunit)); + + // set pin mask + bus_w(PIN_DELAY_1_REG, pinMask); + + uint32_t addr = OUTPUT_DELAY_0_REG; + // set delay + bus_w(addr, bus_r(addr) & (~OUTPUT_DELAY_0_OTPT_STTNG_MSK)); + bus_w(addr, (bus_r(addr) | ((delayunit << OUTPUT_DELAY_0_OTPT_STTNG_OFST) & OUTPUT_DELAY_0_OTPT_STTNG_MSK))); + + // load value + bus_w(addr, bus_r(addr) | OUTPUT_DELAY_0_OTPT_TRGGR_MSK); + + // trigger configuration + bus_w(addr, bus_r(addr) & (~OUTPUT_DELAY_0_OTPT_TRGGR_MSK)); +} + +void setPatternMask(uint64_t mask) { + set64BitReg(mask, PATTERN_MASK_LSB_REG, PATTERN_MASK_MSB_REG); +} + +uint64_t getPatternMask() { + return get64BitReg(PATTERN_MASK_LSB_REG, PATTERN_MASK_MSB_REG); +} + +void setPatternBitMask(uint64_t mask) { + set64BitReg(mask, PATTERN_SET_LSB_REG, PATTERN_SET_MSB_REG); +} + +uint64_t getPatternBitMask() { + return get64BitReg(PATTERN_SET_LSB_REG, PATTERN_SET_MSB_REG); +} + +/* aquisition */ + +int startStateMachine(){ +#ifdef VIRTUAL + virtual_status = 1; + virtual_stop = 0; + if(pthread_create(&pthread_virtual_tid, NULL, &start_timer, NULL)) { + virtual_status = 0; + FILE_LOG(logERROR, ("Could not start Virtual acquisition thread\n")); + return FAIL; + } + FILE_LOG(logINFOGREEN, ("Virtual Acquisition started\n")); + return OK; +#endif + // 1 giga udp + if (!enableTenGigabitEthernet(-1)) { + // create udp socket + if(createUDPSocket() != OK) { + return FAIL; + } + // update header with modId, detType and version. Reset offset and fnum + createUDPPacketHeader(udpPacketData, getHardwareSerialNumber()); + } + + FILE_LOG(logINFOBLUE, ("Starting State Machine\n")); + + cleanFifos(); + unsetFifoReadStrobes(); // FIXME: unnecessary to write bus_w(dumm, 0) as it is 0 in the beginnig and the strobes are always unset if set + + //start state machine + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_STRT_ACQSTN_MSK | CONTROL_STRT_EXPSR_MSK); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_STRT_ACQSTN_MSK & ~CONTROL_STRT_EXPSR_MSK); + + FILE_LOG(logINFO, ("Status Register: %08x\n",bus_r(STATUS_REG))); + return OK; +} + + +#ifdef VIRTUAL +void* start_timer(void* arg) { + int wait_in_s = (setTimer(FRAME_NUMBER, -1) * + setTimer(CYCLES_NUMBER, -1) * + (setTimer(FRAME_PERIOD, -1)/(1E9))); + FILE_LOG(logDEBUG1, ("going to wait for %d s\n", wait_in_s)); + while(!virtual_stop && (wait_in_s >= 0)) { + usleep(1000 * 1000); + wait_in_s--; + } + FILE_LOG(logINFOGREEN, ("Virtual Timer Done\n")); + + virtual_status = 0; + return NULL; +} +#endif + +int stopStateMachine(){ + FILE_LOG(logINFORED, ("Stopping State Machine\n")); +#ifdef VIRTUAL + virtual_stop = 0; + return OK; +#endif + //stop state machine + bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_STP_ACQSTN_MSK); + usleep(WAIT_TIME_US_STP_ACQ); + bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_STP_ACQSTN_MSK); + + FILE_LOG(logINFO, ("Status Register: %08x\n",bus_r(STATUS_REG))); + return OK; +} + + + + + +enum runStatus getRunStatus(){ +#ifdef VIRTUAL + if(virtual_status == 0){ + FILE_LOG(logINFOBLUE, ("Status: IDLE\n")); + return IDLE; + }else{ + FILE_LOG(logINFOBLUE, ("Status: RUNNING\n")); + return RUNNING; + } +#endif + FILE_LOG(logDEBUG1, ("Getting status\n")); + + uint32_t retval = bus_r(STATUS_REG); + FILE_LOG(logINFO, ("Status Register: %08x\n",retval)); + + // error + //if (retval & STATUS_SM_FF_FLL_MSK) { This bit is high when a analog fifo is full Or when external stop + if (retval & STATUS_ANY_FF_FLL_MSK) { // if adc fifo is full + FILE_LOG(logINFORED, ("Status: Error (Any fifo full)\n")); + return ERROR; + } + + // running + if(retval & STATUS_RN_BSY_MSK) { + if (retval & STATUS_WTNG_FR_TRGGR_MSK) { + FILE_LOG(logINFOBLUE, ("Status: Waiting for Trigger\n")); + return WAITING; + } + + FILE_LOG(logINFOBLUE, ("Status: Running\n")); + return RUNNING; + + } + + // not running + else { + if (retval & STATUS_STPPD_MSK) { + FILE_LOG(logINFOBLUE, ("Status: Stopped\n")); + return STOPPED; + } + + if (retval & STATUS_FRM_RN_BSY_MSK) { + FILE_LOG(logINFOBLUE, ("Status: Transmitting (Read machine busy)\n")); + return TRANSMITTING; + } + + + if (! (retval & STATUS_IDLE_MSK)) { + FILE_LOG(logINFOBLUE, ("Status: Idle\n")); + return IDLE; + } + + FILE_LOG(logERROR, ("Status: Unknown status %08x\n", retval)); + return ERROR; + } +} + + +void readandSendUDPFrames(int *ret, char *mess) { + FILE_LOG(logDEBUG1, ("Reading from 1G UDP\n")); + + // validate udp socket + if (getUdPSocketDescriptor() <= 0) { + *ret = FAIL; + sprintf(mess,"UDP Socket not created. sockfd:%d\n", getUdPSocketDescriptor()); + FILE_LOG(logERROR, (mess)); + return; + } + + // every frame read + while(readFrameFromFifo() == OK) { + int bytesToSend = 0, n = 0; + while((bytesToSend = fillUDPPacket(udpPacketData))) { + n += sendUDPPacket(udpPacketData, bytesToSend); + } + if (n >= dataBytes) { + FILE_LOG(logINFO, (" Frame %lld sent (%d packets, %d databytes, n:%d bytes sent)\n", + udpFrameNumber, udpPacketNumber + 1, dataBytes, n)); + } + } + closeUDPSocket(); +} + + + +void readFrame(int *ret, char *mess) { +#ifdef VIRTUAL + while(virtual_status) { + //FILE_LOG(logERROR, ("Waiting for finished flag\n"); + usleep(5000); + } + return; +#endif + // 1G + if (!enableTenGigabitEthernet(-1)) { + readandSendUDPFrames(ret, mess); + } + // 10G + else { + // wait for acquisition to be done + while(runBusy()){ + usleep(500); // random + } + } + + // ret could be fail in 1gudp for not creating udp sockets + if (*ret != FAIL) { + // frames left to give status + int64_t retval = getTimeLeft(FRAME_NUMBER) + 2; + if ( retval > 1) { + *ret = (int)FAIL; + sprintf(mess,"No data and run stopped: %lld frames left\n",(long long int)retval); + FILE_LOG(logERROR, (mess)); + } else { + *ret = (int)OK; + FILE_LOG(logINFOGREEN, ("Acquisition successfully finished\n")); + } + } +} + +void unsetFifoReadStrobes() { + bus_w(DUMMY_REG, bus_r(DUMMY_REG) & (~DUMMY_ANLG_FIFO_RD_STRBE_MSK)); +} + +void readSample(int ns) { + uint32_t addr = DUMMY_REG; + // read analog data + uint32_t fifoAddr = FIFO_DATA_REG; + + // read strobe to all analog fifos + bus_w(addr, bus_r(addr) | DUMMY_ANLG_FIFO_RD_STRBE_MSK); + bus_w(addr, bus_r(addr) & (~DUMMY_ANLG_FIFO_RD_STRBE_MSK)); + // wait as it is connected directly to fifo running on a different clock + //usleep(WAIT_TIME_FIFO_RD_STROBE); + if (!(ns%1000)) { + FILE_LOG(logDEBUG1, ("Reading sample ns:%d of %d AEmtpy:0x%x AFull:0x%x Status:0x%x\n", + ns, nSamples, bus_r(FIFO_EMPTY_REG), bus_r(FIFO_FULL_REG), bus_r(STATUS_REG))); + } + + // loop through all channels + int ich = 0; + for (ich = 0; ich < NCHAN; ++ich) { + + // if channel is in ROI + if ((1 << ich) & ~(adcDisableMask)) { + + // unselect channel + bus_w(addr, bus_r(addr) & ~(DUMMY_FIFO_CHNNL_SLCT_MSK)); + + // select channel + bus_w(addr, bus_r(addr) | ((ich << DUMMY_FIFO_CHNNL_SLCT_OFST) & DUMMY_FIFO_CHNNL_SLCT_MSK)); + + // read fifo and write it to current position of data pointer + *((uint16_t*)now_ptr) = bus_r16(fifoAddr); + + // keep reading till the value is the same + /* while (*((uint16_t*)now_ptr) != bus_r16(fifoAddr)) { + FILE_LOG(logDEBUG1, ("%d ", ich)); + *((uint16_t*)now_ptr) = bus_r16(fifoAddr); + }*/ + + // increment pointer to data out destination + now_ptr += 2; + } + } + +} + +uint32_t checkDataInFifo() { + uint32_t dataPresent = 0; + uint32_t analogFifoEmpty = bus_r(FIFO_EMPTY_REG); + FILE_LOG(logDEBUG2, ("Analog Fifo Empty (32 channels): 0x%x\n",analogFifoEmpty)); + dataPresent = (~analogFifoEmpty); + FILE_LOG(logDEBUG2, ("Data in Fifo :0x%x\n", dataPresent)); + return dataPresent; +} + +// only called for first sample +int checkFifoForEndOfAcquisition() { + uint32_t dataPresent = checkDataInFifo(); + FILE_LOG(logDEBUG2, ("status:0x%x\n", bus_r(STATUS_REG))); + + // as long as no data + while (!dataPresent) { + // acquisition done + if (!runBusy()) { + // wait to be sure there is no data in fifo + usleep(WAIT_TME_US_FR_ACQDONE_REG); + + // still no data + if (!checkDataInFifo()) { + FILE_LOG(logINFO, ("Acquisition Finished (State: 0x%08x), " + "no frame found .\n", bus_r(STATUS_REG))); + return FAIL; + } + // got data, exit + else { + break; + } + } + // check if data in fifo again + dataPresent = checkDataInFifo(); + } + FILE_LOG(logDEBUG1, ("Got data :0x%x\n", dataPresent)); + return OK; +} + + +int readFrameFromFifo() { + int ns = 0; + // point the data pointer to the starting position of data + now_ptr = ramValues; + + // no data for this frame + if (checkFifoForEndOfAcquisition() == FAIL) { + return FAIL; + } + + // read Sample + while(ns < nSamples) { + // chceck if no data in fifo, return ns?//FIXME: ask Anna + readSample(ns); + ns++; + } + + // got frame + return OK; +} + + +uint32_t runBusy() { +#ifdef VIRTUAL + return virtual_status; +#endif + uint32_t s = (bus_r(STATUS_REG) & STATUS_RN_BSY_MSK); + //FILE_LOG(logDEBUG1, ("Status Register: %08x\n", s)); + return s; +} + + + + + + + + +/* common */ + +int calculateDataBytes(){ + return dataBytes; +} + +int getTotalNumberOfChannels(){return ((int)getNumberOfChannelsPerChip() * (int)getNumberOfChips());} +int getNumberOfChips(){return NCHIP;} +int getNumberOfDACs(){return NDAC;} +int getNumberOfChannelsPerChip(){return NCHAN;} + + diff --git a/slsDetectorServers/moenchDetectorServer/slsDetectorFunctionList.h b/slsDetectorServers/moenchDetectorServer/slsDetectorFunctionList.h new file mode 120000 index 000000000..345b8c029 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/slsDetectorFunctionList.h @@ -0,0 +1 @@ +../slsDetectorServer/slsDetectorFunctionList.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/slsDetectorServer.c b/slsDetectorServers/moenchDetectorServer/slsDetectorServer.c new file mode 120000 index 000000000..a7eb59acb --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/slsDetectorServer.c @@ -0,0 +1 @@ +../slsDetectorServer/slsDetectorServer.c \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/slsDetectorServer_defs.h b/slsDetectorServers/moenchDetectorServer/slsDetectorServer_defs.h new file mode 100755 index 000000000..c9ab6eb48 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/slsDetectorServer_defs.h @@ -0,0 +1,80 @@ +#pragma once +#include "sls_detector_defs.h" +#include "RegisterDefs.h" + + +#define MIN_REQRD_VRSN_T_RD_API 0x180314 +#define REQRD_FRMWR_VRSN 0x180314 + +#define CTRL_SRVR_INIT_TIME_US (300 * 1000) + +/* Struct Definitions */ +typedef struct ip_header_struct { + uint16_t ip_len; + uint8_t ip_tos; + uint8_t ip_ihl:4 ,ip_ver:4; + uint16_t ip_offset:13,ip_flag:3; + uint16_t ip_ident; + uint16_t ip_chksum; + uint8_t ip_protocol; + uint8_t ip_ttl; + uint32_t ip_sourceip; + uint32_t ip_destip; +} ip_header; + +/* Enums */ +enum CLKINDEX {RUN_CLK, ADC_CLK, SYNC_CLK, DBIT_CLK, NUM_CLOCKS}; +enum DACINDEX {D0, D1, D2, D3, D4, D5, D6, D7}; + +/* Hardware Definitions */ +#define NCHAN (32) +#define NCHIP (1) +#define NDAC (8) +#define DYNAMIC_RANGE (16) +#define NUM_BYTES_PER_PIXEL (DYNAMIC_RANGE / 8) +#define CLK_FREQ (156.25) /* MHz */ + +/** Default Parameters */ +#define DEFAULT_DATA_BYTES (NCHIP * NCHAN * NUM_BITS_PER_PIXEL) +#define DEFAULT_NUM_SAMPLES (1) +#define DEFAULT_EXPTIME (0) +#define DEFAULT_NUM_FRAMES (100 * 1000 * 1000) +#define DEFAULT_NUM_CYCLES (1) +#define DEFAULT_PERIOD (1 * 1000 * 1000) //ns +#define DEFAULT_DELAY (0) +#define DEFAULT_HIGH_VOLTAGE (0) +#define DEFAULT_VLIMIT (-100) +#define DEFAULT_TIMING_MODE (AUTO_TIMING) +#define DEFAULT_TX_UDP_PORT (0x7e9a) +#define DEFAULT_RUN_CLK (40) +#define DEFAULT_ADC_CLK (20) +#define DEFAULT_SYNC_CLK (20) +#define DEFAULT_DBIT_CLK (200) + +#define HIGHVOLTAGE_MIN (60) +#define HIGHVOLTAGE_MAX (200) +#define DAC_MIN_MV (0) +#define DAC_MAX_MV (2500) + +/* Defines in the Firmware */ +#define MAX_PATTERN_LENGTH (0xFFFF) +#define DIGITAL_IO_DELAY_MAXIMUM_PS ((OUTPUT_DELAY_0_OTPT_STTNG_MSK >> OUTPUT_DELAY_0_OTPT_STTNG_OFST) * OUTPUT_DELAY_0_OTPT_STTNG_STEPS) +#define MAX_PHASE_SHIFTS_STEPS (8) + +#define WAIT_TME_US_FR_ACQDONE_REG (100) // wait time in us after acquisition done to ensure there is no data in fifo +#define WAIT_TIME_US_PLL (10 * 1000) +#define WAIT_TIME_US_STP_ACQ (100) +#define WAIT_TIME_CONFIGURE_MAC (500 * 1000) +#define WAIT_TIME_PATTERN_READ (10) +#define WAIT_TIME_FIFO_RD_STROBE (10) + +/* MSB & LSB DEFINES */ +#define MSB_OF_64_BIT_REG_OFST (32) +#define LSB_OF_64_BIT_REG_OFST (0) +#define BIT_32_MSK (0xFFFFFFFF) + +#define IP_PACKETSIZE (0x2032) +#define ADC_PORT_INVERT_VAL (0x453b2593) //FIXME: a default value? +#define MAXIMUM_ADC_CLK (40) +#define PLL_VCO_FREQ_MHZ (800) + diff --git a/slsDetectorServers/moenchDetectorServer/slsDetectorServer_funcs.c b/slsDetectorServers/moenchDetectorServer/slsDetectorServer_funcs.c new file mode 120000 index 000000000..a7532ccd4 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/slsDetectorServer_funcs.c @@ -0,0 +1 @@ +../slsDetectorServer/slsDetectorServer_funcs.c \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/slsDetectorServer_funcs.h b/slsDetectorServers/moenchDetectorServer/slsDetectorServer_funcs.h new file mode 120000 index 000000000..7569daf47 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/slsDetectorServer_funcs.h @@ -0,0 +1 @@ +../slsDetectorServer/slsDetectorServer_funcs.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/sls_detector_defs.h b/slsDetectorServers/moenchDetectorServer/sls_detector_defs.h new file mode 120000 index 000000000..2af30d73a --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/sls_detector_defs.h @@ -0,0 +1 @@ +../../slsSupportLib/include/sls_detector_defs.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/sls_detector_funcs.h b/slsDetectorServers/moenchDetectorServer/sls_detector_funcs.h new file mode 120000 index 000000000..3f48959a9 --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/sls_detector_funcs.h @@ -0,0 +1 @@ +../../slsSupportLib/include/sls_detector_funcs.h \ No newline at end of file diff --git a/slsDetectorServers/moenchDetectorServer/versionAPI.h b/slsDetectorServers/moenchDetectorServer/versionAPI.h new file mode 120000 index 000000000..5e580d8bb --- /dev/null +++ b/slsDetectorServers/moenchDetectorServer/versionAPI.h @@ -0,0 +1 @@ +../../slsSupportLib/include/versionAPI.h \ No newline at end of file diff --git a/slsDetectorServers/slsDetectorServer/AD7689.h b/slsDetectorServers/slsDetectorServer/AD7689.h new file mode 100755 index 000000000..9e6c8f59a --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/AD7689.h @@ -0,0 +1,238 @@ +#pragma once + +#include "commonServerFunctions.h" // blackfin.h, ansi.h +#include "common.h" + +/* AD7689 ADC DEFINES */ + +/** Read back CFG Register */ +#define AD7689_CFG_RB_OFST (0) +#define AD7689_CFG_RB_MSK (0x00000001 << AD7689_CFG_RB_OFST) + +/** Channel sequencer */ +#define AD7689_CFG_SEQ_OFST (1) +#define AD7689_CFG_SEQ_MSK (0x00000003 << AD7689_CFG_SEQ_OFST) +#define AD7689_CFG_SEQ_DSBLE_VAL ((0x0 << AD7689_CFG_SEQ_OFST) & AD7689_CFG_SEQ_MSK) +#define AD7689_CFG_SEQ_UPDTE_DRNG_SQNCE_VAL ((0x1 << AD7689_CFG_SEQ_OFST) & AD7689_CFG_SEQ_MSK) +#define AD7689_CFG_SEQ_SCN_WTH_TMP_VAL ((0x2 << AD7689_CFG_SEQ_OFST) & AD7689_CFG_SEQ_MSK) +#define AD7689_CFG_SEQ_SCN_WTHT_TMP_VAL ((0x3 << AD7689_CFG_SEQ_OFST) & AD7689_CFG_SEQ_MSK) + +/** Reference/ buffer selection */ +#define AD7689_CFG_REF_OFST (3) +#define AD7689_CFG_REF_MSK (0x00000007 << AD7689_CFG_REF_OFST) +/** Internal reference. REF = 2.5V buffered output. Temperature sensor enabled. */ +#define AD7689_CFG_REF_INT_2500MV_VAL ((0x0 << AD7689_CFG_REF_OFST) & AD7689_CFG_REF_OFST) +/** Internal reference. REF = 4.096V buffered output. Temperature sensor enabled. */ +#define AD7689_CFG_REF_INT_4096MV_VAL ((0x1 << AD7689_CFG_REF_OFST) & AD7689_CFG_REF_MSK) +/** External reference. Temperature sensor enabled. Internal buffer disabled. */ +#define AD7689_CFG_REF_EXT_TMP_VAL ((0x2 << AD7689_CFG_REF_OFST) & AD7689_CFG_REF_MSK) +/** External reference. Temperature sensor enabled. Internal buffer enabled. */ +#define AD7689_CFG_REF_EXT_TMP_INTBUF_VAL ((0x3 << AD7689_CFG_REF_OFST) & AD7689_CFG_REF_MSK) +/** External reference. Temperature sensor disabled. Internal buffer disabled. */ +#define AD7689_CFG_REF_EXT_VAL ((0x6 << AD7689_CFG_REF_OFST) & AD7689_CFG_REF_MSK) +/** External reference. Temperature sensor disabled. Internal buffer enabled. */ +#define AD7689_CFG_REF_EXT_INTBUF_VAL ((0x7 << AD7689_CFG_REF_OFST) & AD7689_CFG_REF_MSK) + +/** bandwidth of low pass filter */ +#define AD7689_CFG_BW_OFST (6) +#define AD7689_CFG_BW_MSK (0x00000001 << AD7689_CFG_REF_OFST) +#define AD7689_CFG_BW_ONE_FOURTH_VAL ((0x0 << AD7689_CFG_BW_OFST) & AD7689_CFG_BW_MSK) +#define AD7689_CFG_BW_FULL_VAL ((0x1 << AD7689_CFG_BW_OFST) & AD7689_CFG_BW_MSK) + +/** input channel selection IN0 - IN7 */ +#define AD7689_CFG_IN_OFST (7) +#define AD7689_CFG_IN_MSK (0x00000007 << AD7689_CFG_IN_OFST) + +/** input channel configuration */ +#define AD7689_CFG_INCC_OFST (10) +#define AD7689_CFG_INCC_MSK (0x00000007 << AD7689_CFG_INCC_OFST) +#define AD7689_CFG_INCC_BPLR_DFFRNTL_PRS_VAL ((0x0 << AD7689_CFG_INCC_OFST) & AD7689_CFG_INCC_MSK) +#define AD7689_CFG_INCC_BPLR_IN_COM_VAL ((0x2 << AD7689_CFG_INCC_OFST) & AD7689_CFG_INCC_MSK) +#define AD7689_CFG_INCC_TMP_VAL ((0x3 << AD7689_CFG_INCC_OFST) & AD7689_CFG_INCC_MSK) +#define AD7689_CFG_INCC_UNPLR_DFFRNTL_PRS_VAL ((0x4 << AD7689_CFG_INCC_OFST) & AD7689_CFG_INCC_MSK) +#define AD7689_CFG_INCC_UNPLR_IN_COM_VAL ((0x6 << AD7689_CFG_INCC_OFST) & AD7689_CFG_INCC_MSK) +#define AD7689_CFG_INCC_UNPLR_IN_GND_VAL ((0x7 << AD7689_CFG_INCC_OFST) & AD7689_CFG_INCC_MSK) + +/** configuration update */ +#define AD7689_CFG_CFG_OFST (13) +#define AD7689_CFG_CFG_MSK (0x00000001 << AD7689_CFG_CFG_OFST) +#define AD7689_CFG_CFG_NO_UPDATE_VAL ((0x0 << AD7689_CFG_CFG_OFST) & AD7689_CFG_CFG_MSK) +#define AD7689_CFG_CFG_OVRWRTE_VAL ((0x1 << AD7689_CFG_CFG_OFST) & AD7689_CFG_CFG_MSK) + +#define AD7689_ADC_CFG_NUMBITS (14) +#define AD7689_ADC_DATA_NUMBITS (16) +#define AD7689_NUM_CHANNELS (8) +#define AD7689_NUM_INVALID_CONVERSIONS (3) + +#define AD7689_INT_REF_MAX_MV (2500) // chosen using reference buffer selection in config reg +#define AD7689_INT_REF_MIN_MV (0) +#define AD7689_INT_MAX_STEPS (0xFFFF + 1) +#define AD7689_TMP_C_FOR_1_MV (25.00 / 283.00) + + +uint32_t AD7689_Reg = 0x0; +uint32_t AD7689_ROReg = 0x0; +uint32_t AD7689_CnvMask = 0x0; +uint32_t AD7689_ClkMask = 0x0; +uint32_t AD7689_DigMask = 0x0; +int AD7689_DigOffset = 0x0; + +/** + * Set Defines + * @param reg spi register + * @param roreg spi readout register + * @param cmsk conversion mask + * @param clkmsk clock output mask + * @param dmsk digital output mask + * @param dofst digital output offset + */ +void AD7689_SetDefines(uint32_t reg, uint32_t roreg, uint32_t cmsk, uint32_t clkmsk, uint32_t dmsk, int dofst) { + FILE_LOG(logDEBUG, ("AD7689: reg:0x%x roreg:0x%x cmsk:0x%x clkmsk:0x%x dmsk:0x%x dofst:%d\n", + reg, roreg, cmsk, clkmsk, dmsk, dofst)); + AD7689_Reg = reg; + AD7689_ROReg = roreg; + AD7689_CnvMask = cmsk; + AD7689_ClkMask = clkmsk; + AD7689_DigMask = dmsk; + AD7689_DigOffset = dofst; +} + +/** + * Disable SPI + */ +void AD7689_Disable() { + bus_w(AD7689_Reg, (bus_r(AD7689_Reg) + &~(AD7689_CnvMask) + &~AD7689_ClkMask + &~(AD7689_DigMask))); +} + +/** + * Set SPI reg value + * @param codata value to be set + */ +void AD7689_Set(u_int32_t codata) { + FILE_LOG(logINFO, ("\tSetting ADC SPI Register. Writing 0x%08x to Config Reg\n", codata)); + serializeToSPI(AD7689_Reg, codata, AD7689_CnvMask, AD7689_ADC_CFG_NUMBITS, + AD7689_ClkMask, AD7689_DigMask, AD7689_DigOffset, 1); +} + +/** + * Get SPI reg value + * @returns SPI reg value + */ +uint16_t AD7689_Get() { + FILE_LOG(logINFO, ("\tGetting ADC SPI Register.\n")); + return (uint16_t)serializeFromSPI(AD7689_Reg, AD7689_CnvMask, AD7689_ADC_DATA_NUMBITS, + AD7689_ClkMask, AD7689_DigMask, AD7689_ROReg, 1); +} + +/** + * Get temperature + * @returns temperature in °C + */ +int AD7689_GetTemperature() { + AD7689_Set( + // read back + AD7689_CFG_RB_MSK | + // disable sequencer (different from config) + AD7689_CFG_SEQ_DSBLE_VAL | + // Internal reference. REF = 2.5V buffered output. Temperature sensor enabled. + AD7689_CFG_REF_INT_2500MV_VAL | + // full bandwidth of low pass filter + AD7689_CFG_BW_FULL_VAL | + // all channel (different from config) + AD7689_CFG_IN_MSK | + // temperature sensor (different from config) + AD7689_CFG_INCC_TMP_VAL | + // overwrite configuration + AD7689_CFG_CFG_OVRWRTE_VAL); + + // FIXME: do we have to read it 8 times?? (sequencer is disabled anyway) or are we sequencing, then we read only last channel + int regval = AD7689_Get(); + + // value in mV FIXME: page 17? reference voltage temperature coefficient or t do with -40 to 85 °C + int retval = 0; + ConvertToDifferentRange(0, AD7689_INT_MAX_STEPS, + AD7689_INT_REF_MIN_MV, AD7689_INT_REF_MAX_MV, + regval, &retval); + FILE_LOG(logDEBUG1, ("voltage read for temp: %d mV\n", retval)); + + // value in °C + double tempValue = AD7689_TMP_C_FOR_1_MV * (double)retval; + + FILE_LOG(logINFO, ("\ttemp read : %f °C\n", tempValue)); + + return tempValue; + +} + +/** + * Reads channels voltage + * @param ichan channel number from 0 to 7 + * @returns channel voltage in mV + */ +int AD7689_GetChannel(int ichan) { + // filter channels val + if (ichan < 0 || ichan >= AD7689_NUM_CHANNELS) { + FILE_LOG(logERROR, ("Cannot get slow adc channel. " + "%d out of bounds (0 to %d)\n", ichan, AD7689_NUM_CHANNELS - 1)); + return -1; + } + + AD7689_Set( + // read back + AD7689_CFG_RB_MSK | + // disable sequencer (different from config) + AD7689_CFG_SEQ_DSBLE_VAL | + // Internal reference. REF = 2.5V buffered output. Temperature sensor enabled. + AD7689_CFG_REF_INT_2500MV_VAL | + // full bandwidth of low pass filter + AD7689_CFG_BW_FULL_VAL | + // specific channel (different from config) + ((ichan << AD7689_CFG_IN_OFST) & AD7689_CFG_IN_MSK) | + // input channel configuration (unipolar. inx to gnd) + AD7689_CFG_INCC_UNPLR_IN_GND_VAL | + // overwrite configuration + AD7689_CFG_CFG_OVRWRTE_VAL); + + // FIXME: do we have to read it 8 times?? (sequencer is disabled anyway) or are we sequencing, then we read only last channel + int regval = AD7689_Get(); + + // value in mV + int retval = 0; + ConvertToDifferentRange(0, AD7689_INT_MAX_STEPS, + AD7689_INT_REF_MIN_MV, AD7689_INT_REF_MAX_MV, + regval, &retval); + FILE_LOG(logINFO, ("\tvoltage read for chan %d: %d mV\n", ichan, retval)); + + return retval; +} + +/** + * Configure + */ +void AD7689_Configure(){ + FILE_LOG(logINFOBLUE, ("Configuring AD7689 (Slow ADCs): \n")); + + // from power up, 3 invalid conversions + FILE_LOG(logINFO, ("\tConfiguring %d x due to invalid conversions from power up\n", AD7689_NUM_INVALID_CONVERSIONS)); + int i = 0; + for (i = 0; i < AD7689_NUM_INVALID_CONVERSIONS; ++i) { + AD7689_Set( + // read back + AD7689_CFG_RB_MSK | + // scan sequence IN0-IN7 then temperature sensor + AD7689_CFG_SEQ_SCN_WTH_TMP_VAL | + // Internal reference. REF = 2.5V buffered output. Temperature sensor enabled. + AD7689_CFG_REF_INT_2500MV_VAL | + // full bandwidth of low pass filter + AD7689_CFG_BW_FULL_VAL | + // scan upto channel 7 + AD7689_CFG_IN_MSK | + // input channel configuration (unipolar. inx to gnd) + AD7689_CFG_INCC_UNPLR_IN_GND_VAL | + // overwrite configuration + AD7689_CFG_CFG_OVRWRTE_VAL); + } +} diff --git a/slsDetectorServers/slsDetectorServer/AD9252.h b/slsDetectorServers/slsDetectorServer/AD9252.h new file mode 100755 index 000000000..db378113a --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/AD9252.h @@ -0,0 +1,197 @@ +#pragma once + +#include "commonServerFunctions.h" // blackfin.h, ansi.h +#ifdef GOTTHARDD +#include +#endif + +/* AD9252 ADC DEFINES */ +#define AD9252_ADC_NUMBITS (24) + +// default value is 0xF +#define AD9252_DEV_IND_2_REG (0x04) +#define AD9252_CHAN_H_OFST (0) +#define AD9252_CHAN_H_MSK (0x00000001 << AD9252_CHAN_H_OFST) +#define AD9252_CHAN_G_OFST (1) +#define AD9252_CHAN_G_MSK (0x00000001 << AD9252_CHAN_G_OFST) +#define AD9252_CHAN_F_OFST (2) +#define AD9252_CHAN_F_MSK (0x00000001 << AD9252_CHAN_F_OFST) +#define AD9252_CHAN_E_OFST (3) +#define AD9252_CHAN_E_MSK (0x00000001 << AD9252_CHAN_E_OFST) + +// default value is 0x0F +#define AD9252_DEV_IND_1_REG (0x05) +#define AD9252_CHAN_D_OFST (0) +#define AD9252_CHAN_D_MSK (0x00000001 << AD9252_CHAN_D_OFST) +#define AD9252_CHAN_C_OFST (1) +#define AD9252_CHAN_C_MSK (0x00000001 << AD9252_CHAN_C_OFST) +#define AD9252_CHAN_B_OFST (2) +#define AD9252_CHAN_B_MSK (0x00000001 << AD9252_CHAN_B_OFST) +#define AD9252_CHAN_A_OFST (3) +#define AD9252_CHAN_A_MSK (0x00000001 << AD9252_CHAN_A_OFST) +#define AD9252_CLK_CH_DCO_OFST (4) +#define AD9252_CLK_CH_DCO_MSK (0x00000001 << AD9252_CLK_CH_DCO_OFST) +#define AD9252_CLK_CH_IFCO_OFST (5) +#define AD9252_CLK_CH_IFCO_MSK (0x00000001 << AD9252_CLK_CH_IFCO_OFST) + +// default value is 0x00 +#define AD9252_POWER_MODE_REG (0x08) +#define AD9252_POWER_INTERNAL_OFST (0) +#define AD9252_POWER_INTERNAL_MSK (0x00000007 << AD9252_POWER_INTERNAL_OFST) +#define AD9252_INT_CHIP_RUN_VAL ((0x0 << AD9252_POWER_INTERNAL_OFST) & AD9252_POWER_INTERNAL_MSK) +#define AD9252_INT_FULL_PWR_DWN_VAL ((0x1 << AD9252_POWER_INTERNAL_OFST) & AD9252_POWER_INTERNAL_MSK) +#define AD9252_INT_STANDBY_VAL ((0x2 << AD9252_POWER_INTERNAL_OFST) & AD9252_POWER_INTERNAL_MSK) +#define AD9252_INT_RESET_VAL ((0x3 << AD9252_POWER_INTERNAL_OFST) & AD9252_POWER_INTERNAL_MSK) + + +// default value is 0x0 +#define AD9252_TEST_MODE_REG (0x0D) +#define AD9252_OUT_TEST_OFST (0) +#define AD9252_OUT_TEST_MSK (0x0000000F << AD9252_OUT_TEST_OFST) +#define AD9252_TST_OFF_VAL ((0x0 << AD9252_OUT_TEST_OFST) & AD9252_OUT_TEST_MSK) +#define AD9252_TST_MDSCL_SHRT_VAL ((0x1 << AD9252_OUT_TEST_OFST) & AD9252_OUT_TEST_MSK) +#define AD9252_TST_PSTV_FS_VAL ((0x2 << AD9252_OUT_TEST_OFST) & AD9252_OUT_TEST_MSK) +#define AD9252_TST_NGTV_FS_VAL ((0x3 << AD9252_OUT_TEST_OFST) & AD9252_OUT_TEST_MSK) +#define AD9252_TST_ALTRNTNG_CHKRBRD_VAL ((0x4 << AD9252_OUT_TEST_OFST) & AD9252_OUT_TEST_MSK) +#define AD9252_TST_PN_23_SQNC_VAL ((0x5 << AD9252_OUT_TEST_OFST) & AD9252_OUT_TEST_MSK) +#define AD9252_TST_PN_9_SQNC__VAL ((0x6 << AD9252_OUT_TEST_OFST) & AD9252_OUT_TEST_MSK) +#define AD9252_TST_1_0_WRD_TGGL_VAL ((0x7 << AD9252_OUT_TEST_OFST) & AD9252_OUT_TEST_MSK) +#define AD9252_TST_USR_INPT_VAL ((0x8 << AD9252_OUT_TEST_OFST) & AD9252_OUT_TEST_MSK) +#define AD9252_TST_1_0_BT_TGGL_VAL ((0x9 << AD9252_OUT_TEST_OFST) & AD9252_OUT_TEST_MSK) +#define AD9252_TST_1_x_SYNC_VAL ((0xa << AD9252_OUT_TEST_OFST) & AD9252_OUT_TEST_MSK) +#define AD9252_TST_1_BIT_HGH_VAL ((0xb << AD9252_OUT_TEST_OFST) & AD9252_OUT_TEST_MSK) +#define AD9252_TST_MXD_BT_FRQ_VAL ((0xc << AD9252_OUT_TEST_OFST) & AD9252_OUT_TEST_MSK) +#define AD9252_TST_RST_SHRT_GN_OFST (4) +#define AD9252_TST_RST_SHRT_GN_MSK (0x00000001 << AD9252_TST_RST_SHRT_GN_OFST) +#define AD9252_TST_RST_LNG_GN_OFST (5) +#define AD9252_TST_RST_LNG_GN_MSK (0x00000001 << AD9252_TST_RST_LNG_GN_OFST) +#define AD9252_USER_IN_MODE_OFST (6) +#define AD9252_USER_IN_MODE_MSK (0x00000003 << AD9252_USER_IN_MODE_OFST) +#define AD9252_USR_IN_SNGL_VAL ((0x0 << AD9252_USER_IN_MODE_OFST) & AD9252_USER_IN_MODE_MSK) +#define AD9252_USR_IN_ALTRNT_VAL ((0x1 << AD9252_USER_IN_MODE_OFST) & AD9252_USER_IN_MODE_MSK) +#define AD9252_USR_IN_SNGL_ONC_VAL ((0x2 << AD9252_USER_IN_MODE_OFST) & AD9252_USER_IN_MODE_MSK) +#define AD9252_USR_IN_ALTRNT_ONC_VAL ((0x3 << AD9252_USER_IN_MODE_OFST) & AD9252_USER_IN_MODE_MSK) + +// default value is 0x00 +#define AD9252_OUT_MODE_REG (0x14) +#define AD9252_OUT_FORMAT_OFST (0) +#define AD9252_OUT_FORMAT_MSK (0x00000003 << AD9252_OUT_FORMAT_OFST) +#define AD9252_OUT_BINARY_OFST_VAL ((0x0 << AD9252_OUT_FORMAT_OFST) & AD9252_OUT_FORMAT_MSK) +#define AD9252_OUT_TWOS_COMPL_VAL ((0x1 << AD9252_OUT_FORMAT_OFST) & AD9252_OUT_FORMAT_MSK) +#define AD9252_OUT_OTPT_INVRT_OFST (2) +#define AD9252_OUT_OTPT_INVRT_MSK (0x00000001 << AD9252_OUT_OTPT_INVRT_OFST) +#define AD9252_OUT_LVDS_OPT_OFST (6) +#define AD9252_OUT_LVDS_OPT_MSK (0x00000001 << AD9252_OUT_LVDS_OPT_OFST) +#define AD9252_OUT_LVDS_ANSI_VAL ((0x0 << AD9252_OUT_LVDS_OPT_OFST) & AD9252_OUT_LVDS_OPT_MSK) +#define AD9252_OUT_LVDS_IEEE_VAL ((0x1 << AD9252_OUT_LVDS_OPT_OFST) & AD9252_OUT_LVDS_OPT_MSK) + +// default value is 0x3 +#define AD9252_OUT_PHASE_REG (0x16) +#define AD9252_OUT_CLK_OFST (0) +#define AD9252_OUT_CLK_MSK (0x0000000F << AD9252_OUT_CLK_OFST) +#define AD9252_OUT_CLK_0_VAL ((0x0 << AD9252_OUT_CLK_OFST) & AD9252_OUT_CLK_MSK) +#define AD9252_OUT_CLK_60_VAL ((0x1 << AD9252_OUT_CLK_OFST) & AD9252_OUT_CLK_MSK) +#define AD9252_OUT_CLK_120_VAL ((0x2 << AD9252_OUT_CLK_OFST) & AD9252_OUT_CLK_MSK) +#define AD9252_OUT_CLK_180_VAL ((0x3 << AD9252_OUT_CLK_OFST) & AD9252_OUT_CLK_MSK) +#define AD9252_OUT_CLK_300_VAL ((0x5 << AD9252_OUT_CLK_OFST) & AD9252_OUT_CLK_MSK) +#define AD9252_OUT_CLK_360_VAL ((0x6 << AD9252_OUT_CLK_OFST) & AD9252_OUT_CLK_MSK) +#define AD9252_OUT_CLK_480_VAL ((0x8 << AD9252_OUT_CLK_OFST) & AD9252_OUT_CLK_MSK) +#define AD9252_OUT_CLK_540_VAL ((0x9 << AD9252_OUT_CLK_OFST) & AD9252_OUT_CLK_MSK) +#define AD9252_OUT_CLK_600_VAL ((0xa << AD9252_OUT_CLK_OFST) & AD9252_OUT_CLK_MSK) +#define AD9252_OUT_CLK_660_VAL ((0xb << AD9252_OUT_CLK_OFST) & AD9252_OUT_CLK_MSK) // 0xb - 0xf is 660 + +uint32_t AD9252_Reg = 0x0; +uint32_t AD9252_CsMask = 0x0; +uint32_t AD9252_ClkMask = 0x0; +uint32_t AD9252_DigMask = 0x0; +int AD9252_DigOffset = 0x0; + +/** + * Set Defines + * @param reg spi register + * @param cmsk chip select mask + * @param clkmsk clock output mask + * @param dmsk digital output mask + * @param dofst digital output offset + */ +void AD9252_SetDefines(uint32_t reg, uint32_t cmsk, uint32_t clkmsk, uint32_t dmsk, int dofst) { + AD9252_Reg = reg; + AD9252_CsMask = cmsk; + AD9252_ClkMask = clkmsk; + AD9252_DigMask = dmsk; + AD9252_DigOffset = dofst; +} + +/** + * Disable SPI + */ +void AD9252_Disable() { + bus_w(AD9252_Reg, (bus_r(AD9252_Reg) + | AD9252_CsMask + | AD9252_ClkMask) + &~(AD9252_DigMask)); +} + +/** + * Set SPI reg value + * @param codata value to be set + */ +void AD9252_Set(int addr, int val) { + + u_int32_t codata; + codata = val + (addr << 8); + FILE_LOG(logINFO, ("\tSetting ADC SPI Register. Wrote 0x%04x at 0x%04x\n", val, addr)); + serializeToSPI(AD9252_Reg, codata, AD9252_CsMask, AD9252_ADC_NUMBITS, + AD9252_ClkMask, AD9252_DigMask, AD9252_DigOffset, 0); +} + +/** + * Configure + */ +void AD9252_Configure(){ + FILE_LOG(logINFOBLUE, ("Configuring ADC9252:\n")); + + //power mode reset + FILE_LOG(logINFO, ("\tPower mode reset\n")); + AD9252_Set(AD9252_POWER_MODE_REG, AD9252_INT_RESET_VAL); + + //power mode chip run + FILE_LOG(logINFO, ("\tPower mode chip run\n")); + AD9252_Set(AD9252_POWER_MODE_REG, AD9252_INT_CHIP_RUN_VAL); + + // binary offset + FILE_LOG(logINFO, ("\tBinary offset\n")); + AD9252_Set(AD9252_OUT_MODE_REG, AD9252_OUT_BINARY_OFST_VAL); + + //output clock phase +#ifdef GOTTHARDD + FILE_LOG(logINFO, ("\tOutput clock phase is at default: 180\n")); +#else + FILE_LOG(logINFO, ("\tOutput clock phase: 60\n")); + AD9257_Set(AD9257_OUT_PHASE_REG, AD9257_OUT_CLK_60_VAL); +#endif + + // lvds-iee reduced , binary offset + FILE_LOG(logINFO, ("\tLvds-iee reduced, binary offset\n")); + AD9252_Set(AD9252_OUT_MODE_REG, AD9252_OUT_LVDS_IEEE_VAL); + + // all devices on chip to receive next command + FILE_LOG(logINFO, ("\tAll devices on chip to receive next command\n")); + AD9252_Set(AD9252_DEV_IND_2_REG, + AD9252_CHAN_H_MSK | AD9252_CHAN_G_MSK | AD9252_CHAN_F_MSK | AD9252_CHAN_E_MSK); + AD9252_Set(AD9252_DEV_IND_1_REG, + AD9252_CHAN_D_MSK | AD9252_CHAN_C_MSK | AD9252_CHAN_B_MSK | AD9252_CHAN_A_MSK | + AD9252_CLK_CH_DCO_MSK | AD9252_CLK_CH_IFCO_MSK); + + // no test mode + FILE_LOG(logINFO, ("\tNo test mode\n")); + AD9252_Set(AD9252_TEST_MODE_REG, AD9252_TST_OFF_VAL); + +#ifdef TESTADC + FILE_LOG(logINFOBLUE, ("Putting ADC in Test Mode!\n"); + // mixed bit frequency test mode + FILE_LOG(logINFO, ("\tMixed bit frequency test mode\n")); + AD9252_Set(AD9252_TEST_MODE_REG, AD9252_TST_MXD_BT_FRQ_VAL); +#endif +} + diff --git a/slsDetectorServers/slsDetectorServer/AD9257.h b/slsDetectorServers/slsDetectorServer/AD9257.h new file mode 100755 index 000000000..87c096309 --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/AD9257.h @@ -0,0 +1,247 @@ +#pragma once + +#include "commonServerFunctions.h" // blackfin.h, ansi.h +#ifdef GOTTHARDD +#include +#endif + +/* AD9257 ADC DEFINES */ +#define AD9257_ADC_NUMBITS (24) + +// default value is 0xF +#define AD9257_DEV_IND_2_REG (0x04) +#define AD9257_CHAN_H_OFST (0) +#define AD9257_CHAN_H_MSK (0x00000001 << AD9257_CHAN_H_OFST) +#define AD9257_CHAN_G_OFST (1) +#define AD9257_CHAN_G_MSK (0x00000001 << AD9257_CHAN_G_OFST) +#define AD9257_CHAN_F_OFST (2) +#define AD9257_CHAN_F_MSK (0x00000001 << AD9257_CHAN_F_OFST) +#define AD9257_CHAN_E_OFST (3) +#define AD9257_CHAN_E_MSK (0x00000001 << AD9257_CHAN_E_OFST) + +// default value is 0x3F +#define AD9257_DEV_IND_1_REG (0x05) +#define AD9257_CHAN_D_OFST (0) +#define AD9257_CHAN_D_MSK (0x00000001 << AD9257_CHAN_D_OFST) +#define AD9257_CHAN_C_OFST (1) +#define AD9257_CHAN_C_MSK (0x00000001 << AD9257_CHAN_C_OFST) +#define AD9257_CHAN_B_OFST (2) +#define AD9257_CHAN_B_MSK (0x00000001 << AD9257_CHAN_B_OFST) +#define AD9257_CHAN_A_OFST (3) +#define AD9257_CHAN_A_MSK (0x00000001 << AD9257_CHAN_A_OFST) +#define AD9257_CLK_CH_DCO_OFST (4) +#define AD9257_CLK_CH_DCO_MSK (0x00000001 << AD9257_CLK_CH_DCO_OFST) +#define AD9257_CLK_CH_IFCO_OFST (5) +#define AD9257_CLK_CH_IFCO_MSK (0x00000001 << AD9257_CLK_CH_IFCO_OFST) + +// default value is 0x00 +#define AD9257_POWER_MODE_REG (0x08) +#define AD9257_POWER_INTERNAL_OFST (0) +#define AD9257_POWER_INTERNAL_MSK (0x00000003 << AD9257_POWER_INTERNAL_OFST) +#define AD9257_INT_CHIP_RUN_VAL ((0x0 << AD9257_POWER_INTERNAL_OFST) & AD9257_POWER_INTERNAL_MSK) +#define AD9257_INT_FULL_PWR_DWN_VAL ((0x1 << AD9257_POWER_INTERNAL_OFST) & AD9257_POWER_INTERNAL_MSK) +#define AD9257_INT_STANDBY_VAL ((0x2 << AD9257_POWER_INTERNAL_OFST) & AD9257_POWER_INTERNAL_MSK) +#define AD9257_INT_RESET_VAL ((0x3 << AD9257_POWER_INTERNAL_OFST) & AD9257_POWER_INTERNAL_MSK) +#define AD9257_POWER_EXTERNAL_OFST (5) +#define AD9257_POWER_EXTERNAL_MSK (0x00000001 << AD9257_POWER_EXTERNAL_OFST) +#define AD9257_EXT_FULL_POWER_VAL ((0x0 << AD9257_POWER_EXTERNAL_OFST) & AD9257_POWER_EXTERNAL_MSK) +#define AD9257_EXT_STANDBY_VAL ((0x1 << AD9257_POWER_EXTERNAL_OFST) & AD9257_POWER_EXTERNAL_MSK) + +// default value is 0x0 +#define AD9257_TEST_MODE_REG (0x0D) +#define AD9257_OUT_TEST_OFST (0) +#define AD9257_OUT_TEST_MSK (0x0000000F << AD9257_OUT_TEST_OFST) +#define AD9257_TST_OFF_VAL ((0x0 << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK) +#define AD9257_TST_MDSCL_SHRT_VAL ((0x1 << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK) +#define AD9257_TST_PSTV_FS_VAL ((0x2 << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK) +#define AD9257_TST_NGTV_FS_VAL ((0x3 << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK) +#define AD9257_TST_ALTRNTNG_CHKRBRD_VAL ((0x4 << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK) +#define AD9257_TST_PN_23_SQNC_VAL ((0x5 << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK) +#define AD9257_TST_PN_9_SQNC__VAL ((0x6 << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK) +#define AD9257_TST_1_0_WRD_TGGL_VAL ((0x7 << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK) +#define AD9257_TST_USR_INPT_VAL ((0x8 << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK) +#define AD9257_TST_1_0_BT_TGGL_VAL ((0x9 << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK) +#define AD9257_TST_1_x_SYNC_VAL ((0xa << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK) +#define AD9257_TST_1_BIT_HGH_VAL ((0xb << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK) +#define AD9257_TST_MXD_BT_FRQ_VAL ((0xc << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK) +#define AD9257_TST_RST_SHRT_GN_OFST (4) +#define AD9257_TST_RST_SHRT_GN_MSK (0x00000001 << AD9257_TST_RST_SHRT_GN_OFST) +#define AD9257_TST_RST_LNG_GN_OFST (5) +#define AD9257_TST_RST_LNG_GN_MSK (0x00000001 << AD9257_TST_RST_LNG_GN_OFST) +#define AD9257_USER_IN_MODE_OFST (6) +#define AD9257_USER_IN_MODE_MSK (0x00000003 << AD9257_USER_IN_MODE_OFST) +#define AD9257_USR_IN_SNGL_VAL ((0x0 << AD9257_USER_IN_MODE_OFST) & AD9257_USER_IN_MODE_MSK) +#define AD9257_USR_IN_ALTRNT_VAL ((0x1 << AD9257_USER_IN_MODE_OFST) & AD9257_USER_IN_MODE_MSK) +#define AD9257_USR_IN_SNGL_ONC_VAL ((0x2 << AD9257_USER_IN_MODE_OFST) & AD9257_USER_IN_MODE_MSK) +#define AD9257_USR_IN_ALTRNT_ONC_VAL ((0x3 << AD9257_USER_IN_MODE_OFST) & AD9257_USER_IN_MODE_MSK) + +// default value is 0x01 +#define AD9257_OUT_MODE_REG (0x14) +#define AD9257_OUT_FORMAT_OFST (0) +#define AD9257_OUT_FORMAT_MSK (0x00000001 << AD9257_OUT_FORMAT_OFST) +#define AD9257_OUT_BINARY_OFST_VAL ((0x0 << AD9257_OUT_FORMAT_OFST) & AD9257_OUT_FORMAT_MSK) +#define AD9257_OUT_TWOS_COMPL_VAL ((0x1 << AD9257_OUT_FORMAT_OFST) & AD9257_OUT_FORMAT_MSK) +#define AD9257_OUT_OTPT_INVRT_OFST (2) +#define AD9257_OUT_OTPT_INVRT_MSK (0x00000001 << AD9257_OUT_OTPT_INVRT_OFST) +#define AD9257_OUT_LVDS_OPT_OFST (6) +#define AD9257_OUT_LVDS_OPT_MSK (0x00000001 << AD9257_OUT_LVDS_OPT_OFST) +#define AD9257_OUT_LVDS_ANSI_VAL ((0x0 << AD9257_OUT_LVDS_OPT_OFST) & AD9257_OUT_LVDS_OPT_MSK) +#define AD9257_OUT_LVDS_IEEE_VAL ((0x1 << AD9257_OUT_LVDS_OPT_OFST) & AD9257_OUT_LVDS_OPT_MSK) + +// default value is 0x3 +#define AD9257_OUT_PHASE_REG (0x16) +#define AD9257_OUT_CLK_OFST (0) +#define AD9257_OUT_CLK_MSK (0x0000000F << AD9257_OUT_CLK_OFST) +#define AD9257_OUT_CLK_0_VAL ((0x0 << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK) +#define AD9257_OUT_CLK_60_VAL ((0x1 << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK) +#define AD9257_OUT_CLK_120_VAL ((0x2 << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK) +#define AD9257_OUT_CLK_180_VAL ((0x3 << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK) +#define AD9257_OUT_CLK_240_VAL ((0x4 << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK) +#define AD9257_OUT_CLK_300_VAL ((0x5 << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK) +#define AD9257_OUT_CLK_360_VAL ((0x6 << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK) +#define AD9257_OUT_CLK_420_VAL ((0x7 << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK) +#define AD9257_OUT_CLK_480_VAL ((0x8 << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK) +#define AD9257_OUT_CLK_540_VAL ((0x9 << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK) +#define AD9257_OUT_CLK_600_VAL ((0xa << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK) +#define AD9257_OUT_CLK_660_VAL ((0xb << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK) +#define AD9257_IN_CLK_OFST (4) +#define AD9257_IN_CLK_MSK (0x00000007 << AD9257_IN_CLK_OFST) +#define AD9257_IN_CLK_0_VAL ((0x0 << AD9257_IN_CLK_OFST) & AD9257_IN_CLK_MSK) +#define AD9257_IN_CLK_1_VAL ((0x1 << AD9257_IN_CLK_OFST) & AD9257_IN_CLK_MSK) +#define AD9257_IN_CLK_2_VAL ((0x2 << AD9257_IN_CLK_OFST) & AD9257_IN_CLK_MSK) +#define AD9257_IN_CLK_3_VAL ((0x3 << AD9257_IN_CLK_OFST) & AD9257_IN_CLK_MSK) +#define AD9257_IN_CLK_4_VAL ((0x4 << AD9257_IN_CLK_OFST) & AD9257_IN_CLK_MSK) +#define AD9257_IN_CLK_5_VAL ((0x5 << AD9257_IN_CLK_OFST) & AD9257_IN_CLK_MSK) +#define AD9257_IN_CLK_6_VAL ((0x6 << AD9257_IN_CLK_OFST) & AD9257_IN_CLK_MSK) +#define AD9257_IN_CLK_7_VAL ((0x7 << AD9257_IN_CLK_OFST) & AD9257_IN_CLK_MSK) + +// default value is 0x4 +#define AD9257_VREF_REG (0x18) +#define AD9257_VREF_OFST (0) +#define AD9257_VREF_MSK (0x00000007 << AD9257_VREF_OFST) +#define AD9257_VREF_1_0_VAL ((0x0 << AD9257_VREF_OFST) & AD9257_VREF_MSK) +#define AD9257_VREF_1_14_VAL ((0x1 << AD9257_VREF_OFST) & AD9257_VREF_MSK) +#define AD9257_VREF_1_33_VAL ((0x2 << AD9257_VREF_OFST) & AD9257_VREF_MSK) +#define AD9257_VREF_1_6_VAL ((0x3 << AD9257_VREF_OFST) & AD9257_VREF_MSK) +#define AD9257_VREF_2_0_VAL ((0x4 << AD9257_VREF_OFST) & AD9257_VREF_MSK) + +uint32_t AD9257_Reg = 0x0; +uint32_t AD9257_CsMask = 0x0; +uint32_t AD9257_ClkMask = 0x0; +uint32_t AD9257_DigMask = 0x0; +int AD9257_DigOffset = 0x0; + +/** + * Set Defines + * @param reg spi register + * @param cmsk chip select mask + * @param clkmsk clock output mask + * @param dmsk digital output mask + * @param dofst digital output offset + */ +void AD9257_SetDefines(uint32_t reg, uint32_t cmsk, uint32_t clkmsk, uint32_t dmsk, int dofst) { + AD9257_Reg = reg; + AD9257_CsMask = cmsk; + AD9257_ClkMask = clkmsk; + AD9257_DigMask = dmsk; + AD9257_DigOffset = dofst; +} + +/** + * Disable SPI + */ +void AD9257_Disable() { + bus_w(AD9257_Reg, (bus_r(AD9257_Reg) + | AD9257_CsMask + | AD9257_ClkMask) + & ~(AD9257_DigMask)); +} + +/** + * Get max valid vref value + * @param get max vref voltage unit (4 for 2.0V) + */ +int AD9257_GetMaxValidVref() { + return 0x4; +} + +/** + * Set vref voltage + * @param val voltage to be set (0 for 1.0V, 1 for 1.14V, 2 for 1.33V, 3 for 1.6V, 4 for 2.0V + */ +void AD9257_SetVrefVoltage(int val) { + AD9257_Set(AD9257_VREF_REG, val); +} + +/** + * Set SPI reg value + * @param codata value to be set + */ +void AD9257_Set(int addr, int val) { + + u_int32_t codata; + codata = val + (addr << 8); + FILE_LOG(logINFO, ("\tSetting ADC SPI Register. Wrote 0x%04x at 0x%04x\n", val, addr)); + serializeToSPI(AD9257_Reg, codata, AD9257_CsMask, AD9257_ADC_NUMBITS, + AD9257_ClkMask, AD9257_DigMask, AD9257_DigOffset, 0); +} + +/** + * Configure + */ +void AD9257_Configure(){ + FILE_LOG(logINFOBLUE, ("Configuring ADC9257:\n")); + + //power mode reset + FILE_LOG(logINFO, ("\tPower mode reset\n")); + AD9257_Set(AD9257_POWER_MODE_REG, AD9257_INT_RESET_VAL); + + //power mode chip run + FILE_LOG(logINFO, ("\tPower mode chip run\n")); + AD9257_Set(AD9257_POWER_MODE_REG, AD9257_INT_CHIP_RUN_VAL); + + // binary offset + FILE_LOG(logINFO, ("\tBinary offset\n")); + AD9257_Set(AD9257_OUT_MODE_REG, AD9257_OUT_BINARY_OFST_VAL); + + //output clock phase +#if defined(GOTTHARDD) || defined(JUNGFRAUD) + FILE_LOG(logINFO, ("\tOutput clock phase is at default: 180\n")); +#else + FILE_LOG(logINFO, ("\tOutput clock phase: 60\n")); + AD9257_Set(AD9257_OUT_PHASE_REG, AD9257_OUT_CLK_60_VAL); +#endif + + // lvds-iee reduced , binary offset + FILE_LOG(logINFO, ("\tLvds-iee reduced, binary offset\n")); + AD9257_Set(AD9257_OUT_MODE_REG, AD9257_OUT_LVDS_IEEE_VAL); + + // all devices on chip to receive next command + FILE_LOG(logINFO, ("\tAll devices on chip to receive next command\n")); + AD9257_Set(AD9257_DEV_IND_2_REG, + AD9257_CHAN_H_MSK | AD9257_CHAN_G_MSK | AD9257_CHAN_F_MSK | AD9257_CHAN_E_MSK); + + AD9257_Set(AD9257_DEV_IND_1_REG, + AD9257_CHAN_D_MSK | AD9257_CHAN_C_MSK | AD9257_CHAN_B_MSK | AD9257_CHAN_A_MSK | + AD9257_CLK_CH_DCO_MSK | AD9257_CLK_CH_IFCO_MSK); + + // vref +#ifdef GOTTHARDD + FILE_LOG(logINFO, ("\tVref default at 2.0\n")); +#else + FILE_LOG(logINFO, ("\tVref 1.33\n")); + AD9257_Set(AD9257_VREF_REG, AD9257_VREF_1_33_VAL); +#endif + + // no test mode + FILE_LOG(logINFO, ("\tNo test mode\n")); + AD9257_Set(AD9257_TEST_MODE_REG, AD9257_TST_OFF_VAL); + +#ifdef TESTADC + FILE_LOG(logINFOBLUE, ("Putting ADC in Test Mode!\n"); + // mixed bit frequency test mode + FILE_LOG(logINFO, ("\tMixed bit frequency test mode\n")); + AD9257_Set(AD9257_TEST_MODE_REG, AD9257_TST_MXD_BT_FRQ_VAL); +#endif + +} diff --git a/slsDetectorServers/slsDetectorServer/ALTERA_PLL.h b/slsDetectorServers/slsDetectorServer/ALTERA_PLL.h new file mode 100755 index 000000000..008c39c79 --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/ALTERA_PLL.h @@ -0,0 +1,240 @@ +#pragma once + +#include // usleep + +/* Altera PLL DEFINES */ + +/** PLL Reconfiguration Registers */ +//https://www.altera.com/documentation/mcn1424769382940.html +#define ALTERA_PLL_MODE_REG (0x00) + +#define ALTERA_PLL_MODE_WT_RQUST_VAL (0) +#define ALTERA_PLL_MODE_PLLNG_MD_VAL (1) + +#define ALTERA_PLL_STATUS_REG (0x01) +#define ALTERA_PLL_START_REG (0x02) +#define ALTERA_PLL_N_COUNTER_REG (0x03) +#define ALTERA_PLL_M_COUNTER_REG (0x04) +#define ALTERA_PLL_C_COUNTER_REG (0x05) + +#define ALTERA_PLL_C_COUNTER_LW_CNT_OFST (0) +#define ALTERA_PLL_C_COUNTER_LW_CNT_MSK (0x000000FF << ALTERA_PLL_C_COUNTER_LW_CNT_OFST) +#define ALTERA_PLL_C_COUNTER_HGH_CNT_OFST (8) +#define ALTERA_PLL_C_COUNTER_HGH_CNT_MSK (0x000000FF << ALTERA_PLL_C_COUNTER_HGH_CNT_OFST) +/* total_div = lw_cnt + hgh_cnt */ +#define ALTERA_PLL_C_COUNTER_BYPSS_ENBL_OFST (16) +#define ALTERA_PLL_C_COUNTER_BYPSS_ENBL_MSK (0x00000001 << ALTERA_PLL_C_COUNTER_BYPSS_ENBL_OFST) +/* if bypss_enbl = 0, fout = f(vco)/total_div; else fout = f(vco) (c counter is bypassed) */ +#define ALTERA_PLL_C_COUNTER_ODD_DVSN_OFST (17) +#define ALTERA_PLL_C_COUNTER_ODD_DVSN_MSK (0x00000001 << ALTERA_PLL_C_COUNTER_ODD_DVSN_OFST) +/** if odd_dvsn = 0 (even), duty cycle = hgh_cnt/ total_div; else duty cycle = (hgh_cnt - 0.5) / total_div */ +#define ALTERA_PLL_C_COUNTER_SLCT_OFST (18) +#define ALTERA_PLL_C_COUNTER_SLCT_MSK (0x0000001F << ALTERA_PLL_C_COUNTER_SLCT_OFST) + +#define ALTERA_PLL_PHASE_SHIFT_REG (0x06) + +#define ALTERA_PLL_SHIFT_NUM_SHIFTS_OFST (0) +#define ALTERA_PLL_SHIFT_NUM_SHIFTS_MSK (0x0000FFFF << ALTERA_PLL_SHIFT_NUM_SHIFTS_OFST) + +#define ALTERA_PLL_SHIFT_CNT_SELECT_OFST (16) +#define ALTERA_PLL_SHIFT_CNT_SELECT_MSK (0x0000001F << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C0_VAL ((0x0 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C1_VAL ((0x1 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C2_VAL ((0x2 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C3_VAL ((0x3 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C4_VAL ((0x4 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C5_VAL ((0x5 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C6_VAL ((0x6 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C7_VAL ((0x7 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C8_VAL ((0x8 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C9_VAL ((0x9 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C10_VAL ((0x10 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C11_VAL ((0x11 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C12_VAL ((0x12 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C13_VAL ((0x13 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C14_VAL ((0x14 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C15_VAL ((0x15 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C16_VAL ((0x16 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) +#define ALTERA_PLL_SHIFT_CNT_SLCT_C17_VAL ((0x17 << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) + +#define ALTERA_PLL_SHIFT_UP_DOWN_OFST (21) +#define ALTERA_PLL_SHIFT_UP_DOWN_MSK (0x00000001 << ALTERA_PLL_SHIFT_UP_DOWN_OFST) +#define ALTERA_PLL_SHIFT_UP_DOWN_NEG_VAL ((0x0 << ALTERA_PLL_SHIFT_UP_DOWN_OFST) & ALTERA_PLL_SHIFT_UP_DOWN_MSK) +#define ALTERA_PLL_SHIFT_UP_DOWN_POS_VAL ((0x1 << ALTERA_PLL_SHIFT_UP_DOWN_OFST) & ALTERA_PLL_SHIFT_UP_DOWN_MSK) + +#define ALTERA_PLL_K_COUNTER_REG (0x07) +#define ALTERA_PLL_BANDWIDTH_REG (0x08) +#define ALTERA_PLL_CHARGEPUMP_REG (0x09) +#define ALTERA_PLL_VCO_DIV_REG (0x1c) +#define ALTERA_PLL_MIF_REG (0x1f) + + +#define ALTERA_PLL_WAIT_TIME_US (10 * 1000) + + +uint32_t ALTERA_PLL_Cntrl_Reg = 0x0; +uint32_t ALTERA_PLL_Param_Reg = 0x0; +uint32_t ALTERA_PLL_Cntrl_RcnfgPrmtrRstMask = 0x0; +uint32_t ALTERA_PLL_Cntrl_WrPrmtrMask = 0x0; +uint32_t ALTERA_PLL_Cntrl_PLLRstMask = 0x0; +uint32_t ALTERA_PLL_Cntrl_AddrMask = 0x0; +int ALTERA_PLL_Cntrl_AddrOfst = 0; + + +/** + * Set Defines + * @param creg control register + * @param preg parameter register + * @param rprmsk reconfig parameter reset mask + * @param wpmsk write parameter mask + * @param prmsk pll reset mask + * @param amsk address mask + * @param aofst address offset + */ +void ALTERA_PLL_SetDefines(uint32_t creg, uint32_t preg, uint32_t rprmsk, uint32_t wpmsk, uint32_t prmsk, uint32_t amsk, int aofst) { + ALTERA_PLL_Cntrl_Reg = creg; + ALTERA_PLL_Param_Reg = preg; + ALTERA_PLL_Cntrl_RcnfgPrmtrRstMask = rprmsk; + ALTERA_PLL_Cntrl_WrPrmtrMask = wpmsk; + ALTERA_PLL_Cntrl_PLLRstMask = prmsk; + ALTERA_PLL_Cntrl_AddrMask = amsk; + ALTERA_PLL_Cntrl_AddrOfst = aofst; +} + +/** + * Reset only PLL + */ +void ALTERA_PLL_ResetPLL () { + FILE_LOG(logINFO, ("Resetting only PLL\n")); + + FILE_LOG(logDEBUG2, ("pllrstmsk:0x%x\n", ALTERA_PLL_Cntrl_PLLRstMask)); + + bus_w(ALTERA_PLL_Cntrl_Reg, bus_r(ALTERA_PLL_Cntrl_Reg) | ALTERA_PLL_Cntrl_PLLRstMask); + FILE_LOG(logDEBUG2, ("Set PLL Reset mSk: ALTERA_PLL_Cntrl_Reg:0x%x\n", bus_r(ALTERA_PLL_Cntrl_Reg))); + + usleep(ALTERA_PLL_WAIT_TIME_US); + + bus_w(ALTERA_PLL_Cntrl_Reg, bus_r(ALTERA_PLL_Cntrl_Reg) & ~ALTERA_PLL_Cntrl_PLLRstMask); + FILE_LOG(logDEBUG2, ("UnSet PLL Reset mSk: ALTERA_PLL_Cntrl_Reg:0x%x\n", bus_r(ALTERA_PLL_Cntrl_Reg))); + +} + +/** + * Reset PLL Reconfiguration and PLL + */ +void ALTERA_PLL_ResetPLLAndReconfiguration () { + FILE_LOG(logINFO, ("Resetting PLL and Reconfiguration\n")); + + bus_w(ALTERA_PLL_Cntrl_Reg, bus_r(ALTERA_PLL_Cntrl_Reg) | ALTERA_PLL_Cntrl_RcnfgPrmtrRstMask | ALTERA_PLL_Cntrl_PLLRstMask); + usleep(ALTERA_PLL_WAIT_TIME_US); + bus_w(ALTERA_PLL_Cntrl_Reg, bus_r(ALTERA_PLL_Cntrl_Reg) & ~ALTERA_PLL_Cntrl_RcnfgPrmtrRstMask & ~ALTERA_PLL_Cntrl_PLLRstMask); +} + + +/** + * Set PLL Reconfig register + * @param reg register + * @param val value + */ +void ALTERA_PLL_SetPllReconfigReg(uint32_t reg, uint32_t val) { + FILE_LOG(logDEBUG1, ("Setting PLL Reconfig Reg, reg:0x%x, val:0x%x)\n", reg, val)); + + FILE_LOG(logDEBUG2, ("pllparamreg:0x%x pllcontrolreg:0x%x addrofst:%d addrmsk:0x%x wrmask:0x%x\n", + ALTERA_PLL_Param_Reg, ALTERA_PLL_Cntrl_Reg, ALTERA_PLL_Cntrl_AddrOfst, ALTERA_PLL_Cntrl_AddrMask, ALTERA_PLL_Cntrl_WrPrmtrMask)); + + // set parameter + bus_w(ALTERA_PLL_Param_Reg, val); + FILE_LOG(logDEBUG2, ("Set Parameter: ALTERA_PLL_Param_Reg:0x%x\n", bus_r(ALTERA_PLL_Param_Reg))); + usleep(ALTERA_PLL_WAIT_TIME_US); + + // set address + bus_w(ALTERA_PLL_Cntrl_Reg, (reg << ALTERA_PLL_Cntrl_AddrOfst) & ALTERA_PLL_Cntrl_AddrMask); + FILE_LOG(logDEBUG2, ("Set Address: ALTERA_PLL_Cntrl_Reg:0x%x\n", bus_r(ALTERA_PLL_Cntrl_Reg))); + usleep(ALTERA_PLL_WAIT_TIME_US); + + //write parameter + bus_w(ALTERA_PLL_Cntrl_Reg, bus_r(ALTERA_PLL_Cntrl_Reg) | ALTERA_PLL_Cntrl_WrPrmtrMask); + FILE_LOG(logDEBUG2, ("Set WR bit: ALTERA_PLL_Cntrl_Reg:0x%x\n", bus_r(ALTERA_PLL_Cntrl_Reg))); + + usleep(ALTERA_PLL_WAIT_TIME_US); + + bus_w(ALTERA_PLL_Cntrl_Reg, bus_r(ALTERA_PLL_Cntrl_Reg) & ~ALTERA_PLL_Cntrl_WrPrmtrMask); + FILE_LOG(logDEBUG2, ("Unset WR bit: ALTERA_PLL_Cntrl_Reg:0x%x\n", bus_r(ALTERA_PLL_Cntrl_Reg))); + + usleep(ALTERA_PLL_WAIT_TIME_US); +} + +/** + * Write Phase Shift + * @param phase phase shift + * @param clkIndex clock index + * @param pos 1 if up down direction of shift is positive, else 0 + */ +void ALTERA_PLL_SetPhaseShift(int32_t phase, int clkIndex, int pos) { + FILE_LOG(logINFO, ("\tWriting PLL Phase Shift\n")); + uint32_t value = (((phase << ALTERA_PLL_SHIFT_NUM_SHIFTS_OFST) & ALTERA_PLL_SHIFT_NUM_SHIFTS_MSK) | + ((clkIndex << ALTERA_PLL_SHIFT_CNT_SELECT_OFST) & ALTERA_PLL_SHIFT_CNT_SELECT_MSK) | + (pos ? ALTERA_PLL_SHIFT_UP_DOWN_POS_VAL : ALTERA_PLL_SHIFT_UP_DOWN_NEG_VAL)); + + FILE_LOG(logDEBUG1, ("C%d phase word:0x%08x\n", clkIndex, value)); + + // write phase shift + ALTERA_PLL_SetPllReconfigReg(ALTERA_PLL_PHASE_SHIFT_REG, value); +} + +/** + * Set PLL mode register to polling mode + */ +void ALTERA_PLL_SetModePolling() { + FILE_LOG(logINFO, ("\tSetting Polling Mode\n")); + ALTERA_PLL_SetPllReconfigReg(ALTERA_PLL_MODE_REG, ALTERA_PLL_MODE_PLLNG_MD_VAL); +} + +/** + * Calculate and write output frequency + * @param clkIndex clock index + * @param pllVCOFreqMhz PLL VCO Frequency in Mhz + * @param value frequency to set to + * @param frequency set + */ +int ALTERA_PLL_SetOuputFrequency (int clkIndex, int pllVCOFreqMhz, int value) { + FILE_LOG(logDEBUG1, ("C%d: Setting output frequency to %d (pllvcofreq: %dMhz)\n", clkIndex, value, pllVCOFreqMhz)); + + // calculate output frequency + float total_div = (float)pllVCOFreqMhz / (float)value; + + // assume 50% duty cycle + uint32_t low_count = total_div / 2; + uint32_t high_count = low_count; + uint32_t odd_division = 0; + + // odd division + if (total_div > (float)(2 * low_count)) { + ++high_count; + odd_division = 1; + } + FILE_LOG(logINFO, ("\tC%d: Low:%d, High:%d, Odd:%d\n", clkIndex, low_count, high_count, odd_division)); + + // command to set output frequency + uint32_t val = (((low_count << ALTERA_PLL_C_COUNTER_LW_CNT_OFST) & ALTERA_PLL_C_COUNTER_LW_CNT_MSK) | + ((high_count << ALTERA_PLL_C_COUNTER_HGH_CNT_OFST) & ALTERA_PLL_C_COUNTER_HGH_CNT_MSK) | + ((odd_division << ALTERA_PLL_C_COUNTER_ODD_DVSN_OFST) & ALTERA_PLL_C_COUNTER_ODD_DVSN_MSK) | + ((clkIndex << ALTERA_PLL_C_COUNTER_SLCT_OFST) & ALTERA_PLL_C_COUNTER_SLCT_MSK)); + FILE_LOG(logDEBUG1, ("C%d word:0x%08x\n", clkIndex, val)); + + // write frequency (post-scale output counter C) + ALTERA_PLL_SetPllReconfigReg(ALTERA_PLL_C_COUNTER_REG, val); + + // reset required to keep the phase + ALTERA_PLL_ResetPLL (); + + /*double temp = ((double)pllVCOFreqMhz / (double)(low_count + high_count)); + if ((temp - (int)temp) > 0.0001) { + temp += 0.5; + } + return (int)temp; + */ + return value; +} + + diff --git a/slsDetectorServers/slsDetectorServer/I2C.h b/slsDetectorServers/slsDetectorServer/I2C.h new file mode 100755 index 000000000..8768076f3 --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/I2C.h @@ -0,0 +1,262 @@ +#pragma once + +#include "blackfin.h" +#include // usleep + +/** + * Intel: Embedded Peripherals IP User Guide + * https://www.intel.com/content/dam/www/programmable/us/en/pdfs/literature/ug/ug_embedded_ip.pdf + * To be defined + * + * (in blackfin.h) + * I2C_CLOCK_MHZ + * + * (RegisterDefs.h) + * I2C_SCL_LOW_COUNT_REG + * I2C_SCL_HIGH_COUNT_REG + * I2C_SDA_HOLD_REG + * I2C_CONTROL_REG + * I2C_STATUS_REG + * I2C_TRANSFER_COMMAND_FIFO_REG + * I2C_RX_DATA_FIFO_LEVEL_REG + * I2C_RX_DATA_FIFO_REG + */ + + +#define I2C_DATA_RATE_KBPS (200) + +/** Control Register */ +#define I2C_CTRL_ENBLE_CORE_OFST (0) +#define I2C_CTRL_ENBLE_CORE_MSK (0x00000001 << I2C_CTRL_ENBLE_CORE_OFST) +#define I2C_CTRL_BUS_SPEED_OFST (1) +#define I2C_CTRL_BUS_SPEED_MSK (0x00000001 << I2C_CTRL_BUS_SPEED_OFST) +#define I2C_CTRL_BUS_SPEED_STNDRD_100_VAL ((0x0 << I2C_CTRL_BUS_SPEED_OFST) & I2C_CTRL_BUS_SPEED_MSK) // standard mode (up to 100 kbps) +#define I2C_CTRL_BUS_SPEED_FAST_400_VAL ((0x1 << I2C_CTRL_BUS_SPEED_OFST) & I2C_CTRL_BUS_SPEED_MSK) // fast mode (up to 400 kbps) +/** if actual level of transfer command fifo <= thd level, TX_READY interrupt asserted */ +#define I2C_CTRL_TFR_CMD_FIFO_THD_OFST (2) +#define I2C_CTRL_TFR_CMD_FIFO_THD_MSK (0x00000003 << I2C_CTRL_TFR_CMD_FIFO_THD_OFST) +#define I2C_CTRL_TFR_CMD_EMPTY_VAL ((0x0 << I2C_CTRL_TFR_CMD_FIFO_THD_OFST) & I2C_CTRL_TFR_CMD_FIFO_THD_MSK) +#define I2C_CTRL_TFR_CMD_ONE_FOURTH_VAL ((0x1 << I2C_CTRL_TFR_CMD_FIFO_THD_OFST) & I2C_CTRL_TFR_CMD_FIFO_THD_MSK) +#define I2C_CTRL_TFR_CMD_ONE_HALF_VAL ((0x2 << I2C_CTRL_TFR_CMD_FIFO_THD_OFST) & I2C_CTRL_TFR_CMD_FIFO_THD_MSK) +#define I2C_CTRL_TFR_CMD_NOT_FULL_VAL ((0x3 << I2C_CTRL_TFR_CMD_FIFO_THD_OFST) & I2C_CTRL_TFR_CMD_FIFO_THD_MSK) +/** if actual level of receive data fifo <= thd level, RX_READY interrupt asserted */ +#define I2C_CTRL_RX_DATA_FIFO_THD_OFST (4) +#define I2C_CTRL_RX_DATA_FIFO_THD_MSK (0x00000003 << I2C_CTRL_RX_DATA_FIFO_THD_OFST) +#define I2C_CTRL_RX_DATA_1_VALID_ENTRY_VAL ((0x0 << I2C_CTRL_RX_DATA_FIFO_THD_OFST) & I2C_CTRL_RX_DATA_FIFO_THD_MSK) +#define I2C_CTRL_RX_DATA_ONE_FOURTH_VAL ((0x1 << I2C_CTRL_RX_DATA_FIFO_THD_OFST) & I2C_CTRL_RX_DATA_FIFO_THD_MSK) +#define I2C_CTRL_RX_DATA_ONE_HALF_VAL ((0x2 << I2C_CTRL_RX_DATA_FIFO_THD_OFST) & I2C_CTRL_RX_DATA_FIFO_THD_MSK) +#define I2C_CTRL_RX_DATA_FULL_VAL ((0x3 << I2C_CTRL_RX_DATA_FIFO_THD_OFST) & I2C_CTRL_RX_DATA_FIFO_THD_MSK) + +/** Transfer Command Fifo register */ +#define I2C_TFR_CMD_RW_OFST (0) +#define I2C_TFR_CMD_RW_MSK (0x00000001 << I2C_TFR_CMD_RW_OFST) +#define I2C_TFR_CMD_RW_WRITE_VAL ((0x0 << I2C_TFR_CMD_RW_OFST) & I2C_TFR_CMD_RW_MSK) +#define I2C_TFR_CMD_RW_READ_VAL ((0x1 << I2C_TFR_CMD_RW_OFST) & I2C_TFR_CMD_RW_MSK) +#define I2C_TFR_CMD_ADDR_OFST (1) +#define I2C_TFR_CMD_ADDR_MSK (0x0000007F << I2C_TFR_CMD_ADDR_OFST) +/** when writing, rw and addr converts to data to be written mask */ +#define I2C_TFR_CMD_DATA_FR_WR_OFST (0) +#define I2C_TFR_CMD_DATA_FR_WR_MSK (0x000000FF << I2C_TFR_CMD_DATA_FR_WR_OFST) +#define I2C_TFR_CMD_STOP_OFST (8) +#define I2C_TFR_CMD_STOP_MSK (0x00000001 << I2C_TFR_CMD_STOP_OFST) +#define I2C_TFR_CMD_RPTD_STRT_OFST (9) +#define I2C_TFR_CMD_RPTD_STRT_MSK (0x00000001 << I2C_TFR_CMD_RPTD_STRT_OFST) + +/** Receive DataFifo register */ +#define I2C_RX_DATA_FIFO_RXDATA_OFST (0) +#define I2C_RX_DATA_FIFO_RXDATA_MSK (0x000000FF << I2C_RX_DATA_FIFO_RXDATA_OFST) + +/** Status register */ +#define I2C_STATUS_BUSY_OFST (0) +#define I2C_STATUS_BUSY_MSK (0x00000001 << I2C_STATUS_BUSY_OFST) + +/** SCL Low Count register */ +#define I2C_SCL_LOW_COUNT_PERIOD_OFST (0) +#define I2C_SCL_LOW_COUNT_PERIOD_MSK (0x0000FFFF << I2C_SCL_LOW_COUNT_PERIOD_OFST) + +/** SCL High Count register */ +#define I2C_SCL_HIGH_COUNT_PERIOD_OFST (0) +#define I2C_SCL_HIGH_COUNT_PERIOD_MSK (0x0000FFFF << I2C_SCL_HIGH_COUNT_PERIOD_OFST) + +/** SDA Hold Count register */ +#define I2C_SDA_HOLD_COUNT_PERIOD_OFST (0) +#define I2C_SDA_HOLD_COUNT_PERIOD_MSK (0x0000FFFF << I2C_SDA_HOLD_COUNT_PERIOD_OFST) + +/** Receive Data Fifo Level register */ +//#define I2C_RX_DATA_FIFO_LVL_OFST (0) +//#define I2C_RX_DATA_FIFO_LVL_MSK (0x000000FF << I2C_RX_DATA_FIFO_LVL_OFST) + +uint32_t I2C_Control_Reg = 0x0; +uint32_t I2C_Status_Reg = 0x0; +uint32_t I2C_Rx_Data_Fifo_Reg = 0x0; +uint32_t I2C_Rx_Data_Fifo_Level_Reg = 0x0; +uint32_t I2C_Scl_Low_Count_Reg = 0x0; +uint32_t I2C_Scl_High_Count_Reg = 0x0; +uint32_t I2C_Sda_Hold_Reg = 0x0; +uint32_t I2C_Transfer_Command_Fifo_Reg = 0x0; + +/** + * Configure the I2C core, + * Enable core and + * Calibrate the calibration register for current readout + * @param creg control register (defined in RegisterDefs.h) + * @param sreg status register (defined in RegisterDefs.h) + * @param rreg rx data fifo register (defined in RegisterDefs.h) + * @param rlvlreg rx data fifo level register (defined in RegisterDefs.h) + * @param slreg scl low count register (defined in RegisterDefs.h) + * @param shreg scl high count register (defined in RegisterDefs.h) + * @param sdreg sda hold register (defined in RegisterDefs.h) + * @param treg transfer command fifo register (defined in RegisterDefs.h) + */ +void I2C_ConfigureI2CCore(uint32_t creg, uint32_t sreg, + uint32_t rreg, uint32_t rlvlreg, + uint32_t slreg, uint32_t shreg, uint32_t sdreg, uint32_t treg) { + FILE_LOG(logINFO, ("\tConfiguring I2C Core for %d kbps:\n", I2C_DATA_RATE_KBPS)); + FILE_LOG(logDEBUG1,("controlreg,:0x%x, statusreg,:0x%x, " + "rxrdatafiforeg: 0x%x, rxdatafifocountreg,:0x%x, " + "scllow,:0x%x, sclhighreg,:0x%x, sdaholdreg,:0x%x, transfercmdreg,:0x%x\n", + creg, sreg, rreg, rlvlreg, slreg, shreg, sdreg, treg)); + + I2C_Control_Reg = creg; + I2C_Status_Reg = sreg; + I2C_Rx_Data_Fifo_Reg = rreg; + I2C_Rx_Data_Fifo_Level_Reg = rlvlreg; + I2C_Scl_Low_Count_Reg = slreg; + I2C_Scl_High_Count_Reg = shreg; + I2C_Sda_Hold_Reg = sdreg; + I2C_Transfer_Command_Fifo_Reg = treg; + + // calculate scl low and high period count + uint32_t sclPeriodNs = ((1000.00 * 1000.00 * 1000.00) / ((double)I2C_DATA_RATE_KBPS * 1000.00)); + // scl low period same as high period + uint32_t sclLowPeriodNs = sclPeriodNs / 2; + // convert to us, then to clock (defined in blackfin.h) + uint32_t sclLowPeriodCount = (sclLowPeriodNs / 1000.00) * I2C_CLOCK_MHZ; + + // calculate sda hold data count + uint32_t sdaDataHoldTimeNs = (sclLowPeriodNs / 2); // scl low period same as high period + // convert to us, then to clock (defined in blackfin.h) + uint32_t sdaDataHoldCount = ((sdaDataHoldTimeNs / 1000.00) * I2C_CLOCK_MHZ); + + FILE_LOG(logINFO, ("\tSetting SCL Low Period: %d ns (%d clocks)\n", sclLowPeriodNs, sclLowPeriodCount)); + bus_w(I2C_Scl_Low_Count_Reg, bus_r(I2C_Scl_Low_Count_Reg) | + ((sclLowPeriodCount << I2C_SCL_LOW_COUNT_PERIOD_OFST) & I2C_SCL_LOW_COUNT_PERIOD_MSK)); + FILE_LOG(logDEBUG1, ("SCL Low reg:0x%x\n", bus_r(I2C_Scl_Low_Count_Reg))); + + FILE_LOG(logINFO, ("\tSetting SCL High Period: %d ns (%d clocks)\n", sclLowPeriodNs, sclLowPeriodCount)); + bus_w(I2C_Scl_High_Count_Reg, bus_r(I2C_Scl_High_Count_Reg) | + ((sclLowPeriodCount << I2C_SCL_HIGH_COUNT_PERIOD_OFST) & I2C_SCL_HIGH_COUNT_PERIOD_MSK)); + FILE_LOG(logDEBUG1, ("SCL High reg:0x%x\n", bus_r(I2C_Scl_High_Count_Reg))); + + FILE_LOG(logINFO, ("\tSetting SDA Hold Time: %d ns (%d clocks)\n", sdaDataHoldTimeNs, sdaDataHoldCount)); + bus_w(I2C_Sda_Hold_Reg, bus_r(I2C_Sda_Hold_Reg) | + ((sdaDataHoldCount << I2C_SDA_HOLD_COUNT_PERIOD_OFST) & I2C_SDA_HOLD_COUNT_PERIOD_MSK)); + FILE_LOG(logDEBUG1, ("SDA Hold reg:0x%x\n", bus_r(I2C_Sda_Hold_Reg))); + + FILE_LOG(logINFO, ("\tEnabling core and bus speed to fast (up to 400 kbps)\n")); + bus_w(I2C_Control_Reg, bus_r(I2C_Control_Reg) | + I2C_CTRL_ENBLE_CORE_MSK | I2C_CTRL_BUS_SPEED_FAST_400_VAL);// fixme: (works?) + FILE_LOG(logDEBUG1, ("Control reg:0x%x\n", bus_r(I2C_Control_Reg))); + //The INA226 supports the transmission protocol for fast mode (1 kHz to 400 kHz) and high-speed mode (1 kHz to 2.94 MHz). +} + +/** + * Read register + * @param deviceId device Id + * @param addr register address + * @returns value read from register + */ +uint32_t I2C_Read(uint32_t devId, uint32_t addr) { + FILE_LOG(logDEBUG2, (" ================================================\n")); + FILE_LOG(logDEBUG2, (" Reading from I2C device 0x%x and reg 0x%x\n", devId, addr)); + // device Id mask + uint32_t devIdMask = ((devId << I2C_TFR_CMD_ADDR_OFST) & I2C_TFR_CMD_ADDR_MSK); + FILE_LOG(logDEBUG2, (" devId:0x%x\n", devIdMask)); + + // write I2C ID + bus_w(I2C_Transfer_Command_Fifo_Reg, (devIdMask & ~(I2C_TFR_CMD_RW_MSK))); + FILE_LOG(logDEBUG2, (" write devID and R/-W:0x%x\n", (devIdMask & ~(I2C_TFR_CMD_RW_MSK)))); + + // write register addr + bus_w(I2C_Transfer_Command_Fifo_Reg, addr); + FILE_LOG(logDEBUG2, (" write addr:0x%x\n", addr)); + + // repeated start with read (repeated start needed here because it was in write operation mode earlier, for the device ID) + bus_w(I2C_Transfer_Command_Fifo_Reg, (devIdMask | I2C_TFR_CMD_RPTD_STRT_MSK | I2C_TFR_CMD_RW_READ_VAL)); + FILE_LOG(logDEBUG2, (" repeated start:0x%x\n", (devIdMask | I2C_TFR_CMD_RPTD_STRT_MSK | I2C_TFR_CMD_RW_READ_VAL))); + + // continue reading + bus_w(I2C_Transfer_Command_Fifo_Reg, 0x0); + FILE_LOG(logDEBUG2, (" continue reading:0x%x\n", 0x0)); + + // stop reading + bus_w(I2C_Transfer_Command_Fifo_Reg, I2C_TFR_CMD_STOP_MSK); + FILE_LOG(logDEBUG2, (" stop reading:0x%x\n", I2C_TFR_CMD_STOP_MSK)); + + // read value + uint32_t retval = 0; + + //In case one wants to do something more general (INA226 receives only 2 bytes) + // wait till status is idle + int status = 1; + while(status) { + status = bus_r(I2C_Status_Reg) & I2C_STATUS_BUSY_MSK; + FILE_LOG(logDEBUG2, (" status:%d\n", status)); + usleep(0); + } + // get rx fifo level (get number of bytes to be received) + int level = bus_r(I2C_Rx_Data_Fifo_Level_Reg); + FILE_LOG(logDEBUG2, (" level:%d\n", level)); + + int iloop = level - 1; + + // level bytes to read, read 1 byte at a time + for (iloop = level - 1; iloop >= 0; --iloop) { + u_int16_t byte = bus_r(I2C_Rx_Data_Fifo_Reg) & I2C_RX_DATA_FIFO_RXDATA_MSK; + FILE_LOG(logDEBUG2, (" byte nr %d:0x%x\n", iloop, byte)); + // push by 1 byte at a time + retval |= (byte << (8 * iloop)); + } + FILE_LOG(logDEBUG2, (" retval:0x%x\n", retval)); + FILE_LOG(logDEBUG2, (" ================================================\n")); + return retval; +} + +/** + * Write register (16 bit value) + * @param deviceId device Id + * @param addr register address + * @param data data to be written (16 bit) + */ +void I2C_Write(uint32_t devId, uint32_t addr, uint16_t data) { + FILE_LOG(logDEBUG2, (" ================================================\n")); + FILE_LOG(logDEBUG2, (" Writing to I2C (Device:0x%x, reg:0x%x, data:%d)\n", devId, addr, data)); + // device Id mask + uint32_t devIdMask = ((devId << I2C_TFR_CMD_ADDR_OFST) & I2C_TFR_CMD_ADDR_MSK); + FILE_LOG(logDEBUG2, (" devId:0x%x\n", devId)); + + // write I2C ID + bus_w(I2C_Transfer_Command_Fifo_Reg, (devIdMask & ~(I2C_TFR_CMD_RW_MSK))); + FILE_LOG(logDEBUG2, (" write devID and R/-W:0x%x\n", (devIdMask & ~(I2C_TFR_CMD_RW_MSK)))); + + // write register addr + bus_w(I2C_Transfer_Command_Fifo_Reg, addr); + FILE_LOG(logDEBUG2, (" write addr:0x%x\n", addr)); + + // do not do the repeated start as it is already in write operation mode (else it wont work) + + uint8_t msb = (uint8_t)((data & 0xFF00) >> 8); + uint8_t lsb = (uint8_t)(data & 0x00FF); + FILE_LOG(logDEBUG2, (" msb:0x%02x, lsb:0x%02x\n", msb, lsb)); + + // writing data MSB + bus_w(I2C_Transfer_Command_Fifo_Reg, ((msb << I2C_TFR_CMD_DATA_FR_WR_OFST) & I2C_TFR_CMD_DATA_FR_WR_MSK)); + FILE_LOG(logDEBUG2, (" write msb:0x%02x\n", ((msb << I2C_TFR_CMD_DATA_FR_WR_OFST) & I2C_TFR_CMD_DATA_FR_WR_MSK))); + + // writing data LSB and stop writing bit + bus_w(I2C_Transfer_Command_Fifo_Reg, ((lsb << I2C_TFR_CMD_DATA_FR_WR_OFST) & I2C_TFR_CMD_DATA_FR_WR_MSK) | I2C_TFR_CMD_STOP_MSK); + FILE_LOG(logDEBUG2, (" write lsb and stop writing:0x%x\n", ((lsb << I2C_TFR_CMD_DATA_FR_WR_OFST) & I2C_TFR_CMD_DATA_FR_WR_MSK) | I2C_TFR_CMD_STOP_MSK)); + FILE_LOG(logDEBUG2, (" ================================================\n")); +} + + diff --git a/slsDetectorServers/slsDetectorServer/INA226.h b/slsDetectorServers/slsDetectorServer/INA226.h new file mode 100755 index 000000000..b7f2769ee --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/INA226.h @@ -0,0 +1,180 @@ +#pragma once + +#include "I2C.h" +#include "math.h" + +/** + * To be defined in + * + * (slsDetectorServer_defs.h) + * I2C_SHUNT_RESISTER_OHMS + * device ids that are passed as arguments + */ + +/** INA226 defines */ + +/** Register set */ +#define INA226_CONFIGURATION_REG (0x00) //R/W +#define INA226_SHUNT_VOLTAGE_REG (0x01) //R +#define INA226_BUS_VOLTAGE_REG (0x02) //R +#define INA226_POWER_REG (0x03) //R +#define INA226_CURRENT_REG (0x04) //R +#define INA226_CALIBRATION_REG (0x05) //R/W +#define INA226_MASK_ENABLE_REG (0x06) //R/W +#define INA226_ALERT_LIMIT_REG (0x07) //R/W +#define INA226_MANUFACTURER_ID_REG (0xFE) //R +#define INA226_DIE_ID_REG (0xFF) //R + +/** bus voltage register */ +#define INA226_BUS_VOLTAGE_VMIN_UV (1250) // 1.25mV +#define INA226_BUS_VOLTAGE_MX_STPS (0x7FFF + 1) +#define INA226_BUS_VOLTAGE_VMAX_UV (INA226_BUS_VOLTAGE_VMIN_UV * INA226_BUS_VOLTAGE_MX_STPS) // 40960000uV, 40.96V + + +/** shunt voltage register */ +#define INA226_SHUNT_VOLTAGE_VMIN_NV (2500) // 2.5uV +#define INA226_SHUNT_VOLTAGE_MX_STPS (0x7FFF + 1) +#define INA226_SHUNT_VOLTAGE_VMAX_NV (INA226_SHUNT_VOLTAGE_VMIN_NV * INA226_SHUNT_VOLTAGE_MX_STPS) // 81920000nV, 81.92mV +#define INA226_SHUNT_NEGATIVE_MSK (1 << 15) +#define INA226_SHUNT_ABS_VALUE_MSK (0x7FFF) + + + +/** current precision for calibration register */ +#define INA226_CURRENT_IMIN_UA (100) //100uA can be changed + +/** calibration register */ +#define INA226_CALIBRATION_MSK (0x7FFF) + +/** get calibration register value to be set */ +#define INA226_getCalibrationValue(rOhm) (0.00512 /(INA226_CURRENT_IMIN_UA * 1e-6 * rOhm)) + +/** get current unit */ +#define INA226_getConvertedCurrentUnits(shuntV, calibReg) ((double)shuntV * (double)calibReg / (double)2048) + +double INA226_Shunt_Resistor_Ohm = 0.0; +int INA226_Calibration_Register_Value = 0; + +#define INA226_CALIBRATION_CURRENT_TOLERANCE (1.2268) + + +/** + * Configure the I2C core and Enable core + * @param rOhm shunt resister value in Ohms (defined in slsDetectorServer_defs.h) + * @param creg control register (defined in RegisterDefs.h) + * @param sreg status register (defined in RegisterDefs.h) + * @param rreg rx data fifo register (defined in RegisterDefs.h) + * @param rlvlreg rx data fifo level register (defined in RegisterDefs.h) + * @param slreg scl low count register (defined in RegisterDefs.h) + * @param shreg scl high count register (defined in RegisterDefs.h) + * @param sdreg sda hold register (defined in RegisterDefs.h) + * @param treg transfer command fifo register (defined in RegisterDefs.h) + */ +void INA226_ConfigureI2CCore(double rOhm, uint32_t creg, uint32_t sreg, + uint32_t rreg, uint32_t rlvlreg, + uint32_t slreg, uint32_t shreg, uint32_t sdreg, uint32_t treg) { + FILE_LOG(logINFOBLUE, ("Configuring INA226\n")); + FILE_LOG(logDEBUG1, ("Shunt ohm resistor: %f\n", rOhm)); + INA226_Shunt_Resistor_Ohm = rOhm; + + I2C_ConfigureI2CCore(creg, sreg, rreg, rlvlreg, slreg, shreg, sdreg, treg); +} + +/** + * Calibrate resolution of current register + * @param deviceId device Id (defined in slsDetectorServer_defs.h) + */ +void INA226_CalibrateCurrentRegister(uint32_t deviceId) { + FILE_LOG(logINFO, ("Calibrating Current Register for Device ID: 0x%x\n", deviceId)); + // get calibration value based on shunt resistor + uint16_t calVal = ((uint16_t)INA226_getCalibrationValue(INA226_Shunt_Resistor_Ohm)) & INA226_CALIBRATION_MSK; + FILE_LOG(logINFO, ("\tCalculated calibration reg value: 0x%0x (%d)\n", calVal, calVal)); + + calVal = ((double)calVal / INA226_CALIBRATION_CURRENT_TOLERANCE) + 0.5; + FILE_LOG(logINFO, ("\tRealculated (for tolerance) calibration reg value: 0x%0x (%d)\n", calVal, calVal)); + INA226_Calibration_Register_Value = calVal; + + // calibrate current register + I2C_Write(deviceId, INA226_CALIBRATION_REG, calVal); + + // read back calibration register + int retval = I2C_Read(deviceId, INA226_CALIBRATION_REG); + if (retval != calVal) { + FILE_LOG(logERROR, ("Cannot set calibration register for I2C. Set 0x%x, read 0x%x\n", calVal, retval)); + } +} + +/** + * Read voltage of device + * @param deviceId device Id + * @returns voltage in mV + */ +int INA226_ReadVoltage(uint32_t deviceId) { + FILE_LOG(logDEBUG1, (" Reading voltage\n")); + uint32_t regval = I2C_Read(deviceId, INA226_BUS_VOLTAGE_REG); + FILE_LOG(logDEBUG1, (" bus voltage reg: 0x%08x\n", regval)); + + // value in uV + int voltageuV = 0; + ConvertToDifferentRange(0, INA226_BUS_VOLTAGE_MX_STPS, + INA226_BUS_VOLTAGE_VMIN_UV, INA226_BUS_VOLTAGE_VMAX_UV, + regval, &voltageuV); + FILE_LOG(logDEBUG1, (" voltage: 0x%d uV\n", voltageuV)); + + // value in mV + int voltagemV = voltageuV / 1000; + FILE_LOG(logDEBUG1, (" voltage: %d mV\n", voltagemV)); + FILE_LOG(logINFO, ("Voltage via I2C (Device: 0x%x): %d mV\n", deviceId, voltagemV)); + + return voltagemV; +} + +/** + * Read current + * @param deviceId device Id + * @returns current in mA + */ +int INA226_ReadCurrent(uint32_t deviceId) { + FILE_LOG(logDEBUG1, (" Reading current\n")); + + // read shunt voltage register + FILE_LOG(logDEBUG1, (" Reading shunt voltage reg\n")); + uint32_t shuntVoltageRegVal = I2C_Read(deviceId, INA226_SHUNT_VOLTAGE_REG); + FILE_LOG(logDEBUG1, (" shunt voltage reg: %d\n", shuntVoltageRegVal)); + + // read it once more as this error has occured once + if (shuntVoltageRegVal == 0xFFFF) { + FILE_LOG(logDEBUG1, (" Reading shunt voltage reg again\n")); + shuntVoltageRegVal = I2C_Read(deviceId, INA226_SHUNT_VOLTAGE_REG); + FILE_LOG(logDEBUG1, (" shunt voltage reg: %d\n", shuntVoltageRegVal)); + } + // value for current + int retval = INA226_getConvertedCurrentUnits(shuntVoltageRegVal, INA226_Calibration_Register_Value); + FILE_LOG(logDEBUG1, (" current unit value: %d\n", retval)); + + + // reading directly the current reg + FILE_LOG(logDEBUG1, (" Reading current reg\n")); + int cuurentRegVal = I2C_Read(deviceId, INA226_CURRENT_REG); + FILE_LOG(logDEBUG1, (" current reg: %d\n", cuurentRegVal)); + // read it once more as this error has occured once + if (cuurentRegVal >= 0xFFF0) { + FILE_LOG(logDEBUG1, (" Reading current reg again\n")); + cuurentRegVal = I2C_Read(deviceId, INA226_CURRENT_REG); + FILE_LOG(logDEBUG1, (" current reg: %d\n", cuurentRegVal)); + } + + // should be the same + FILE_LOG(logDEBUG1, (" ===============current reg: %d, current unit cal:%d=================================\n", cuurentRegVal, retval)); + // current in uA + int currentuA = cuurentRegVal * INA226_CURRENT_IMIN_UA; + FILE_LOG(logDEBUG1, (" current: %d uA\n", currentuA)); + + // current in mA + int currentmA = (currentuA / 1000.00) + 0.5; + FILE_LOG(logDEBUG1, (" current: %d mA\n", currentmA)); + + FILE_LOG(logINFO, ("Current via I2C (Device: 0x%x): %d mA\n", deviceId, currentmA)); + + return currentmA; +} diff --git a/slsDetectorServers/slsDetectorServer/LTC2620.h b/slsDetectorServers/slsDetectorServer/LTC2620.h new file mode 100755 index 000000000..f2b0bff9b --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/LTC2620.h @@ -0,0 +1,311 @@ +#pragma once + +#include "commonServerFunctions.h" // blackfin.h, ansi.h +#include "common.h" + +#include + +/* LTC2620 DAC DEFINES */ +// first 4 bits are 0 as this is a 12 bit dac +#define LTC2620_DAC_DATA_OFST (4) +#define LTC2620_DAC_DATA_MSK (0x00000FFF << LTC2620_DAC_DATA_OFST) +#define LTC2620_DAC_ADDR_OFST (16) +#define LTC2620_DAC_ADDR_MSK (0x0000000F << LTC2620_DAC_ADDR_OFST) +#define LTC2620_DAC_CMD_OFST (20) +#define LTC2620_DAC_CMD_MSK (0x0000000F << LTC2620_DAC_CMD_OFST) + +#define LTC2620_DAC_CMD_WR_IN_VAL ((0x0 << LTC2620_DAC_CMD_OFST) & LTC2620_DAC_CMD_MSK) // write to input register +#define LTC2620_DAC_CMD_UPDTE_DAC_VAL ((0x1 << LTC2620_DAC_CMD_OFST) & LTC2620_DAC_CMD_MSK) // update dac (power up) +#define LTC2620_DAC_CMD_WR_IN_UPDTE_DAC_VAL ((0x2 << LTC2620_DAC_CMD_OFST) & LTC2620_DAC_CMD_MSK) // write to input register and update dac (power up) +#define LTC2620_DAC_CMD_WR_UPDTE_DAC_VAL ((0x3 << LTC2620_DAC_CMD_OFST) & LTC2620_DAC_CMD_MSK) // write to and update dac (power up) +#define LTC2620_DAC_CMD_PWR_DWN_VAL ((0x4 << LTC2620_DAC_CMD_OFST) & LTC2620_DAC_CMD_MSK) +#define LTC2620_DAC_CMD_NO_OPRTN_VAL ((0xF << LTC2620_DAC_CMD_OFST) & LTC2620_DAC_CMD_MSK) + +#define LTC2620_NUMBITS (24) +#define LTC2620_DAISY_CHAIN_NUMBITS (32) // due to shift register FIXME: was 33 earlier +#define LTC2620_NUMCHANNELS (8) +#define LTC2620_PWR_DOWN_VAL (-100) +#define LTC2620_MIN_VAL (0) +#define LTC2620_MAX_VAL (4095) // 12 bits +#define LTC2620_MAX_STEPS (LTC2620_MAX_VAL + 1) + +uint32_t LTC2620_Reg = 0x0; +uint32_t LTC2620_CsMask = 0x0; +uint32_t LTC2620_ClkMask = 0x0; +uint32_t LTC2620_DigMask = 0x0; +int LTC2620_DigOffset = 0x0; +int LTC2620_Ndac = 0; +int LTC2620_MinVoltage = 0; +int LTC2620_MaxVoltage = 0; + +/** + * Set Defines + * @param reg spi register + * @param cmsk chip select mask + * @param clkmsk clock output mask + * @param dmsk digital output mask + * @param dofst digital output offset + * @param nd total number of dacs for this board (for dac channel and daisy chain chip id) + * @param minMV minimum voltage determined by hardware + * @param maxMV maximum voltage determined by hardware + */ +void LTC2620_SetDefines(uint32_t reg, uint32_t cmsk, uint32_t clkmsk, uint32_t dmsk, int dofst, int nd, int minMV, int maxMV) { + LTC2620_Reg = reg; + LTC2620_CsMask = cmsk; + LTC2620_ClkMask = clkmsk; + LTC2620_DigMask = dmsk; + LTC2620_DigOffset = dofst; + LTC2620_Ndac = nd; + LTC2620_MinVoltage = minMV; + LTC2620_MaxVoltage = maxMV; +} + + +/** + * Disable SPI + */ +void LTC2620_Disable() { + bus_w(LTC2620_Reg, (bus_r(LTC2620_Reg) + | LTC2620_CsMask + | LTC2620_ClkMask) + & ~(LTC2620_DigMask)); +} + + +/** + * Convert voltage to dac units + * @param voltage value in mv + * @param dacval pointer to value converted to dac units + * @returns FAIL when voltage outside limits, OK if conversion successful + */ +int LTC2620_VoltageToDac(int voltage, int* dacval) { + return ConvertToDifferentRange(LTC2620_MinVoltage, LTC2620_MaxVoltage, + LTC2620_MIN_VAL, LTC2620_MAX_VAL, + voltage, dacval); +} + + +/** + * Convert dac units to voltage + * @param dacval dac units + * @param voltage pointer to value converted to mV + * @returns FAIL when voltage outside limits, OK if conversion successful + */ +int LTC2620_DacToVoltage(int dacval, int* voltage) { + return ConvertToDifferentRange( LTC2620_MIN_VAL, LTC2620_MAX_VAL, + LTC2620_MinVoltage, LTC2620_MaxVoltage, + dacval, voltage); +} + + +/** + * Set a single chip (all non ctb detectors use this) + * when max dac is 8 + * @param cmd command + * @param data dac value to be set + * @param dacaddr dac channel number in chip + */ +void LTC2620_SetSingle(int cmd, int data, int dacaddr) { + FILE_LOG(logDEBUG2, ("(Single) dac addr:%d, dac value:%d, cmd:%d\n", dacaddr, data, cmd)); + + uint32_t codata = (((data << LTC2620_DAC_DATA_OFST) & LTC2620_DAC_DATA_MSK) | + ((dacaddr << LTC2620_DAC_ADDR_OFST) & LTC2620_DAC_ADDR_MSK) | + cmd); + FILE_LOG(logDEBUG2, ("codata: 0x%x\n", codata)); + + serializeToSPI (LTC2620_Reg, codata, LTC2620_CsMask, LTC2620_NUMBITS, + LTC2620_ClkMask, LTC2620_DigMask, LTC2620_DigOffset, 0); +} + + +/** + * bit bang the data into all the chips daisy fashion + * @param valw current value of register while bit banging + * @param val data to be sent (data, dac addr and command) + */ +void LTC2620_SendDaisyData(uint32_t* valw, uint32_t val) { + sendDataToSPI(valw, LTC2620_Reg, val, LTC2620_DAISY_CHAIN_NUMBITS, + LTC2620_ClkMask, LTC2620_DigMask, LTC2620_DigOffset); +} + + +/** + * Set a single chip (all non ctb detectors use this) + * when max dac is 8 + * @param cmd command + * @param data dac value to be set + * @param dacaddr dac channel number in chip + * @param chipIndex index of the chip + */ +void LTC2620_SetDaisy(int cmd, int data, int dacaddr, int chipIndex) { + + int nchip = LTC2620_Ndac / LTC2620_NUMCHANNELS; + uint32_t valw = 0; + int ichip = 0; + + FILE_LOG(logDEBUG2, ("(Daisy) desired chip index:%d, nchip:%d, dac ch:%d, val:%d, cmd:0x%x \n", + chipIndex, nchip, dacaddr, data, cmd)); + + // data to be bit banged + uint32_t codata = (((data << LTC2620_DAC_DATA_OFST) & LTC2620_DAC_DATA_MSK) | + ((dacaddr << LTC2620_DAC_ADDR_OFST) & LTC2620_DAC_ADDR_MSK) | + cmd); + FILE_LOG(logDEBUG2, ("codata: 0x%x\n", codata)); + + // select all chips (ctb daisy chain; others 1 chip) + FILE_LOG(logDEBUG2, ("Selecting LTC2620\n")); + SPIChipSelect (&valw, LTC2620_Reg, LTC2620_CsMask, LTC2620_ClkMask, LTC2620_DigMask, 0); + + // send same data to all + if (chipIndex < 0) { + FILE_LOG(logDEBUG2, ("Send same data to all\n")); + for (ichip = 0; ichip < nchip; ++ichip) { + FILE_LOG(logDEBUG2, ("Send data (0x%x) to ichip %d\n", codata, ichip)); + LTC2620_SendDaisyData(&valw, codata); + } + } + + // send to one chip, nothing to others + else { + // send nothing to subsequent ichips (daisy chain) (if any chips after desired chip) + for (ichip = chipIndex + 1; ichip < nchip; ++ichip) { + FILE_LOG(logDEBUG2, ("Send nothing to ichip %d\n", ichip)); + LTC2620_SendDaisyData(&valw, LTC2620_DAC_CMD_NO_OPRTN_VAL); + } + + // send data to desired chip + FILE_LOG(logDEBUG2, ("Send data (0x%x) to ichip %d\n", codata, chipIndex)); + LTC2620_SendDaisyData(&valw, codata); + + // send nothing to preceding ichips (daisy chain) (if any chips in front of desired chip) + for (ichip = 0; ichip < chipIndex; ++ichip) { + FILE_LOG(logDEBUG2, ("Send nothing to ichip %d\n", ichip)); + LTC2620_SendDaisyData(&valw, LTC2620_DAC_CMD_NO_OPRTN_VAL); + } + } + + // deselect all chips (ctb daisy chain; others 1 chip) + FILE_LOG(logDEBUG2, ("Deselecting LTC2620\n")); + SPIChipDeselect(&valw, LTC2620_Reg, LTC2620_CsMask, LTC2620_ClkMask, LTC2620_DigMask, 0); +} + + +/** + * Sets a single chip (LTC2620_SetSingle) or multiple chip (LTC2620_SetDaisy) + * multiple chip is only for ctb where the multiple chips are connected in daisy fashion + * @param cmd command to send + * @param data dac value to be set + * @param dacaddr dac channel number for the chip + * @param chipIndex the chip to be set + */ +void LTC2620_Set(int cmd, int data, int dacaddr, int chipIndex) { + FILE_LOG(logDEBUG1, ("cmd:0x%x, data:%d, dacaddr:%d, chipIndex:%d\n", cmd, data, dacaddr, chipIndex)); + FILE_LOG(logDEBUG2, (" ================================================\n")); + // ctb + if (LTC2620_Ndac > LTC2620_NUMCHANNELS) + LTC2620_SetDaisy(cmd, data, dacaddr, chipIndex); + // others + else + LTC2620_SetSingle(cmd, data, dacaddr); + FILE_LOG(logDEBUG2, (" ================================================\n")); +} + + +/** + * Configure (obtains dacaddr, command and ichip and calls LTC2620_Set) + */ +void LTC2620_Configure(){ + FILE_LOG(logINFOBLUE, ("Configuring LTC2620\n")); + + // dac channel - all channels + int addr = (LTC2620_DAC_ADDR_MSK >> LTC2620_DAC_ADDR_OFST); + + // data (any random low value, just writing to power up) + int data = 0x6; + + // command + int cmd = LTC2620_DAC_CMD_WR_IN_VAL; //FIXME: should be command update and not write(does not power up) + // also why do we need to power up (for jctb, we power down next) + + LTC2620_Set(cmd, data, addr, -1); +} + + +/** + * Set Dac (obtains dacaddr, command and ichip and calls LTC2620_Set) + * @param dacnum dac number + * @param data dac value to set + */ +void LTC2620_SetDAC (int dacnum, int data) { + FILE_LOG(logDEBUG1, ("Setting dac %d to %d\n", dacnum, data)); + // LTC2620 index + int ichip = dacnum / LTC2620_NUMCHANNELS; + + // dac channel + int addr = dacnum % LTC2620_NUMCHANNELS; + + // command + int cmd = LTC2620_DAC_CMD_WR_UPDTE_DAC_VAL; + + // power down mode, value is ignored + if (data == LTC2620_PWR_DOWN_VAL) { + cmd = LTC2620_DAC_CMD_PWR_DWN_VAL; + FILE_LOG(logDEBUG1, ("POWER DOWN\n")); + } else { + FILE_LOG(logDEBUG1,("Write to Input Register and Update\n")); + } + + LTC2620_Set(cmd, data, addr, ichip); +} + +/** + * Set dac in dac units or mV + * @param dacnum dac index + * @param val value in dac units or mV + * @param mV 0 for dac units and 1 for mV unit + * @param dacval pointer to value in dac units + * @returns OK or FAIL for success of operation + */ +int LTC2620_SetDACValue (int dacnum, int val, int mV, int* dacval) { + FILE_LOG(logDEBUG1, ("dacnum:%d, val:%d, ismV:%d\n", dacnum, val, mV)); + // validate index + if (dacnum < 0 || dacnum >= LTC2620_Ndac) { + FILE_LOG(logERROR, ("Dac index %d is out of bounds (0 to %d)\n", dacnum, LTC2620_Ndac - 1)); + return FAIL; + } + + // get + if (val < 0 && val != LTC2620_PWR_DOWN_VAL) + return FAIL; + + // convert to dac or get mV value + *dacval = val; + int dacmV = val; + int ret = OK; + int ndacsonly = LTC2620_Ndac; +#ifdef CHIPTESTBOARDD + ndacsonly = NDAC_ONLY; +#endif + if (mV) { + ret = LTC2620_VoltageToDac(val, dacval); + } else if (val >= 0 && dacnum <= ndacsonly) { + // do not convert power down dac val + //(if not ndacsonly (pwr/vchip): dont need to print mV value as it will be wrong (wrong limits)) + ret = LTC2620_DacToVoltage(val, &dacmV); + } + + // conversion out of bounds + if (ret == FAIL) { + FILE_LOG(logERROR, ("Setting Dac %d %s is out of bounds\n", dacnum, (mV ? "mV" : "dac units"))); + return FAIL; + } + + // set + if ( (*dacval >= 0) || (*dacval == LTC2620_PWR_DOWN_VAL)) { +#ifndef CHIPTESTBOARDD + FILE_LOG(logINFO, ("Setting DAC %d: %d dac (%d mV)\n",dacnum, *dacval, dacmV)); +#endif + LTC2620_SetDAC(dacnum, *dacval); + } + return OK; +} diff --git a/slsDetectorServers/slsDetectorServer/MAX1932.h b/slsDetectorServers/slsDetectorServer/MAX1932.h new file mode 100755 index 000000000..99aabed01 --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/MAX1932.h @@ -0,0 +1,97 @@ +#pragma once + +#include "commonServerFunctions.h" // blackfin.h, ansi.h + +/* MAX1932 HV DEFINES */ + +#define MAX1932_HV_NUMBITS (8) +#define MAX1932_HV_DATA_OFST (0) +#define MAX1932_HV_DATA_MSK (0x000000FF << MAX1932_HV_DATA_OFST) +// higher voltage requires lower dac value, 0 is off +#define MAX1932_MIN_DAC_VAL (0xFF) +#define MAX1932_MAX_DAC_VAL (0x1) +#define MAX1932_POWER_OFF_DAC_VAL (0x0) + +uint32_t MAX1932_Reg = 0x0; +uint32_t MAX1932_CsMask = 0x0; +uint32_t MAX1932_ClkMask = 0x0; +uint32_t MAX1932_DigMask = 0x0; +int MAX1932_DigOffset = 0x0; +int MAX1932_MinVoltage = 0; +int MAX1932_MaxVoltage = 0; + + +/** + * Set Defines + * @param reg spi register + * @param cmsk chip select mask + * @param clkmsk clock output mask + * @param dmsk digital output mask + * @param dofst digital output offset + * @param minMV minimum voltage determined by hardware + * @param maxMV maximum voltage determined by hardware + */ +void MAX1932_SetDefines(uint32_t reg, uint32_t cmsk, uint32_t clkmsk, uint32_t dmsk, int dofst, + int minMV, int maxMV) { + FILE_LOG(logINFOBLUE, ("Configuring High Voltage\n")); + MAX1932_Reg = reg; + MAX1932_CsMask = cmsk; + MAX1932_ClkMask = clkmsk; + MAX1932_DigMask = dmsk; + MAX1932_DigOffset = dofst; + MAX1932_MinVoltage = minMV; + MAX1932_MaxVoltage = maxMV; +} + + +/** + * Disable SPI + */ +void MAX1932_Disable() { + bus_w(MAX1932_Reg, (bus_r(MAX1932_Reg) + | MAX1932_CsMask + | MAX1932_ClkMask) + & ~(MAX1932_DigMask)); +} + + +/** + * Set value + * @param val value to set + * @return OK or FAIL + */ +int MAX1932_Set (int val) { + FILE_LOG(logDEBUG1, ("Setting high voltage to %d\n", val)); + if (val < 0) + return FAIL; + + int dacvalue = 0; + + // limit values (normally < 60 => 0 (off)) + if (val < MAX1932_MinVoltage) { + dacvalue = MAX1932_POWER_OFF_DAC_VAL; + val = 0; + } + // limit values (normally > 200 => 0x1 (max)) + else if (val > MAX1932_MaxVoltage) { + dacvalue = MAX1932_MAX_DAC_VAL; + val = MAX1932_MaxVoltage; + } + // convert value + else { + // no failure in conversion as limits handled (range from 0x1 to 0xFF) + ConvertToDifferentRange(MAX1932_MinVoltage, MAX1932_MaxVoltage, + MAX1932_MIN_DAC_VAL, MAX1932_MAX_DAC_VAL, + val, &dacvalue); + dacvalue &= MAX1932_HV_DATA_MSK; + } + + FILE_LOG(logINFO, ("\t%dV (dacval %d)\n", val, dacvalue)); + serializeToSPI(MAX1932_Reg, dacvalue, MAX1932_CsMask, MAX1932_HV_NUMBITS, + MAX1932_ClkMask, MAX1932_DigMask, MAX1932_DigOffset, 0); + return OK; +} + + + + diff --git a/slsDetectorServers/slsDetectorServer/UDPPacketHeaderGenerator.h b/slsDetectorServers/slsDetectorServer/UDPPacketHeaderGenerator.h new file mode 100755 index 000000000..9b6b0123f --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/UDPPacketHeaderGenerator.h @@ -0,0 +1,105 @@ +#pragma once + +#include "logger.h" +#include "sls_detector_defs.h" + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern const enum detectorType myDetectorType; +extern int nSamples; +extern int dataBytes; +extern int nframes; +extern char* ramValues; + +#define UDP_PACKET_HEADER_VERSION (0x1) + + +uint32_t udpPacketNumber = 0; +uint64_t udpFrameNumber = 0; + +int numSamplesPerPacket = 0; +int dataBytesPerSample = 0; +int dataBytesPerPacket = 0; +int udpHeaderOffset = 0; + +uint32_t getUDPPacketNumber() { + return udpPacketNumber; +} + +uint64_t getUDPFrameNumber() { + return udpFrameNumber; +} + + +/** + * Called for each UDP packet header creation + * + */ +void createUDPPacketHeader(char* buffer, uint16_t id) { + memset(buffer, 0, sizeof(sls_detector_header)); + sls_detector_header* header = (sls_detector_header*)(buffer); + + header->modId = id; + // row and column remains 0 (only used by ctb now) + // uint64_t timestamp FIXME: needed? + header->detType = (uint16_t)myDetectorType; + header->version = UDP_PACKET_HEADER_VERSION; + + // reset offset + udpHeaderOffset = 0; + // reset frame number + udpFrameNumber = 0; +} + + +int fillUDPPacket(char* buffer) { + FILE_LOG(logDEBUG2, ("Databytes:%d offset:%d\n", dataBytes, udpHeaderOffset)); + // reached end of data for one frame + if (udpHeaderOffset >= dataBytes) { + // reset offset + udpHeaderOffset = 0; + return 0; + } + + sls_detector_header* header = (sls_detector_header*)(buffer); + + // update frame number, starts at 1 (reset packet number) + if (udpHeaderOffset == 0) { + ++udpFrameNumber; + header->frameNumber = udpFrameNumber; + udpPacketNumber = -1; + } + + // increment and copy udp packet number (starts at 0) + ++udpPacketNumber; + header->packetNumber = udpPacketNumber; + FILE_LOG(logDEBUG2, ("Creating packet number %d (fnum:%lld)\n", udpPacketNumber, (long long int) udpFrameNumber)); + + // calculate number of bytes to copy + int numBytesToCopy = ((udpHeaderOffset + UDP_PACKET_DATA_BYTES) <= dataBytes) ? + UDP_PACKET_DATA_BYTES : (dataBytes - udpHeaderOffset); + + // copy data + memcpy(buffer + sizeof(sls_detector_header), ramValues + udpHeaderOffset, numBytesToCopy); + // pad last packet if extra space + if (numBytesToCopy < UDP_PACKET_DATA_BYTES) { + int bytes = UDP_PACKET_DATA_BYTES - numBytesToCopy; + FILE_LOG(logDEBUG1, ("Padding %d bytes for fnum:%lld pnum:%d\n", bytes, (long long int)udpFrameNumber, udpPacketNumber)); + memset(buffer + sizeof(sls_detector_header) + numBytesToCopy, 0, bytes); + } + + // increment offset + udpHeaderOffset += numBytesToCopy; + + return UDP_PACKET_DATA_BYTES + sizeof(sls_detector_header); +} diff --git a/slsDetectorSoftware/slsDetectorServer/blackfin.h b/slsDetectorServers/slsDetectorServer/blackfin.h similarity index 68% rename from slsDetectorSoftware/slsDetectorServer/blackfin.h rename to slsDetectorServers/slsDetectorServer/blackfin.h index f95cd4ffe..604797148 100755 --- a/slsDetectorSoftware/slsDetectorServer/blackfin.h +++ b/slsDetectorServers/slsDetectorServer/blackfin.h @@ -1,9 +1,7 @@ -#ifndef BLACKFIN_H -#define BLACKFIN_H +#pragma once #include "ansi.h" -#include #include // open #include // mmap @@ -12,9 +10,10 @@ u_int64_t CSP0BASE = 0; #define CSP0 0x20200000 #define MEM_SIZE 0x100000 -#define MEM_MAP_SHIFT 1 +/** I2C defines */ +#define I2C_CLOCK_MHZ (131.25) /** * Write into a 16 bit register @@ -73,7 +72,7 @@ int64_t get64BitReg(int aLSB, int aMSB){ vMSB=bus_r(aMSB); v64=vMSB; v64=(v64<<32) | vLSB; - printf(" reg64(%x,%x) %x %x %llx\n", aLSB, aMSB, vLSB, vMSB, (long long unsigned int)v64); + FILE_LOG(logDEBUG5, (" reg64(%x,%x) %x %x %llx\n", aLSB, aMSB, vLSB, vMSB, (long long unsigned int)v64)); return v64; } @@ -117,6 +116,25 @@ u_int32_t writeRegister(u_int32_t offset, u_int32_t data) { return readRegister(offset); } +/** + * Read from a 16 bit register (literal register value provided by client) + * @param offset address offset + * @retuns 16 bit data read + */ +u_int32_t readRegister16(u_int32_t offset) { + return (u_int32_t)bus_r16(offset << MEM_MAP_SHIFT); +} + +/** + * Write into a 16 bit register (literal register value provided by client) + * @param offset address offset + * @param data 16 bit data + */ +u_int32_t writeRegister16(u_int32_t offset, u_int32_t data) { + bus_w16(offset << MEM_MAP_SHIFT, (u_int16_t)data); + return readRegister16(offset); +} + /** * Map FPGA @@ -124,39 +142,33 @@ u_int32_t writeRegister(u_int32_t offset, u_int32_t data) { int mapCSP0(void) { // if not mapped if (CSP0BASE == 0) { - printf("Mapping memory\n"); + FILE_LOG(logINFO, ("Mapping memory\n")); #ifdef VIRTUAL CSP0BASE = malloc(MEM_SIZE); if (CSP0BASE == NULL) { - cprintf(BG_RED, "Error: Could not allocate virtual memory.\n"); + FILE_LOG(logERROR, ("Could not allocate virtual memory.\n")); return FAIL; } - printf("memory allocated\n"); + FILE_LOG(logINFO, ("memory allocated\n")); #else int fd; fd = open("/dev/mem", O_RDWR | O_SYNC, 0); if (fd == -1) { - cprintf(BG_RED, "Error: Can't find /dev/mem\n"); + FILE_LOG(logERROR, ("Can't find /dev/mem\n")); return FAIL; } -#ifdef VERBOSE - printf("/dev/mem opened\n"); -#endif + FILE_LOG(logDEBUG1, ("/dev/mem opened\n")); CSP0BASE = mmap(0, MEM_SIZE, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, CSP0); if (CSP0BASE == MAP_FAILED) { - cprintf(BG_RED, "Error: Can't map memmory area\n"); + FILE_LOG(logERROR, ("Can't map memmory area\n")); return FAIL; } #endif - printf("CSPOBASE mapped from 0x%llx to 0x%llx\n", + FILE_LOG(logINFO, ("CSPOBASE mapped from 0x%llx to 0x%llx\n", (long long unsigned int)CSP0BASE, - (long long unsigned int)(CSP0BASE+MEM_SIZE)); - printf("Status Register: %08x\n",bus_r(STATUS_REG)); - + (long long unsigned int)(CSP0BASE+MEM_SIZE))); + FILE_LOG(logINFO, ("Status Register: %08x\n", bus_r(STATUS_REG))); }else - printf("Memory already mapped before\n"); + FILE_LOG(logINFO, ("Memory already mapped before\n")); return OK; } - - -#endif //BLACKFIN_H diff --git a/slsDetectorServers/slsDetectorServer/common.h b/slsDetectorServers/slsDetectorServer/common.h new file mode 100755 index 000000000..a367b18ff --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/common.h @@ -0,0 +1,44 @@ +#pragma once + +/** + * Convert a value from a range to a different range (eg voltage to dac or vice versa) + * @param inputMin input minimum + * @param inputMax input maximum + * @param outputMin output minimum + * @param outputMax output maximum + * @param inputValue input value + * @param outputValue pointer to output value + * @returns FAIL if input value is out of bounds, else OK + */ +int ConvertToDifferentRange(int inputMin, int inputMax, int outputMin, int outputMax, + int inputValue, int* outputValue) { + FILE_LOG(logDEBUG1, (" Input Value: %d (Input:(%d - %d), Output:(%d - %d))\n", + inputValue, inputMin, inputMax, outputMin, outputMax)); + + // validate within bounds + // eg. MAX1932 range is v(60 - 200) to dac(255 - 1), here inputMin > inputMax (when dac to voltage) + int smaller = inputMin; + int bigger = inputMax; + if (smaller > bigger) { + smaller = inputMax; + bigger = inputMin; + } + if ((inputValue < smaller) || (inputValue > bigger)) { + FILE_LOG(logERROR, ("Input Value is outside bounds (%d to %d): %d\n", inputValue, smaller, bigger)); + *outputValue = -1; + return FAIL; + } + + double value = ((double)(inputValue - inputMin) * (double)(outputMax - outputMin)) + / (double)(inputMax - inputMin) + outputMin; + + // double to integer conversion (if decimal places, round to integer) + if ((value - (int)value) > 0.0001) { + value += 0.5; + } + *outputValue = value; + + FILE_LOG(logDEBUG1, (" Converted Output Value: %d\n", *outputValue)); + return OK; +} + diff --git a/slsDetectorServers/slsDetectorServer/commonServerFunctions.h b/slsDetectorServers/slsDetectorServer/commonServerFunctions.h new file mode 100755 index 000000000..1f44df843 --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/commonServerFunctions.h @@ -0,0 +1,145 @@ +#pragma once + +#include "blackfin.h" +#include // usleep + +void SPIChipSelect (uint32_t* valw, uint32_t addr, uint32_t csmask, uint32_t clkmask, uint32_t digoutmask, int convBit) { + FILE_LOG(logDEBUG2, ("SPI chip select. valw:0x%08x addr:0x%x csmask:0x%x, clkmask:0x%x digmask:0x%x convbit:%d\n", + *valw, addr, csmask, clkmask, digoutmask, convBit)); + + // needed for the slow adcs for apprx 20 ns before and after rising of convbit (usleep val is vague assumption) + if (convBit) + usleep(20); + + // start point + (*valw) = ((bus_r(addr) | csmask | clkmask) &(~digoutmask)); + bus_w (addr, (*valw)); + FILE_LOG(logDEBUG2, ("startpoint. valw:0x%08x\n", *valw)); + + // needed for the slow adcs for apprx 10 ns before and after rising of convbit (usleep val is vague assumption) + if (convBit) + usleep(10); + + // chip sel bar down + (*valw) &= ~csmask; + bus_w (addr, (*valw)); + FILE_LOG(logDEBUG2, ("chip sel bar down. valw:0x%08x\n", *valw)); +} + + +void SPIChipDeselect (uint32_t* valw, uint32_t addr, uint32_t csmask, uint32_t clkmask, uint32_t digoutmask, int convBit) { + FILE_LOG(logDEBUG2, ("SPI chip deselect. valw:0x%08x addr:0x%x csmask:0x%x, clkmask:0x%x digmask:0x%x convbit:%d\n", + *valw, addr, csmask, clkmask, digoutmask, convBit)); + + // needed for the slow adcs for apprx 20 ns before and after rising of convbit (usleep val is vague assumption) + if (convBit) + usleep(20); + + // chip sel bar up + (*valw) |= csmask; + bus_w (addr, (*valw)); + FILE_LOG(logDEBUG2, ("chip sel bar up. valw:0x%08x\n", *valw)); + + // needed for the slow adcs for apprx 10 ns before and after rising of convbit (usleep val is vague assumption) + if (convBit) + usleep(10); + + //clk down + (*valw) &= ~clkmask; + bus_w (addr, (*valw)); + FILE_LOG(logDEBUG2, ("clk down. valw:0x%08x\n", *valw)); + + // stop point = start point of course + (*valw) &= ~digoutmask; + // slow adcs use convBit (has to go high and then low) instead of csmask + if (convBit) { + (*valw) &= ~csmask; + } else { + (*valw) |= csmask; + } + bus_w (addr, (*valw)); //FIXME: for ctb slow adcs, might need to set it to low again + FILE_LOG(logDEBUG2, ("stop point. valw:0x%08x\n", *valw)); +} + +void sendDataToSPI (uint32_t* valw, uint32_t addr, uint32_t val, int numbitstosend, uint32_t clkmask, uint32_t digoutmask, int digofset) { + FILE_LOG(logDEBUG2, ("SPI send data. valw:0x%08x addr:0x%x val:0x%x, numbitstosend:%d, clkmask:0x%x digmask:0x%x digofst:%d\n", + *valw, addr, val, numbitstosend, clkmask, digoutmask, digofset)); + + int i = 0; + for (i = 0; i < numbitstosend; ++i) { + + // clk down + (*valw) &= ~clkmask; + bus_w (addr, (*valw)); + FILE_LOG(logDEBUG2, ("clk down. valw:0x%08x\n", *valw)); + + // write data (i) + (*valw) = (((*valw) & ~digoutmask) + // unset bit + (((val >> (numbitstosend - 1 - i)) & 0x1) << digofset)); // each bit from val starting from msb + bus_w (addr, (*valw)); + FILE_LOG(logDEBUG2, ("write data %d. valw:0x%08x\n", i, *valw)); + + // clk up + (*valw) |= clkmask ; + bus_w (addr, (*valw)); + FILE_LOG(logDEBUG2, ("clk up. valw:0x%08x\n", *valw)); + } +} + +uint32_t receiveDataFromSPI (uint32_t* valw, uint32_t addr, int numbitstoreceive, uint32_t clkmask, uint32_t readaddr) { + FILE_LOG(logDEBUG2, ("SPI send data. valw:0x%08x addr:0x%x numbitstoreceive:%d, clkmask:0x%x readaddr:0x%x \n", + *valw, addr, numbitstoreceive, clkmask, readaddr)); + + uint32_t retval = 0; + int i = 0; + for (i = 0; i < numbitstoreceive; ++i) { + + // clk down + (*valw) &= ~clkmask; + bus_w (addr, (*valw)); + FILE_LOG(logDEBUG2, ("clk down. valw:0x%08x\n", *valw)); + + // read data (i) + retval |= ((bus_r(readaddr) & 0x1) << (numbitstoreceive - 1 - i)); + FILE_LOG(logDEBUG2, ("read data %d. retval:0x%08x\n", i, retval)); + + // clk up + (*valw) |= clkmask ; + bus_w (addr, (*valw)); + FILE_LOG(logDEBUG2, ("clk up. valw:0x%08x\n", *valw)); + } + return retval; +} + +void serializeToSPI(uint32_t addr, uint32_t val, uint32_t csmask, int numbitstosend, uint32_t clkmask, uint32_t digoutmask, int digofset, int convBit) { + if (numbitstosend == 16) { + FILE_LOG(logDEBUG2, ("Writing to SPI Register: 0x%04x\n", val)); + } else { + FILE_LOG(logDEBUG2, ("Writing to SPI Register: 0x%08x\n", val)); + } + uint32_t valw; + + SPIChipSelect (&valw, addr, csmask, clkmask, digoutmask, convBit); + + sendDataToSPI(&valw, addr, val, numbitstosend, clkmask, digoutmask, digofset); + + SPIChipDeselect(&valw, addr, csmask, clkmask, digoutmask, convBit); +} + +uint32_t serializeFromSPI(uint32_t addr, uint32_t csmask, int numbitstoreceive, uint32_t clkmask, uint32_t digoutmask, uint32_t readaddr, int convBit) { + + uint32_t valw; + + SPIChipSelect (&valw, addr, csmask, clkmask, digoutmask, convBit); + + uint32_t retval = receiveDataFromSPI(&valw, addr, numbitstoreceive, clkmask, readaddr); + + SPIChipDeselect(&valw, addr, csmask, clkmask, digoutmask, convBit); // moving this before bringin up earlier changes temp of slow adc + + if (numbitstoreceive == 16) { + FILE_LOG(logDEBUG2, ("Read From SPI Register: 0x%04x\n", retval)); + } else { + FILE_LOG(logDEBUG2, ("Read From SPI Register: 0x%08x\n", retval)); + } + return retval; +} diff --git a/slsDetectorServers/slsDetectorServer/communication_funcs.c b/slsDetectorServers/slsDetectorServer/communication_funcs.c new file mode 100755 index 000000000..9dbfbacee --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/communication_funcs.c @@ -0,0 +1,522 @@ +#include "communication_funcs.h" +#include "logger.h" + +#include +#include +#include +#include + +#define SEND_REC_MAX_SIZE 4096 +#define DEFAULT_PORTNO 1952 +#define DEFAULT_BACKLOG 5 + +// blackfin limits +#define CPU_DRVR_SND_LMT (30000) // rough limit +#define CPU_RSND_PCKT_LOOP (10) +#define CPU_RSND_WAIT_US (1) + + +// Global variables from errno.h +extern int errno; + +// Variables that will be exported +int lockStatus = 0; +char lastClientIP[INET_ADDRSTRLEN] = ""; +char thisClientIP[INET_ADDRSTRLEN] = ""; +int differentClients = 0; +int isControlServer = 1; +int ret = FAIL; +int fnum = 0; +char mess[MAX_STR_LENGTH]; + +// Local variables +char dummyClientIP[INET_ADDRSTRLEN] = ""; +int myport = -1; +// socket descriptor set +fd_set readset, tempset; +// number of socket descrptor listening to +int isock = 0; +// value of socket descriptor, +//becomes max value of socket descriptor (listen) and file descriptor (accept) +int maxfd = 0; + + +int bindSocket(unsigned short int port_number) { + ret = FAIL; + int socketDescriptor = -1; + int i = 0; + struct sockaddr_in addressS; + + // same port + if (myport == port_number) { + sprintf(mess, "Cannot create %s socket with port %d. Already in use before.\n", + (isControlServer ? "control":"stop"), port_number); + FILE_LOG(logERROR, (mess)); + } + // port ok + else { + + // create socket + socketDescriptor = socket(AF_INET, SOCK_STREAM,0); + // socket error + if (socketDescriptor < 0) { + sprintf(mess, "Cannot create %s socket with port %d\n", + (isControlServer ? "control":"stop"), port_number); + FILE_LOG(logERROR, (mess)); + } + // socket success + else { + i = 1; + // set port reusable + setsockopt(socketDescriptor, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i)); + // Set some fields in the serverAddress structure + addressS.sin_family = AF_INET; + addressS.sin_addr.s_addr = htonl(INADDR_ANY); + addressS.sin_port = htons(port_number); + + // bind socket error + if(bind(socketDescriptor,(struct sockaddr *) &addressS,sizeof(addressS)) < 0){ + sprintf(mess, "Cannot bind %s socket to port %d.\n", + (isControlServer ? "control":"stop"), port_number); + FILE_LOG(logERROR, (mess)); + } + // bind socket ok + else { + + // listen to socket + if (listen(socketDescriptor, DEFAULT_BACKLOG) == 0) { + // clear set of descriptors. set of descriptors needed? + if (isock == 0) { + FD_ZERO(&readset); + } + // add a socket descriptor from listen + FD_SET(socketDescriptor, &readset); + isock++; + maxfd = socketDescriptor; + // success + myport = port_number; + ret = OK; + FILE_LOG(logDEBUG1, ("%s socket bound: isock=%d, port=%d, fd=%d\n", + (isControlServer ? "Control":"Stop"), isock, port_number, socketDescriptor)); + + } + // listen socket error + else { + sprintf(mess, "Cannot bind %s socket to port %d.\n", + (isControlServer ? "control":"stop"), port_number); + FILE_LOG(logERROR, (mess)); + } + } + } + } + + return socketDescriptor; +} + + + +int acceptConnection(int socketDescriptor) { + int j; + struct sockaddr_in addressC; + int file_des = -1; + struct timeval tv; + socklen_t address_length = sizeof(struct sockaddr_in); + + if (socketDescriptor < 0) + return -1; + + // copy file descriptor set temporarily + memcpy(&tempset, &readset, sizeof(tempset)); + + // set time out as 2777.77 hours? + tv.tv_sec = 10000000; + tv.tv_usec = 0; + + // monitor file descrptors + int result = select(maxfd + 1, &tempset, NULL, NULL, &tv); + + // timeout + if (result == 0) { + FILE_LOG(logDEBUG3, ("%s socket select() timed out!\n", + (isControlServer ? "control":"stop"), myport)); + } + + // error (not signal caught) + else if (result < 0 && errno != EINTR) { + FILE_LOG(logERROR, ("%s socket select() error: %s\n", + (isControlServer ? "control":"stop"), myport, strerror(errno))); + } + + // activity in descriptor set + else if (result > 0) { + FILE_LOG(logDEBUG3, ("%s select returned!\n", (isControlServer ? "control":"stop"))); + + // loop through the file descriptor set + for (j = 0; j < maxfd + 1; ++j) { + + // checks if file descriptor part of set + if (FD_ISSET(j, &tempset)) { + FILE_LOG(logDEBUG3, ("fd %d is set\n",j)); + + // clear the temporary set + FD_CLR(j, &tempset); + + // accept connection (if error) + if ((file_des = accept(j,(struct sockaddr *) &addressC, &address_length)) < 0) { + FILE_LOG(logERROR, ("%s socket accept() error. Connection refused.\n", + "Error Number: %d, Message: %s\n", + (isControlServer ? "control":"stop"), + myport, errno, strerror(errno))); + switch(errno) { + case EWOULDBLOCK: + FILE_LOG(logERROR, ("ewouldblock eagain")); + break; + case EBADF: + FILE_LOG(logERROR, ("ebadf\n")); + break; + case ECONNABORTED: + FILE_LOG(logERROR, ("econnaborted\n")); + break; + case EFAULT: + FILE_LOG(logERROR, ("efault\n")); + break; + case EINTR: + FILE_LOG(logERROR, ("eintr\n")); + break; + case EINVAL: + FILE_LOG(logERROR, ("einval\n")); + break; + case EMFILE: + FILE_LOG(logERROR, ("emfile\n")); + break; + case ENFILE: + FILE_LOG(logERROR, ("enfile\n")); + break; + case ENOTSOCK: + FILE_LOG(logERROR, ("enotsock\n")); + break; + case EOPNOTSUPP: + FILE_LOG(logERROR, ("eOPNOTSUPP\n")); + break; + case ENOBUFS: + FILE_LOG(logERROR, ("ENOBUFS\n")); + break; + case ENOMEM: + FILE_LOG(logERROR, ("ENOMEM\n")); + break; + case ENOSR: + FILE_LOG(logERROR, ("ENOSR\n")); + break; + case EPROTO: + FILE_LOG(logERROR, ("EPROTO\n")); + break; + default: + FILE_LOG(logERROR, ("unknown error\n")); + } + } + // accept success + else { + inet_ntop(AF_INET, &(addressC.sin_addr), dummyClientIP, INET_ADDRSTRLEN); + FILE_LOG(logDEBUG3, ("%s socket accepted connection, fd= %d\n", + (isControlServer ? "control":"stop"), file_des)); + // add the file descriptor from accept + FD_SET(file_des, &readset); + maxfd = (maxfd < file_des)?file_des:maxfd; + } + } + } + } + return file_des; +} + + + + + + + +void closeConnection(int file_des) { + if(file_des >= 0) + close(file_des); + // remove file descriptor from set + FD_CLR(file_des, &readset); +} + +void exitServer(int socketDescriptor) { + if (socketDescriptor >= 0) + close(socketDescriptor); + FILE_LOG(logINFO, ("Closing %s server\n", (isControlServer ? "control":"stop"))); + FD_CLR(socketDescriptor, &readset); + isock--; + fflush(stdout); +} + + + + +void swapData(void* val,int length,intType itype){ + int i; + int16_t* c = (int16_t*)val; + int32_t* a = (int32_t*)val; + int64_t* b = (int64_t*)val; + for(i = 0; length > 0; i++){ + switch(itype){ + case INT16: + c[i] = ((c[i] & 0x00FF) << 8) | ((c[i] & 0xFF00) >> 8); + length -= sizeof(int16_t); + break; + case INT32: + a[i] = ((a[i] << 8) & 0xFF00FF00) | ((a[i] >> 8) & 0xFF00FF ); + a[i] = (a[i] << 16) | ((a[i] >> 16) & 0xFFFF); + length -= sizeof(int32_t); + break; + case INT64: + b[i] = ((b[i] << 8) & 0xFF00FF00FF00FF00ULL ) | ((b[i] >> 8) & 0x00FF00FF00FF00FFULL ); + b[i] = ((b[i] << 16) & 0xFFFF0000FFFF0000ULL ) | ((b[i] >> 16) & 0x0000FFFF0000FFFFULL ); + b[i] = (b[i] << 32) | ((b[i] >> 32) & 0xFFFFFFFFULL); + length -= sizeof(int64_t); + break; + default: + length = 0; + break; + } + } +} + +int sendData(int file_des, void* buf,int length, intType itype){ +#ifndef PCCOMPILE +#ifdef EIGERD + swapData(buf, length, itype); +#endif +#endif + return sendDataOnly(file_des, buf, length); +} + + +int receiveData(int file_des, void* buf,int length, intType itype){ + int lret = receiveDataOnly(file_des, buf, length); +#ifndef PCCOMPILE +#ifdef EIGERD + if (lret >= 0) swapData(buf, length, itype); +#endif +#endif + return lret; +} + + +int sendDataOnly(int file_des, void* buf,int length) { + if (!length) + return 0; + + + int bytesSent = 0; + int retry = 0; // retry index when buffer is blocked (write returns 0) + while (bytesSent < length) { + + // setting a max packet size for blackfin driver (and network driver does not do a check if packets sent) + int bytesToSend = length - bytesSent; + if (bytesToSend > CPU_DRVR_SND_LMT) + bytesToSend = CPU_DRVR_SND_LMT; + + // send + int rc = write(file_des, (char*)((char*)buf + bytesSent), bytesToSend); + // error + if (rc < 0) { + FILE_LOG(logERROR, ("Could not write to %s socket. Possible socket crash\n", + (isControlServer ? "control":"stop"))); + return bytesSent; + } + // also error, wrote nothing, buffer blocked up, too fast sending for client + if (rc == 0) { + FILE_LOG(logERROR, ("Could not write to %s socket. Buffer full. Retry: %d\n", + (isControlServer ? "control":"stop"), retry)); + ++retry; + // wrote nothing for many loops + if (retry >= CPU_RSND_PCKT_LOOP) { + FILE_LOG(logERROR, ("Could not write to %s socket. Buffer full! Too fast! No more.\n", + (isControlServer ? "control":"stop"))); + return bytesSent; + } + usleep(CPU_RSND_WAIT_US); + } + // wrote something, reset retry + else { + retry = 0; + if (rc != bytesToSend) { + FILE_LOG(logWARNING, ("Only partial write to %s socket. Expected to write %d bytes, wrote %d\n", + (isControlServer ? "control":"stop"), bytesToSend, rc)); + } + } + bytesSent += rc; + } + + return bytesSent; +} + + +int receiveDataOnly(int file_des, void* buf,int length) { + + int total_received = 0; + int nreceiving; + int nreceived; + if (file_des<0) return -1; + FILE_LOG(logDEBUG3, ("want to receive %d Bytes to %s server\n", + length, (isControlServer ? "control":"stop"))); + + while(length > 0) { + nreceiving = (length>SEND_REC_MAX_SIZE) ? SEND_REC_MAX_SIZE:length; // (condition) ? if_true : if_false + nreceived = read(file_des,(char*)buf+total_received,nreceiving); + if(!nreceived){ + if(!total_received) { + return -1; //to handle it + } + break; + } + length -= nreceived; + total_received += nreceived; + } + + if (total_received>0) + strcpy(thisClientIP,dummyClientIP); + + if (strcmp(lastClientIP,thisClientIP)) { + differentClients = 1; + } + else + differentClients = 0; + + return total_received; +} + + + + +int sendModule(int file_des, sls_detector_module *myMod) { + int ts = 0, n = 0; + n = sendData(file_des,&(myMod->serialnumber),sizeof(myMod->serialnumber),INT32); + if (!n) return -1; ts += n; + n = sendData(file_des,&(myMod->nchan), sizeof(myMod->nchan), INT32); + if (!n) return -1; ts += n; + n = sendData(file_des,&(myMod->nchip), sizeof(myMod->nchip), INT32); + if (!n) return -1; ts += n; + n = sendData(file_des,&(myMod->ndac), sizeof(myMod->ndac), INT32); + if (!n) return -1; ts += n; + n = sendData(file_des,&(myMod->reg), sizeof(myMod->reg), INT32); + if (!n) return -1; ts += n; + n = sendData(file_des,&(myMod->iodelay), sizeof(myMod->iodelay), INT32); + if (!n) return -1; ts += n; + n = sendData(file_des,&(myMod->tau), sizeof(myMod->tau), INT32); + if (!n) return -1; ts += n; + n = sendData(file_des,&(myMod->eV), sizeof(myMod->eV), INT32); + if (!n) return -1; ts += n; + // dacs + n = sendData(file_des,myMod->dacs, sizeof(int)*(myMod->ndac), INT32); + if (!n) return -1; ts += n; + // channels +#ifdef EIGERD + n = sendData(file_des,myMod->chanregs, sizeof(int) * (myMod->nchan), INT32); + if (!n) return -1; ts += n; +#endif + FILE_LOG(logDEBUG1, ("module of size %d sent register %x\n", ts, myMod->reg)); + return ts; +} + + + +int receiveModule(int file_des, sls_detector_module* myMod) { + enum TLogLevel level = logDEBUG1; + FILE_LOG(level, ("Receiving Module\n")); + int ts = 0, n = 0; + int nDacs = myMod->ndac; +#ifdef EIGERD + int nChans = myMod->nchan; // can be zero for no trimbits + FILE_LOG(level, ("nChans: %d\n",nChans)); +#endif + n = receiveData(file_des,&(myMod->serialnumber), sizeof(myMod->serialnumber), INT32); + if (!n) return -1; ts += n; + FILE_LOG(level, ("serialno received. %d bytes. serialno: %d\n", n, myMod->serialnumber)); + n = receiveData(file_des,&(myMod->nchan), sizeof(myMod->nchan), INT32); + if (!n) return -1; ts += n; + FILE_LOG(level, ("nchan received. %d bytes. nchan: %d\n", n, myMod->nchan)); + n = receiveData(file_des,&(myMod->nchip), sizeof(myMod->nchip), INT32); + if (!n) return -1; ts += n; + FILE_LOG(level, ("nchip received. %d bytes. nchip: %d\n", n, myMod->nchip)); + n = receiveData(file_des,&(myMod->ndac), sizeof(myMod->ndac), INT32); + if (!n) return -1; ts += n; + FILE_LOG(level, ("ndac received. %d bytes. ndac: %d\n", n, myMod->ndac)); + n = receiveData(file_des,&(myMod->reg), sizeof(myMod->reg), INT32); + if (!n) return -1; ts += n; + FILE_LOG(level, ("reg received. %d bytes. reg: %d\n", n, myMod->reg)); + n = receiveData(file_des,&(myMod->iodelay), sizeof(myMod->iodelay), INT32); + if (!n) return -1; ts += n; + FILE_LOG(level, ("iodelay received. %d bytes. iodelay: %d\n", n, myMod->iodelay)); + n = receiveData(file_des,&(myMod->tau), sizeof(myMod->tau), INT32); + if (!n) return -1; ts += n; + FILE_LOG(level, ("tau received. %d bytes. tau: %d\n", n, myMod->tau)); + n = receiveData(file_des,&(myMod->eV), sizeof(myMod->eV), INT32); + if (!n) return -1; ts += n; + FILE_LOG(level, ("eV received. %d bytes. eV: %d\n", n, myMod->eV)); + // dacs + if (nDacs != (myMod->ndac)) { + FILE_LOG(logERROR, ("received wrong number of dacs. " + "Expected %d, got %d\n", nDacs, myMod->ndac)); + return 0; + } + n = receiveData(file_des, myMod->dacs, sizeof(int) * (myMod->ndac), INT32); + if (!n) return -1; ts += n; + FILE_LOG(level, ("dacs received. %d bytes.\n", n)); + // channels +#ifdef EIGERD + if (((myMod->nchan) != 0 ) && // no trimbits + (nChans != (myMod->nchan))) { // with trimbits + FILE_LOG(logERROR, ("received wrong number of channels. " + "Expected %d, got %d\n", nChans, (myMod->nchan))); + return 0; + } + n = receiveData(file_des, myMod->chanregs, sizeof(int) * (myMod->nchan), INT32); + FILE_LOG(level, ("chanregs received. %d bytes.\n", n)); + if (!n) return -1; ts += n; +#endif + FILE_LOG(level, ("received module of size %d register %x\n",ts,myMod->reg)); + return ts; +} + + +void Server_LockedError() { + ret = FAIL; + sprintf(mess,"Detector locked by %s\n", lastClientIP); + FILE_LOG(logWARNING, (mess)); +} + + +int Server_VerifyLock() { + if (differentClients && lockStatus) + Server_LockedError(); + return ret; +} + + +int Server_SendResult(int fileDes, intType itype, int update, void* retval, int retvalSize) { + + // update if different clients (ret can be ok or acquisition finished), not fail to not overwrite e message + if (update && isControlServer && ret != FAIL && differentClients) + ret = FORCE_UPDATE; + + // send success of operation + int ret1 = ret; + sendData(fileDes, &ret1,sizeof(ret1), INT32); + if(ret == FAIL) { + // send error message + if (strlen(mess)) + sendData(fileDes, mess, MAX_STR_LENGTH, OTHER); + // debugging feature. should not happen. + else + FILE_LOG(logERROR, ("No error message provided for this failure in %s " + "server. Will mess up TCP.\n", + (isControlServer ? "control":"stop"))); + } + // send return value + sendData(fileDes, retval, retvalSize, itype); + + return ret; +} diff --git a/slsDetectorServers/slsDetectorServer/communication_funcs.h b/slsDetectorServers/slsDetectorServer/communication_funcs.h new file mode 100755 index 000000000..633139740 --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/communication_funcs.h @@ -0,0 +1,55 @@ +#ifndef COMMUNICATION_FUNCS_H +#define COMMUNICATION_FUNCS_H + + +#include "sls_detector_defs.h" + +typedef enum{ + INT16, + INT32, + INT64, + OTHER +}intType; + + +int bindSocket(unsigned short int port_number); +int acceptConnection(int socketDescriptor); +void closeConnection(int file_Des); +void exitServer(int socketDescriptor); + +void swapData(void* val,int length,intType itype); +int sendData(int file_des, void* buf,int length, intType itype); +int receiveData(int file_des, void* buf,int length, intType itype); +int sendDataOnly(int file_des, void* buf,int length); +int receiveDataOnly(int file_des, void* buf,int length); + +int sendModule(int file_des, sls_detector_module *myMod); +int receiveModule(int file_des, sls_detector_module* myMod); + +/** + * Servers sets and prints error message for locked server + * @returns success of operaton + */ +void Server_LockedError(); + + +/** + * Server verifies if it is unlocked, + * sets and prints appropriate message if it is locked and different clients + * @returns success of operaton + */ +int Server_VerifyLock(); + + +/** + * Server sends result to client (also set ret to force_update if different clients) + * @param fileDes file descriptor for the socket + * @param itype 32 or 64 or others to determine to swap data from big endian to little endian + * @param update 1 if one must update if different clients, else 0 + * @param retval pointer to result + * @param retvalSize size of result + * @returns result of operation + */ +int Server_SendResult(int fileDes, intType itype, int update, void* retval, int retvalSize); + +#endif diff --git a/slsDetectorServers/slsDetectorServer/communication_funcs_UDP.h b/slsDetectorServers/slsDetectorServer/communication_funcs_UDP.h new file mode 100755 index 000000000..c983eb18e --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/communication_funcs_UDP.h @@ -0,0 +1,116 @@ +#pragma once + +#include "logger.h" +#include "sls_detector_defs.h" + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int udpSockfd = -1; +struct addrinfo* udpServerAddrInfo = 0; +unsigned short int udpDestinationPort = 0; +char udpDestinationIp[MAX_STR_LENGTH] = ""; + +//DEFAULT_TX_UDP_PORT;// src port +int getUdPSocketDescriptor() { + return udpSockfd; +} + +int setUDPDestinationDetails(const char* ip, unsigned short int port) { + udpDestinationPort = port; + size_t len = strlen(ip); + strncpy(udpDestinationIp, ip, len > MAX_STR_LENGTH ? MAX_STR_LENGTH : len ); + + if (udpServerAddrInfo) { + freeaddrinfo(udpServerAddrInfo); + udpServerAddrInfo = 0; + } + + // convert ip to internet address + struct addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; + hints.ai_flags = 0; + hints.ai_protocol = 0; + char sport[100]; + memset(sport, 0, 100); + sprintf(sport, "%d", udpDestinationPort); + int err = getaddrinfo(udpDestinationIp, sport, &hints, &udpServerAddrInfo); + if (err != 0) { + FILE_LOG(logERROR, ("Failed to resolve remote socket address %s at port %d. " + "(Error code:%d, %s)\n", udpDestinationIp, udpDestinationPort, err, gai_strerror(err))); + return FAIL; + } + if (udpServerAddrInfo == NULL) { + FILE_LOG(logERROR, ("Failed to resolve remote socket address %s at port %d " + "(getaddrinfo returned NULL)\n", udpDestinationIp, udpDestinationPort)); + udpServerAddrInfo = 0; + return FAIL; + } + + return OK; +} + +int createUDPSocket() { + FILE_LOG(logDEBUG2, ("Creating UDP Socket\n")); + if (!strlen(udpDestinationIp)) { + FILE_LOG(logERROR, ("No destination UDP ip specified.\n")); + return FAIL; + } + + if (udpSockfd != -1) { + FILE_LOG(logERROR, ("Strange that Udp socket was still open. Closing it to create a new one\n")); + close(udpSockfd); + udpSockfd = -1; + } + + // Creating socket file descriptor + udpSockfd = socket(udpServerAddrInfo->ai_family, udpServerAddrInfo->ai_socktype, udpServerAddrInfo->ai_protocol); + if (udpSockfd == -1 ) { + FILE_LOG(logERROR, ("UDP socket at port %d failed. (Error code:%d, %s)\n", + udpDestinationPort, errno, gai_strerror(errno))); + return FAIL; + } + FILE_LOG(logINFO, ("Udp client socket created for server (port %d, ip:%s)\n", + udpDestinationPort, udpDestinationIp)); + + // connecting allows to use "send/write" instead of "sendto", avoiding checking for server address for each packet + // using write without a connect will end in segv + if (connect(udpSockfd,udpServerAddrInfo->ai_addr, udpServerAddrInfo->ai_addrlen)==-1) { + FILE_LOG(logERROR, ("Could not connect to UDP server at ip:%s, port:%d. (Error code:%d, %s)\n", + udpDestinationIp, udpDestinationPort, errno, gai_strerror(errno))); + } + FILE_LOG(logINFO, ("Udp client socket connected\n", + udpDestinationPort, udpDestinationIp)); + return OK; +} + +int sendUDPPacket(const char* buf, int length) { + int n = write(udpSockfd, buf, length); + // udp sends atomically, no need to handle partial data + if (n == -1) { + FILE_LOG(logERROR, ("Could not send udp packet. (Error code:%d, %s)\n", + n, errno, gai_strerror(errno))); + } else { + FILE_LOG(logDEBUG2, ("%d bytes sent\n", n)); + } + return n; +} + +void closeUDPSocket() { + if (udpSockfd != -1) { + FILE_LOG(logINFO, ("Udp client socket closed\n")); + close(udpSockfd); + udpSockfd = -1; + } +} diff --git a/slsDetectorServers/slsDetectorServer/logger.h b/slsDetectorServers/slsDetectorServer/logger.h new file mode 100755 index 000000000..4f8c9b707 --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/logger.h @@ -0,0 +1,67 @@ +#pragma once + +#include "ansi.h" + +#include +#include +#include + + +#ifdef FIFODEBUG +#define FILELOG_MAX_LEVEL logDEBUG5 +#elif VERYVERBOSE +#define FILELOG_MAX_LEVEL logDEBUG4 +#elif VERBOSE +#define FILELOG_MAX_LEVEL logDEBUG +#elif DEBUG1 +#define FILELOG_MAX_LEVEL logDEBUG1 +#endif + +#ifndef FILELOG_MAX_LEVEL +#define FILELOG_MAX_LEVEL logINFO +#endif + +enum TLogLevel{ +logERROR, logWARNING, logINFOBLUE, logINFOGREEN, logINFORED, logINFO, +logDEBUG, logDEBUG1, logDEBUG2, logDEBUG3, logDEBUG4, logDEBUG5 +}; + +#define ERROR_MSG_LENGTH 1000 + +#define FILE_LOG(lvl, fmt, ...) \ + if (lvl > FILELOG_MAX_LEVEL); \ + else {char* temp = FILELOG_BuildLog fmt; FILELOG_PrintLog(lvl, temp);free(temp);} + +static inline void FILELOG_PrintLog(enum TLogLevel level, char* m) { + switch(level) { + case logERROR: cprintf(RED BOLD, "ERROR: %s", m); break; + case logWARNING: cprintf(YELLOW BOLD, "WARNING: %s", m); break; + case logINFOBLUE: cprintf(BLUE, "INFO: %s", m); break; + case logINFOGREEN: cprintf(GREEN, "INFO: %s", m); break; + case logINFORED: cprintf(RED, "INFO: %s", m); break; + case logINFO: cprintf(RESET, "INFO: %s", m); break; + case logDEBUG: cprintf(MAGENTA, "DEBUG: %s", m); break; + case logDEBUG1: cprintf(MAGENTA, "DEBUG1: %s", m); break; + case logDEBUG2: cprintf(MAGENTA, "DEBUG2: %s", m); break; + case logDEBUG3: cprintf(MAGENTA, "DEBUG3: %s", m); break; + case logDEBUG4: cprintf(MAGENTA, "DEBUG4: %s", m); break; + case logDEBUG5: cprintf(MAGENTA, "DEBUG5: %s", m); break; + } +} + +static inline char* FILELOG_BuildLog(const char* fmt, ...) { + char* p; + va_list ap; + p = malloc(ERROR_MSG_LENGTH); + va_start(ap, fmt); + int ret = vsnprintf(p, ERROR_MSG_LENGTH, fmt, ap); + va_end(ap); + if (ret < 0 || ret >= ERROR_MSG_LENGTH) { + FILELOG_PrintLog(logERROR, ("Could not print the " + "complete error message in the next print.\n")); + } + return p; +}; + + + diff --git a/slsDetectorSoftware/slsDetectorServer/programfpga.h b/slsDetectorServers/slsDetectorServer/programfpga.h similarity index 65% rename from slsDetectorSoftware/slsDetectorServer/programfpga.h rename to slsDetectorServers/slsDetectorServer/programfpga.h index b37f521de..91fdd692d 100755 --- a/slsDetectorSoftware/slsDetectorServer/programfpga.h +++ b/slsDetectorServers/slsDetectorServer/programfpga.h @@ -1,19 +1,16 @@ -#ifndef PROGRAM_FPGA_H -#define PROGRAM_FPGA_H +#pragma once #include "ansi.h" -#include #include // usleep #include /* global variables */ -#define CTRL_SRVR_INIT_TIME_US (300 * 1000) -int gpioDefined=0; -#define MTDSIZE 10 -char mtdvalue[MTDSIZE]; +#define MTDSIZE 10 +int gpioDefined = 0; +char mtdvalue[MTDSIZE] = {0}; /** @@ -27,9 +24,9 @@ void defineGPIOpins(){ //define their direction system("echo in > /sys/class/gpio/gpio7/direction"); system("echo out > /sys/class/gpio/gpio9/direction"); - printf("gpio pins defined\n"); + FILE_LOG(logINFO, ("gpio pins defined\n")); gpioDefined = 1; - }else printf("gpio pins already defined earlier\n"); + }else FILE_LOG(logDEBUG1, ("gpio pins already defined earlier\n")); } /** @@ -54,7 +51,7 @@ void FPGATouchFlash(){ * Reset FPGA */ void resetFPGA(){ - cprintf(BLUE,"\n*** Reseting FPGA ***\n"); + FILE_LOG(logINFOBLUE, ("Reseting FPGA\n")); FPGAdontTouchFlash(); FPGATouchFlash(); usleep(CTRL_SRVR_INIT_TIME_US); @@ -64,14 +61,12 @@ void resetFPGA(){ * Erasing flash */ void eraseFlash(){ -#ifdef VERY_VERBOSE - printf("\nErasing Flash\n"); -#endif + FILE_LOG(logDEBUG1, ("Erasing Flash\n")); char command[255]; memset(command, 0, 255); sprintf(command,"flash_eraseall %s",mtdvalue); system(command); - printf("Flash erased\n"); + FILE_LOG(logINFO, ("Flash erased\n")); } /** @@ -81,43 +76,40 @@ void eraseFlash(){ * @return 0 for success, 1 for fail (cannot open file for writing program) */ int startWritingFPGAprogram(FILE** filefp){ -#ifdef VERY_VERBOSE - printf("\nStart Writing of FPGA program\n"); -#endif + FILE_LOG(logDEBUG1, ("Start Writing of FPGA program\n")); //getting the drive char output[255]; memset(output, 0, 255); FILE* fp = popen("awk \'$4== \"\\\"bitfile(spi)\\\"\" {print $1}\' /proc/mtd", "r"); if (fp == NULL) { - cprintf(RED,"popen returned NULL. Need that to get mtd drive.\n"); + FILE_LOG(logERROR, ("popen returned NULL. Need that to get mtd drive.\n")); return 1; } if (fgets(output, sizeof(output), fp) == NULL) { - cprintf(RED,"fgets returned NULL. Need that to get mtd drive.\n"); + FILE_LOG(logERROR, ("fgets returned NULL. Need that to get mtd drive.\n")); return 1; } pclose(fp); - //cprintf(RED,"output: %s\n", output); memset(mtdvalue, 0, MTDSIZE); strcpy(mtdvalue,"/dev/"); char* pch = strtok(output,":"); if(pch == NULL){ - cprintf(RED,"Could not get mtd value\n"); + FILE_LOG(logERROR, ("Could not get mtd value\n")); return 1; } strcat(mtdvalue,pch); - printf ("\nFlash drive found: %s\n",mtdvalue); + FILE_LOG(logINFO, ("Flash drive found: %s\n", mtdvalue)); FPGAdontTouchFlash(); //writing the program to flash *filefp = fopen(mtdvalue, "w"); if(*filefp == NULL){ - cprintf(RED,"Unable to open %s in write mode\n",mtdvalue); + FILE_LOG(logERROR, ("Unable to open %s in write mode\n", mtdvalue)); return 1; } - printf("Flash ready for writing\n"); + FILE_LOG(logINFO, ("Flash ready for writing\n")); return 0; } @@ -128,9 +120,7 @@ int startWritingFPGAprogram(FILE** filefp){ * @param filefp pointer to flash */ void stopWritingFPGAprogram(FILE* filefp){ -#ifdef VERY_VERBOSE - printf("\nStopping of writing FPGA program\n"); -#endif + FILE_LOG(logDEBUG1, ("Stopping of writing FPGA program\n")); int wait = 0; if(filefp!= NULL){ @@ -142,9 +132,7 @@ void stopWritingFPGAprogram(FILE* filefp){ FPGATouchFlash(); if(wait){ -#ifdef VERY_VERBOSE - printf("Waiting for FPGA to program from flash\n"); -#endif + FILE_LOG(logDEBUG1, ("Waiting for FPGA to program from flash\n")); //waiting for success or done char output[255]; int res=0; @@ -153,12 +141,10 @@ void stopWritingFPGAprogram(FILE* filefp){ fgets(output, sizeof(output), sysFile); pclose(sysFile); sscanf(output,"%d",&res); -#ifdef VERY_VERBOSE - printf("gpi07 returned %d\n",res); -#endif + FILE_LOG(logDEBUG1, ("gpi07 returned %d\n", res)); } } - printf("FPGA has picked up the program from flash\n\n"); + FILE_LOG(logINFO, ("FPGA has picked up the program from flash\n")); } @@ -170,21 +156,15 @@ void stopWritingFPGAprogram(FILE* filefp){ * @return 0 for success, 1 for fail (cannot write) */ int writeFPGAProgram(char* fpgasrc, size_t fsize, FILE* filefp){ -#ifdef VERY_VERBOSE - printf("\nWriting of FPGA Program\n"); - cprintf(BLUE,"address of fpgasrc:%p\n",(void *)fpgasrc); - cprintf(BLUE,"fsize:%lu\n",fsize); - cprintf(BLUE,"pointer:%p\n",(void*)filefp); -#endif + FILE_LOG(logDEBUG1, ("Writing of FPGA Program\n" + "\taddress of fpgasrc:%p\n" + "\tfsize:%lu\n\tpointer:%p\n", + (void *)fpgasrc, fsize, (void*)filefp)); if(fwrite((void*)fpgasrc , sizeof(char) , fsize , filefp )!= fsize){ - cprintf(RED,"Could not write FPGA source to flash (size:%lu)\n", fsize); + FILE_LOG(logERROR, ("Could not write FPGA source to flash (size:%lu)\n", fsize)); return 1; } -#ifdef VERY_VERBOSE - cprintf(BLUE, "program written to flash\n"); -#endif + FILE_LOG(logDEBUG1, ("program written to flash\n")); return 0; } - -#endif //PROGRAM_FPGA_H diff --git a/slsDetectorServers/slsDetectorServer/slsDetectorFunctionList.h b/slsDetectorServers/slsDetectorServer/slsDetectorFunctionList.h new file mode 100755 index 000000000..8e870019b --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/slsDetectorFunctionList.h @@ -0,0 +1,371 @@ +#include "sls_detector_defs.h" +#include "slsDetectorServer_defs.h" // DAC_INDEX, ADC_INDEX, also include RegisterDefs.h +#ifdef GOTTHARDD +#include "logger.h" // runState(enum TLogLevel) +#endif +#include +#include // FILE + + +/**************************************************** +This functions are used by the slsDetectroServer_funcs interface. +Here are the definitions, but the actual implementation should be done for each single detector. + +****************************************************/ + + +// basic tests +int isFirmwareCheckDone(); +int getFirmwareCheckResult(char** mess); +void basictests(); +#if defined(GOTTHARDD) || defined(JUNGFRAUD) || defined(CHIPTESTBOARDD) || defined(MOENCHD) +int checkType(); +int testFpga(); +int testBus(); +#endif + +#ifdef GOTTHARDD +int detectorTest(enum digitalTestMode arg, int ival); +#elif defined(JUNGFRAUD) || defined(CHIPTESTBOARDD) || defined(MOENCHD) +int detectorTest(enum digitalTestMode arg); +#endif + +// Ids +int64_t getDetectorId(enum idMode arg); +u_int64_t getFirmwareVersion(); +u_int64_t getFirmwareAPIVersion(); +#if defined(JUNGFRAUD) || defined(CHIPTESTBOARDD) || defined(MOENCHD) +u_int16_t getHardwareVersionNumber(); +u_int16_t getHardwareSerialNumber(); +#endif +u_int32_t getDetectorNumber(); +u_int64_t getDetectorMAC(); +u_int32_t getDetectorIP(); +#ifdef GOTTHARDD +u_int32_t getBoardRevision(); +#endif + + +// initialization +void initControlServer(); +void initStopServer(); +#ifdef EIGERD +void getModuleConfiguration(); +#endif + +// set up detector +#ifdef EIGERD +void allocateDetectorStructureMemory(); +#endif +void setupDetector(); +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) +int allocateRAM(); +void updateDataBytes(); +int getChannels(); +#endif + +#if defined(GOTTHARDD) || defined(JUNGFRAUD) +int setDefaultDacs(); +#endif + + +// advanced read/write reg +#ifdef EIGERD +uint32_t writeRegister(uint32_t offset, uint32_t data); +uint32_t readRegister(uint32_t offset); +#elif GOTTHARDD +uint32_t writeRegister16And32(uint32_t offset, uint32_t data); //FIXME its not there in ctb or moench? +uint32_t readRegister16And32(uint32_t offset); +#else +extern u_int32_t writeRegister(u_int32_t offset, u_int32_t data); // blackfin.h +extern u_int32_t readRegister(u_int32_t offset); // blackfin.h +#endif + + +// firmware functions (resets) +#ifdef JUNGFRAUD +void cleanFifos(); +void resetCore(); +void resetPeripheral(); +#elif GOTTHARDD +void setPhaseShiftOnce(); +void setPhaseShift(int numphaseshift); +void cleanFifos(); +void setADCSyncRegister(); +void setDAQRegister(); +void setChipOfInterestRegister(int adc); +void setROIADC(int adc); +void setGbitReadout(); +int readConfigFile(); +void setMasterSlaveConfiguration(); +#elif CHIPTESTBOARDD +void cleanFifos(); +void resetCore(); +void resetPeripheral(); +#elif MOENCHD +void cleanFifos(); +void resetCore(); +void resetPeripheral(); +#endif + +// parameters - dr, roi +int setDynamicRange(int dr); +#if defined(GOTTHARDD) || defined(CHIPTESTBOARDD) || defined(MOENCHD) +ROI* setROI(int n, ROI arg[], int *retvalsize, int *ret); +#endif + +// parameters - readout +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) || defined(JUNGFRAUD) +void setSpeed(enum speedVariable ind, int val, int mode); +int getSpeed(enum speedVariable ind, int mode); +#else +void setSpeed(enum speedVariable ind, int val); +int getSpeed(enum speedVariable ind); +#endif + +#if defined(EIGERD) || defined(CHIPTESTBOARDD) +enum readOutFlags setReadOutFlags(enum readOutFlags val); +#endif + +// parameters - timer +#ifdef JUNGFRAUD +int selectStoragecellStart(int pos); +#endif +int64_t setTimer(enum timerIndex ind, int64_t val); +int64_t getTimeLeft(enum timerIndex ind); +#if defined(JUNGFRAUD) || defined(GOTTHARDD) || defined(CHIPTESTBOARDD) || defined(MOENCHD) +int validateTimer(enum timerIndex ind, int64_t val, int64_t retval); +#endif + +// parameters - module, settings +#if (!defined(CHIPTESTBOARDD)) && (!defined(MOENCHD)) +int setModule(sls_detector_module myMod, char* mess); +int getModule(sls_detector_module *myMod); +enum detectorSettings setSettings(enum detectorSettings sett); +#endif +enum detectorSettings getSettings(); + +// parameters - threshold +#ifdef EIGERD +int getThresholdEnergy(); +int setThresholdEnergy(int ev); +#endif + +// parameters - dac, adc, hv +#ifdef GOTTHARDD +extern void AD9252_Set(int addr, int val); // AD9252.h (old board) +#endif +#if defined(GOTTHARDD) || defined(JUNGFRAUD) || defined(CHIPTESTBOARDD) || defined(MOENCHD) +extern void AD9257_Set(int addr, int val); // AD9257.h +#endif +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) +extern int AD9257_GetMaxValidVref(); // AD9257.h +extern void AD9257_SetVrefVoltage(int val); // AD9257.h +#endif + +void setDAC(enum DACINDEX ind, int val, int mV); +int getDAC(enum DACINDEX ind, int mV); +int getMaxDacSteps(); +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) +int dacToVoltage(int dac); +int checkVLimitCompliant(int mV); +int checkVLimitDacCompliant(int dac); +int getVLimit(); +void setVLimit(int l); +#endif + +#ifdef CHIPTESTBOARDD +int isVchipValid(int val); +int getVchip(); +void setVchip(int val); +int getVChipToSet(enum DACINDEX ind, int val); +int getDACIndexFromADCIndex(enum ADCINDEX ind); +int getADCIndexFromDACIndex(enum DACINDEX ind); +int isPowerValid(enum DACINDEX ind, int val); +int getPower(); +void setPower(enum DACINDEX ind, int val); +void powerOff(); +#endif + +#ifndef MOENCHD +int getADC(enum ADCINDEX ind); +#endif + +int setHighVoltage(int val); + + + +// parameters - timing, extsig +void setTiming( enum externalCommunicationMode arg); +enum externalCommunicationMode getTiming(); +#ifdef GOTTHARDD +void setExtSignal(enum externalSignalFlag mode); +int getExtSignal(); +#endif + +// configure mac +#ifdef GOTTHARDD +void calcChecksum(mac_conf* mac, int sourceip, int destip); +#endif +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) +long int calcChecksum(int sourceip, int destip); +#endif +#ifdef GOTTHARDD +int getAdcConfigured(); +#endif + +#ifdef EIGERD +int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport, uint32_t udpport2); +#elif JUNGFRAUD +int configureMAC(int numInterfaces, int selInterface, + uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport, + uint32_t destip2, uint64_t destmac2, uint64_t sourcemac2, uint32_t sourceip2, uint32_t udpport2); +#else +int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport); +#endif + +#if defined(JUNGFRAUD) || defined(EIGERD) +int setDetectorPosition(int pos[]); +#endif +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) || defined(EIGERD) +int enableTenGigabitEthernet(int val); +#endif + + +// very detector specific + +// moench specific - powerchip +#ifdef MOENCHD +int powerChip (int on); +#endif + +// chip test board or moench specific - configure frequency, phase, pll, flashing firmware +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) +void configurePhase(enum CLKINDEX ind, int val, int degrees); +int getPhase(enum CLKINDEX ind, int degrees); +int getMaxPhase(enum CLKINDEX ind); +int validatePhaseinDegrees(enum speedVariable ind, int val, int retval); +void configureFrequency(enum CLKINDEX ind, int val); +int getFrequency(enum CLKINDEX ind); +void configureSyncFrequency(enum CLKINDEX ind); +void setAdcOffsetRegister(int adc, int val); +int getAdcOffsetRegister(int adc); +extern void eraseFlash(); // programfpga.h +extern int startWritingFPGAprogram(FILE** filefp); // programfpga.h +extern void stopWritingFPGAprogram(FILE* filefp); // programfpga.h +extern int writeFPGAProgram(char* fpgasrc, size_t fsize, FILE* filefp); // programfpga.h +// patterns +uint64_t writePatternIOControl(uint64_t word); +uint64_t writePatternClkControl(uint64_t word); +uint64_t readPatternWord(int addr); +uint64_t writePatternWord(int addr, uint64_t word); +int setPatternWaitAddress(int level, int addr); +uint64_t setPatternWaitTime(int level, uint64_t t); +void setPatternLoop(int level, int *startAddr, int *stopAddr, int *nLoop); +int setLEDEnable(int enable); +void setDigitalIODelay(uint64_t pinMask, int delay); +void setPatternMask(uint64_t mask); +uint64_t getPatternMask(); +void setPatternBitMask(uint64_t mask); +uint64_t getPatternBitMask(); +#endif + +// gotthard specific - image, pedestal +#ifdef GOTTHARDD +void loadImage(enum imageType index, short int imageVals[]); +int readCounterBlock(int startACQ, short int counterVals[]); +int resetCounterBlock(int startACQ); + +// jungfrau specific - powerchip, autocompdisable, clockdiv, asictimer, clock, pll, flashing firmware +#elif JUNGFRAUD +int powerChip (int on); +int autoCompDisable(int on); +void configureASICTimer(); +void setClockDivider(int val); +int getClockDivider(); +void setAdcPhase(int val, int degrees); +int getPhase(int degrees); +int getMaxPhaseShift(); +int validatePhaseinDegrees(int val, int retval); +int setThresholdTemperature(int val); +int setTemperatureControl(int val); +int setTemperatureEvent(int val); +extern void eraseFlash(); // programfpga.h +extern int startWritingFPGAprogram(FILE** filefp); // programfpga.h +extern void stopWritingFPGAprogram(FILE* filefp); // programfpga.h +extern int writeFPGAProgram(char* fpgasrc, size_t fsize, FILE* filefp); // programfpga.h +void alignDeserializer(); + +// eiger specific - iodelay, pulse, rate, temp, activate, delay nw parameter +#elif EIGERD +int setIODelay(int val); +int setCounterBit(int val); +int pulsePixel(int n, int x, int y); +int pulsePixelNMove(int n, int x, int y); +int pulseChip(int n); +int64_t setRateCorrection(int64_t custom_tau_in_nsec); +int getRateCorrectionEnable(); +int getDefaultSettingsTau_in_nsec(); +void setDefaultSettingsTau_in_nsec(int t); +int64_t getCurrentTau(); +void setExternalGating(int enable[]); +int setAllTrimbits(int val); +int getAllTrimbits(); +int getBebFPGATemp(); +int activate(int enable); +#endif + +#if defined(JUNGFRAUD) || defined(EIGERD) +int setNetworkParameter(enum NETWORKINDEX mode, int value); +#endif + + + + +// aquisition +#ifdef EIGERD +int prepareAcquisition(); +#endif +int startStateMachine(); +#ifdef VIRTUAL +void* start_timer(void* arg); +#endif +int stopStateMachine(); +#ifdef EIGERD +int softwareTrigger(); +#endif + +#ifdef EIGERD +int startReadOut(); +#endif +enum runStatus getRunStatus(); +void readFrame(int *ret, char *mess); +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) +void readandSendUDPFrames(int *ret, char *mess); +void unsetFifoReadStrobes(); +void readSample(int ns); +uint32_t checkDataInFifo(); +int checkFifoForEndOfAcquisition(); +int readFrameFromFifo(); +#endif + +#if defined(GOTTHARDD) || defined(JUNGFRAUD) || defined(CHIPTESTBOARDD) || defined(MOENCHD) +u_int32_t runBusy(); +#endif + +#ifdef GOTTHARDD +u_int32_t runState(enum TLogLevel lev); +#endif + + +//common +#ifdef EIGERD +int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod); +#endif +int calculateDataBytes(); +int getTotalNumberOfChannels(); +int getNumberOfChips(); +int getNumberOfDACs(); +int getNumberOfChannelsPerChip(); + + diff --git a/slsDetectorServers/slsDetectorServer/slsDetectorServer.c b/slsDetectorServers/slsDetectorServer/slsDetectorServer.c new file mode 100755 index 000000000..6c8413ed5 --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/slsDetectorServer.c @@ -0,0 +1,145 @@ +/* A simple server in the internet domain using TCP + The port number is passed as an argument */ + +#include "sls_detector_defs.h" +#include "logger.h" +#include "communication_funcs.h" +#include "slsDetectorServer_funcs.h" +#include "slsDetectorServer_defs.h" +#include "versionAPI.h" + +#include +#include + + +// Global variables from communication_funcs +extern int isControlServer; +extern int ret; + +// Global variables from slsDetectorServer_funcs +extern int sockfd; +extern int debugflag; + +// Global variables from slsDetectorFunctionList +#ifdef GOTTHARDD +extern int phaseShift; +#endif + +void error(char *msg){ + perror(msg); +} + +int main(int argc, char *argv[]){ + + // print version + if (argc > 1 && !strcasecmp(argv[1], "-version")) { + int version = 0; +#ifdef GOTTHARDD + version = APIGOTTHARD; +#elif EIGERD + version = APIEIGER; +#elif JUNGFRAUD + version = APIJUNGFRAU; +#elif CHIPTESTBOARDD + version = APICTB; +#elif MOENCHD + version = APIMOENCH; +#endif + FILE_LOG(logINFO, ("SLS Detector Server %s (0x%x)\n", GITBRANCH, version)); + } + + int portno = DEFAULT_PORTNO; + int retval = OK; + int fd = 0; + + // if socket crash, ignores SISPIPE, prevents global signal handler + // subsequent read/write to socket gives error - must handle locally + signal(SIGPIPE, SIG_IGN); + + // circumvent the basic tests + { + int i; + for (i = 1; i < argc; ++i) { + if(!strcasecmp(argv[i],"-stopserver")) { + FILE_LOG(logINFO, ("Detected stop server\n")); + isControlServer = 0; + } + else if(!strcasecmp(argv[i],"-devel")){ + FILE_LOG(logINFO, ("Detected developer mode\n")); + debugflag = 1; + } +#ifdef GOTTHARDD + else if(!strcasecmp(argv[i],"-phaseshift")){ + if ((i + 1) >= argc) { + FILE_LOG(logERROR, ("no phase shift value given. Exiting.\n")); + return -1; + } + if (sscanf(argv[i + 1], "%d", &phaseShift) == 0) { + FILE_LOG(logERROR, ("cannot decode phase shift value %s. Exiting.\n", argv[i + 1])); + return -1; + } + FILE_LOG(logINFO, ("Detected phase shift of %d\n", phaseShift)); + } +#endif + } + } + +#ifdef STOP_SERVER + char cmd[100]; + memset(cmd, 0, 100); +#endif + if (isControlServer) { + portno = DEFAULT_PORTNO; + FILE_LOG(logINFO, ("Opening control server on port %d \n", portno)); +#ifdef STOP_SERVER + { + int i; + for (i = 0; i < argc; ++i) + sprintf(cmd, "%s %s", cmd, argv[i]); + sprintf(cmd,"%s -stopserver&", cmd); + FILE_LOG(logDEBUG1, ("Command to start stop server:%s\n", cmd)); + system(cmd); + } +#endif + } else { + portno = DEFAULT_PORTNO + 1; + FILE_LOG(logINFO,("Opening stop server on port %d \n", portno)); + } + + init_detector(); + + { // bind socket + sockfd = bindSocket(portno); + if (ret == FAIL) + return -1; + } + + // assign function table + function_table(); + + if (isControlServer) { + FILE_LOG(logINFOBLUE, ("Control Server Ready...\n\n")); + } else { + FILE_LOG(logINFO, ("Stop Server Ready...\n\n")); + } + + // waits for connection + while(retval != GOODBYE && retval != REBOOT) { + fd = acceptConnection(sockfd); + if (fd > 0) { + retval = decode_function(fd); + closeConnection(fd); + } + } + + exitServer(sockfd); + + if (retval == REBOOT) { + FILE_LOG(logINFOBLUE,("Rebooting!\n")); + fflush(stdout); + system("reboot"); + } + FILE_LOG(logINFO,("Goodbye!\n")); + return 0; +} + diff --git a/slsDetectorServers/slsDetectorServer/slsDetectorServer_funcs.c b/slsDetectorServers/slsDetectorServer/slsDetectorServer_funcs.c new file mode 100755 index 000000000..f8d3e10bf --- /dev/null +++ b/slsDetectorServers/slsDetectorServer/slsDetectorServer_funcs.c @@ -0,0 +1,3856 @@ +#include "slsDetectorServer_funcs.h" +#include "slsDetectorFunctionList.h" +#include "communication_funcs.h" +#include "logger.h" + +#include +#include +#include + +//defined in the detector specific Makefile +#ifdef GOTTHARDD +const enum detectorType myDetectorType = GOTTHARD; +#elif EIGERD +const enum detectorType myDetectorType = EIGER; +#elif JUNGFRAUD +const enum detectorType myDetectorType = JUNGFRAU; +#elif CHIPTESTBOARDD +const enum detectorType myDetectorType = CHIPTESTBOARD; +#elif MOENCHD +const enum detectorType myDetectorType = MOENCH; +#else +const enum detectorType myDetectorType = GENERIC; +#endif + +// Global variables from communication_funcs +extern int lockStatus; +extern char lastClientIP[INET_ADDRSTRLEN]; +extern char thisClientIP[INET_ADDRSTRLEN]; +extern int differentClients; +extern int isControlServer; +extern int ret; +extern int fnum; +extern char mess[MAX_STR_LENGTH]; + +// Variables that will be exported +int sockfd = 0; +int debugflag = 0; + +// Local variables +int (*flist[NUM_DET_FUNCTIONS])(int); +#ifdef EIGERD +uint32_t dhcpipad = 0; +#endif + +enum updateRet {NO_UPDATE, UPDATE}; + +/* initialization functions */ + +int printSocketReadError() { + FILE_LOG(logERROR, ("Error reading from socket. Possible socket crash.\n")); + return FAIL; +} + + +void init_detector() { +#ifdef VIRTUAL + FILE_LOG(logINFO, ("This is a VIRTUAL detector\n")); +#endif + if (isControlServer) { + basictests(); + initControlServer(); +#ifdef EIGERD + dhcpipad = getDetectorIP(); +#endif + } + else initStopServer(); + strcpy(mess,"dummy message"); + strcpy(lastClientIP,"none"); + strcpy(thisClientIP,"none1"); + lockStatus=0; +} + + +int decode_function(int file_des) { + ret = FAIL; + + int n = receiveData(file_des,&fnum,sizeof(fnum),INT32); + if (n <= 0) { + FILE_LOG(logDEBUG3, ("ERROR reading from socket n=%d, fnum=%d, file_des=%d, fname=%s\n", + n, fnum, file_des, getFunctionName((enum detFuncs)fnum))); + return FAIL; + } else + FILE_LOG(logDEBUG3, ("Received %d bytes\n", n )); + + if (fnum < 0 || fnum >= NUM_DET_FUNCTIONS) { + FILE_LOG(logERROR, ("Unknown function enum %d\n", fnum)); + ret=(M_nofunc)(file_des); + } else { + FILE_LOG(logDEBUG1, (" calling function fnum=%d, (%s)\n", + fnum, getFunctionName((enum detFuncs)fnum))); + ret = (*flist[fnum])(file_des); + + if (ret == FAIL) { + FILE_LOG(logDEBUG1, ("Error executing the function = %d (%s)\n", + fnum, getFunctionName((enum detFuncs)fnum))); + } else FILE_LOG(logDEBUG1, ("Function (%s) executed %s\n", + getFunctionName((enum detFuncs)fnum), getRetName())); + } + return ret; +} + +const char* getRetName() { + switch(ret) { + case OK: return "OK"; + case FAIL: return "FAIL"; + case FORCE_UPDATE: return "FORCE_UPDATE"; + case GOODBYE: return "GOODBYE"; + case REBOOT: return "REBOOT"; + default: return "unknown"; + } +} + +const char* getTimerName(enum timerIndex ind) { + switch (ind) { + case FRAME_NUMBER: return "frame_number"; + case ACQUISITION_TIME: return "acquisition_time"; + case FRAME_PERIOD: return "frame_period"; + case DELAY_AFTER_TRIGGER: return "delay_after_trigger"; + case GATES_NUMBER: return "gates_number"; + case CYCLES_NUMBER: return "cycles_number"; + case ACTUAL_TIME: return "actual_time"; + case MEASUREMENT_TIME: return "measurement_time"; + case PROGRESS: return "progress"; + case MEASUREMENTS_NUMBER: return "measurements_number"; + case FRAMES_FROM_START: return "frames_from_start"; + case FRAMES_FROM_START_PG: return "frames_from_start_pg"; + case SAMPLES: return "samples"; + case SUBFRAME_ACQUISITION_TIME: return "subframe_acquisition_time"; + case SUBFRAME_DEADTIME: return "subframe_deadtime"; + case STORAGE_CELL_NUMBER: return "storage_cell_number"; + case STORAGE_CELL_DELAY: return "storage_cell_delay"; + default: return "unknown_timer"; + } +} + + +const char* getSpeedName(enum speedVariable ind) { + switch (ind) { + case CLOCK_DIVIDER: return "clock_divider"; + case ADC_CLOCK: return "adc_clock"; + case ADC_PHASE: return "adc_phase"; + case ADC_PIPELINE: return "adc_pipeline"; + case DBIT_CLOCK: return "dbit_clock"; + case DBIT_PHASE: return "dbit_phase"; + case DBIT_PIPELINE: return "dbit_pipeline"; + case MAX_ADC_PHASE_SHIFT: return "max_adc_phase_shift"; + case MAX_DBIT_PHASE_SHIFT: return "max_dbit_phase_shift"; + default: return "unknown_speed"; + } +} + +const char* getRunStateName(enum runStatus ind) { + switch (ind) { + case IDLE: return "idle"; + case ERROR: return "error"; + case WAITING: return "waiting"; + case RUN_FINISHED: return "run_finished"; + case TRANSMITTING: return "transmitting"; + case RUNNING: return "running"; + case STOPPED: return "stopped"; + default: return "unknown"; + } +} + +const char* getFunctionName(enum detFuncs func) { + switch (func) { + case F_EXEC_COMMAND: return "F_EXEC_COMMAND"; + case F_GET_DETECTOR_TYPE: return "F_GET_DETECTOR_TYPE"; + case F_SET_EXTERNAL_SIGNAL_FLAG: return "F_SET_EXTERNAL_SIGNAL_FLAG"; + case F_SET_EXTERNAL_COMMUNICATION_MODE: return "F_SET_EXTERNAL_COMMUNICATION_MODE"; + case F_GET_ID: return "F_GET_ID"; + case F_DIGITAL_TEST: return "F_DIGITAL_TEST"; + case F_SET_DAC: return "F_SET_DAC"; + case F_GET_ADC: return "F_GET_ADC"; + case F_WRITE_REGISTER: return "F_WRITE_REGISTER"; + case F_READ_REGISTER: return "F_READ_REGISTER"; + case F_SET_MODULE: return "F_SET_MODULE"; + case F_GET_MODULE: return "F_GET_MODULE"; + case F_SET_SETTINGS: return "F_SET_SETTINGS"; + case F_GET_THRESHOLD_ENERGY: return "F_GET_THRESHOLD_ENERGY"; + case F_START_ACQUISITION: return "F_START_ACQUISITION"; + case F_STOP_ACQUISITION: return "F_STOP_ACQUISITION"; + case F_START_READOUT: return "F_START_READOUT"; + case F_GET_RUN_STATUS: return "F_GET_RUN_STATUS"; + case F_START_AND_READ_ALL: return "F_START_AND_READ_ALL"; + case F_READ_ALL: return "F_READ_ALL"; + case F_SET_TIMER: return "F_SET_TIMER"; + case F_GET_TIME_LEFT: return "F_GET_TIME_LEFT"; + case F_SET_DYNAMIC_RANGE: return "F_SET_DYNAMIC_RANGE"; + case F_SET_READOUT_FLAGS: return "F_SET_READOUT_FLAGS"; + case F_SET_ROI: return "F_SET_ROI"; + case F_SET_SPEED: return "F_SET_SPEED"; + case F_EXIT_SERVER: return "F_EXIT_SERVER"; + case F_LOCK_SERVER: return "F_LOCK_SERVER"; + case F_GET_LAST_CLIENT_IP: return "F_GET_LAST_CLIENT_IP"; + case F_SET_PORT: return "F_SET_PORT"; + case F_UPDATE_CLIENT: return "F_UPDATE_CLIENT"; + case F_CONFIGURE_MAC: return "F_CONFIGURE_MAC"; + case F_LOAD_IMAGE: return "F_LOAD_IMAGE"; + case F_READ_COUNTER_BLOCK: return "F_READ_COUNTER_BLOCK"; + case F_RESET_COUNTER_BLOCK: return "F_RESET_COUNTER_BLOCK"; + case F_ENABLE_TEN_GIGA: return "F_ENABLE_TEN_GIGA"; + case F_SET_ALL_TRIMBITS: return "F_SET_ALL_TRIMBITS"; + case F_SET_PATTERN: return "F_SET_PATTERN"; + case F_SET_PATTERN_MASK: return "F_SET_PATTERN_MASK"; + case F_GET_PATTERN_MASK: return "F_GET_PATTERN_MASK"; + case F_SET_PATTERN_BIT_MASK: return "F_SET_PATTERN_BIT_MASK"; + case F_GET_PATTERN_BIT_MASK: return "F_GET_PATTERN_BIT_MASK"; + case F_WRITE_ADC_REG: return "F_WRITE_ADC_REG"; + case F_SET_COUNTER_BIT: return "F_SET_COUNTER_BIT"; + case F_PULSE_PIXEL: return "F_PULSE_PIXEL"; + case F_PULSE_PIXEL_AND_MOVE: return "F_PULSE_PIXEL_AND_MOVE"; + case F_PULSE_CHIP: return "F_PULSE_CHIP"; + case F_SET_RATE_CORRECT: return "F_SET_RATE_CORRECT"; + case F_GET_RATE_CORRECT: return "F_GET_RATE_CORRECT"; + case F_SET_NETWORK_PARAMETER: return "F_SET_NETWORK_PARAMETER"; + case F_PROGRAM_FPGA: return "F_PROGRAM_FPGA"; + case F_RESET_FPGA: return "F_RESET_FPGA"; + case F_POWER_CHIP: return "F_POWER_CHIP"; + case F_ACTIVATE: return "F_ACTIVATE"; + case F_PREPARE_ACQUISITION: return "F_PREPARE_ACQUISITION"; + case F_THRESHOLD_TEMP: return "F_THRESHOLD_TEMP"; + case F_TEMP_CONTROL: return "F_TEMP_CONTROL"; + case F_TEMP_EVENT: return "F_TEMP_EVENT"; + case F_AUTO_COMP_DISABLE: return "F_AUTO_COMP_DISABLE"; + case F_STORAGE_CELL_START: return "F_STORAGE_CELL_START"; + case F_CHECK_VERSION: return "F_CHECK_VERSION"; + case F_SOFTWARE_TRIGGER: return "F_SOFTWARE_TRIGGER"; + case F_LED: return "F_LED"; + case F_DIGITAL_IO_DELAY: return "F_DIGITAL_IO_DELAY"; + case F_COPY_DET_SERVER: return "F_COPY_DET_SERVER"; + case F_REBOOT_CONTROLLER: return "F_REBOOT_CONTROLLER"; + + default: return "Unknown Function"; + } +} + +void function_table() { + flist[F_EXEC_COMMAND] = &exec_command; + flist[F_GET_DETECTOR_TYPE] = &get_detector_type; + flist[F_SET_EXTERNAL_SIGNAL_FLAG] = &set_external_signal_flag; + flist[F_SET_EXTERNAL_COMMUNICATION_MODE] = &set_external_communication_mode; + flist[F_GET_ID] = &get_id; + flist[F_DIGITAL_TEST] = &digital_test; + flist[F_SET_DAC] = &set_dac; + flist[F_GET_ADC] = &get_adc; + flist[F_WRITE_REGISTER] = &write_register; + flist[F_READ_REGISTER] = &read_register; + flist[F_SET_MODULE] = &set_module; + flist[F_GET_MODULE] = &get_module; + flist[F_SET_SETTINGS] = &set_settings; + flist[F_GET_THRESHOLD_ENERGY] = &get_threshold_energy; + flist[F_START_ACQUISITION] = &start_acquisition; + flist[F_STOP_ACQUISITION] = &stop_acquisition; + flist[F_START_READOUT] = &start_readout; + flist[F_GET_RUN_STATUS] = &get_run_status; + flist[F_START_AND_READ_ALL] = &start_and_read_all; + flist[F_READ_ALL] = &read_all; + flist[F_SET_TIMER] = &set_timer; + flist[F_GET_TIME_LEFT] = &get_time_left; + flist[F_SET_DYNAMIC_RANGE] = &set_dynamic_range; + flist[F_SET_READOUT_FLAGS] = &set_readout_flags; + flist[F_SET_ROI] = &set_roi; + flist[F_SET_SPEED] = &set_speed; + flist[F_EXIT_SERVER] = &exit_server; + flist[F_LOCK_SERVER] = &lock_server; + flist[F_GET_LAST_CLIENT_IP] = &get_last_client_ip; + flist[F_SET_PORT] = &set_port; + flist[F_UPDATE_CLIENT] = &update_client; + flist[F_CONFIGURE_MAC] = &configure_mac; + flist[F_LOAD_IMAGE] = &load_image; + flist[F_READ_COUNTER_BLOCK] = &read_counter_block; + flist[F_RESET_COUNTER_BLOCK] = &reset_counter_block; + flist[F_ENABLE_TEN_GIGA] = &enable_ten_giga; + flist[F_SET_ALL_TRIMBITS] = &set_all_trimbits; + flist[F_SET_PATTERN] = &set_pattern; + flist[F_SET_PATTERN_MASK] = &set_pattern_mask; + flist[F_GET_PATTERN_MASK] = &get_pattern_mask; + flist[F_SET_PATTERN_BIT_MASK] = &set_pattern_bit_mask; + flist[F_GET_PATTERN_BIT_MASK] = &get_pattern_bit_mask; + flist[F_WRITE_ADC_REG] = &write_adc_register; + flist[F_SET_COUNTER_BIT] = &set_counter_bit; + flist[F_PULSE_PIXEL] = &pulse_pixel; + flist[F_PULSE_PIXEL_AND_MOVE] = &pulse_pixel_and_move; + flist[F_PULSE_CHIP] = &pulse_chip; + flist[F_SET_RATE_CORRECT] = &set_rate_correct; + flist[F_GET_RATE_CORRECT] = &get_rate_correct; + flist[F_SET_NETWORK_PARAMETER] = &set_network_parameter; + flist[F_PROGRAM_FPGA] = &program_fpga; + flist[F_RESET_FPGA] = &reset_fpga; + flist[F_POWER_CHIP] = &power_chip; + flist[F_ACTIVATE] = &set_activate; + flist[F_PREPARE_ACQUISITION] = &prepare_acquisition; + flist[F_THRESHOLD_TEMP] = &threshold_temp; + flist[F_TEMP_CONTROL] = &temp_control; + flist[F_TEMP_EVENT] = &temp_event; + flist[F_AUTO_COMP_DISABLE] = &auto_comp_disable; + flist[F_STORAGE_CELL_START] = &storage_cell_start; + flist[F_CHECK_VERSION] = &check_version; + flist[F_SOFTWARE_TRIGGER] = &software_trigger; + flist[F_LED] = &led; + flist[F_DIGITAL_IO_DELAY] = &digital_io_delay; + flist[F_COPY_DET_SERVER] = ©_detector_server; + flist[F_REBOOT_CONTROLLER] = &reboot_controller; + + // check + if (NUM_DET_FUNCTIONS >= RECEIVER_ENUM_START) { + FILE_LOG(logERROR, ("The last detector function enum has reached its limit\nGoodbye!\n")); + exit(EXIT_FAILURE); + } + + int iloop = 0; + for (iloop = 0; iloop < NUM_DET_FUNCTIONS ; ++iloop) { + FILE_LOG(logDEBUG1, ("function fnum=%d, (%s)\n", iloop, + getFunctionName((enum detFuncs)iloop))); + } +} + +void functionNotImplemented() { + ret = FAIL; + sprintf(mess, "Function (%s) is not implemented for this detector\n", + getFunctionName((enum detFuncs)fnum)); + FILE_LOG(logERROR, (mess)); +} + +void modeNotImplemented(char* modename, int mode) { + ret = FAIL; + sprintf(mess, "%s (%d) is not implemented for this detector\n", modename, mode); + FILE_LOG(logERROR,(mess)); +} + +void validate(int arg, int retval, char* modename, enum numberMode nummode) { + if (ret == OK && arg != -1 && retval != arg) { + ret = FAIL; + if (nummode == HEX) + sprintf(mess, "Could not %s. Set 0x%x, but read 0x%x\n", + modename, arg, retval); + else + sprintf(mess, "Could not %s. Set %d, but read %d\n", + modename, arg, retval); + FILE_LOG(logERROR,(mess)); + } +} + +void validate64(int64_t arg, int64_t retval, char* modename, enum numberMode nummode) { + if (ret == OK && arg != -1 && retval != arg) { + ret = FAIL; + if (nummode == HEX) + sprintf(mess, "Could not %s. Set 0x%llx, but read 0x%llx\n", + modename, (long long unsigned int)arg, (long long unsigned int)retval); + else + sprintf(mess, "Could not %s. Set %lld, but read %lld\n", + modename, (long long unsigned int)arg, (long long unsigned int)retval); + FILE_LOG(logERROR,(mess)); + } +} + +int executeCommand(char* command, char* result, enum TLogLevel level) { + const size_t tempsize = 256; + char temp[tempsize]; + memset(temp, 0, tempsize); + memset(result, 0, MAX_STR_LENGTH); + + FILE_LOG(level, ("Executing command:\n[%s]\n", command)); + strcat(command, " 2>&1"); + + fflush(stdout); + FILE* sysFile = popen(command, "r"); + while(fgets(temp, tempsize, sysFile) != NULL) { + // size left excludes terminating character + size_t sizeleft = MAX_STR_LENGTH - strlen(result) - 1; + // more than the command + if (tempsize > sizeleft) { + strncat(result, temp, sizeleft); + break; + } + strncat(result, temp, tempsize); + memset(temp, 0, tempsize); + } + int sucess = pclose(sysFile); + if (strlen(result)) { + if (sucess) { + sucess = FAIL; + FILE_LOG(logERROR, ("%s\n", result)); + } else { + FILE_LOG(level, ("Result:\n[%s]\n", result)); + } + } + return sucess; +} + +int M_nofunc(int file_des) { + ret = FAIL; + memset(mess, 0, sizeof(mess)); + + // to receive any arguments + int n = 1; + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + + sprintf(mess,"Unrecognized Function enum %d. Please do not proceed.\n", fnum); + FILE_LOG(logERROR, (mess)); + return Server_SendResult(file_des, OTHER, NO_UPDATE, NULL, 0); +} + + +// Jungfrau program mode +int M_nofuncMode(int file_des) { + ret = FAIL; + memset(mess, 0, sizeof(mess)); + + // to receive any arguments + int n = 1; + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + + sprintf(mess,"This Function %s cannot be executed as the " + "On-board detector server in update mode.\n" + "Restart detector server in normal mode (without any arguments) to continue.\n", + getFunctionName((enum detFuncs)fnum)); + FILE_LOG(logERROR, (mess)); + return Server_SendResult(file_des, OTHER, NO_UPDATE, NULL, 0); +} + + + + +int exec_command(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + char cmd[MAX_STR_LENGTH] = {0}; + char retval[MAX_STR_LENGTH] = {0}; + + if (receiveData(file_des, cmd, MAX_STR_LENGTH, OTHER) < 0) + return printSocketReadError(); + + // set + if (Server_VerifyLock() == OK) { + ret = executeCommand(cmd, retval, logINFO); + } + return Server_SendResult(file_des, OTHER, NO_UPDATE, retval, sizeof(retval)); +} + + + + +int get_detector_type(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + enum detectorType retval = myDetectorType; + FILE_LOG(logDEBUG1,("Returning detector type %d\n", retval)); + return Server_SendResult(file_des, INT32, NO_UPDATE, &retval, sizeof(retval)); +} + + + + + +int set_external_signal_flag(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[2] = {-1,-1}; + enum externalSignalFlag retval= GET_EXTERNAL_SIGNAL_FLAG; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + + int signalindex = args[0]; + enum externalSignalFlag flag = args[1]; + FILE_LOG(logDEBUG1, ("Setting external signal %d to flag %d\n", signalindex, flag)); + +#ifndef GOTTHARDD + functionNotImplemented(); +#else + if (signalindex > 0) + modeNotImplemented("Signal index", signalindex); + else { + // set + if ((flag != GET_EXTERNAL_SIGNAL_FLAG) && (Server_VerifyLock() == OK)) { + setExtSignal(flag); + } + // get + retval = getExtSignal(); + validate((int)flag, (int)retval, "set external signal flag", DEC); + FILE_LOG(logDEBUG1, ("External Signal Flag: %d\n", retval)); + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + +int set_external_communication_mode(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + enum externalCommunicationMode arg = GET_EXTERNAL_COMMUNICATION_MODE; + enum externalCommunicationMode retval = GET_EXTERNAL_COMMUNICATION_MODE; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Setting external communication mode to %d\n", arg)); + + // set + if ((arg != GET_EXTERNAL_COMMUNICATION_MODE) && (Server_VerifyLock() == OK)) { + switch (arg) { + case AUTO_TIMING: + case TRIGGER_EXPOSURE: +#ifdef EIGERD + case GATED: + case BURST_TRIGGER: +#endif + setTiming(arg); + break; + default: + modeNotImplemented("Timing mode", (int)arg); + break; + } + } + // get + retval = getTiming(); + validate((int)arg, (int)retval, "set timing mode", DEC); + FILE_LOG(logDEBUG1, ("Timing Mode: %d\n",retval)); + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + +int get_id(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + enum idMode arg = 0; + int64_t retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Getting Id %d\n", arg)); + + // get + switch (arg) { +#ifndef GOTTHARDD + case SOFTWARE_FIRMWARE_API_VERSION: + case DETECTOR_SERIAL_NUMBER: +#endif + case DETECTOR_FIRMWARE_VERSION: + case DETECTOR_SOFTWARE_VERSION: + retval = getDetectorId(arg); + FILE_LOG(logDEBUG1, ("Id(%d): %lld\n", retval)); + break; + default: + modeNotImplemented("ID Index", (int)arg); + break; + } + return Server_SendResult(file_des, INT64, UPDATE, &retval, sizeof(retval)); +} + + + + + +int digital_test(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[2] = {-1, -1}; + int retval = -1; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + enum digitalTestMode mode = args[0]; +#ifdef GOTTHARDD + int ival = args[1]; + FILE_LOG(logDEBUG1, ("Digital test, mode = %d, ival:%d\n", mode, ival)); +#else + FILE_LOG(logDEBUG1, ("Digital test, mode = %d\n", mode)); +#endif + +#ifdef EIGERD + functionNotImplemented(); +#else + // only set + if (Server_VerifyLock() == OK) { + switch (mode) { + + case DETECTOR_FIRMWARE_TEST: + case DETECTOR_BUS_TEST: +#ifdef GOTTHARDD + case DIGITAL_BIT_TEST: + retval = detectorTest(mode, ival); + break; +#else + retval = detectorTest(mode); +#endif + FILE_LOG(logDEBUG1, ("Digital Test (%d): %d\n", mode, retval)); + break; + default: + modeNotImplemented("Digital Test Mode", (int)mode); + break; + } + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + + + +int set_dac(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[3] = {-1, -1, -1}; + int retval = -1; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + enum dacIndex ind = args[0]; + int mV = args[1]; + int val = args[2]; + enum DACINDEX serverDacIndex = 0; + + // check if dac exists for this detector + switch (ind) { +#ifdef GOTTHARDD + case G_VREF_DS : + serverDacIndex = VREF_DS; + break; + case G_VCASCN_PB: + serverDacIndex = VCASCN_PB; + break; + case G_VCASCP_PB: + serverDacIndex = VCASCP_PB; + break; + case G_VOUT_CM: + serverDacIndex = VOUT_CM; + break; + case G_VCASC_OUT: + serverDacIndex = VCASC_OUT; + break; + case G_VIN_CM: + serverDacIndex = VIN_CM; + break; + case G_VREF_COMP: + serverDacIndex = VREF_COMP; + break; + case G_IB_TESTC: + serverDacIndex = IB_TESTC; + break; + case HIGH_VOLTAGE: + break; +#elif EIGERD + case TRIMBIT_SIZE: + serverDacIndex = VTR; + break; + case THRESHOLD: + serverDacIndex = VTHRESHOLD; + break; + case E_SvP: + serverDacIndex = SVP; + break; + case E_SvN: + serverDacIndex = SVN; + break; + case E_Vtr: + serverDacIndex = VTR; + break; + case E_Vrf: + serverDacIndex = VRF; + break; + case E_Vrs: + serverDacIndex = VRS; + break; + case E_Vtgstv: + serverDacIndex = VTGSTV; + break; + case E_Vcmp_ll: + serverDacIndex = VCMP_LL; + break; + case E_Vcmp_lr: + serverDacIndex = VCMP_LR; + break; + case E_cal: + serverDacIndex = CAL; + break; + case E_Vcmp_rl: + serverDacIndex = VCMP_RL; + break; + case E_Vcmp_rr: + serverDacIndex = VCMP_RR; + break; + case E_rxb_rb: + serverDacIndex = RXB_RB; + break; + case E_rxb_lb: + serverDacIndex = RXB_LB; + break; + case E_Vcp: + serverDacIndex = VCP; + break; + case E_Vcn: + serverDacIndex = VCN; + break; + case E_Vis: + serverDacIndex = VIS; + break; + case HIGH_VOLTAGE: + case IO_DELAY: + break; +#elif CHIPTESTBOARDD + case ADC_VPP: + case HIGH_VOLTAGE: + break; + case V_POWER_A: + serverDacIndex = D_PWR_A; + break; + case V_POWER_B: + serverDacIndex = D_PWR_B; + break; + case V_POWER_C: + serverDacIndex = D_PWR_C; + break; + case V_POWER_D: + serverDacIndex = D_PWR_D; + break; + case V_POWER_IO: + serverDacIndex = D_PWR_IO; + break; + case V_POWER_CHIP: + serverDacIndex = D_PWR_CHIP; + break; + case V_LIMIT: + break; +#elif MOENCHD + case ADC_VPP: + case HIGH_VOLTAGE: + case V_LIMIT: + break; +#endif + default: +#ifdef JUNGFRAUD + if ((ind == HIGH_VOLTAGE) || (ind < NDAC_OLDBOARD)) { //for compatibility with old board + serverDacIndex = ind; + break; + } +#elif CHIPTESTBOARDD + if (ind < NDAC_ONLY) { + serverDacIndex = ind; + break; + } +#elif MOENCHD + if (ind < NDAC) { + serverDacIndex = ind; + break; + } +#endif + modeNotImplemented("Dac Index", (int)ind); + break; + } + + // index exists + if (ret == OK) { + + FILE_LOG(logDEBUG1, ("Setting DAC %d to %d %s\n", serverDacIndex, val, + (mV ? "mV" : "dac units"))); + + // set & get + if ((val == -1) || (Server_VerifyLock() == OK)) { + switch(ind) { + + // adc vpp +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) + case ADC_VPP: + if (val < 0 || val > AD9257_GetMaxValidVref()) { + ret = FAIL; + sprintf(mess,"Could not set dac. Adc Vpp value should be between 0 and %d\n", AD9257_GetMaxValidVref()); + FILE_LOG(logERROR,(mess)); + } else { + AD9257_SetVrefVoltage(val); + retval = val; // cannot read + } + break; +#endif + + // io delay +#ifdef EIGERD + case IO_DELAY: + retval = setIODelay(val); + FILE_LOG(logDEBUG1, ("IODelay: %d\n", retval)); + validate(val, retval, "set iodelay", DEC); + break; +#endif + + // high voltage + case HIGH_VOLTAGE: + retval = setHighVoltage(val); + FILE_LOG(logDEBUG1, ("High Voltage: %d\n", retval)); +#if defined(JUNGFRAUD) || defined (CHIPTESTBOARDD) || defined(MOENCHD) + validate(val, retval, "set high voltage", DEC); +#endif +#ifdef GOTTHARDD + if (retval == -1) { + ret = FAIL; + strcpy(mess,"Invalid Voltage. Valid values are 0, 90, 110, 120, 150, 180, 200\n"); + FILE_LOG(logERROR,(mess)); + } else + validate(val, retval, "set high voltage", DEC); +#elif EIGERD + if ((retval != SLAVE_HIGH_VOLTAGE_READ_VAL) && (retval < 0)) { + ret = FAIL; + if (retval == -1) + sprintf(mess, "Setting high voltage failed. Bad value %d. " + "The range is from 0 to 200 V.\n",val); + else if (retval == -2) + strcpy(mess, "Setting high voltage failed. " + "Serial/i2c communication failed.\n"); + else if (retval == -3) + strcpy(mess, "Getting high voltage failed. " + "Serial/i2c communication failed.\n"); + FILE_LOG(logERROR,(mess)); + } +#endif + break; + + // power, vlimit +#ifdef CHIPTESTBOARDD + case V_POWER_A: + case V_POWER_B: + case V_POWER_C: + case V_POWER_D: + case V_POWER_IO: + if (val != -1) { + if (!mV) { + ret = FAIL; + sprintf(mess,"Could not set power. Power regulator %d should be in mV and not dac units.\n", ind); + FILE_LOG(logERROR,(mess)); + } else if (checkVLimitCompliant(val) == FAIL) { + ret = FAIL; + sprintf(mess,"Could not set power. Power regulator %d exceeds voltage limit %d.\n", ind, getVLimit()); + FILE_LOG(logERROR,(mess)); + } else if (!isPowerValid(serverDacIndex, val)) { + ret = FAIL; + sprintf(mess,"Could not set power. Power regulator %d should be between %d and %d mV\n", + ind, (serverDacIndex == D_PWR_IO ? VIO_MIN_MV : POWER_RGLTR_MIN), (VCHIP_MAX_MV - VCHIP_POWER_INCRMNT)); + FILE_LOG(logERROR,(mess)); + } else { + setPower(serverDacIndex, val); + + } + } + retval = getPower(serverDacIndex); + FILE_LOG(logDEBUG1, ("Power regulator(%d): %d\n", ind, retval)); + validate(val, retval, "set power regulator", DEC); + break; + + + case V_POWER_CHIP: + if (val >= 0) { + ret = FAIL; + sprintf(mess,"Can not set Vchip. Can only be set automatically in the background (+200mV from highest power regulator voltage).\n"); + FILE_LOG(logERROR,(mess)); + /* restrict users from setting vchip + if (!mV) { + ret = FAIL; + sprintf(mess,"Could not set Vchip. Should be in mV and not dac units.\n"); + FILE_LOG(logERROR,(mess)); + } else if (!isVchipValid(val)) { + ret = FAIL; + sprintf(mess,"Could not set Vchip. Should be between %d and %d mV\n", VCHIP_MIN_MV, VCHIP_MAX_MV); + FILE_LOG(logERROR,(mess)); + } else { + setVchip(val); + } + */ + } + retval = getVchip(); + FILE_LOG(logDEBUG1, ("Vchip: %d\n", retval)); + if (ret == OK && val != -1 && val != -100 && retval != val) { + ret = FAIL; + sprintf(mess, "Could not set vchip. Set %d, but read %d\n", val, retval); + FILE_LOG(logERROR,(mess)); + } + break; +#endif + +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) + case V_LIMIT: + if (val >= 0) { + if (!mV) { + ret = FAIL; + strcpy(mess,"Could not set power. VLimit should be in mV and not dac units.\n"); + FILE_LOG(logERROR,(mess)); + } else { + setVLimit(val); + } + } + retval = getVLimit(); + FILE_LOG(logDEBUG1, ("VLimit: %d\n", retval)); + validate(val, retval, "set vlimit", DEC); + break; +#endif + + // dacs + default: + if (mV && val > DAC_MAX_MV) { + ret = FAIL; + sprintf(mess,"Could not set dac %d to value %d. Allowed limits (0 - %d mV).\n", ind, val, DAC_MAX_MV); + FILE_LOG(logERROR,(mess)); + } else if (!mV && val > getMaxDacSteps() ) { + ret = FAIL; + sprintf(mess,"Could not set dac %d to value %d. Allowed limits (0 - %d dac units).\n", ind, val, getMaxDacSteps()); + FILE_LOG(logERROR,(mess)); + } else { +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) + if ((val != -1 && mV && checkVLimitCompliant(val) == FAIL) || + (val != -1 && !mV && checkVLimitDacCompliant(val) == FAIL)) { + ret = FAIL; + sprintf(mess,"Could not set dac %d to value %d. " + "Exceeds voltage limit %d.\n", + ind, (mV ? val : dacToVoltage(val)), getVLimit()); + FILE_LOG(logERROR,(mess)); + } else +#endif + setDAC(serverDacIndex, val, mV); + retval = getDAC(serverDacIndex, mV); + } +#ifdef EIGERD + if (val != -1) { + //changing dac changes settings to undefined + switch(serverDacIndex) { + case VCMP_LL: + case VCMP_LR: + case VCMP_RL: + case VCMP_RR: + case VRF: + case VCP: + setSettings(UNDEFINED); + FILE_LOG(logERROR, ("Settings has been changed " + "to undefined (changed specific dacs)\n")); + break; + default: + break; + } + } +#endif + //check + if (ret == OK) { + if ((abs(retval - val) <= 5) || val == -1) { + ret = OK; + } else { + ret = FAIL; + sprintf(mess,"Setting dac %d : wrote %d but read %d\n", serverDacIndex, val, retval); + FILE_LOG(logERROR,(mess)); + } + } + FILE_LOG(logDEBUG1, ("Dac (%d): %d %s\n\n", serverDacIndex, retval, (mV ? "mV" : "dac units"))); + break; + } + } + } + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + + + +int get_adc(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + enum dacIndex ind = 0; + int retval = -1; + + if (receiveData(file_des, &ind, sizeof(ind), INT32) < 0) + return printSocketReadError(); + +#ifdef MOENCHD + functionNotImplemented(); +#else + enum ADCINDEX serverAdcIndex = 0; + + // get + switch (ind) { +#if defined(GOTTHARDD) || defined(JUNGFRAUD) + case TEMPERATURE_FPGA: + serverAdcIndex = TEMP_FPGA; + break; + case TEMPERATURE_ADC: + serverAdcIndex = TEMP_ADC; + break; +#elif EIGERD + case TEMPERATURE_FPGAEXT: + serverAdcIndex = TEMP_FPGAEXT; + break; + case TEMPERATURE_10GE: + serverAdcIndex = TEMP_10GE; + break; + case TEMPERATURE_DCDC: + serverAdcIndex = TEMP_DCDC; + break; + case TEMPERATURE_SODL: + serverAdcIndex = TEMP_SODL; + break; + case TEMPERATURE_SODR: + serverAdcIndex = TEMP_SODR; + break; + case TEMPERATURE_FPGA: + serverAdcIndex = TEMP_FPGA; + break; + case TEMPERATURE_FPGA2: + serverAdcIndex = TEMP_FPGAFEBL; + break; + case TEMPERATURE_FPGA3: + serverAdcIndex = TEMP_FPGAFEBR; + break; +#elif CHIPTESTBOARDD + case V_POWER_A: + serverAdcIndex = V_PWR_A; + break; + case V_POWER_B: + serverAdcIndex = V_PWR_B; + break; + case V_POWER_C: + serverAdcIndex = V_PWR_C; + break; + case V_POWER_D: + serverAdcIndex = V_PWR_D; + break; + case V_POWER_IO: + serverAdcIndex = V_PWR_IO; + break; + case I_POWER_A: + serverAdcIndex = I_PWR_A; + break; + case I_POWER_B: + serverAdcIndex = I_PWR_B; + break; + case I_POWER_C: + serverAdcIndex = I_PWR_C; + break; + case I_POWER_D: + serverAdcIndex = I_PWR_D; + break; + case I_POWER_IO: + serverAdcIndex = I_PWR_IO; + break; +#endif + default: +#ifdef CHIPTESTBOARDD + if (ind >= SLOW_ADC0 && ind <= SLOW_ADC_TEMP) { + serverAdcIndex = ind; + break; + } +#endif + modeNotImplemented("Adc Index", (int)ind); + break; + } + + // valid index + if (ret == OK) { + FILE_LOG(logDEBUG1, ("Getting ADC %d\n", serverAdcIndex)); + retval = getADC(serverAdcIndex); + FILE_LOG(logDEBUG1, ("ADC(%d): %d\n", serverAdcIndex, retval)); + } +#endif + + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + + +int write_register(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + uint32_t args[2] = {-1, -1}; + uint32_t retval = -1; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + uint32_t addr = args[0]; + uint32_t val = args[1]; + FILE_LOG(logDEBUG1, ("Writing to register 0x%x, data 0x%x\n", addr, val)); + + // only set + if (Server_VerifyLock() == OK) { +#ifdef GOTTHARDD + retval = writeRegister16And32(addr, val); +#else + retval = writeRegister(addr, val); +#endif + // validate + if (retval != val) { + ret = FAIL; + sprintf(mess,"Could not write to register 0x%x. Wrote 0x%x but read 0x%x\n", addr, val, retval); + FILE_LOG(logERROR,(mess)); + } + FILE_LOG(logDEBUG1, ("Write register (0x%x): 0x%x\n", retval)); + } + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + + +int read_register(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + uint32_t addr = -1; + uint32_t retval = -1; + + if (receiveData(file_des, &addr, sizeof(addr), INT32) < 0) + return printSocketReadError(); + + FILE_LOG(logDEBUG1, ("Reading from register 0x%x\n", addr)); + + // get +#ifdef GOTTHARDD + retval = readRegister16And32(addr); +#else + retval = readRegister(addr); +#endif + FILE_LOG(logINFO, ("Read register (0x%x): 0x%x\n", addr, retval)); + + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + +int set_module(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + enum detectorSettings retval = -1; + +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) + functionNotImplemented(); +#else + + sls_detector_module module; + int *myDac = NULL; + int *myChan = NULL; + module.dacs = NULL; + module.chanregs = NULL; + + // allocate to receive arguments + // allocate dacs + myDac = (int*)malloc(getNumberOfDACs() * sizeof(int)); + // error + if (getNumberOfDACs() > 0 && myDac == NULL) { + ret = FAIL; + sprintf(mess, "Could not allocate dacs\n"); + FILE_LOG(logERROR,(mess)); + } else + module.dacs = myDac; + +#ifdef EIGERD + // allocate chans + if (ret == OK) { + myChan = (int*)malloc(getTotalNumberOfChannels() * sizeof(int)); + if (getTotalNumberOfChannels() > 0 && myChan == NULL) { + ret = FAIL; + sprintf(mess,"Could not allocate chans\n"); + FILE_LOG(logERROR,(mess)); + } else + module.chanregs = myChan; + } +#endif + // receive arguments + if (ret == OK) { + module.nchip = getNumberOfChips(); + module.nchan = getTotalNumberOfChannels(); + module.ndac = getNumberOfDACs(); + int ts = receiveModule(file_des, &module); + if (ts < 0) { + if (myChan != NULL) free(myChan); + if (myDac != NULL) free(myDac); + return printSocketReadError(); + } + FILE_LOG(logDEBUG1, ("module register is %d, nchan %d, nchip %d, " + "ndac %d, iodelay %d, tau %d, eV %d\n", + module.reg, module.nchan, module.nchip, + module.ndac, module.iodelay, module.tau, module.eV)); + // should at least have a dac + if (ts <= sizeof(sls_detector_module)) { + ret = FAIL; + sprintf(mess, "Cannot set module. Received incorrect number of dacs or channels\n"); + FILE_LOG(logERROR,(mess)); + } + } + + // receive all arguments + if (ret == FAIL) { + int n = 1; + while (n > 0) + n = receiveData(file_des, mess, MAX_STR_LENGTH, OTHER); + } + + // only set + else if (Server_VerifyLock() == OK) { + // check index + switch (module.reg) { +#ifdef EIGERD + case STANDARD: + case HIGHGAIN: + case LOWGAIN: + case VERYHIGHGAIN: + case VERYLOWGAIN: +#elif JUNGFRAUD + case GET_SETTINGS: + case DYNAMICGAIN: + case DYNAMICHG0: + case FIXGAIN1: + case FIXGAIN2: + case FORCESWITCHG1: + case FORCESWITCHG2: +#elif GOTTHARDD + case GET_SETTINGS: + case DYNAMICGAIN: + case HIGHGAIN: + case LOWGAIN: + case MEDIUMGAIN: + case VERYHIGHGAIN: +#endif + break; + default: + modeNotImplemented("Settings", (int)module.reg); + break; + } + + ret = setModule(module, mess); + retval = getSettings(); + validate(module.reg, (int)retval, "set module (settings)", DEC); + FILE_LOG(logDEBUG1, ("Settings: %d\n", retval)); + } + if (myChan != NULL) free(myChan); + if (myDac != NULL) free(myDac); +#endif + + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + +int get_module(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + sls_detector_module module; + int *myDac = NULL; + int *myChan = NULL; + module.dacs = NULL; + module.chanregs = NULL; + + // allocate to send arguments + // allocate dacs + myDac = (int*)malloc(getNumberOfDACs() * sizeof(int)); + // error + if (getNumberOfDACs() > 0 && myDac == NULL) { + ret = FAIL; + sprintf(mess, "Could not allocate dacs\n"); + FILE_LOG(logERROR,(mess)); + } else + module.dacs = myDac; + +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) + functionNotImplemented(); +#endif + +#ifdef EIGERD + // allocate chans + if (ret == OK) { + myChan = (int*)malloc(getTotalNumberOfChannels() * sizeof(int)); + if (getTotalNumberOfChannels() > 0 && myChan == NULL) { + ret = FAIL; + sprintf(mess,"Could not allocate chans\n"); + FILE_LOG(logERROR,(mess)); + } else + module.chanregs=myChan; + } +#endif + + // get module + if (ret == OK) { + module.nchip = getNumberOfChips(); + module.nchan = getTotalNumberOfChannels(); + module.ndac = getNumberOfDACs(); + + // only get + FILE_LOG(logDEBUG1, ("Getting module\n")); +#if !defined(CHIPTESTBOARDD) && !defined(MOENCHD) + getModule(&module); +#endif + FILE_LOG(logDEBUG1, ("Getting module. Settings:%d\n", module.reg)); + } + + Server_SendResult(file_des, INT32, UPDATE, NULL, 0); + + // send module, 0 is to receive partially (without trimbits etc) + if (ret != FAIL) { + ret = sendModule(file_des, &module); + } + if (myChan != NULL) free(myChan); + if (myDac != NULL) free(myDac); + return ret; +} + + + + + + +int set_settings(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + enum detectorSettings isett = GET_SETTINGS; + enum detectorSettings retval = GET_SETTINGS; + + if (receiveData(file_des, &isett, sizeof(isett), INT32) < 0) + return printSocketReadError(); + +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) + functionNotImplemented(); +#else + FILE_LOG(logDEBUG1, ("Setting settings %d\n", isett)); + + //set & get + if ((isett == GET_SETTINGS) || (Server_VerifyLock() == OK)) { + + // check index + switch(isett) { + case GET_SETTINGS: +#ifdef JUNGFRAUD + case DYNAMICGAIN: + case DYNAMICHG0: + case FIXGAIN1: + case FIXGAIN2: + case FORCESWITCHG1: + case FORCESWITCHG2: +#elif GOTTHARDD + case DYNAMICGAIN: + case HIGHGAIN: + case LOWGAIN: + case MEDIUMGAIN: + case VERYHIGHGAIN: +#endif + break; + default: + if (myDetectorType == EIGER) { + ret = FAIL; + sprintf(mess, "Cannot set settings via SET_SETTINGS, use SET_MODULE\n"); + FILE_LOG(logERROR,(mess)); + } else + modeNotImplemented("Settings Index", (int)isett); + break; + } + + // if index is okay, set & get + if (ret == OK) { + retval = setSettings(isett); + FILE_LOG(logDEBUG1, ("Settings: %d\n", retval)); + validate((int)isett, (int)retval, "set settings", DEC); +#if defined(JUNGFRAUD) || defined (GOTTHARDD) + if (ret == OK && isett >= 0) { + ret = setDefaultDacs(); + if (ret == FAIL) { + strcpy(mess,"Could change settings, but could not set to default dacs\n"); + FILE_LOG(logERROR,(mess)); + } + } +#endif + } + } +#endif + + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + + +int get_threshold_energy(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int retval = -1; + + FILE_LOG(logDEBUG1, ("Getting Threshold energy\n")); +#ifndef EIGERD + functionNotImplemented(); +#else + // only get + retval = getThresholdEnergy(); + FILE_LOG(logDEBUG1, ("Threshold energy: %d eV\n", retval)); +#endif + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + + + +int start_acquisition(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + + FILE_LOG(logDEBUG1, ("Starting Acquisition\n")); + // only set + if (Server_VerifyLock() == OK) { + ret = startStateMachine(); + if (ret == FAIL) { +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) + sprintf(mess, "Could not start acquisition. Could not create udp socket in server. Check rx_udpip & rx_udpport.\n"); +#else + sprintf(mess, "Could not start acquisition\n"); +#endif + FILE_LOG(logERROR,(mess)); + } + FILE_LOG(logDEBUG2, ("Starting Acquisition ret: %d\n", ret)); + } + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + + + +int stop_acquisition(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + + FILE_LOG(logDEBUG1, ("Stopping Acquisition\n")); + // only set + if (Server_VerifyLock() == OK) { + ret = stopStateMachine(); + if (ret == FAIL) { + sprintf(mess, "Could not stop acquisition\n"); + FILE_LOG(logERROR,(mess)); + } + FILE_LOG(logDEBUG1, ("Stopping Acquisition ret: %d\n", ret)); + } + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + + + + + +int start_readout(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + + FILE_LOG(logDEBUG1, ("Starting readout\n")); +#ifndef EIGERD + functionNotImplemented(); +#else + // only set + if (Server_VerifyLock() == OK) { + ret = startReadOut(); + if (ret == FAIL) { + sprintf(mess, "Could not start readout\n"); + FILE_LOG(logERROR,(mess)); + } + FILE_LOG(logDEBUG1, ("Starting readout ret: %d\n", ret)); + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + + + + + + +int get_run_status(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + enum runStatus retval = ERROR; + + FILE_LOG(logDEBUG1, ("Getting status\n")); + // only get + retval = getRunStatus(); + FILE_LOG(logDEBUG1, ("Status: %d\n", retval)); + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + + +int start_and_read_all(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + + FILE_LOG(logDEBUG1, ("Starting Acquisition and read all frames\n")); + // start state machine + FILE_LOG(logDEBUG1, ("Starting Acquisition\n")); + // only set + if (Server_VerifyLock() == OK) { + ret = startStateMachine(); + if (ret == FAIL) { +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) + sprintf(mess, "Could not start acquisition. Could not create udp socket in server. Check rx_udpip & rx_udpport.\n"); +#else + sprintf(mess, "Could not start acquisition\n"); +#endif + FILE_LOG(logERROR,(mess)); + } + FILE_LOG(logDEBUG2, ("Starting Acquisition ret: %d\n", ret)); + + } + + // lock or acquisition start error + if (ret == FAIL) + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); + + // read all (again validate lock, but should pass and not fail) + return read_all(file_des); +} + + + + +int read_all(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + + FILE_LOG(logDEBUG1, ("Reading all frames\n")); + // only set + if (Server_VerifyLock() == OK) { + readFrame(&ret, mess); + } + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + + + + + + +int set_timer(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int64_t args[2] = {-1,-1}; + int64_t retval = -1; + + if (receiveData(file_des, args, sizeof(args), INT64) < 0) + return printSocketReadError(); + enum timerIndex ind = (int)args[0]; + int64_t tns = args[1]; + char timerName[50] = {0}; + strcpy(timerName, getTimerName(ind)); +#ifdef EIGERD + int64_t subexptime = 0; +#endif + FILE_LOG(logDEBUG1, ("Setting timer %s(%d) to %lld ns\n", timerName, (int)ind, tns)); + + // set & get + if ((tns == -1) || (Server_VerifyLock() == OK)) { + + // check index + switch (ind) { + case FRAME_NUMBER: + case ACQUISITION_TIME: + case FRAME_PERIOD: + case CYCLES_NUMBER: +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) + case SAMPLES: +#endif +#ifndef EIGERD + case DELAY_AFTER_TRIGGER: +#endif + retval = setTimer(ind, tns); + break; +#ifdef JUNGFRAUD + case STORAGE_CELL_NUMBER: + if (tns > MAX_STORAGE_CELL_VAL) { + ret = FAIL; + strcpy(mess,"Max Storage cell number should not exceed 15\n"); + FILE_LOG(logERROR,(mess)); + break; + } + retval = setTimer(ind,tns); + break; + + case STORAGE_CELL_DELAY: + if (tns > MAX_STORAGE_CELL_DLY_NS_VAL) { + ret = FAIL; + sprintf(mess,"Max Storage cell delay value should not exceed %d ns\n", MAX_STORAGE_CELL_DLY_NS_VAL); + FILE_LOG(logERROR,(mess)); + break; + } + retval = setTimer(ind,tns); + break; +#endif +#ifdef EIGERD + case SUBFRAME_ACQUISITION_TIME: + if (tns > ((int64_t)MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS*10) ) { + ret = FAIL; + strcpy(mess,"Sub Frame exposure time should not exceed 5.368 seconds\n"); + FILE_LOG(logERROR,(mess)); + break; + } + retval = setTimer(ind,tns); + break; + case SUBFRAME_DEADTIME: + subexptime = setTimer(SUBFRAME_ACQUISITION_TIME, -1); + if ((tns + subexptime) > ((int64_t)MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS*10) ) { + ret = FAIL; + sprintf(mess,"Sub Frame Period should not exceed 5.368 seconds. " + "So sub frame dead time should not exceed %lfu seconds " + "(subexptime = %lf seconds)\n", + ((((int64_t)MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS*10) - subexptime)/1E9), + (subexptime/1E9)); + FILE_LOG(logERROR,(mess)); + break; + } + retval = setTimer(ind,tns); + break; +#endif + default: + modeNotImplemented(timerName, (int)ind); + break; + } + + // validate + if (ret != FAIL) { + char vtimerName[50] = {0}; + sprintf(vtimerName, "set %s", timerName); +#ifdef EIGERD + validate64(tns, retval, vtimerName, DEC); // copied to server, not read from detector register +#else + switch(ind) { + case FRAME_NUMBER: + case CYCLES_NUMBER: + case STORAGE_CELL_NUMBER: + validate64(tns, retval, vtimerName, DEC); // no conversion, so all good + break; + case SAMPLES: + if (retval == -1) { + ret = FAIL; + retval = setTimer(ind, -1); + sprintf(mess, "Could not set samples to %lld. Could not allocate RAM\n", + (long long unsigned int)tns); + FILE_LOG(logERROR,(mess)); + } else + validate64(tns, retval, vtimerName, DEC); // no conversion, so all good + case ACQUISITION_TIME: + case FRAME_PERIOD: + case DELAY_AFTER_TRIGGER: + case SUBFRAME_ACQUISITION_TIME: + case SUBFRAME_DEADTIME: + case STORAGE_CELL_DELAY: + // losing precision due to conversion to clock (also gotthard master delay is different) + if (validateTimer(ind, tns, retval) == FAIL) { + ret = FAIL; + sprintf(mess, "Could not %s. Set %lld, but read %lld\n", vtimerName, + (long long unsigned int)tns, (long long unsigned int)retval); + FILE_LOG(logERROR,(mess)); + } + break; + + default: + break; + } +#endif + } + } + if (ret != FAIL) { + FILE_LOG(logDEBUG1, ("Timer index %d: %lld\n", ind, retval)); + } + return Server_SendResult(file_des, INT64, UPDATE, &retval, sizeof(retval)); +} + + + + + + + +int get_time_left(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + enum timerIndex ind = -1; + int64_t retval = -1; + + if (receiveData(file_des, &ind, sizeof(ind), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Getting timer left index %d\n", ind)); + + // only get + // check index +#ifdef JUNGFRAUD + if (ind == DELAY_AFTER_TRIGGER) { + ret = FAIL; + sprintf(mess,"Timer Left Index (%d) is not implemented for this release.\n", (int)ind); + FILE_LOG(logERROR,(mess)); + } +#endif + if (ret == OK) { + switch(ind) { +#ifdef EIGERD + case MEASURED_PERIOD: + case MEASURED_SUBPERIOD: +#elif JUNGFRAUD + case FRAMES_FROM_START: + case FRAMES_FROM_START_PG: + case ACTUAL_TIME: + case MEASUREMENT_TIME: + case FRAME_NUMBER: + case FRAME_PERIOD: + case DELAY_AFTER_TRIGGER: + case CYCLES_NUMBER: +#elif GOTTHARDD + case ACQUISITION_TIME: + case FRAME_NUMBER: + case FRAME_PERIOD: + case DELAY_AFTER_TRIGGER: + case CYCLES_NUMBER: +#elif CHIPTESTBOARDD + case FRAMES_FROM_START: + case FRAMES_FROM_START_PG: + case ACTUAL_TIME: + case MEASUREMENT_TIME: + case FRAME_NUMBER: + case FRAME_PERIOD: + case DELAY_AFTER_TRIGGER: + case CYCLES_NUMBER: +#elif MOENCHD + case FRAMES_FROM_START: + case FRAMES_FROM_START_PG: + case ACTUAL_TIME: + case MEASUREMENT_TIME: + case FRAME_NUMBER: + case FRAME_PERIOD: + case DELAY_AFTER_TRIGGER: + case CYCLES_NUMBER: +#endif + retval = getTimeLeft(ind); + FILE_LOG(logDEBUG1, ("Timer left index %d: %lld\n", ind, retval)); + break; + default: + modeNotImplemented("Timer left index", (int)ind); + break; + } + } + return Server_SendResult(file_des, INT64, UPDATE, &retval, sizeof(retval)); +} + + + + + + +int set_dynamic_range(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int dr = -1; + int retval = -1; + + if (receiveData(file_des, &dr, sizeof(dr), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Setting dr to %d\n", dr)); + + // set & get + if ((dr == -1) || (Server_VerifyLock() == OK)) { + +#ifdef EIGERD + int old_dr = setDynamicRange(-1); +#endif + // check dr + switch(dr) { + case -1: + case 16: +#ifdef EIGERD + case 4: case 8: case 32: +#endif + retval = setDynamicRange(dr); + FILE_LOG(logDEBUG1, ("Dynamic range: %d\n", retval)); + validate(dr, retval, "set dynamic range", DEC); + break; + default: + modeNotImplemented("Dynamic range", dr); + break; + } + +#ifdef EIGERD + if (dr != -1 && getRateCorrectionEnable()) { + // 4 or 8 bit, switch off rate corr (only if dr worked) + if ((dr != 32) && (dr != 16) && (ret == OK)) { + setRateCorrection(0); + ret = FAIL; + strcpy(mess,"Switching off Rate Correction. Must be in 32 or 16 bit mode\n"); + FILE_LOG(logERROR,(mess)); + } + + // 16, 32 (diff from old value), set new tau in rate table(-1), if it didnt work, give error + else if ((dr == 16 || dr == 32) && (old_dr != dr)) { + setRateCorrection(-1); //tau_ns will not be -1 here + // it didnt work + if (!getRateCorrectionEnable()) { + ret = FAIL; + strcpy(mess,"Deactivating Rate Correction. Could not set it.\n"); + FILE_LOG(logERROR,(mess)); + } + } + } +#endif + } + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + + + +int set_readout_flags(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + enum readOutFlags arg = GET_READOUT_FLAGS; + enum readOutFlags retval = GET_READOUT_FLAGS; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Setting readout flags to %d\n", arg)); + +#if defined(JUNGFRAUD) || defined(GOTTHARDD) || defined(MOENCHD) + functionNotImplemented(); +#else + // set & get + if ((arg == GET_READOUT_FLAGS) || (Server_VerifyLock() == OK)) { + + switch(arg) { + case GET_READOUT_FLAGS: +#ifdef EIGERD + case STORE_IN_RAM: + case CONTINOUS_RO: + case PARALLEL: + case NONPARALLEL: + case SAFE: + case SHOW_OVERFLOW: + case NOOVERFLOW: +#elif CHIPTESTBOARDD + case NORMAL_READOUT: + case DIGITAL_ONLY: + case ANALOG_AND_DIGITAL: +#endif + retval = setReadOutFlags(arg); + FILE_LOG(logDEBUG1, ("Read out flags: 0x%x\n", retval)); + validate((int)arg, (int)(retval & arg), "set readout flag", HEX); +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) + if (retval == -2) { + ret = FAIL; + sprintf(mess, "Readout Flags failed. Cannot allocate RAM\n"); + FILE_LOG(logERROR,(mess)); + } +#endif + break; + default: + modeNotImplemented("Read out flag index", (int)arg); + break; + } + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + + + +int set_roi(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int narg = -1; + ROI arg[MAX_ROIS]; + int nretval = -1; + ROI* retval = NULL; + + // receive number of ROIs + if (receiveData(file_des, &narg, sizeof(narg), INT32) < 0) + return printSocketReadError(); + // receive ROIs + { + int iloop = 0; + for (iloop = 0; iloop < narg; ++iloop) { + if (receiveData(file_des, &arg[iloop].xmin, sizeof(int), INT32) < 0) + return printSocketReadError(); + if (receiveData(file_des, &arg[iloop].xmax, sizeof(int), INT32) < 0) + return printSocketReadError(); + if (receiveData(file_des, &arg[iloop].ymin, sizeof(int), INT32) < 0) + return printSocketReadError(); + if (receiveData(file_des, &arg[iloop].ymax, sizeof(int), INT32) < 0) + return printSocketReadError(); + } + } + FILE_LOG(logDEBUG1, ("Set ROI (narg:%d)\n", narg)); + { + int iloop = 0; + for (iloop = 0; iloop < narg; ++iloop) { + FILE_LOG(logDEBUG1, ("%d: %d\t%d\t%d\t%d\n", + arg[iloop].xmin, arg[iloop].xmax, arg[iloop].ymin, arg[iloop].ymax)); + } + } + +#if defined(JUNGFRAUD) || defined(EIGERD) + functionNotImplemented(); +#else + // set & get + if ((narg == GET_READOUT_FLAGS) || (Server_VerifyLock() == OK)) { + if (myDetectorType == GOTTHARD && narg > 1) { + ret = FAIL; + strcpy(mess,"Can not set more than one ROI per module.\n"); + FILE_LOG(logERROR,(mess)); + } else { + retval = setROI(narg, arg, &nretval, &ret); + if (ret == FAIL) { + if (nretval == -1) // chip test board + sprintf(mess,"Could not set ROI. Max ROI level (100) reached!\n"); + else if (nretval == -2) + sprintf(mess, "Could not set ROI. Could not allocate RAM\n"); + else + sprintf(mess,"Could not set all roi. " + "Set %d rois, but read %d rois\n", narg, nretval); + FILE_LOG(logERROR,(mess)); + } + FILE_LOG(logDEBUG1, ("nRois: %d\n", nretval)); + } + } +#endif + + Server_SendResult(file_des, INT32, UPDATE, NULL, 0); + + if (ret != FAIL) { + //retvalsize could be swapped during sendData + int nretval1 = nretval; + sendData(file_des, &nretval1, sizeof(nretval1), INT32); + int iloop = 0; + for(iloop = 0; iloop < nretval; ++iloop) { + sendData(file_des, &retval[iloop].xmin, sizeof(int), INT32); + sendData(file_des, &retval[iloop].xmax, sizeof(int), INT32); + sendData(file_des, &retval[iloop].ymin, sizeof(int), INT32); + sendData(file_des, &retval[iloop].ymax, sizeof(int), INT32); + } + } + return ret; +} + + + + + +int set_speed(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[3] = {-1, -1, -1}; + int retval = -1; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + + enum speedVariable ind = args[0]; + int val = args[1]; + int mode = args[2]; + + char speedName[20] = {0}; + strcpy(speedName, getSpeedName(ind)); + FILE_LOG(logDEBUG1, ("Setting speed index %s (speedVariable %d) to %d (mode: %d)\n", speedName, ind, val, mode)); + + // check index + switch(ind) { +#ifdef JUNGFRAUD + case ADC_PHASE: + case CLOCK_DIVIDER: + case MAX_ADC_PHASE_SHIFT: +#elif CHIPTESTBOARDD + case ADC_PHASE: + case DBIT_PHASE: + case MAX_ADC_PHASE_SHIFT: + case MAX_DBIT_PHASE_SHIFT: + case ADC_CLOCK: + case DBIT_CLOCK: + case CLOCK_DIVIDER: + case ADC_PIPELINE: + case DBIT_PIPELINE: +#elif MOENCHD + case ADC_PHASE: + case DBIT_PHASE: + case MAX_ADC_PHASE_SHIFT: + case MAX_DBIT_PHASE_SHIFT: + case ADC_CLOCK: + case DBIT_CLOCK: + case CLOCK_DIVIDER: + case ADC_PIPELINE: + case DBIT_PIPELINE: +#elif GOTTHARDD + case ADC_PHASE: +#elif EIGERD + case CLOCK_DIVIDER: +#endif + break; + default: + modeNotImplemented(speedName, (int)ind); + break; + } +#if (!defined(CHIPTESTBOARDD)) && (!defined(MOENCHD)) && (!defined(JUNGFRAUD)) + if (ret == OK && mode == 1) { + ret = FAIL; + strcpy(mess, "deg is not defined for this detector.\n"); + FILE_LOG(logERROR,(mess)); + } +#endif + + if (ret == OK) { + // set + if ((val != -1) && (Server_VerifyLock() == OK)) { +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) || defined(JUNGFRAUD) + setSpeed(ind, val, mode); +#else + setSpeed(ind, val); +#endif + } + // get +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) || defined(JUNGFRAUD) + retval = getSpeed(ind, mode); +#else + retval = getSpeed(ind); +#endif + FILE_LOG(logDEBUG1, ("%s: %d (mode:%d)\n", speedName, retval, mode)); + // validate + char validateName[20] = {0}; + sprintf(validateName, "set %s", speedName); +#ifndef GOTTHARDD +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) || defined(JUNGFRAUD) + if ((ind == ADC_PHASE || ind == DBIT_PHASE) && mode == 1) { +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) + ret = validatePhaseinDegrees(ind, val, retval); +#else + ret = validatePhaseinDegrees(val, retval); +#endif + if (ret == FAIL) { + sprintf(mess, "Could not set %s. Set %d, got %d\n", validateName, val, retval); + FILE_LOG(logERROR,(mess)); + } + } else + validate(val, retval, validateName, DEC); +#else + validate(val, retval, validateName, DEC); +#endif +#endif + } + + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + + + +int exit_server(int file_des) { + FILE_LOG(logINFORED, ("Closing Server\n")); + ret = OK; + memset(mess, 0, sizeof(mess)); + Server_SendResult(file_des, INT32, NO_UPDATE, NULL, 0); + return GOODBYE; +} + + + + +int lock_server(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int lock = 0; + + if (receiveData(file_des, &lock, sizeof(lock), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Locking Server to %d\n", lock)); + + // set + if (lock >= 0) { + if (!lockStatus || // if it was unlocked, anyone can lock + (!strcmp(lastClientIP, thisClientIP)) || // if it was locked, need same ip + (!strcmp(lastClientIP,"none"))) { // if it was locked, must be by "none" + lockStatus = lock; + if (lock) { + FILE_LOG(logINFO, ("Server lock to %s\n", lastClientIP)); + } else { + FILE_LOG(logINFO, ("Server unlocked\n")); + } + strcpy(lastClientIP, thisClientIP); + } else { + Server_LockedError(); + } + } + int retval = lockStatus; + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + +int get_last_client_ip(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + return Server_SendResult(file_des, OTHER, UPDATE, lastClientIP, sizeof(lastClientIP)); +} + + + + +int set_port(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int p_number = -1; + char oldLastClientIP[INET_ADDRSTRLEN] = {0}; + + if (receiveData(file_des, &p_number, sizeof(p_number), INT32) < 0) + return printSocketReadError(); + + // set only + int sd = -1; + if ((Server_VerifyLock() == OK)) { + // port number too low + if (p_number < 1024) { + ret = FAIL; + sprintf(mess,"%s port Number (%d) too low\n", + (isControlServer ? "control":"stop"), p_number); + FILE_LOG(logERROR,(mess)); + } else { + FILE_LOG(logINFO, ("Setting %s port to %d\n", + (isControlServer ? "control":"stop"), p_number)); + strcpy(oldLastClientIP, lastClientIP); + sd = bindSocket(p_number); + } + } + + Server_SendResult(file_des, INT32, UPDATE, &p_number, sizeof(p_number)); + // delete old socket + if (ret != FAIL) { + closeConnection(file_des); + exitServer(sockfd); + sockfd = sd; + strcpy(lastClientIP, oldLastClientIP); + } + return ret; +} + + + + +int update_client(int file_des) { + ret = FORCE_UPDATE; + memset(mess, 0, sizeof(mess)); + Server_SendResult(file_des, INT32, NO_UPDATE, NULL, 0); + return send_update(file_des); +} + + + + +int send_update(int file_des) { + ret = OK; + int n = 0; + int i32 = -1; + int64_t i64 = -1; + + n = sendData(file_des,lastClientIP,sizeof(lastClientIP),OTHER); + if (n < 0) return printSocketReadError(); + + // dr + i32 = setDynamicRange(GET_FLAG); + n = sendData(file_des,&i32,sizeof(i32),INT32); + if (n < 0) return printSocketReadError(); + + // databytes + i32 = calculateDataBytes(); + n = sendData(file_des,&i32,sizeof(i32),INT32); + if (n < 0) return printSocketReadError(); + + // settings +#if defined(EIGERD) || defined(JUNGFRAUD) || defined(GOTTHARDD) + i32 = (int)getSettings(); + n = sendData(file_des,&i32,sizeof(i32),INT32); + if (n < 0) return printSocketReadError(); +#endif + + // threshold energy +#ifdef EIGERD + i32 = getThresholdEnergy(GET_FLAG); + n = sendData(file_des,&i32,sizeof(i32),INT32); + if (n < 0) return printSocketReadError(); +#endif + + // #frames + i64 = setTimer(FRAME_NUMBER,GET_FLAG); + n = sendData(file_des,&i64,sizeof(i64),INT64); + if (n < 0) return printSocketReadError(); + + // exptime + i64 = setTimer(ACQUISITION_TIME,GET_FLAG); + n = sendData(file_des,&i64,sizeof(i64),INT64); + if (n < 0) return printSocketReadError(); + + // subexptime, subdeadtime +#ifdef EIGERD + i64 = setTimer(SUBFRAME_ACQUISITION_TIME,GET_FLAG); + n = sendData(file_des,&i64,sizeof(i64),INT64); + if (n < 0) return printSocketReadError(); + + i64 = setTimer(SUBFRAME_DEADTIME,GET_FLAG); + n = sendData(file_des,&i64,sizeof(i64),INT64); + if (n < 0) return printSocketReadError(); +#endif + + // period + i64 = setTimer(FRAME_PERIOD,GET_FLAG); + n = sendData(file_des,&i64,sizeof(i64),INT64); + if (n < 0) return printSocketReadError(); + + // delay +#ifndef EIGERD + i64 = setTimer(DELAY_AFTER_TRIGGER,GET_FLAG); + n = sendData(file_des,&i64,sizeof(i64),INT64); + if (n < 0) return printSocketReadError(); +#endif + + // #storage cell, storage_cell_delay +#ifdef JUNGFRAUD + i64 = setTimer(STORAGE_CELL_NUMBER,GET_FLAG); + n = sendData(file_des,&i64,sizeof(i64),INT64); + if (n < 0) return printSocketReadError(); + + i64 = setTimer(STORAGE_CELL_DELAY,GET_FLAG); + n = sendData(file_des,&i64,sizeof(i64),INT64); + if (n < 0) return printSocketReadError(); +#endif + + // #cycles + i64 = setTimer(CYCLES_NUMBER,GET_FLAG); + n = sendData(file_des,&i64,sizeof(i64),INT64); + if (n < 0) return printSocketReadError(); + + // readout flags +#if defined(EIGERD) || defined(CHIPTESTBOARDD) + i32 = setReadOutFlags(GET_READOUT_FLAGS); + n = sendData(file_des,&i32,sizeof(i32),INT32); + if (n < 0) return printSocketReadError(); +#endif + + // #samples, roi +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) || defined(GOTTHARDD) + i64 = setTimer(SAMPLES,GET_FLAG); + n = sendData(file_des,&i64,sizeof(i64),INT64); + if (n < 0) return printSocketReadError(); + + // roi + ROI* retval = NULL; + ROI arg[1]; + int ret = OK, nretval = 0; + retval = setROI(-1, arg, &nretval, &ret); + //retvalsize could be swapped during sendData + int nretval1 = nretval; + sendData(file_des, &nretval1, sizeof(nretval1), INT32); + int iloop = 0; + for(iloop = 0; iloop < nretval; ++iloop) { + sendData(file_des, &retval[iloop].xmin, sizeof(int), INT32); + sendData(file_des, &retval[iloop].xmax, sizeof(int), INT32); + sendData(file_des, &retval[iloop].ymin, sizeof(int), INT32); + sendData(file_des, &retval[iloop].ymax, sizeof(int), INT32); + } + + +#endif + + if (lockStatus == 0) { + strcpy(lastClientIP,thisClientIP); + } + + return ret; +} + + + + + + +int configure_mac(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + const size_t array_size = 50; + const size_t n_args = 14; + const size_t n_retvals = 2; + char args[n_args][array_size]; + char retvals[n_retvals][array_size]; + + memset(args, 0, sizeof(args)); + memset(retvals, 0, sizeof(retvals)); + + if (receiveData(file_des, args, sizeof(args), OTHER) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("\n Configuring MAC\n")); + + // dest port + uint32_t dstPort = 0; + sscanf(args[0], "%x", &dstPort); + FILE_LOG(logDEBUG1, ("Dst Port: %x\n", dstPort)); + // dest ip + uint32_t dstIp = 0; + sscanf(args[1], "%x", &dstIp); + FILE_LOG(logDEBUG1, ("Dst Ip Addr: %d.%d.%d.%d = 0x%x \n", + (dstIp >> 24) & 0xff, (dstIp >> 16) & 0xff, (dstIp >> 8) & 0xff, (dstIp) & 0xff, + dstIp)); + // dest mac + uint64_t dstMac = 0; +#ifdef VIRTUAL + sscanf(args[2], "%lx", &dstMac); +#else + sscanf(args[2], "%llx", &dstMac); +#endif + FILE_LOG(logDEBUG1, ("Dst Mac Addr: (0x) ")); + { + int iloop = 5; + for (iloop = 5; iloop >= 0; --iloop) { + printf ("%x", (unsigned int)(((dstMac >> (8 * iloop)) & 0xFF))); + if (iloop > 0) { + printf(":"); + } + } + } + FILE_LOG(logDEBUG1, (" = %llx\n", dstMac)); + // source ip + uint32_t srcIp = 0; + sscanf(args[3], "%x", &srcIp); + FILE_LOG(logDEBUG1, ("Src Ip Addr: %d.%d.%d.%d = 0x%x \n", + (srcIp >> 24) & 0xff, (srcIp >> 16) & 0xff, (srcIp >> 8) & 0xff, (srcIp) & 0xff, + srcIp)); + // source mac + uint64_t srcMac = 0; +#ifdef VIRTUAL + sscanf(args[4], "%lx", &srcMac); +#else + sscanf(args[4], "%llx", &srcMac); +#endif + FILE_LOG(logDEBUG1, ("Src Mac Addr: (0x) ")); + { + int iloop = 5; + for (iloop = 5; iloop >= 0; --iloop) { + printf("%x", (unsigned int)(((srcMac >> (8 * iloop)) & 0xFF))); + if (iloop > 0) { + printf(":"); + } + } + } + FILE_LOG(logDEBUG1, (" = %llx\n", srcMac)); + +#if defined(JUNGFRAUD) || defined(EIGERD) + // source port 2 + uint32_t dstPort2 = 0; + sscanf(args[5], "%x", &dstPort2); + FILE_LOG(logDEBUG1, ("Dst Port2: %x\n", dstPort2)); +#endif +#ifdef JUNGFRAUD + // dest ip2 + uint32_t dstIp2 = 0; + sscanf(args[6], "%x", &dstIp2); + FILE_LOG(logDEBUG1, ("Dst Ip Addr: %d.%d.%d.%d = 0x%x \n", + (dstIp2 >> 24) & 0xff, (dstIp2 >> 16) & 0xff, (dstIp2 >> 8) & 0xff, (dstIp2) & 0xff, + dstIp2)); + // dest mac2 + uint64_t dstMac2 = 0; +#ifdef VIRTUAL + sscanf(args[7], "%lx", &dstMac2); +#else + sscanf(args[7], "%llx", &dstMac2); +#endif + FILE_LOG(logDEBUG1, ("Dst Mac Addr: (0x) ")); + { + int iloop = 5; + for (iloop = 5; iloop >= 0; --iloop) { + printf ("%x", (unsigned int)(((dstMac2 >> (8 * iloop)) & 0xFF))); + if (iloop > 0) { + printf(":"); + } + } + } + FILE_LOG(logDEBUG1, (" = %llx\n", dstMac2)); + // source ip2 + uint32_t srcIp2 = 0; + sscanf(args[8], "%x", &srcIp2); + FILE_LOG(logDEBUG1, ("Src Ip Addr: %d.%d.%d.%d = 0x%x \n", + (srcIp2 >> 24) & 0xff, (srcIp2 >> 16) & 0xff, (srcIp2 >> 8) & 0xff, (srcIp2) & 0xff, + srcIp2)); + // source mac2 + uint64_t srcMac2 = 0; +#ifdef VIRTUAL + sscanf(args[9], "%lx", &srcMac2); +#else + sscanf(args[9], "%llx", &srcMac2); +#endif + FILE_LOG(logDEBUG1, ("Src Mac Addr: (0x) ")); + { + int iloop = 5; + for (iloop = 5; iloop >= 0; --iloop) { + printf("%x", (unsigned int)(((srcMac2 >> (8 * iloop)) & 0xFF))); + if (iloop > 0) { + printf(":"); + } + } + } + FILE_LOG(logDEBUG1, (" = %llx\n", srcMac2)); + + // number of interfaces + int numInterfaces = 0; + sscanf(args[10], "%d", &numInterfaces); + int selInterface = 1; + sscanf(args[11], "%d", &selInterface); + +#endif +#if defined(JUNGFRAUD) || defined(EIGERD) + int pos[2] = {0, 0}; + sscanf(args[12], "%x", &pos[0]); + sscanf(args[13], "%x", &pos[1]); + FILE_LOG(logDEBUG1, ("Position: [%d, %d]\n", pos[0], pos[1])); +#endif + + + // set only + if ((Server_VerifyLock() == OK)) { + + // stop detector if it was running + enum runStatus status = getRunStatus(); + if (status != IDLE && status != RUN_FINISHED && status != STOPPED) { + if (status == RUNNING) + stopStateMachine(); +#ifndef EIGERD + cleanFifos(); +#endif + status = getRunStatus(); + if (status != IDLE && status != RUN_FINISHED && status != STOPPED) { + ret = FAIL; + sprintf(mess, "Cannot configure mac when detector is not idle. Detector at %s state\n", getRunStateName(status)); + FILE_LOG(logERROR,(mess)); + } + } + + if (ret == OK) { +#ifdef EIGERD + // change mac to hardware mac + if (srcMac != getDetectorMAC()) { + FILE_LOG(logWARNING, ("actual detector mac address %llx does not match " + "the one from client %llx\n", + (long long unsigned int)getDetectorMAC(), + (long long unsigned int)srcMac)); + srcMac = getDetectorMAC(); + FILE_LOG(logWARNING,("matched detectormac to the hardware mac now\n")); + } + + // always remember the ip sent from the client (could be for 10g(if not dhcp)) + if (srcIp != getDetectorIP()) + dhcpipad = srcIp; + + //only for 1Gbe, change ip to hardware ip + if (!enableTenGigabitEthernet(-1)) { + FILE_LOG(logWARNING, ("Using DHCP IP for Configuring MAC\n")); + srcIp = getDetectorIP(); + } + // 10 gbe (use ip given from client) + else + srcIp = dhcpipad; + ret = configureMAC(dstIp, dstMac, srcMac, srcIp, dstPort, dstPort2); +#elif JUNGFRAUD + ret = configureMAC(numInterfaces, selInterface, dstIp, dstMac, srcMac, srcIp, dstPort, dstIp2, dstMac2, srcMac2, srcIp2, dstPort2); +#else + ret = configureMAC(dstIp, dstMac, srcMac, srcIp, dstPort); +#endif +#if defined(CHIPTESTBOARDD) || defined(MOENCHD) + if (ret != OK) { + if (ret == FAIL) + sprintf(mess,"Could not configure mac because of incorrect udp 1G destination IP and port\n"); + else if (ret == -1) + sprintf(mess, "Could not allocate RAM\n"); + FILE_LOG(logERROR,(mess)); + } +#else + if (ret == FAIL) { + sprintf(mess,"Configure Mac failed\n"); + FILE_LOG(logERROR,(mess)); + } +#endif + else { + FILE_LOG(logINFO, ("\tConfigure MAC successful\n")); + } +#if defined(EIGERD) || defined (JUNGFRAUD) + if (ret != FAIL) { + ret = setDetectorPosition(pos); + if (ret == FAIL) { + sprintf(mess, "Could not set detector position\n"); + FILE_LOG(logERROR,(mess)); + } + } +#endif + // set retval vals + if (ret != FAIL) { + sprintf(retvals[0],"%llx", (long long unsigned int)srcMac); + sprintf(retvals[1],"%x", srcIp); + } + } + } + + return Server_SendResult(file_des, OTHER, UPDATE, retvals, sizeof(retvals)); +} + + + + + +int load_image(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[2] = {-1, -1}; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + + enum imageType index = args[0]; + int numChannels = args[1]; + short int imageVals[numChannels]; + memset(imageVals, 0, numChannels * sizeof(short int)); + if (numChannels > 0) { + if (receiveData(file_des, imageVals, numChannels * sizeof(short int), OTHER) < 0) { + return printSocketReadError(); + } + } + FILE_LOG(logDEBUG1, ("Loading %s image (ind:%d)\n", (index == DARK_IMAGE) ? "dark" : + ((index == GAIN_IMAGE) ? "gain" : "unknown"), index)); + +#ifndef GOTTHARDD + functionNotImplemented(); +#else + + // set only + if (Server_VerifyLock() == OK) { + switch (index) { + case DARK_IMAGE : + case GAIN_IMAGE : + // size of image does not match expected size + if (numChannels != (calculateDataBytes()/sizeof(short int))) { + ret = FAIL; + sprintf(mess, "Could not load image. " + "Number of Channels do not match. Expected %d, got %d\n", + calculateDataBytes(), numChannels); + FILE_LOG(logERROR,(mess)); + } else + loadImage(index, imageVals); + break; + default: + modeNotImplemented("Image index", (int)index); + break; + } + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + + + + + + +int read_counter_block(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[2] = {-1, -1}; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + int startACQ = args[0]; + int numChannels = args[1]; + short int retval[numChannels]; + memset(retval, 0, numChannels * sizeof(short int)); + FILE_LOG(logDEBUG1, ("Read counter block with start acq bit: %d\n", startACQ)); + +#ifndef GOTTHARDD + functionNotImplemented(); +#else + + // only set + if (Server_VerifyLock() == OK) { + // size of image does not match expected size + if (numChannels != (calculateDataBytes()/sizeof(short int))) { + ret = FAIL; + sprintf(mess, "Could not load image. " + "Number of Channels do not match. Expected %d, got %d\n", + calculateDataBytes(), numChannels); + FILE_LOG(logERROR,(mess)); + } else { + ret = readCounterBlock(startACQ, retval); + if (ret == FAIL) { + strcpy(mess, "Could not read counter block\n"); + FILE_LOG(logERROR,(mess)); + } + } + } +#endif + return Server_SendResult(file_des, OTHER, UPDATE, retval, numChannels * sizeof(short int)); +} + + + + + +int reset_counter_block(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int startACQ = -1; + + if (receiveData(file_des, &startACQ, sizeof(startACQ), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Reset counter block with start acq bit: %d\n", startACQ)); + +#ifndef GOTTHARDD + functionNotImplemented(); +#else + // only set + if (Server_VerifyLock() == OK) { + ret = resetCounterBlock(startACQ); + if (ret == FAIL) { + strcpy(mess, "Could not reset counter block\n"); + FILE_LOG(logERROR, (mess)); + } + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + + + + + +int enable_ten_giga(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Enable/ Disable 10GbE : %d\n", arg)); + +#if defined(JUNGFRAUD) || defined(GOTTHARDD) + functionNotImplemented(); +#else + // set & get + if ((arg == -1) || (Server_VerifyLock() == OK)) { + retval = enableTenGigabitEthernet(arg); + FILE_LOG(logDEBUG1, ("10GbE: %d\n", retval)); + validate(arg, retval, "enable/disable 10GbE", DEC); + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + +int set_all_trimbits(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Set all trmbits to %d\n", arg)); + +#ifndef EIGERD + functionNotImplemented(); +#else + + // set + if (arg >= 0 && Server_VerifyLock() == OK) { + ret = setAllTrimbits(arg); + //changes settings to undefined + setSettings(UNDEFINED); + FILE_LOG(logERROR, ("Settings has been changed to undefined (change all trimbits)\n")); + } + // get + retval = getAllTrimbits(); + FILE_LOG(logDEBUG1, ("All trimbits: %d\n", retval)); + validate(arg, retval, "set all trimbits", DEC); +#endif + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + +int set_pattern(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + + // receive mode + uint64_t arg = -1; + if (receiveData(file_des, &arg, sizeof(arg), INT64) < 0) + return printSocketReadError(); + int mode = (int)arg; + FILE_LOG(logDEBUG1, ("Setting Pattern: mode %d\n", mode)); + + + + // mode 0: control or word + if (mode == 0) { + // receive arguments + uint64_t args[2] = {-1, -1}; + if (receiveData(file_des, args, sizeof(args), INT64) < 0) + return printSocketReadError(); + int64_t retval64 = -1; + +#if !defined(CHIPTESTBOARDD) && !defined(MOENCHD) + functionNotImplemented(); + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +#else + int addr = (int)args[0]; + uint64_t word = args[1]; + FILE_LOG(logDEBUG1, (" addr:0x%x word:0x%llx\n", addr, word)); + + if ((word == -1) || (Server_VerifyLock() == OK)) { + + // address for set word should be valid (if not -1 or -2, it goes to setword) + if (addr < -2 || addr > MAX_PATTERN_LENGTH) { + ret = FAIL; + sprintf(mess, "Cannot set Pattern (Word, addr:0x%x). Addr must be <= 0x%x\n", + addr, MAX_PATTERN_LENGTH); + FILE_LOG(logERROR, (mess)); + } else { + char tempName[100]; + memset(tempName, 0, 100); + + switch (addr) { + case -1: + strcpy(tempName, "Pattern (I/O Control Register)"); + FILE_LOG(logDEBUG1, (" Setting %s, word to 0x%llx\n", tempName, (long long int) word)); + retval64 = writePatternIOControl(word); + FILE_LOG(logDEBUG1, (" %s: 0x%llx\n", tempName, (long long int)retval64)); + validate64(word, retval64, tempName, HEX); + break; + case -2: + strcpy(tempName, "Pattern (Clock Control Register)"); + FILE_LOG(logDEBUG1, (" Setting %s, word to 0x%llx\n", tempName, (long long int) word)); + retval64 = writePatternClkControl(word); + FILE_LOG(logDEBUG1, (" %s: 0x%llx\n", tempName, (long long int)retval64)); + validate64(word, retval64, tempName, HEX); + break; + default: + sprintf(tempName, "Pattern (Word, addr:0x%x)", addr); + FILE_LOG(logDEBUG1, (" Setting %s, word to 0x%llx\n", tempName, (long long int) word)); + retval64 = writePatternWord(addr, word); + FILE_LOG(logDEBUG1, (" %s: 0x%llx\n", tempName, (long long int)retval64)); + // do not validate as it can be different due to masking + //validate64(word, retval64, tempName, HEX); + break; + } + } + } +#endif + return Server_SendResult(file_des, INT64, UPDATE, &retval64, sizeof(retval64)); + } + + + + // mode 1: pattern loop + else if (mode == 1) { + // receive arguments + uint64_t args[4] = {-1, -1, -1, -1}; + if (receiveData(file_des, args, sizeof(args), INT64) < 0) + return printSocketReadError(); + int retvals[3] = {-1, -1, -1}; + +#if !defined(CHIPTESTBOARDD) && !defined(MOENCHD) + functionNotImplemented(); + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +#else + int loopLevel = (int)args[0]; + int startAddr = (int)args[1]; + int stopAddr = (int)args[2]; + int numLoops = (int)args[3]; + FILE_LOG(logDEBUG1, (" loopLevel:%d startAddr:0x%x stopAddr:0x%x numLoops:%d\n", loopLevel, startAddr, stopAddr, numLoops)); + + if (loopLevel < -1 || loopLevel > 2) { // -1 complete pattern + ret = FAIL; + sprintf(mess, "Pattern (Pattern Loop) Level (%d) is not implemented for this detector\n", loopLevel); + FILE_LOG(logERROR,(mess)); + } + + // level 0-2, addr upto patternlength + 1 + else if ((loopLevel != -1) && (startAddr > MAX_PATTERN_LENGTH || stopAddr > MAX_PATTERN_LENGTH )) { + ret = FAIL; + sprintf(mess, "Cannot set Pattern (Pattern Loop, level:%d, startaddr:0x%x, stopaddr:0x%x). " + "Addr must be <= 0x%x\n", + loopLevel, startAddr, stopAddr, MAX_PATTERN_LENGTH); + FILE_LOG(logERROR, (mess)); + } + + //level -1, addr upto patternlength + else if ((loopLevel == -1) && (startAddr > MAX_PATTERN_LENGTH || stopAddr > MAX_PATTERN_LENGTH)) { + ret = FAIL; + sprintf(mess, "Cannot set Pattern (Pattern Loop, complete pattern, startaddr:0x%x, stopaddr:0x%x). " + "Addr must be <= 0x%x\n", + startAddr, stopAddr, MAX_PATTERN_LENGTH); + FILE_LOG(logERROR, (mess)); + } + + else if ((startAddr == -1 && stopAddr == -1 && numLoops == -1) || (Server_VerifyLock() == OK)) { + setPatternLoop(loopLevel, &startAddr, &stopAddr, &numLoops); + } + retvals[0] = startAddr; + retvals[1] = stopAddr; + retvals[2] = numLoops; +#endif + return Server_SendResult(file_des, INT32, UPDATE, retvals, sizeof(retvals)); + } + + + + // mode 2: wait address + else if (mode == 2) { + // receive arguments + uint64_t args[2] = {-1, -1}; + if (receiveData(file_des, args, sizeof(args), INT64) < 0) + return printSocketReadError(); + int retval32 = -1; + +#if !defined(CHIPTESTBOARDD) && !defined(MOENCHD) + functionNotImplemented(); + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +#else + int loopLevel = (int)args[0]; + int addr = (int)args[1]; + FILE_LOG(logDEBUG1, (" loopLevel:%d addr:0x%x\n", loopLevel, addr)); + + if ((addr == -1) || (Server_VerifyLock() == OK)) { + if (loopLevel < 0 || loopLevel > 2) { + ret = FAIL; + sprintf(mess, "Pattern (Wait Address) Level (0x%x) is not implemented for this detector\n", loopLevel); + FILE_LOG(logERROR,(mess)); + } else if (addr > MAX_PATTERN_LENGTH) { + ret = FAIL; + sprintf(mess, "Cannot set Pattern (Wait Address, addr:0x%x). Addr must be <= 0x%x\n", + addr, MAX_PATTERN_LENGTH); + FILE_LOG(logERROR, (mess)); + } else { + char tempName[100]; + memset(tempName, 0, 100); + sprintf(tempName, "Pattern (Wait Address, Level:%d)", loopLevel); + + FILE_LOG(logDEBUG1, (" Setting %s to 0x%x\n", tempName, addr)); + retval32 = setPatternWaitAddress(loopLevel, addr); + FILE_LOG(logDEBUG1, (" %s: 0x%x\n", tempName, retval32)); + validate(addr, retval32, tempName, HEX); + } + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, &retval32, sizeof(retval32)); + } + + + + // mode 3: wait time + else if (mode == 3) { + // receive arguments + uint64_t args[2] = {-1, -1}; + if (receiveData(file_des, args, sizeof(args), INT64) < 0) + return printSocketReadError(); + int64_t retval64 = -1; + +#if !defined(CHIPTESTBOARDD) && !defined(MOENCHD) + functionNotImplemented(); + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +#else + int loopLevel = (int)args[0]; + uint64_t timeval = args[1]; + FILE_LOG(logDEBUG1, (" loopLevel:%d timeval:0x%lld\n", loopLevel, timeval)); + + if ((timeval == -1) || (Server_VerifyLock() == OK)) { + if (loopLevel < 0 || loopLevel > 2) { + ret = FAIL; + sprintf(mess, "Pattern (Wait Time) Level (%d) is not implemented for this detector\n", loopLevel); + FILE_LOG(logERROR,(mess)); + } else { + char tempName[100]; + memset(tempName, 0, 100); + sprintf(tempName, "Pattern (Wait Time, Level:%d)", loopLevel); + + FILE_LOG(logDEBUG1, (" Setting %s to 0x%lld\n", tempName, (long long int)timeval)); + retval64 = setPatternWaitTime(loopLevel, timeval); + FILE_LOG(logDEBUG1, (" %s: 0x%lld\n", tempName, (long long int)retval64)); + validate64(timeval, retval64, tempName, HEX); + } + } +#endif + return Server_SendResult(file_des, INT64, UPDATE, &retval64, sizeof(retval64)); + } + + + // mode not defined + else { + ret = FAIL; + sprintf(mess, "Pattern mode index (%d) is not implemented for this detector\n", mode); + FILE_LOG(logERROR,(mess)); + return Server_SendResult(file_des, INT64, UPDATE, NULL, 0); + } +} + +int set_pattern_mask(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + uint64_t arg = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT64) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Set Pattern Mask to %d\n", arg)); + +#if (!defined(MOENCHD)) && (!defined(CHIPTESTBOARDD)) + functionNotImplemented(); +#else + // only set + if (Server_VerifyLock() == OK) { + setPatternMask(arg); + uint64_t retval64 = getPatternMask(); + FILE_LOG(logDEBUG1, ("Pattern mask: 0x%llx\n", (long long unsigned int) retval64)); + validate64(arg, retval64, "Set Pattern Mask", HEX); + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + +int get_pattern_mask(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + uint64_t retval64 = -1; + + FILE_LOG(logDEBUG1, ("Get Pattern Mask\n")); + +#if (!defined(MOENCHD)) && (!defined(CHIPTESTBOARDD)) + functionNotImplemented(); +#else + // only get + retval64 = getPatternMask(); + FILE_LOG(logDEBUG1, ("Get Pattern mask: 0x%llx\n", (long long unsigned int) retval64)); + +#endif + return Server_SendResult(file_des, INT64, UPDATE, &retval64, sizeof(retval64)); +} + +int set_pattern_bit_mask(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + uint64_t arg = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT64) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Set Pattern Bit Mask to %d\n", arg)); + +#if (!defined(MOENCHD)) && (!defined(CHIPTESTBOARDD)) + functionNotImplemented(); +#else + // only set + if (Server_VerifyLock() == OK) { + setPatternBitMask(arg); + uint64_t retval64 = getPatternBitMask(); + FILE_LOG(logDEBUG1, ("Pattern bit mask: 0x%llx\n", (long long unsigned int) retval64)); + validate64(arg, retval64, "Set Pattern Bit Mask", HEX); + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + +int get_pattern_bit_mask(int file_des){ + ret = OK; + memset(mess, 0, sizeof(mess)); + uint64_t retval64 = -1; + + FILE_LOG(logDEBUG1, ("Get Pattern Bit Mask\n")); + +#if (!defined(MOENCHD)) && (!defined(CHIPTESTBOARDD)) + functionNotImplemented(); +#else + // only get + retval64 = getPatternBitMask(); + FILE_LOG(logDEBUG1, ("Get Pattern Bitmask: 0x%llx\n", (long long unsigned int) retval64)); + +#endif + return Server_SendResult(file_des, INT64, UPDATE, &retval64, sizeof(retval64)); +} + +int write_adc_register(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + uint32_t args[2] = {-1, -1}; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + uint32_t addr = args[0]; + uint32_t val = args[1]; + FILE_LOG(logDEBUG1, ("Writing 0x%x to ADC Register 0x%x\n", val, addr)); + +#ifdef EIGERD + functionNotImplemented(); +#else +#ifndef VIRTUAL + // only set + if (Server_VerifyLock() == OK) { +#if defined(JUNGFRAUD) || defined(CHIPTESTBOARDD) || defined(MOENCHD) + AD9257_Set(addr, val); +#elif GOTTHARDD + if (getBoardRevision() == 1) { + AD9252_Set(addr, val); + } else { + AD9257_Set(addr, val); + } +#endif + } +#endif +#endif + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + + + + +int set_counter_bit(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Set counter bit with value: %d\n", arg)); + +#ifndef EIGERD + functionNotImplemented(); +#else + + // set + if (arg >= 0 && Server_VerifyLock() == OK) { + setCounterBit(arg); + } + // get + retval = setCounterBit(-1); + FILE_LOG(logDEBUG1, ("Set counter bit retval: %d\n", retval)); + validate(arg, retval, "set counter bit", DEC); +#endif + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + + +int pulse_pixel(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[3] = {-1,-1,-1}; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Pulse pixel, n: %d, x: %d, y: %d\n", args[0], args[1], args[2])); + +#ifndef EIGERD + functionNotImplemented(); +#else + // only set + if (Server_VerifyLock() == OK) { + ret = pulsePixel(args[0], args[1], args[2]); + if (ret == FAIL) { + strcpy(mess, "Could not pulse pixel\n"); + FILE_LOG(logERROR,(mess)); + } + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + + + + +int pulse_pixel_and_move(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[3] = {-1,-1,-1}; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Pulse pixel and move, n: %d, x: %d, y: %d\n", + args[0], args[1], args[2])); + +#ifndef EIGERD + functionNotImplemented(); +#else + // only set + if (Server_VerifyLock() == OK) { + ret = pulsePixelNMove(args[0], args[1], args[2]); + if (ret == FAIL) { + strcpy(mess, "Could not pulse pixel and move\n"); + FILE_LOG(logERROR,(mess)); + } + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + + + + + + +int pulse_chip(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Pulse chip: %d\n", arg)); + +#ifndef EIGERD + functionNotImplemented(); +#else + // only set + if (Server_VerifyLock() == OK) { + ret = pulseChip(arg); + if (ret == FAIL) { + strcpy(mess, "Could not pulse chip\n"); + FILE_LOG(logERROR,(mess)); + } + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + + + + + +int set_rate_correct(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int64_t tau_ns = -1; + + if (receiveData(file_des, &tau_ns, sizeof(tau_ns), INT64) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Set rate correct with tau %lld\n", (long long int)tau_ns)); + +#ifndef EIGERD + functionNotImplemented(); +#else + // only set + if (Server_VerifyLock() == OK) { + + int dr = setDynamicRange(-1); + + // switching on in wrong bit mode + if ((tau_ns != 0) && (dr != 32) && (dr != 16)) { + ret = FAIL; + strcpy(mess,"Rate correction Deactivated, must be in 32 or 16 bit mode\n"); + FILE_LOG(logERROR,(mess)); + } + + // switching on in right mode + else { + if (tau_ns < 0) + tau_ns = getDefaultSettingsTau_in_nsec(); + else if (tau_ns > 0) { + //changing tau to a user defined value changes settings to undefined + setSettings(UNDEFINED); + FILE_LOG(logERROR, ("Settings has been changed to undefined (tau changed)\n")); + } + int64_t retval = setRateCorrection(tau_ns); + validate64(tau_ns, retval, "set rate correction", DEC); + } + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + + + + + +int get_rate_correct(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int64_t retval = -1; + + FILE_LOG(logDEBUG1, ("Getting rate correction\n")); +#ifndef EIGERD + functionNotImplemented(); +#else + retval = getCurrentTau(); + FILE_LOG(logDEBUG1, ("Tau: %lld\n", (long long int)retval)); +#endif + return Server_SendResult(file_des, INT64, UPDATE, &retval, sizeof(retval)); +} + + + + + +int set_network_parameter(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int args[2] = {-1,-1}; + int retval = -1; + + if (receiveData(file_des, args, sizeof(args), INT32) < 0) + return printSocketReadError(); + enum networkParameter mode = args[0]; + int value = args[1]; + FILE_LOG(logDEBUG1, ("Set network parameter index %d to %d\n", mode, value)); + +#if defined(GOTTHARDD) || defined (CHIPTESTBOARDD) || defined(MOENCHD) + functionNotImplemented(); +#else + enum NETWORKINDEX serverIndex = 0; + + // set & get + if ((value == -1) || (Server_VerifyLock() == OK)) { + // check index + switch (mode) { +#ifdef EIGERD + case FLOW_CONTROL_10G: + serverIndex = FLOWCTRL_10G; + break; + case DETECTOR_TXN_DELAY_LEFT: + serverIndex = TXN_LEFT; + break; + case DETECTOR_TXN_DELAY_RIGHT: + serverIndex = TXN_RIGHT; + break; +#endif + case DETECTOR_TXN_DELAY_FRAME: + serverIndex = TXN_FRAME; +#ifdef JUNGFRAUD + if (value > MAX_TIMESLOT_VAL) { + ret = FAIL; + sprintf(mess,"Transmission delay %d should be in range: 0 - %d\n", + value, MAX_TIMESLOT_VAL); + FILE_LOG(logERROR, (mess)); + } +#endif + break; + default: + modeNotImplemented("Image index", (int)serverIndex); + break; + } + // valid index + if (ret == OK) { + retval = setNetworkParameter(serverIndex, value); + FILE_LOG(logDEBUG1, ("Network Parameter index %d: %d\n", serverIndex, retval)); + validate(value, retval, "set network parameter", DEC); + } + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + + + +int program_fpga(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + +#if defined(EIGERD) || defined(GOTTHARDD) + //to receive any arguments + int n = 1; + while (n > 0) + n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); + functionNotImplemented(); +#else +#ifndef VIRTUAL + // only set + if (Server_VerifyLock() == OK) { + + FILE_LOG(logINFOBLUE, ("Programming FPGA...\n")); + + size_t filesize = 0; + size_t totalsize = 0; + size_t unitprogramsize = 0; + char* fpgasrc = NULL; + FILE* fp = NULL; + + // filesize + if (receiveData(file_des,&filesize,sizeof(filesize),INT32) < 0) + return printSocketReadError(); + totalsize = filesize; + FILE_LOG(logDEBUG1, ("Total program size is: %d\n", totalsize)); + + + // opening file pointer to flash and telling FPGA to not touch flash + if (startWritingFPGAprogram(&fp) != OK) { + ret = FAIL; + sprintf(mess,"Could not write to flash. Error at startup.\n"); + FILE_LOG(logERROR,(mess)); + } + Server_SendResult(file_des, INT32, NO_UPDATE, NULL, 0); + + + //erasing flash + if (ret != FAIL) { + eraseFlash(); + fpgasrc = (char*)malloc(MAX_FPGAPROGRAMSIZE); + } + + + //writing to flash part by part + while(ret != FAIL && filesize) { + + unitprogramsize = MAX_FPGAPROGRAMSIZE; //2mb + if (unitprogramsize > filesize) //less than 2mb + unitprogramsize = filesize; + FILE_LOG(logDEBUG1, ("unit size to receive is:%d\nfilesize:%d\n", unitprogramsize, filesize)); + + //receive part of program + if (receiveData(file_des,fpgasrc,unitprogramsize,OTHER) < 0) + return printSocketReadError(); + + if (!(unitprogramsize - filesize)) { + fpgasrc[unitprogramsize] = '\0'; + filesize -= unitprogramsize; + unitprogramsize++; + } else + filesize -= unitprogramsize; + + // write part to flash + ret = writeFPGAProgram(fpgasrc, unitprogramsize, fp); + Server_SendResult(file_des, INT32, NO_UPDATE, NULL, 0); + if (ret == FAIL) { + FILE_LOG(logERROR, ("Failure: Breaking out of program receiving\n")); + } else { + //print progress + FILE_LOG(logINFO, ("Writing to Flash:%d%%\r", + (int) (((double)(totalsize-filesize)/totalsize)*100) )); + fflush(stdout); + } + } + printf("\n"); + if (ret == OK) { + FILE_LOG(logINFO, ("Done copying program\n")); + } + + // closing file pointer to flash and informing FPGA + stopWritingFPGAprogram(fp); + + //free resources + if (fpgasrc != NULL) + free(fpgasrc); + if (fp != NULL) + fclose(fp); + + FILE_LOG(logINFO, ("Completed program fpga command with %s\n", (ret == OK ? "success" : "fail"))); + } +#endif +#endif + return ret; +} + + + + + +int reset_fpga(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + + FILE_LOG(logDEBUG1, ("Reset FPGA\n")); +#if defined(EIGERD) || defined(GOTTHARDD) + functionNotImplemented(); +#else + // only set + if (Server_VerifyLock() == OK) { + if (isControlServer) { + basictests(); // mapping of control server at least + initControlServer(); + } + else initStopServer(); //remapping of stop server + ret = FORCE_UPDATE; + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + + + +int power_chip(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Powering chip to %d\n", arg)); + +#if (!defined(JUNGFRAUD)) && (!defined(MOENCHD)) + functionNotImplemented(); +#else + // set & get + if ((arg == -1) || (Server_VerifyLock() == OK)) { + retval = powerChip(arg); + FILE_LOG(logDEBUG1, ("Power chip: %d\n", retval)); + validate(arg, retval, "power on/off chip", DEC); +#ifdef JUNGFRAUD + // narrow down error when powering on + if (ret == FAIL && arg > 0) { + if (setTemperatureEvent(-1) == 1) + sprintf(mess,"Powering chip failed due to over-temperature event. " + "Clear event & power chip again. Set %d, read %d \n", arg, retval); + FILE_LOG(logERROR, (mess)); + } +#endif + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + +int set_activate(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Setting activate mode to %d\n", arg)); + +#ifndef EIGERD + functionNotImplemented(); +#else + // set & get + if ((arg == -1) || (Server_VerifyLock() == OK)) { + retval = activate(arg); + FILE_LOG(logDEBUG1, ("Activate: %d\n", retval)); + validate(arg, retval, "set activate", DEC); + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + +int prepare_acquisition(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + + FILE_LOG(logDEBUG1, ("Preparing Acquisition\n")); +#ifndef EIGERD + functionNotImplemented(); +#else + // only set + if (Server_VerifyLock() == OK) { + ret = prepareAcquisition(); + if (ret == FAIL) { + strcpy(mess, "Could not prepare acquisition\n"); + FILE_LOG(logERROR, (mess)); + } + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + + + + +// stop server +int threshold_temp(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Setting threshold temperature to %d\n", arg)); + +#ifndef JUNGFRAUD + functionNotImplemented(); +#else + // set & get + if ((arg == -1) || (Server_VerifyLock() == OK)) { + if (arg > MAX_THRESHOLD_TEMP_VAL) { + ret = FAIL; + sprintf(mess,"Threshold Temp %d should be in range: 0 - %d\n", + arg, MAX_THRESHOLD_TEMP_VAL); + FILE_LOG(logERROR, (mess)); + } + // valid temp + else { + retval = setThresholdTemperature(arg); + FILE_LOG(logDEBUG1, ("Threshold temperature: %d\n", retval)); + validate(arg, retval, "set threshold temperature", DEC); + } + } +#endif + return Server_SendResult(file_des, INT32, NO_UPDATE, &retval, sizeof(retval)); +} + + +// stop server +int temp_control(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Setting temperature control to %d\n", arg)); + +#ifndef JUNGFRAUD + functionNotImplemented(); +#else + // set & get + if ((arg == -1) || (Server_VerifyLock() == OK)) { + retval = setTemperatureControl(arg); + FILE_LOG(logDEBUG1, ("Temperature control: %d\n", retval)); + validate(arg, retval, "set temperature control", DEC); + } +#endif + return Server_SendResult(file_des, INT32, NO_UPDATE, &retval, sizeof(retval)); +} + + + +// stop server +int temp_event(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Setting temperature event to %d\n", arg)); + +#ifndef JUNGFRAUD + functionNotImplemented(); +#else + // set & get + if ((arg == -1) || (Server_VerifyLock() == OK)) { + retval = setTemperatureEvent(arg); + FILE_LOG(logDEBUG1, ("Temperature event: %d\n", retval)); + validate(arg, retval, "set temperature event", DEC); + } +#endif + return Server_SendResult(file_des, INT32, NO_UPDATE, &retval, sizeof(retval)); +} + + + + + +int auto_comp_disable(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Setting Auto comp disable to %d\n", arg)); + +#ifndef JUNGFRAUD + functionNotImplemented(); +#else + // set & get + if ((arg == -1) || (Server_VerifyLock() == OK)) { + retval = autoCompDisable(arg); + FILE_LOG(logDEBUG1, ("Auto comp disable: %d\n", retval)); + validate(arg, retval, "set auto comp disable", DEC); + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + + +int storage_cell_start(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Setting Storage cell start to %d\n", arg)); + +#ifndef JUNGFRAUD + functionNotImplemented(); +#else + // set & get + if ((arg == -1) || (Server_VerifyLock() == OK)) { + if (arg > MAX_STORAGE_CELL_VAL) { + ret = FAIL; + strcpy(mess,"Max Storage cell number should not exceed 15\n"); + FILE_LOG(logERROR, (mess)); + } else { + retval = selectStoragecellStart(arg); + FILE_LOG(logDEBUG1, ("Storage cell start: %d\n", retval)); + validate(arg, retval, "set storage cell start", DEC); + } + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + +int check_version(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int64_t arg = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT64) < 0) + return printSocketReadError(); + + // check software- firmware compatibility and basic tests + if (isControlServer) { + FILE_LOG(logDEBUG1, ("Checking software-firmware compatibility and basic test result\n")); + + // check if firmware check is done + if (!isFirmwareCheckDone()) { + usleep(3 * 1000 * 1000); + if (!isFirmwareCheckDone()) { + ret = FAIL; + strcpy(mess,"Firmware Software Compatibility Check (Server Initialization) " + "still not done done in server. Unexpected.\n"); + FILE_LOG(logERROR,(mess)); + } + } + // check firmware check result + if (ret == OK) { + char* firmware_message = NULL; + if (getFirmwareCheckResult(&firmware_message) == FAIL) { + ret = FAIL; + strcpy(mess, firmware_message); + FILE_LOG(logERROR,(mess)); + } + } + } + + if (ret == OK) { + FILE_LOG(logDEBUG1, ("Checking versioning compatibility with value 0x%llx\n",arg)); + + int64_t client_requiredVersion = arg; + int64_t det_apiVersion = getDetectorId(CLIENT_SOFTWARE_API_VERSION); + int64_t det_version = getDetectorId(DETECTOR_SOFTWARE_VERSION); + + // old client + if (det_apiVersion > client_requiredVersion) { + ret = FAIL; + sprintf(mess,"Client's detector SW API version: (0x%llx). " + "Detector's SW API Version: (0x%llx). " + "Incompatible, update client!\n", + (long long int)client_requiredVersion, (long long int)det_apiVersion); + FILE_LOG(logERROR,(mess)); + } + + // old software + else if (client_requiredVersion > det_version) { + ret = FAIL; + sprintf(mess,"Detector SW Version: (0x%llx). " + "Client's detector SW API Version: (0x%llx). " + "Incompatible, update detector software!\n", + (long long int)det_version, (long long int)client_requiredVersion); + FILE_LOG(logERROR,(mess)); + } + } + return Server_SendResult(file_des, INT32, NO_UPDATE, NULL, 0); +} + + + + +int software_trigger(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + + FILE_LOG(logDEBUG1, ("Software Trigger\n")); +#ifndef EIGERD + functionNotImplemented(); +#else + // only set + if (Server_VerifyLock() == OK) { + ret = softwareTrigger(); + if (ret == FAIL) { + sprintf(mess, "Could not send software trigger\n"); + FILE_LOG(logERROR,(mess)); + } + FILE_LOG(logDEBUG1, ("Software trigger successful\n")); + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + + +int led(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + int arg = -1; + int retval = -1; + + if (receiveData(file_des, &arg, sizeof(arg), INT32) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Setting led enable to %d\n", arg)); + +#if (!defined(MOENCHD)) && (!defined(CHIPTESTBOARDD)) + functionNotImplemented(); +#else + // set & get + if ((arg == -1) || (Server_VerifyLock() == OK)) { + retval = setLEDEnable(arg); + FILE_LOG(logDEBUG1, ("LED Enable: %d\n", retval)); + validate(arg, retval, "LED Enable", DEC); + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, &retval, sizeof(retval)); +} + + + + +int digital_io_delay(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + uint64_t args[2] = {-1, -1}; + + if (receiveData(file_des, args, sizeof(args), INT64) < 0) + return printSocketReadError(); + FILE_LOG(logDEBUG1, ("Digital IO Delay, pinMask: 0x%llx, delay:%d ps\n", args[0], (int)args[1])); + +#if (!defined(MOENCHD)) && (!defined(CHIPTESTBOARDD)) + functionNotImplemented(); +#else + // only set + if (Server_VerifyLock() == OK) { + int delay = (int)args[1]; + if (delay < 0 || delay > DIGITAL_IO_DELAY_MAXIMUM_PS) { + ret = FAIL; + sprintf(mess, "Could not set digital IO delay. Delay maximum is %d ps\n", DIGITAL_IO_DELAY_MAXIMUM_PS); + FILE_LOG(logERROR,(mess)); + } else { + setDigitalIODelay(args[0], delay); + FILE_LOG(logDEBUG1, ("Digital IO Delay successful\n")); + } + } +#endif + return Server_SendResult(file_des, INT32, UPDATE, NULL, 0); +} + +int copy_detector_server(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); + char args[2][MAX_STR_LENGTH]; + char retvals[MAX_STR_LENGTH] = {0}; + + memset(args, 0, sizeof(args)); + memset(retvals, 0, sizeof(retvals)); + + if (receiveData(file_des, args, sizeof(args), OTHER) < 0) + return printSocketReadError(); + +#ifdef EIGERD + functionNotImplemented(); +#else + + // only set + if (Server_VerifyLock() == OK) { + char* sname = args[0]; + char* hostname = args[1]; + FILE_LOG(logINFOBLUE, ("Copying server %s from host %s\n", sname, hostname)); + + char cmd[MAX_STR_LENGTH]; + memset(cmd, 0, MAX_STR_LENGTH); + + // copy server + sprintf(cmd, "tftp %s -r %s -g", hostname, sname); + int success = executeCommand(cmd, retvals, logDEBUG1); + if (success == FAIL) { + ret = FAIL; + strcpy(mess, retvals); + //FILE_LOG(logERROR, (mess)); already printed in executecommand + } + + // success + else { + FILE_LOG(logINFO, ("Server copied successfully\n")); + // give permissions + sprintf(cmd, "chmod 777 %s", sname); + executeCommand(cmd, retvals, logDEBUG1); + + // edit /etc/inittab + // find line numbers in /etc/inittab where DetectorServer + strcpy(cmd, "sed -n '/DetectorServer/=' /etc/inittab"); + executeCommand(cmd, retvals, logDEBUG1); + while (strlen(retvals)) { + // get first linen number + int lineNumber = atoi(retvals); + // delete that line + sprintf(cmd, "sed -i \'%dd\' /etc/inittab", lineNumber); + executeCommand(cmd, retvals, logDEBUG1); + // find line numbers again + strcpy(cmd, "sed -n '/DetectorServer/=' /etc/inittab"); + executeCommand(cmd, retvals, logDEBUG1); + } + FILE_LOG(logINFO, ("Deleted all lines containing DetectorServer in /etc/inittab\n")); + + // append line + sprintf(cmd, "echo \"ttyS0::respawn:/./%s\" >> /etc/inittab", sname); + executeCommand(cmd, retvals, logDEBUG1); + + FILE_LOG(logINFO, ("/etc/inittab modified to have %s\n", sname)); + } + } +#endif + return Server_SendResult(file_des, OTHER, NO_UPDATE, retvals, sizeof(retvals)); +} + + +int reboot_controller(int file_des) { + ret = OK; + memset(mess, 0, sizeof(mess)); +#ifdef EIGERD + functionNotImplemented(); + return ret; +#else + FILE_LOG(logINFORED, ("Rebooting controller\n")); + return REBOOT; +#endif +} diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.h b/slsDetectorServers/slsDetectorServer/slsDetectorServer_funcs.h similarity index 66% rename from slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.h rename to slsDetectorServers/slsDetectorServer/slsDetectorServer_funcs.h index a4bbaeb64..da2e28d66 100755 --- a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.h +++ b/slsDetectorServers/slsDetectorServer/slsDetectorServer_funcs.h @@ -1,57 +1,48 @@ -#ifndef SERVER_FUNCS_H -#define SERVER_FUNCS_H +#pragma once +#include "sls_detector_defs.h" +#include "logger.h" -#include "sls_receiver_defs.h" -#include +enum numberMode {DEC, HEX}; +#define GOODBYE (-200) +#define REBOOT (-400) // initialization functions int printSocketReadError(); -void setModeFlag(int); -void basictests(); -void init_detector(int); +void init_detector(); int decode_function(int); +const char* getRetName(); +const char* getTimerName(enum timerIndex ind); +const char* getSpeedName(enum speedVariable ind); const char* getFunctionName(enum detFuncs func); void function_table(); +void functionNotImplemented(); +void modeNotImplemented(char* modename, int mode); +void validate(int arg, int retval, char* modename, enum numberMode nummode); +void validate64(int64_t arg, int64_t retval, char* modename, enum numberMode nummode); +int executeCommand(char* command, char* result, enum TLogLevel level); int M_nofunc(int); int M_nofuncMode(int); // functions called by client int exec_command(int); -int get_error(int); int get_detector_type(int); -int set_number_of_modules(int); -int get_max_number_of_modules(int); int set_external_signal_flag(int); int set_external_communication_mode(int); int get_id(int); int digital_test(int); -int analog_test(int); -int enable_analog_out(int); -int calibration_pulse(int); int set_dac(int); int get_adc(int); int write_register(int); int read_register(int); -int write_memory(int); -int read_memory(int); -int set_channel(int); -int get_channel(int); -int set_all_channels(int); -int set_chip(int); -int get_chip(int); -int set_all_chips(int); int set_module(int); int get_module(int); -int set_all_modules(int); int set_settings(int); int get_threshold_energy(int); -int set_threshold_energy(int); int start_acquisition(int); int stop_acquisition(int); int start_readout(int); int get_run_status(int); int start_and_read_all(int); -int read_frame(int); int read_all(int); int set_timer(int); int get_time_left(int); @@ -59,7 +50,6 @@ int set_dynamic_range(int); int set_readout_flags(int); int set_roi(int); int set_speed(int); -int execute_trimming(int); int exit_server(int); int lock_server(int); int get_last_client_ip(int); @@ -68,14 +58,16 @@ int update_client(int); int send_update(int); int configure_mac(int); int load_image(int); -int set_master(int); -int set_synchronization(int); int read_counter_block(int); int reset_counter_block(int); int calibrate_pedestal(int); int enable_ten_giga(int); int set_all_trimbits(int); -int set_ctb_pattern(int); +int set_pattern(int); +int set_pattern_mask(int); +int get_pattern_mask(int); +int set_pattern_bit_mask(int); +int get_pattern_bit_mask(int); int write_adc_register(int); int set_counter_bit(int); int pulse_pixel(int); @@ -89,7 +81,6 @@ int reset_fpga(int); int power_chip(int); int set_activate(int); int prepare_acquisition(int); -int cleanup_acquisition(int); int threshold_temp(int); int temp_control(int); int temp_event(int); @@ -97,5 +88,8 @@ int auto_comp_disable(int); int storage_cell_start(int); int check_version(int); int software_trigger(int); +int led(int); +int digital_io_delay(int); +int copy_detector_server(int); +int reboot_controller(int); -#endif diff --git a/slsDetectorSoftware/.gitignore b/slsDetectorSoftware/.gitignore deleted file mode 100644 index 825dda897..000000000 --- a/slsDetectorSoftware/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -*.o -*~ -#*# -.project diff --git a/slsDetectorSoftware/CMakeLists.txt b/slsDetectorSoftware/CMakeLists.txt old mode 100644 new mode 100755 index 55aca177f..a7c7c8db6 --- a/slsDetectorSoftware/CMakeLists.txt +++ b/slsDetectorSoftware/CMakeLists.txt @@ -1,74 +1,44 @@ set(SOURCES - multiSlsDetector/multiSlsDetector.cpp - sharedMemory/SharedMemory.cpp - slsDetector/slsDetectorUsers.cpp - slsDetector/slsDetectorUtils.cpp - slsDetector/slsDetectorCommand.cpp - slsDetector/slsDetectorActions.cpp - slsDetector/slsDetector.cpp - slsDetectorAnalysis/angularConversion.cpp - slsDetectorAnalysis/angularConversionStatic.cpp - slsDetectorAnalysis/energyConversion.cpp - slsDetectorAnalysis/fileIO.cpp - slsDetectorAnalysis/postProcessing.cpp - slsDetectorAnalysis/postProcessingFuncs.cpp - slsReceiverInterface/receiverInterface.cpp - threadFiles/CondVar.cpp - threadFiles/Mutex.cpp - threadFiles/ThreadPool.cpp - usersFunctions/usersFunctions.cpp + src/multiSlsDetector.cpp + src/slsDetectorUsers.cpp + src/slsDetectorCommand.cpp + src/slsDetector.cpp ) set(HEADERS ) -include_directories( -commonFiles -multiSlsDetector -sharedMemory -slsDetector -slsDetectorUtils -slsDetectorCommand -slsDetectorAnalysis -slsReceiverInterface -threadFiles -usersFunctions -../slsReceiverSoftware/include -../slsReceiverSoftware/MySocketTCP -) - -add_definitions( - -DDACS_INT -) - add_library(slsDetectorShared SHARED ${SOURCES} ${HEADERS} ) + + +check_ipo_supported(RESULT result) +if(result) + set_property(TARGET slsDetectorShared PROPERTY INTERPROCEDURAL_OPTIMIZATION True) +endif() + + +target_include_directories(slsDetectorShared PUBLIC + "$" + "$" +) + +target_link_libraries(slsDetectorShared PUBLIC + slsProjectOptions + slsProjectWarnings + slsSupportLib + ${ZeroMQ_LIBRARIES} +) + set(PUBLICHEADERS - commonFiles/sls_detector_defs.h - commonFiles/sls_detector_funcs.h - commonFiles/error_defs.h - commonFiles/versionAPI.h - sharedMemory/SharedMemory.h - slsDetector/slsDetectorUtils.h - slsDetector/slsDetector.h - slsDetector/slsDetectorActions.h - slsDetector/slsDetectorBase.h - slsDetector/slsDetectorUsers.h - slsDetectorAnalysis/postProcessing.h - slsDetectorAnalysis/detectorData.h - slsDetectorAnalysis/angularConversion.h - slsDetectorAnalysis/angularConversionStatic.h - slsDetectorAnalysis/angleConversionConstant.h - slsDetectorAnalysis/badChannelCorrections.h - slsDetectorAnalysis/energyConversion.h - slsDetectorAnalysis/fileIO.h - slsDetectorAnalysis/fileIOStatic.h - multiSlsDetector/multiSlsDetector.h - slsReceiverInterface/receiverInterface.h - ../slsReceiverSoftware/include/sls_receiver_exceptions.h + include/SharedMemory.h + include/slsDetector.h + include/slsDetectorUsers.h + include/detectorData.h + include/multiSlsDetector.h ) set_target_properties(slsDetectorShared PROPERTIES LIBRARY_OUTPUT_NAME SlsDetector @@ -76,9 +46,83 @@ set_target_properties(slsDetectorShared PROPERTIES PUBLIC_HEADER "${PUBLICHEADERS}" ) +# add_subdirectory(slsDetectorClient) +add_executable(sls_detector_get + src/sls_detector_client.cpp +) +target_link_libraries(sls_detector_get + slsProjectOptions + slsProjectWarnings + slsDetectorShared + slsSupportLib + pthread + ${ZeroMQ_LIBRARIES} + rt +) +set_target_properties(sls_detector_get PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin + COMPILE_DEFINITIONS GET=1 +) + +add_executable(sls_detector_put + src/sls_detector_client.cpp +) +target_link_libraries(sls_detector_put + slsProjectOptions + slsProjectWarnings + slsDetectorShared + pthread + ${ZeroMQ_LIBRARIES} + rt +) +set_target_properties(sls_detector_put PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin + COMPILE_DEFINITIONS PUT=1 +) + +add_executable(sls_detector_acquire + src/sls_detector_client.cpp +) +target_link_libraries(sls_detector_acquire + slsProjectOptions + slsProjectWarnings + slsDetectorShared + pthread + ${ZeroMQ_LIBRARIES} + rt +) +set_target_properties(sls_detector_acquire PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin + COMPILE_DEFINITIONS READOUT=1 +) + +add_executable(sls_detector_help + src/sls_detector_client.cpp +) +target_link_libraries(sls_detector_help + slsProjectOptions + slsProjectWarnings + slsDetectorShared + pthread + ${ZeroMQ_LIBRARIES} + rt +) +set_target_properties(sls_detector_help PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin + COMPILE_DEFINITIONS HELP=1 +) + +check_ipo_supported(RESULT result) +if(result) + set_property(TARGET sls_detector_help PROPERTY INTERPROCEDURAL_OPTIMIZATION True) + set_property(TARGET sls_detector_get PROPERTY INTERPROCEDURAL_OPTIMIZATION True) + set_property(TARGET sls_detector_put PROPERTY INTERPROCEDURAL_OPTIMIZATION True) + set_property(TARGET sls_detector_acquire PROPERTY INTERPROCEDURAL_OPTIMIZATION True) +endif() + +install(TARGETS sls_detector_put sls_detector_get sls_detector_acquire sls_detector_help DESTINATION bin) -add_subdirectory(slsDetectorClient) if(DOXYGEN_FOUND) add_custom_target(doc @@ -89,8 +133,15 @@ if(DOXYGEN_FOUND) ) endif() +if (SLS_USE_TESTS) + add_subdirectory(tests) +endif(SLS_USE_TESTS) + + install(TARGETS slsDetectorShared EXPORT "${TARGETS_EXPORT_NAME}" - LIBRARY DESTINATION lib - PUBLIC_HEADER DESTINATION include - ARCHIVE DESTINATION lib) + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} +) diff --git a/slsDetectorSoftware/Makefile b/slsDetectorSoftware/Makefile deleted file mode 100644 index 1be7ccc6f..000000000 --- a/slsDetectorSoftware/Makefile +++ /dev/null @@ -1,82 +0,0 @@ -include ../Makefile.include - -DESTDIR ?= ../bin -LIBDIR ?= $(DESTDIR) - - -CFLAGS= -g -DC_ONLY -fPIC -#FLAGS+= #-DVERBOSE -DVERYVERBOSE - -DFLAGS= -g -DDACS_INT - -INCLUDES?= -IcommonFiles -IslsDetector -I../slsReceiverSoftware/MySocketTCP -IusersFunctions -ImultiSlsDetector -IslsDetectorUtils -IslsDetectorCommand -IslsDetectorAnalysis -IslsReceiverInterface -I../slsReceiverSoftware/include -IthreadFiles -IsharedMemory -I$(ASM) - -#EPICSFLAGS=-D EPICS -I/usr/local/epics/base/include/ -I /usr/local/epics/base/include/os/Linux/ -L /usr/local/epics/base/lib/$(EPICS_HOST_ARCH) -Wl,-R/usr/local/epics/base/lib/$(EPICS_HOST_ARCH) -lca -lCom - -LIBZMQDIR = ../slsReceiverSoftware/include -LIBZMQ = -L$(LIBZMQDIR) -Wl,-rpath=$(LIBZMQDIR) -lzmq - -SRC_CLNT=slsDetectorAnalysis/fileIO.cpp usersFunctions/usersFunctions.cpp slsDetector/slsDetectorUtils.cpp slsDetector/slsDetectorCommand.cpp slsDetectorAnalysis/angularConversion.cpp slsDetectorAnalysis/angularConversionStatic.cpp slsDetectorAnalysis/energyConversion.cpp slsDetector/slsDetectorActions.cpp slsDetectorAnalysis/postProcessing.cpp slsDetector/slsDetector.cpp multiSlsDetector/multiSlsDetector.cpp slsDetectorAnalysis/postProcessingFuncs.cpp slsReceiverInterface/receiverInterface.cpp slsDetector/slsDetectorUsers.cpp threadFiles/CondVar.cpp threadFiles/Mutex.cpp threadFiles/ThreadPool.cpp sharedMemory/SharedMemory.cpp #../slsReceiverSoftware/MySocketTCP/MySocketTCP.cpp -DEPSINCLUDES = $(LIBZMQDIR)/sls_receiver_defs.h $(LIBZMQDIR)/sls_receiver_funcs.h $(LIBZMQDIR)/ansi.h commonFiles/sls_detector_defs.h commonFiles/sls_detector_funcs.h commonFiles/error_defs.h slsDetector/slsDetectorBase.h slsDetectorAnalysis/angCalLogClass.h slsDetectorAnalysis/angleConversionConstant.h slsDetectorAnalysis/badChannelCorrections.h slsDetectorAnalysis/detectorData.h slsDetectorAnalysis/enCalLogClass.h slsDetectorAnalysis/fileIOStatic.h slsDetectorAnalysis/movingStat.h slsDetectorAnalysis/runningStat.h slsDetectorAnalysis/single_photon_hit.h threadFiles/Global.h threadFiles/Task.h usersFunctions/angleFunction.h sharedMemory/SharedMemory.h $(LIBZMQDIR)/sls_receiver_exceptions.h commonFiles/versionAPI.h - - - -$(info ) -$(info #######################################) -$(info # In slsDetectorSoftware Makefile #) -$(info #######################################) -$(info ) - - - - -OBJS = $(SRC_CLNT:%.cpp=%.o) - -.PHONY: all package clean - -all: package $(SRC_CLNT) - -mythenVirtualServer: $(SRC_MYTHEN_SVC) - cd mythenDetectorServer && make -f Makefile.virtual DESTDIR=$(DESTDIR) - -gotthardVirtualServer: $(SRC_MYTHEN_SVC) - cd gotthardDetectorServer && make -f Makefile.virtual DESTDIR=$(DESTDIR) - - -%.o : %.cpp %.h $(DEPSINCLUDES) Makefile - $(CXX) -o $@ -c $< $(INCLUDES) $(DFLAGS) -fPIC $(EPICSFLAGS) -pthread -lrt $(LIBZMQ) $(FLAGS) - - -package: versioning $(OBJS) $(DESTDIR)/libSlsDetector.so $(DESTDIR)/libSlsDetector.a - -versioning: - $(call colorecho,`./updateGitVersion.sh`) - -$(DESTDIR)/libSlsDetector.so: $(OBJS) - $(call colorecho,"#######################################") - $(call colorecho,"# Compiling slsDetector Library #") - $(call colorecho,"#######################################") - $(CXX) -shared -Wl,-soname,libSlsDetector.so -o libSlsDetector.so $(OBJS) -lc $(INCLUDES) $(DFLAGS) $(FLAGS) $(EPICSFLAGS) -L/usr/lib64 -pthread -lrt $(LIBZMQ) - $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) - mv libSlsDetector.so $(DESTDIR) - -$(DESTDIR)/libSlsDetector.a: $(OBJS) - ar rcs libSlsDetector.a $(OBJS) - mv libSlsDetector.a $(DESTDIR) - -clean: - rm -rf $(DESTDIR)/libSlsDetector.a $(DESTDIR)/libSlsDetector.so core $(OBJS) - cd - - - - -#------------------------------------------------------------------------------- - -install: package - -install_inc: - $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) - cp -P slsDetector/slsDetectorUsers.h slsDetectorAnalysis/detectorData.h $(DESTDIR) - - diff --git a/slsDetectorSoftware/Makefile.Standalone b/slsDetectorSoftware/Makefile.Standalone deleted file mode 100644 index d9a7c0868..000000000 --- a/slsDetectorSoftware/Makefile.Standalone +++ /dev/null @@ -1,68 +0,0 @@ -CFLAGS= -DC_ONLY -#FLAGS= -DVERBOSE -DVERYVERBOSE -INCLUDES= -IcommonFiles -IslsDetector -IMySocketTCP -IusersFunctions -ImultiSlsDetector -IslsDetectorUtils -IslsDetectorCommand -IslsDetectorAnalysis - -#EPICSFLAGS=-D EPICS -I/usr/local/epics/base/include/ -I /usr/local/epics/base/include/os/Linux/ -L /usr/local/epics/base/lib/SL5-x86/ -Wl,-R/usr/local/epics/base/lib/SL5-x86 -lca -lCom -CC=gcc -CXX=g++ - -SRC_CLNT= slsDetectorAnalysis/FileIO_Standalone.cpp MySocketTCP/MySocketTCP.cpp usersFunctions/usersFunctions.cpp slsDetector/slsDetectorUtils.cpp slsDetector/slsDetectorCommand.cpp slsDetectorAnalysis/AngularConversion_Standalone.cpp slsDetectorAnalysis/energyConversion.cpp slsDetector/slsDetectorActions.cpp slsDetectorAnalysis/postProcessingFileIO_Standalone.cpp slsDetector/slsDetector.cpp multiSlsDetector/multiSlsDetector.cpp - -OBJS = $(SRC_CLNT:.cpp=.o) - -HEADERS = $(SRC_CLNT:.cpp=.h) commonFiles/sls_detector_defs.h slsDetectorAnalysis/detectorData.h slsDetector/slsDetectorBase.h slsDetector/slsDetectorUsers.h multiSlsDetector/multiSlsDetectorCommand.h - - - -SRC_MYTHEN_SVC = mythenDetectorServer/server.c mythenDetectorServer/server_funcs.c mythenDetectorServer/communication_funcs.c mythenDetectorServer/firmware_funcs.c mythenDetectorServer/mcb_funcs.c mythenDetectorServer/trimming_funcs.c - -all: package $(SRC_CLNT) - echo "compiling all" - -doc: $(SRC_H) $(SRC_CLNT) - doxygen doxy.config - - - -mythenServer: $(SRC_MYTHEN_SVC) - $(CC) $(SRC_MYTHEN_SVC) $(CFLAGS) $(FLAGS) $(INCLUDES) -ImythenDetectorServer -DVIRTUAL -lm -D MCB_FUNCS -DC_ONLY -DVERBOSE - mv a.out mythenServer - - -picassoServer: $(SRC_MYTHEN_SVC) - $(CC) $(SRC_MYTHEN_SVC) $(CFLAGS) $(FLAGS) $(INCLUDES) -ImythenDetectorServer -D VIRTUAL -lm -DMCB_FUNCS -DPICASSOD -DC_ONLY - mv a.out picassoServer - - - - - -%.o : %.cpp %.h - $(CXX) -Wall -o $@ -c $< $(INCLUDES) $(FLAGS) $(EPICSFLAGS) - - -package: $(OBJS) - $(CXX) -shared -Wl,-soname,libSlsDetector.so -o libSlsDetector.so $(OBJS) -lc $(INCLUDES) $(FLAGS) $(EPICSFLAGS) - ar rcs libSlsDetector.a $(OBJS) - -clean: - rm -rf libSlsDetector.a libSlsDetector.so core docs/* $(OBJS) - - -#------------------------------------------------------------------------------- -lib: package - - -# added install target, HBl -install_lib: lib - $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) - cp -P libSlsDetector.so $(DESTDIR) - -install_inc: - $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) - cp -P $(HEADERS) $(DESTDIR) - - -install_doc: doc - $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) - cp -Pr docs/* $(DESTDIR) diff --git a/slsDetectorSoftware/Makefile.x04sa b/slsDetectorSoftware/Makefile.x04sa deleted file mode 100644 index 59755550f..000000000 --- a/slsDetectorSoftware/Makefile.x04sa +++ /dev/null @@ -1,87 +0,0 @@ -CFLAGS= -DC_ONLY -fPIC -#FLAGS+= #-DVERBOSE -DVERYVERBOSE - -DFLAGS= -DDACS_INT -DTHIS_PATH='"$(shell pwd)"' -DSLS_RECEIVER_FUNCTION_LIST - -#ASM=$(shell echo "/lib/modules/`uname -r`/build/include") - -INCLUDES?= -IcommonFiles -IslsDetector -IMySocketTCP -IusersFunctions -ImultiSlsDetector -IslsDetectorUtils -IslsDetectorCommand -IslsDetectorAnalysis -IslsReceiverInterface -IslsReceiver -I$(ASM) - -EPICSFLAGS=-D EPICS -I/usr/local/epics/base/include/ -I /usr/local/epics/base/include/os/Linux/ -L /usr/local/epics/base/lib/SL5-x86/ -Wl,-R/usr/local/epics/base/lib/SL5-x86 -lca -lCom -CC=g++ - - -SRC_CLNT= slsDetectorAnalysis/fileIO.cpp MySocketTCP/MySocketTCP.cpp usersFunctions/usersFunctions.cpp slsDetector/slsDetectorUtils.cpp slsDetector/slsDetectorCommand.cpp slsDetectorAnalysis/angularConversion.cpp slsDetectorAnalysis/angularConversionStatic.cpp slsDetectorAnalysis/energyConversion.cpp slsDetector/slsDetectorActions.cpp slsDetectorAnalysis/postProcessing.cpp slsDetector/slsDetector.cpp multiSlsDetector/multiSlsDetector.cpp slsDetector/slsDetectorUsers.cpp slsDetectorAnalysis/postProcessingFuncs.cpp slsReceiverInterface/receiverInterface.cpp slsReceiver/slsReceiverFunctionList.cpp slsReceiver/slsReceiver_funcs.cpp slsReceiver/slsReceiverUsers.cpp - -OBJS = $(SRC_CLNT:.cpp=.o) - -HEADERS = $(SRC_CLNT:.cpp=.h) commonFiles/sls_detector_defs.h slsDetectorAnalysis/detectorData.h slsDetector/slsDetectorBase.h multiSlsDetector/multiSlsDetectorCommand.h slsDetectorAnalysis/enCalLogClass.h slsDetectorAnalysis/angCalLogClass.h slsDetectorAnalysis/angleConversionConstant.h usersFunctions/angleFunction.h slsReceiverInterface/receiverInterface.h slsDetector/svnInfoLib.h slsReceiver/circularFifo.h slsReceiver/slsReceiver_funcs.h slsReceiver/svnInfoReceiverTmp.h slsReceiver/receiver_defs.h slsReceiver/slsReceiverFunctionList.h slsReceiver/slsReceiverUsers.h slsReceiver/svnInfoReceiver.h - - - -DESTDIR ?= bin -DOCDIR ?= docs - - -all: package $(SRC_CLNT) - echo "compiling all" - -intdoc: $(SRC_H) $(SRC_CLNT) - doxygen doxy.config - -doc: $(DOCDIR)/pdf/slsDetectorUsersDocs.pdf - -$(DOCDIR)/pdf/slsDetectorUsersDocs.pdf: slsDetectorUsersDocs - cd slsDetectorUsersDocs/latex && make - $(shell test -d $(DOCDIR) || mkdir -p $(DOCDIR)) - $(shell test -d $(DOCDIR)/pdf || mkdir -p $(DOCDIR)/pdf) - cp slsDetectorUsersDocs/latex/refman.pdf $(DOCDIR)/pdf/slsDetectorUsersDocs.pdf - - -htmldoc: $(DOCDIR)/html/slsDetectorUsersDocs - -$(DOCDIR)/html/slsDetectorUsersDocs: slsDetectorUsersDocs - $(shell test -d $(DOCDIR) || mkdir -p $(DOCDIR)) - $(shell test -d $(DOCDIR)/html || mkdir -p $(DOCDIR)/html) - $(shell test -d $(DOCDIR)/html/slsDetectorUsersDocs && rm -r $(DOCDIR)/html/slsDetectorUsersDocs) - cp -r slsDetectorUsersDocs/html $(DOCDIR)/html/slsDetectorUsersDocs - -slsDetectorUsersDocs: slsDetectorUsers.doxy slsDetector/slsDetectorUsers.h slsDetector/slsDetectorUsers.cpp slsDetectorAnalysis/detectorData.h - doxygen slsDetectorUsers.doxy - - -mythenVirtualServer: $(SRC_MYTHEN_SVC) - cd mythenDetectorServer && make -f Makefile.virtual DESTDIR=$(DESTDIR) - -gotthardVirtualServer: $(SRC_MYTHEN_SVC) - cd gotthardDetectorServer && make -f Makefile.virtual DESTDIR=$(DESTDIR) - - - -%.o : %.cpp %.h Makefile - $(CXX) -Wall -o $@ -c $< $(INCLUDES) $(DFLAGS) $(FLAGS) -fPIC $(EPICSFLAGS) -L/usr/lib64/ - -package: $(OBJS) $(DESTDIR)/libSlsDetector.so $(DESTDIR)/libSlsDetector.a - -$(DESTDIR)/libSlsDetector.so: $(OBJS) - $(CXX) -shared -Wl,-soname,libSlsDetector.so -o libSlsDetector.so $(OBJS) -lc $(INCLUDES) $(DFLAGS) $(FLAGS) $(EPICSFLAGS) -L/usr/lib64/ - $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) - mv libSlsDetector.so $(DESTDIR) - -$(DESTDIR)/libSlsDetector.a: $(OBJS) - ar rcs libSlsDetector.a $(OBJS) - mv libSlsDetector.a $(DESTDIR) - -clean: - rm -rf libSlsDetector.a libSlsDetector.so core docs/* slsDetectorUsersDocs $(OBJS) - - -#------------------------------------------------------------------------------- - -install: package - -install_inc: - $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) - cp -P slsDetector/slsDetectorUsers.h slsDetectorAnalysis/detectorData.h $(DESTDIR) slsReceiver/slsReceiverUsers.h - - diff --git a/slsDetectorSoftware/README b/slsDetectorSoftware/README deleted file mode 100644 index b1cfea7a7..000000000 --- a/slsDetectorSoftware/README +++ /dev/null @@ -1,19 +0,0 @@ -This subversion repository contains - -Common directories -Please inform Anna or Dhanya if you make modifications to these directories -- MySocketTCP : socket class -- commonFiles : header file common to server and client -- slsDetector : base class with all main detector functionalities (client side) - - -Mythen specific directories -Please inform Anna if you make modifications to these directories -- mythenDetector : mythen specific funcs (mainly files I/O and angular conversion) -- mythenDetectorServer : mythen server (for etrax compiler) -- firmware lib might be added in the future - -Other Detector specific directories -Please inform Dhanya if you make modifications to these directories - -make doc diff --git a/slsDetectorSoftware/commonFiles/communication_funcs.c b/slsDetectorSoftware/commonFiles/communication_funcs.c deleted file mode 100755 index e00783c33..000000000 --- a/slsDetectorSoftware/commonFiles/communication_funcs.c +++ /dev/null @@ -1,712 +0,0 @@ - - -#include "communication_funcs.h" -//#include -#include /* for TCP_NODELAY */ -#include -#include -#include -#include - -#include -char lastClientIP[INET_ADDRSTRLEN]; -char thisClientIP[INET_ADDRSTRLEN]; -int lockStatus; -int differentClients; - -//int socketDescriptor, file_des; -const int send_rec_max_size=SEND_REC_MAX_SIZE; -extern int errno; - - -char dummyClientIP[INET_ADDRSTRLEN]; - - -fd_set readset, tempset; -int isock=0, maxfd; - - -int myport=-1; - -//struct sockaddr_in address; -//#define VERBOSE - -#define BLACKFIN_DRVR_SND_LMT (30000) // rough limit -#define BLACKFIN_RSND_PCKT_LOOP (10) -#define BLACKFIN_RSND_WAIT_US (1) - -int bindSocket(unsigned short int port_number) { - int i; - - struct sockaddr_in addressS; - int socketDescriptor; - //int file_des; - - //file_des= -1; - - - - - - - - - - - if (myport==port_number) - return -10; - - - - - - socketDescriptor = socket(AF_INET, SOCK_STREAM,0); //tcp - - //socketDescriptor = socket(PF_INET, SOCK_STREAM, 0); - - - - if (socketDescriptor < 0) { - printf("Can not create socket\n"); - } else { - - i = 1; - setsockopt(socketDescriptor, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i)); - // setsockopt(socketDescriptor, IPPROTO_TCP, TCP_NODELAY, (char *) &i, sizeof(i)); - // TCP_CORK - - // Set some fields in the serverAddress structure. - addressS.sin_family = AF_INET; - addressS.sin_addr.s_addr = htonl(INADDR_ANY); - addressS.sin_port = htons(port_number); - - // memset(&address.sin_addr, 0, sizeof(address.sin_addr)); - - - if(bind(socketDescriptor,(struct sockaddr *) &addressS,sizeof(addressS))<0){ - - printf("Can not create socket\n"); - - socketDescriptor=-1; - } else { - if (listen(socketDescriptor, 5)==0) { - - if (isock==0) { - FD_ZERO(&readset); - } - - - FD_SET(socketDescriptor, &readset); - isock++; - maxfd = socketDescriptor; - printf ("%d port %d fd %d\n",isock, port_number,socketDescriptor); - myport=port_number; - } else - printf("error on listen"); - } - } - - - - //int getrlimit(int resource, struct rlimit *rlim); - - - - return socketDescriptor; - -} - - - - - -int getServerError(int socketDescriptor) -{ - if (socketDescriptor<0) return 1; - else return 0; -}; - - -int acceptConnection(int socketDescriptor) { - - - int j; - - - struct sockaddr_in addressC; - int file_des=-1; - struct timeval tv; - int result; - - - //socklen_t address_length; - socklen_t address_length=sizeof(struct sockaddr_in); - - if (socketDescriptor<0) - return -1; - - memcpy(&tempset, &readset, sizeof(tempset)); - tv.tv_sec = 10000000; - tv.tv_usec = 0; - result = select(maxfd + 1, &tempset, NULL, NULL, &tv); - - if (result == 0) { - printf("select() timed out!\n"); - } else if (result < 0 && errno != EINTR) { - printf("Error in select(): %s\n", strerror(errno)); - } else if (result > 0) { -#ifdef VERBOSE - printf("select returned!\n"); -#endif - for (j=0; j=0) - close(file_des); - FD_CLR(file_des, &readset); -} - -void exitServer(int socketDescriptor) { - if (socketDescriptor>=0) - close(socketDescriptor); -#ifdef VERY_VERBOSE - printf("Closing server\n"); -#endif - FD_CLR(socketDescriptor, &readset); - socketDescriptor=-1; - isock--; -} - - - - -void swapData(void* val,int length,intType itype){ - int i; - int16_t* c= (int16_t*)val; - int32_t* a= (int32_t*)val; - int64_t* b= (int64_t*)val; - for(i=0; length > 0; i++){ - switch(itype){ - case INT16: - c[i] = ((c[i] & 0x00FF) << 8) | ((c[i] & 0xFF00) >> 8); - length -= sizeof(int16_t); - break; - case INT32: - a[i]=((a[i] << 8) & 0xFF00FF00) | ((a[i] >> 8) & 0xFF00FF ); - a[i]=(a[i] << 16) | ((a[i] >> 16) & 0xFFFF); - length -= sizeof(int32_t); - break; - case INT64: - b[i] = ((b[i] << 8) & 0xFF00FF00FF00FF00ULL ) | ((b[i] >> 8) & 0x00FF00FF00FF00FFULL ); - b[i] = ((b[i] << 16) & 0xFFFF0000FFFF0000ULL ) | ((b[i] >> 16) & 0x0000FFFF0000FFFFULL ); - b[i] = (b[i] << 32) | ((b[i] >> 32) & 0xFFFFFFFFULL); - length -= sizeof(int64_t); - break; - default: - length = 0; - break; - } - } -} - -int sendData(int file_des, void* buf,int length, intType itype){ -#ifndef PCCOMPILE -#ifdef EIGERD - swapData(buf, length, itype); -#endif -#endif - return sendDataOnly(file_des, buf, length); -} - - -int receiveData(int file_des, void* buf,int length, intType itype){ - int ret = receiveDataOnly(file_des, buf, length); -#ifndef PCCOMPILE -#ifdef EIGERD - if (ret >= 0) swapData(buf, length, itype); -#endif -#endif - return ret; -} - -int sendDataOnly(int file_des, void* buf,int length) { - if (!length) - return 0; - - - int bytesSent = 0; - int retry = 0; // retry index when buffer is blocked (write returns 0) - while (bytesSent < length) { - - // setting a max packet size for blackfin driver (and network driver does not do a check if packets sent) - int bytesToSend = length - bytesSent; - if (bytesToSend > BLACKFIN_DRVR_SND_LMT) - bytesToSend = BLACKFIN_DRVR_SND_LMT; - - // send - int rc = write(file_des, (char*)((char*)buf + bytesSent), bytesToSend); - // error - if (rc < 0) { - cprintf(BG_RED, "Error writing to socket. Possible socket crash: left=%d rc=%d length=%d sent=%d\n", bytesToSend, rc, length, bytesSent); - return bytesSent; - } - // also error, wrote nothing, buffer blocked up, too fast sending for client - if (rc == 0) { - cprintf(RED, "Error writing to socket. Buffer full. Retry: %d\n", retry); - ++retry; - // wrote nothing for many loops - if (retry >= BLACKFIN_RSND_PCKT_LOOP) { - cprintf(BG_RED, "Error writing to socket. Buffer full! Too fast! No more.\n"); - return bytesSent; - } - usleep(BLACKFIN_RSND_WAIT_US); - } - // wrote something, reset retry - else { - retry = 0; - } - bytesSent += rc; - } - - return bytesSent; -} - - - int receiveDataOnly(int file_des, void* buf,int length) { - - int total_received=0; - int nreceiving; - int nreceived; - if (file_des<0) return -1; -#ifdef VERY_VERBOSE - printf("want to receive %d Bytes\n", length); -#endif - - while(length > 0) { - nreceiving = (length>send_rec_max_size) ? send_rec_max_size:length; // (condition) ? if_true : if_false - nreceived = read(file_des,(char*)buf+total_received,nreceiving); - if(!nreceived){ - if(!total_received) { - return -1; //to handle it - } - break; - } - length-=nreceived; - total_received+=nreceived; - } - - if (total_received>0) - strcpy(thisClientIP,dummyClientIP); - - if (strcmp(lastClientIP,thisClientIP)) - differentClients=1; - else - differentClients=0; - - return total_received; -} - - - - - - - - - - - - - - - -int sendChannel(int file_des, sls_detector_channel *myChan) { - int ts=0; - //sendDataOnly(file_des,myChan, sizeof(sls_detector_channel)); - ts+=sendData(file_des,&(myChan->chan),sizeof(myChan->chan),INT32); - ts+=sendData(file_des,&(myChan->chip),sizeof(myChan->chip),INT32); - ts+=sendData(file_des,&(myChan->module),sizeof(myChan->module),INT32); - ts+=sendData(file_des,&(myChan->reg),sizeof(myChan->reg),INT64); - return ts; -} - -int sendChip(int file_des, sls_detector_chip *myChip) { - int ts=0; - //ts+=sendDataOnly(file_des,myChip,sizeof(sls_detector_chip)); - ts+=sendData(file_des,&(myChip->chip),sizeof(myChip->chip),INT32); - ts+=sendData(file_des,&(myChip->module),sizeof(myChip->module),INT32); - ts+=sendData(file_des,&(myChip->nchan),sizeof(myChip->nchan),INT32); - ts+=sendData(file_des,&(myChip->reg),sizeof(myChip->reg),INT32); - ts+=sendData(file_des,(myChip->chanregs),sizeof(myChip->chanregs),INT32); - ts+=sendData(file_des,myChip->chanregs,myChip->nchan*sizeof(int),INT32); - return ts; -} - - -int sendModule(int file_des, sls_detector_module *myMod) { - return sendModuleGeneral(file_des, myMod, 1); -} - - -int sendModuleGeneral(int file_des, sls_detector_module *myMod, int sendAll) { - int ts=0; -#ifdef VERBOSE - int idac; -#endif - int nChips=myMod->nchip; - int nChans=myMod->nchan; - int nAdcs=myMod->nadc; - int nDacs=myMod->ndac; - //ts+= sendDataOnly(file_des,myMod,sizeof(sls_detector_module)); - ts+=sendData(file_des,&(myMod->module),sizeof(myMod->module),INT32); - ts+=sendData(file_des,&(myMod->serialnumber),sizeof(myMod->serialnumber),INT32); - ts+=sendData(file_des,&(myMod->nchan),sizeof(myMod->nchan),INT32); - ts+=sendData(file_des,&(myMod->nchip),sizeof(myMod->nchip),INT32); - ts+=sendData(file_des,&(myMod->ndac),sizeof(myMod->ndac),INT32); - ts+=sendData(file_des,&(myMod->nadc),sizeof(myMod->nadc),INT32); - ts+=sendData(file_des,&(myMod->reg),sizeof(myMod->reg),INT32); - -#ifdef MYTHEND - ts+=sendData(file_des,myMod->dacs,sizeof(myMod->ndac),OTHER); - ts+=sendData(file_des,myMod->adcs,sizeof(myMod->nadc),OTHER); - ts+=sendData(file_des,myMod->chipregs,sizeof(myMod->nchip),OTHER); - ts+=sendData(file_des,myMod->chanregs,sizeof(myMod->nchan),OTHER); - } -#endif - ts+=sendData(file_des,&(myMod->gain), sizeof(myMod->gain),OTHER); - ts+=sendData(file_des,&(myMod->offset), sizeof(myMod->offset),OTHER); - -#ifdef VERBOSE - printf("module %d of size %d sent\n",myMod->module, ts); -#endif - ts+= sendData(file_des,myMod->dacs,sizeof(dacs_t)*nDacs,INT32); -#ifdef VERBOSE - printf("dacs %d of size %d sent\n",myMod->module, ts); - int idac; - for (idac=0; idac< nDacs; idac++) - printf("dac %d is %d\n",idac,(int)myMod->dacs[idac]); -#endif - ts+= sendData(file_des,myMod->adcs,sizeof(dacs_t)*nAdcs,INT32); -#ifdef VERBOSE - printf("adcs %d of size %d sent\n",myMod->module, ts); -#endif - - /*some detectors dont require sending all trimbits etc.*/ - if(sendAll){ - ts+=sendData(file_des,myMod->chipregs,sizeof(int)*nChips,INT32); -#ifdef VERBOSE - printf("chips %d of size %d sent\n",myMod->module, ts); -#endif - ts+=sendData(file_des,myMod->chanregs,sizeof(int)*nChans,INT32); -#ifdef VERBOSE - printf("chans %d of size %d sent - %d\n",myMod->module, ts, myMod->nchan); -#endif - } - -#ifdef VERBOSE - printf("module %d of size %d sent register %x\n",myMod->module, ts, myMod->reg); -#endif - return ts; -} - -int receiveChannel(int file_des, sls_detector_channel *myChan) { - int ts=0; - //receiveDataOnly(file_des,myChan,sizeof(sls_detector_channel)); - ts+=receiveData(file_des,&(myChan->chan),sizeof(myChan->chan),INT32); - ts+=receiveData(file_des,&(myChan->chip),sizeof(myChan->chip),INT32); - ts+=receiveData(file_des,&(myChan->module),sizeof(myChan->module),INT32); - ts+=receiveData(file_des,&(myChan->reg),sizeof(myChan->reg),INT32); - return ts; -} - -int receiveChip(int file_des, sls_detector_chip* myChip) { - - int *ptr=myChip->chanregs; - int ts=0; - int nChans, nchanold=myChip->nchan, chdiff; - - //ts+= receiveDataOnly(file_des,myChip,sizeof(sls_detector_chip)); - ts+=receiveData(file_des,&(myChip->chip),sizeof(myChip->chip),INT32); - ts+=receiveData(file_des,&(myChip->module),sizeof(myChip->module),INT32); - ts+=receiveData(file_des,&(myChip->nchan),sizeof(myChip->nchan),INT32); - ts+=receiveData(file_des,&(myChip->reg),sizeof(myChip->reg),INT32); - ts+=receiveData(file_des,(myChip->chanregs),sizeof(myChip->chanregs),INT32); - - myChip->chanregs=ptr; - nChans=myChip->nchan; - chdiff=nChans-nchanold; - if (nchanold!=nChans) { - printf("wrong number of channels received!\n"); - } - - -#ifdef VERBOSE - printf("chip structure received\n"); - printf("now receiving %d channels\n", nChans); -#endif - - if (chdiff<=0) - ts+=receiveData(file_des,myChip->chanregs, sizeof(int)*nChans,INT32); - else { - ptr=(int*)malloc(chdiff*sizeof(int)); - myChip->nchan=nchanold; - ts+=receiveData(file_des,myChip->chanregs, sizeof(int)*nchanold,INT32); - ts+=receiveData(file_des,ptr, sizeof(int)*chdiff,INT32); - free(ptr); - return FAIL; - } - -#ifdef VERBOSE - printf("chip's channels received\n"); -#endif - return ts; -} - - -int receiveModule(int file_des, sls_detector_module* myMod) { - return receiveModuleGeneral(file_des,myMod,1); -} - -int receiveModuleGeneral(int file_des, sls_detector_module* myMod, int receiveAll) { - int ts=0; - dacs_t *dacptr=myMod->dacs; - dacs_t *adcptr=myMod->adcs; - int *chipptr=myMod->chipregs, *chanptr=myMod->chanregs; - int nChips, nchipold=myMod->nchip, nchipdiff; - int nChans, nchanold=myMod->nchan, nchandiff; - int nDacs, ndold=myMod->ndac, ndacdiff; - int nAdcs, naold=myMod->nadc, nadcdiff; -#ifdef VERBOSE - int id=0; -#endif - // ts+= receiveDataOnly(file_des,myMod,sizeof(sls_detector_module)); - ts+=receiveData(file_des,&(myMod->module),sizeof(myMod->module),INT32); - ts+=receiveData(file_des,&(myMod->serialnumber),sizeof(myMod->serialnumber),INT32); - ts+=receiveData(file_des,&(myMod->nchan),sizeof(myMod->nchan),INT32); - ts+=receiveData(file_des,&(myMod->nchip),sizeof(myMod->nchip),INT32); - ts+=receiveData(file_des,&(myMod->ndac),sizeof(myMod->ndac),INT32); - ts+=receiveData(file_des,&(myMod->nadc),sizeof(myMod->nadc),INT32); - ts+=receiveData(file_des,&(myMod->reg),sizeof(myMod->reg),INT32); -#ifdef MYTHEND - ts+=receiveData(file_des,myMod->dacs,sizeof(myMod->ndac),INT32); - ts+=receiveData(file_des,myMod->adcs,sizeof(myMod->nadc),INT32); - ts+=receiveData(file_des,myMod->chipregs,sizeof(myMod->nchip),INT32); - ts+=receiveData(file_des,myMod->chanregs,sizeof(myMod->nchan),INT32); -#endif - ts+=receiveData(file_des,&(myMod->gain), sizeof(myMod->gain),OTHER); - ts+=receiveData(file_des,&(myMod->offset), sizeof(myMod->offset),OTHER); - - myMod->dacs=dacptr; - myMod->adcs=adcptr; - myMod->chipregs=chipptr; - myMod->chanregs=chanptr; - -#ifdef EIGERD - //feature to exclude sending of trimbtis, nchips=0,nchans=0 in that case - if(myMod->nchip == 0 && myMod->nchan == 0) { - receiveAll=0; - nchipold=0; - nchanold=0; - } -#endif - - - nChips=myMod->nchip; - nchipdiff=nChips-nchipold; - if (nchipold!=nChips) { - printf("received wrong number of chips\n"); - } -#ifdef VERBOSE - else - printf("received %d chips\n",nChips); -#endif - - nChans=myMod->nchan; - nchandiff=nChans-nchanold; - if (nchanold!=nChans) { - printf("received wrong number of channels\n"); - } -#ifdef VERBOSE - else - printf("received %d chans\n",nChans); -#endif - - - nDacs=myMod->ndac; - ndacdiff=nDacs-ndold; - if (ndold!=nDacs) { - printf("received wrong number of dacs\n"); - } -#ifdef VERBOSE - else - printf("received %d dacs\n",nDacs); -#endif - - nAdcs=myMod->nadc; - nadcdiff=nAdcs-naold; - if (naold!=nAdcs) { - printf("received wrong number of adcs\n"); - } -#ifdef VERBOSE - else - printf("received %d adcs\n",nAdcs); -#endif - if (ndacdiff<=0) { - ts+=receiveData(file_des,myMod->dacs, sizeof(dacs_t)*nDacs,INT32); -#ifdef VERBOSE - printf("dacs received\n"); - int id; - for (id=0; iddacs[id]); - - -#endif - } else { - dacptr=(dacs_t*)malloc(ndacdiff*sizeof(dacs_t)); - myMod->ndac=ndold; - ts+=receiveData(file_des,myMod->dacs, sizeof(dacs_t)*ndold,INT32); - ts+=receiveData(file_des,dacptr, sizeof(dacs_t)*ndacdiff,INT32); - free(dacptr); - return FAIL; - } - - if (nadcdiff<=0) { - ts+=receiveData(file_des,myMod->adcs, sizeof(dacs_t)*nAdcs,INT32); -#ifdef VERBOSE - printf("adcs received\n"); -#endif - } else { - adcptr=(dacs_t*)malloc(nadcdiff*sizeof(dacs_t)); - myMod->nadc=naold; - ts+=receiveData(file_des,myMod->adcs, sizeof(dacs_t)*naold,INT32); - ts+=receiveData(file_des,adcptr, sizeof(dacs_t)*nadcdiff,INT32); - free(adcptr); - return FAIL; - } - - - /*some detectors dont require sending all trimbits etc.*/ - if(receiveAll){ - - if (nchipdiff<=0) { - ts+=receiveData(file_des,myMod->chipregs, sizeof(int)*nChips,INT32); -#ifdef VERBOSE - printf("chips received\n"); -#endif - } else { - chipptr=(int*)malloc(nchipdiff*sizeof(int)); - myMod->nchip=nchipold; - ts+=receiveData(file_des,myMod->chipregs, sizeof(int)*nchipold,INT32); - ts+=receiveData(file_des,chipptr, sizeof(int)*nchipdiff,INT32); - free(chipptr); - return FAIL; - } - - if (nchandiff<=0) { - ts+=receiveData(file_des,myMod->chanregs, sizeof(int)*nChans,INT32); -#ifdef VERBOSE - printf("chans received\n"); -#endif - } else { - chanptr=(int*)malloc(nchandiff*sizeof(int)); - myMod->nchan=nchanold; - ts+=receiveData(file_des,myMod->chanregs, sizeof(int)*nchanold,INT32); - ts+=receiveData(file_des,chanptr, sizeof(int)*nchandiff,INT32); - free(chanptr); - return FAIL; - } - } -#ifdef VERBOSE - printf("received module %d of size %d register %x\n",myMod->module,ts,myMod->reg); -#endif - - return ts; -} diff --git a/slsDetectorSoftware/commonFiles/communication_funcs.h b/slsDetectorSoftware/commonFiles/communication_funcs.h deleted file mode 100755 index e4e3fac27..000000000 --- a/slsDetectorSoftware/commonFiles/communication_funcs.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef COMMUNICATION_FUNCS_H -#define COMMUNICATION_FUNCS_H - -#define SEND_REC_MAX_SIZE 4096 -#define DEFAULT_PORTNO 1952 -#include -#include - - -#include -#include -#include -#include - -#include "sls_detector_defs.h" - - - -typedef enum{ - INT16, - INT32, - INT64, - OTHER -}intType; - - - - -int bindSocket(unsigned short int port_number); -int acceptConnection(int socketDescriptor); -void closeConnection(int file_Des); -void exitServer(int socketDescriptor); - -void swapData(void* val,int length,intType itype); -int sendData(int file_des, void* buf,int length, intType itype); -int receiveData(int file_des, void* buf,int length, intType itype); -int sendDataOnly(int file_des, void* buf,int length); -int receiveDataOnly(int file_des, void* buf,int length); - - -int getServerError(int socketDescriptor); -int sendChannel(int file_des, sls_detector_channel *myChan); -int sendChip(int file_des, sls_detector_chip *myChip); -int sendModule(int file_des, sls_detector_module *myMod); -int sendModuleGeneral(int file_des, sls_detector_module *myMod, int sendAll); -int receiveChannel(int file_des, sls_detector_channel *myChan); -int receiveChip(int file_des, sls_detector_chip* myChip); -int receiveModule(int file_des, sls_detector_module* myMod); -int receiveModuleGeneral(int file_des, sls_detector_module* myMod, int receiveAll); - -#endif diff --git a/slsDetectorSoftware/commonFiles/sls_detector_defs.h b/slsDetectorSoftware/commonFiles/sls_detector_defs.h deleted file mode 100755 index 209aa8362..000000000 --- a/slsDetectorSoftware/commonFiles/sls_detector_defs.h +++ /dev/null @@ -1,616 +0,0 @@ -#ifndef SLS_DETECTOR_DEFS_H -#define SLS_DETECTOR_DEFS_H - - -#ifdef __CINT__ -#define MYROOT -#define __cplusplus -#endif - -//#include -#include "sls_receiver_defs.h" - -/** default maximum string length */ -#define MAX_SCAN_STEPS 2000 -/** maxmimum number of modules per controller*/ -#define MAXMODS 24 -/** maxmimum number of detectors ina multidetector structure*/ -#define MAXDET 100 -/** header length for data :gotthard*/ -#define HEADERLENGTH 12 - -/** maximum rois */ -#define MAX_ROIS 100 - -/** maximum trim en */ -#define MAX_TRIMEN 100 - -/** maximum unit size of program sent to detector */ -#define MAX_FPGAPROGRAMSIZE (2 * 1024 *1024) - - - -#define MAX_SCAN_LEVELS 2 - -typedef char mystring[MAX_STR_LENGTH]; -typedef double mysteps[MAX_SCAN_STEPS]; - - - -#ifndef DACS_FLOAT -typedef int dacs_t; -#else -typedef float dacs_t; -#endif - -#define DEFAULT_DET_MAC "00:aa:bb:cc:dd:ee" -#define DEFAULT_DET_IP "129.129.202.46" - - -/** - \file sls_detector_defs.h -This file contains all the basic definitions common to the slsDetector class -and to the server programs running on the detector - - - * @author Anna Bergamaschi - * @version 0.1alpha (any string) - * @see slsDetector - -$Revision: 824 $ - -*/ - - -/** get flag form most functions */ -#define GET_FLAG -1 - - -#ifdef __cplusplus - -/** @short class containing all the structures, constants and enum definitions */ -class slsDetectorDefs: public virtual slsReceiverDefs{ - public: - - slsDetectorDefs(){}; - -#endif - - - enum {startScript, scriptBefore, headerBefore, headerAfter,scriptAfter, stopScript, enCalLog, angCalLog, MAX_ACTIONS}; - - - -/** - @short structure for a detector channel - - should not be used by unexperienced users - - \see ::channelRegisterBit -*/ - typedef struct { - int chan; /**< is the channel number */ - int chip; /**< is the chip number */ - int module; /**< is the module number */ - int64_t reg; /**< is the is the channel register (e.g. trimbits, calibration enable, comparator enable...) */ - } sls_detector_channel; - - /** - @short structure for a detector chip - - should not be used by unexperienced users - \see ::chipRegisterBit ::channelRegisterBit -*/ - typedef struct { - int chip; /**< is the chip number */ - int module; /**< is the module number */ - int nchan; /**< is the number of channels in the chip */ - int reg; /***/ - M_vIbias, /**< mythen 3 >*/ - M_vIinSh, /**< mythen 3 >*/ - M_VdcSh, /**< mythen 3 >*/ - M_Vth2, /**< mythen 3 >*/ - M_VPL, /**< mythen 3 >*/ - M_Vth3, /**< mythen 3 >*/ - M_casSh, /**< mythen 3 >*/ - M_cas, /**< mythen 3 >*/ - M_vIbiasSh, /**< mythen 3 >*/ - M_vIcin, /**< mythen 3 >*/ - M_vIpreOut, /**< mythen 3 >*/ - ZMQ_emin, /**< ZMQ */ - ZMQ_emax,/**< ZMQ */ - V_POWER_A = 100, /**new chiptest board */ - V_POWER_B = 101, /**new chiptest board */ - V_POWER_C = 102, /**new chiptest board */ - V_POWER_D = 103, /**new chiptest board */ - V_POWER_IO =104, /**new chiptest board */ - V_POWER_CHIP=105 ,/**new chiptest board */ - I_POWER_A=106 , /**new chiptest board */ - I_POWER_B=107 , /**new chiptest board */ - I_POWER_C=108 , /**new chiptest board */ - I_POWER_D=109 , /**new chiptest board */ - I_POWER_IO=110 , /**new chiptest board */ - V_LIMIT=111 /**new chiptest board */ -}; - -/** - detector settings indexes -*/ -enum detectorSettings{ - GET_SETTINGS=-1, /**< return current detector settings */ - STANDARD, /**< standard settings */ - FAST, /**< fast settings */ - HIGHGAIN, /**< highgain settings */ - DYNAMICGAIN, /**< dynamic gain settings */ - LOWGAIN, /**< low gain settings */ - MEDIUMGAIN, /**< medium gain settings */ - VERYHIGHGAIN, /**< very high gain settings */ - LOWNOISE, /**< low noise settings */ - DYNAMICHG0, /**< dynamic high gain 0 */ - FIXGAIN1, /**< fix gain 1 */ - FIXGAIN2, /**< fix gain 2 */ - FORCESWITCHG1, /**< force switch gain 1 */ - FORCESWITCHG2, /**< force switch gain 2 */ - VERYLOWGAIN, /**< very low gain settings */ - UNDEFINED=200, /**< undefined or custom settings */ - UNINITIALIZED /**< uninitialiazed (status at startup) */ -}; -/** - meaning of the channel register bits - \see ::sls_detector_channel -*/ -enum channelRegisterBit { - TRIMBIT_OFF=0, /**< offset of trimbit value in the channel register */ - COMPARATOR_ENABLE=0x100, /**< mask of the comparator enable bit */ - ANALOG_SIGNAL_ENABLE=0x200, /**< mask of the analogue output enable bit */ - CALIBRATION_ENABLE=0x300, /**< mask of the calibration input enable bit */ -}; - -#define TRIMBITMASK 0x3f -/** - meaning of the chip register bits - \see ::sls_detector_chip -*/ -enum chipRegisterBit { - ENABLE_ANALOG_OUTPUT=0x1, /**< mask of the analogue output enable bit */ - CHIP_OUTPUT_WIDTH=0x2 /**< mask of the chip output width */ -}; -/** - meaning of the module register bits -*/ -enum moduleRegisterBit { - MY_MODULE_REGISTER_BIT, /**< possible module register bit meaning */ - MODULE_OUTPUT_WIDTH /**< possibly module dynamic range */ -}; - - -/** - important speed parameters -*/ -enum speedVariable { - CLOCK_DIVIDER, /**< readout clock divider */ - WAIT_STATES, /**< wait states for bus read */ - TOT_CLOCK_DIVIDER, /**< wait states for bus read */ - TOT_DUTY_CYCLE, /**< wait states for bus read */ - SET_SIGNAL_LENGTH, /**< set/clear signal length */ - PHASE_SHIFT, /**< adds phase shift */ - OVERSAMPLING, /**< oversampling for analog detectors */ - ADC_CLOCK, /**< adc clock divider */ - ADC_PHASE, /**< adc clock phase */ - ADC_PIPELINE, /**< adc pipeline */ - DBIT_CLOCK, /**< adc clock divider */ - DBIT_PHASE, /**< adc clock phase */ - DBIT_PIPELINE /**< adc pipeline */ -}; - - -/** - readout flags -*/ -enum readOutFlags { - GET_READOUT_FLAGS=-1, /**< return readout flags */ - NORMAL_READOUT=0, /**< no flag */ - STORE_IN_RAM=0x1, /**< data are stored in ram and sent only after end of acquisition for faster frame rate */ - READ_HITS=0x2, /**< return only the number of the channel which counted ate least one */ - ZERO_COMPRESSION=0x4,/**< returned data are 0-compressed */ - PUMP_PROBE_MODE=0x8,/** -#include */ - -#include -#include -#include - - -#include "xparameters.h" -#include "Feb.h" - - - -void Feb_Feb(){ - - Feb_nfebs = 0; - Feb_feb_numb = 0; - - Feb_send_ndata = 0; - Feb_send_buffer_size = 1026; - Feb_send_data_raw = malloc((Feb_send_buffer_size+1)*sizeof(int)); - Feb_send_data = &Feb_send_data_raw[1]; - - Feb_recv_ndata = 0; - Feb_recv_buffer_size = 1026; - Feb_recv_data_raw = malloc((Feb_recv_buffer_size+1)*sizeof(int)); - Feb_recv_data = &Feb_recv_data_raw[1]; - - Local_LocalLinkInterface1(ll,XPAR_PLB_LL_FIFO_AURORA_DUAL_CTRL_FEB_RIGHT_BASEADDR); - -} -/* -~Feb(){ - delete ll; - if(feb_numb) delete [] feb_numb; - delete [] send_data_raw; - delete [] recv_data_raw; -} -*/ - -void Feb_SendCompleteFebList(unsigned int n,unsigned int* list){ - unsigned int i; - if(Feb_feb_numb) free(Feb_feb_numb); - Feb_nfebs = n; - Feb_feb_numb = malloc(n*sizeof(unsigned int)); - for(i=0;i0xfff) return 0; - - Feb_send_data_raw[0] = 0x90000000 | (ch<<16); //we - if(Local_Write(ll,4,Feb_send_data_raw)!=4) return 0; - - Feb_send_data_raw[0] = 0xc0000000; //data - return 1;//((Feb_send_ndata+1)*4==Local_Write(ll,(Feb_send_ndata+1)*4,Feb_send_data_raw)); -} - -int Feb_ReadFrom(unsigned int ch, unsigned int ntrys){ - unsigned int t; - if(ch>=0xfff) return 0; - - Feb_recv_data_raw[0] = 0xa0000000 | (ch<<16); //read data - Local_Write(ll,4,Feb_recv_data_raw); - usleep(20); - - Feb_recv_ndata=-1; - for(t=0;t0){ - Feb_recv_ndata--; - break; - } - printf("\t Read try number: %d\n",t); - usleep(1000); - } - - - return (Feb_recv_ndata>=0); -} - -void Feb_PrintData(){ - int i; - printf("Sent data: %d\n",Feb_send_ndata); - for(i=0;i1&&Feb_recv_ndata>1){ - printf("\t\t Tail sent: %d (0x%x) receiver: %d (0x%x)\n",Feb_send_data[Feb_send_ndata-1],Feb_send_data[Feb_send_ndata-1],Feb_recv_data[Feb_recv_ndata-1],Feb_recv_data[Feb_recv_ndata-1]); - }else{ - printf("Error printing tail, too little data nsent = 0x%x, nrecv = 0x%x.\n",Feb_send_ndata, Feb_recv_ndata); - } - Feb_PrintData(); - } - return header_returned_is_ok; -} - - -int Feb_CheckTail(unsigned int valid_bit_mask){ - if(Feb_send_ndata<=1&&Feb_recv_ndata<=1){ - printf("Error checking tail, too little data nsent = %d, nrecv = %d.\n",Feb_send_ndata, Feb_recv_ndata); - return 0; - } - - unsigned int the_tail = Feb_recv_data[Feb_recv_ndata-1]&valid_bit_mask; - if(the_tail!=0){ - printf("Error returned in tail: 0x%x (%d)\n",the_tail,the_tail); - if(the_tail&0x10000000) printf("\t\tBusy flag address error.\n"); - if(the_tail&0x20000000) printf("\t\tRead register address error.\n"); - if(the_tail&0x40000000) printf("\t\tWrite register address error.\n"); - if(the_tail&0x80000000) printf("\t\tBram number error.\n"); - if(the_tail&0x08000000) printf("\t\tFifo to read from error.\n"); - if(the_tail&0x3ff) printf("\t\tNumber of data send error.\n"); - return 0; //error - } - - return 1; -} - - -int Feb_CheckCommunication(){ - Feb_send_data_raw[0] = 0x8fff0000; //rst-all serial coms and lls - if(Local_Write(ll,4,Feb_send_data_raw)!=4) return 0; - - printf("CheckingCommunication ....\n"); - while((Local_Read(ll,Feb_recv_buffer_size*4,Feb_recv_data_raw)/4)>0) printf("\t) Cleanning buffer ...\n"); - - return Feb_SetByteOrder(); -} - - -int Feb_SetByteOrder(){ - - unsigned int i; - Feb_send_ndata = 2; - Feb_send_data[0] = 0; //header - Feb_send_data[1] = 0; //tail - - unsigned int dst = 0xff; - for( i=0;i=nfebs){ - cout<<"Error invalid sub number "<Feb_send_buffer_size-2) return 0; - - Feb_send_ndata = nreads+2; - Feb_send_data[0] = 0x20000000 | nreads << 14; //cmd -> read "00" , nreads - - for(i=0;iFeb_send_buffer_size-2) return 0; - - //cout<<"Write register : "< write nwrites and how many - Feb_send_data[2*nwrites+1] = 0; //tail - - for(i=0;iFeb_send_buffer_size-2) return 0; - - Feb_send_ndata = nwrites+2; - Feb_send_data[0] = 0xc0000000 | mem_num << 24 | nwrites << 14 | start_address; //cmd -> write to memory, nwrites, mem number, start address - Feb_send_data[nwrites+1] = 0; //tail - for(i=0;i -#include -//#include -//#include - - -#include "FebInterface.h" - - -struct Module{ - unsigned int module_number; - int top_address_valid; - unsigned int top_left_address; - unsigned int top_right_address; - int bottom_address_valid; - unsigned int bottom_left_address; - unsigned int bottom_right_address; - - unsigned int idelay_top[4]; //ll,lr,rl,ll - unsigned int idelay_bottom[4]; //ll,lr,rl,ll - float high_voltage; - int* top_dac; - int* bottom_dac; -}; - - -void Module_Module(struct Module* mod,unsigned int number, unsigned int address_top); -void Module_ModuleBottom(struct Module* mod,unsigned int number, unsigned int address_bottom); -void Module_Module1(struct Module* mod,unsigned int number, unsigned int address_top, unsigned int address_bottom); -unsigned int Module_GetModuleNumber(struct Module* mod); -int Module_TopAddressIsValid(struct Module* mod); -unsigned int Module_GetTopBaseAddress(struct Module* mod); -unsigned int Module_GetTopLeftAddress(struct Module* mod) ; -unsigned int Module_GetTopRightAddress(struct Module* mod); -unsigned int Module_GetBottomBaseAddress(struct Module* mod); -int Module_BottomAddressIsValid(struct Module* mod); -unsigned int Module_GetBottomLeftAddress(struct Module* mod); -unsigned int Module_GetBottomRightAddress(struct Module* mod); -unsigned int Module_SetTopIDelay(struct Module* mod,unsigned int chip,unsigned int value); -unsigned int Module_GetTopIDelay(struct Module* mod,unsigned int chip) ; -unsigned int Module_SetBottomIDelay(struct Module* mod,unsigned int chip,unsigned int value); -unsigned int Module_GetBottomIDelay(struct Module* mod,unsigned int chip); - -float Module_SetHighVoltage(struct Module* mod,float value); -float Module_GetHighVoltage(struct Module* mod); - -int Module_SetTopDACValue(struct Module* mod,unsigned int i, int value); -int Module_GetTopDACValue(struct Module* mod,unsigned int i); -int Module_SetBottomDACValue(struct Module* mod,unsigned int i, int value); -int Module_GetBottomDACValue(struct Module* mod,unsigned int i); - - - - - - -void Feb_Control_activate(int activate); - -int Feb_Control_IsBottomModule(); -int Feb_Control_GetModuleNumber(); - - - - - void Feb_Control_PrintModuleList(); - int Feb_Control_GetModuleIndex(unsigned int module_number, unsigned int* module_index); - int Feb_Control_CheckModuleAddresses(struct Module* m); - int Feb_Control_AddModule(unsigned int module_number, unsigned int top_address); - /*int Feb_Control_AddModule(unsigned int module_number, unsigned int top_address, unsigned int bottom_address, int half_module=0);*/ - int Feb_Control_AddModule1(unsigned int module_number, int top_enable, unsigned int top_address, unsigned int bottom_address, int half_module); - - int Feb_Control_GetDACNumber(char* s, unsigned int* n); - int Feb_Control_SendDACValue(unsigned int dst_num, unsigned int ch, unsigned int* value); - int Feb_Control_VoltageToDAC(float value, unsigned int* digital, unsigned int nsteps, float vmin, float vmax); - float Feb_Control_DACToVoltage(unsigned int digital,unsigned int nsteps,float vmin,float vmax); - - - int Feb_Control_SendIDelays(unsigned int dst_num, int chip_lr, unsigned int channels, unsigned int ndelay_units); - - int Feb_Control_SetStaticBits(); - int Feb_Control_SetStaticBits1(unsigned int the_static_bits); - - int Feb_Control_SendBitModeToBebServer(); - - unsigned int Feb_Control_ConvertTimeToRegister(float time_in_sec); - - unsigned int Feb_Control_AddressToAll(); - int Feb_Control_SetCommandRegister(unsigned int cmd); - int Feb_Control_GetDAQStatusRegister(unsigned int dst_address, unsigned int* ret_status); - /*int Feb_Control_StartDAQOnlyNWaitForFinish(int sleep_time_us=5000);*/ - int Feb_Control_StartDAQOnlyNWaitForFinish(int sleep_time_us); - - int Feb_Control_ResetChipCompletely(); - int Feb_Control_ResetChipPartially(); - - //struct sockaddr_in Feb_Control_serv_addr; - /* - int Feb_Control_SetupSendToSocket(const char* ip_address_hostname, unsigned short int port); - int Feb_Control_WriteNRead(char* message, int length, int max_length); -*/ - - - void Feb_Control_FebControl(); - int Feb_Control_Init(int master, int top, int normal, int module_num); - int Feb_Control_OpenSerialCommunication(); - void Feb_Control_CloseSerialCommunication(); - int Feb_Control_CheckSetup(); - - unsigned int Feb_Control_GetNModules(); - unsigned int Feb_Control_GetNHalfModules(); - - int Feb_Control_SetHighVoltage(int value); - int Feb_Control_GetHighVoltage(int* value); - - int Feb_Control_SendHighVoltage(int dacvalue); - int Feb_Control_ReceiveHighVoltage(unsigned int* value); - - int Feb_Control_SetIDelays(unsigned int module_num, unsigned int ndelay_units); - int Feb_Control_SetIDelays1(unsigned int module_num, unsigned int chip_pos, unsigned int ndelay_units); - - int Feb_Control_DecodeDACString(char* dac_str, unsigned int* module_index, int* top, int* bottom, unsigned int* dac_ch); - /*int Feb_Control_SetDAC(string s, int value, int is_a_voltage_mv=0);*/ - int Feb_Control_SetDAC(char* s, int value, int is_a_voltage_mv); - /* int Feb_Control_GetDAC(string s, int* ret_value, int voltage_mv=0);*/ - int Feb_Control_GetDAC(char* s, int* ret_value, int voltage_mv); - int Feb_Control_GetDACName(unsigned int dac_num,char* s); - - int Feb_Control_SetTrimbits(unsigned int module_num, unsigned int* trimbits); - unsigned int* Feb_Control_GetTrimbits(); - - - /**Added by Dhanya */ - int Feb_Control_SaveAllTrimbitsTo(int value); - - - - int Feb_Control_Reset(); - int Feb_Control_PrepareForAcquisition(); - - int Feb_Control_StartAcquisition(); - int Feb_Control_StopAcquisition(); - int Feb_Control_AcquisitionInProgress(); - int Feb_Control_AcquisitionStartedBit(); - /*int Feb_Control_WaitForFinishedFlag(int sleep_time_us=5000);*/ - int Feb_Control_WaitForFinishedFlag(int sleep_time_us); - int Feb_Control_WaitForStartedFlag(int sleep_time_us, int prev_flag); - - //functions for setting up exposure - void Feb_Control_PrintAcquisitionSetup(); - int Feb_Control_SetNExposures(unsigned int n_images); - unsigned int Feb_Control_GetNExposures(); - int Feb_Control_SetExposureTime(double the_exposure_time_in_sec); - double Feb_Control_GetExposureTime(); - int64_t Feb_Control_GetExposureTime_in_nsec(); - int Feb_Control_SetSubFrameExposureTime(int64_t the_subframe_exposure_time_in_10nsec); - int64_t Feb_Control_GetSubFrameExposureTime(); - int Feb_Control_SetSubFramePeriod(int64_t the_subframe_period_in_10nsec); - int64_t Feb_Control_GetSubFramePeriod(); - int Feb_Control_SetExposurePeriod(double the_exposure_period_in_sec); - double Feb_Control_GetExposurePeriod(); - int Feb_Control_SetDynamicRange(unsigned int four_eight_sixteen_or_thirtytwo); - unsigned int Feb_Control_GetDynamicRange(); - int Feb_Control_SetReadoutSpeed(unsigned int readout_speed); //0 was default, 0->full,1->half,2->quarter or 3->super_slow - int Feb_Control_SetReadoutMode(unsigned int readout_mode); ///0 was default,0->parallel,1->non-parallel,2-> safe_mode - int Feb_Control_SetTriggerMode(unsigned int trigger_mode, int polarity);//0 and 1 was default, - int Feb_Control_SetExternalEnableMode(int use_external_enable, int polarity);//0 and 1 was default, - - //functions for testing - /*int Feb_Control_SetTestModeVariable(int on=1);*/ - int Feb_Control_SetInTestModeVariable(int on); - int Feb_Control_GetTestModeVariable(); - - void Feb_Control_Set_Counter_Bit(int value); - int Feb_Control_Get_Counter_Bit(); - int Feb_Control_Pulse_Pixel(int npulses,int x, int y); - int Feb_Control_PulsePixelNMove(int npulses, int inc_x_pos, int inc_y_pos); - int Feb_Control_Shift32InSerialIn(unsigned int value_to_shift_in); - int Feb_Control_SendTokenIn(); - int Feb_Control_ClockRowClock(unsigned int ntimes); - int Feb_Control_PulseChip(int npulses); - - int64_t Feb_Control_Get_RateTable_Tau_in_nsec(); - int64_t Feb_Control_Get_RateTable_Period_in_nsec(); - int Feb_Control_SetRateCorrectionTau(int64_t tau_in_Nsec); - int Feb_Control_SetRateCorrectionTable(unsigned int *table); - int Feb_Control_GetRateCorrectionVariable(); - void Feb_Control_SetRateCorrectionVariable(int activate_rate_correction); - int Feb_Control_PrintCorrectedValues(); - - int Feb_Control_GetLeftFPGATemp(); - int Feb_Control_GetRightFPGATemp(); - - int64_t Feb_Control_GetMeasuredPeriod(); - int64_t Feb_Control_GetSubMeasuredPeriod(); - - int Feb_Control_SoftwareTrigger(); - - uint32_t Feb_Control_WriteRegister(uint32_t offset, uint32_t data); - uint32_t Feb_Control_ReadRegister(uint32_t offset); -#endif diff --git a/slsDetectorSoftware/eigerDetectorServer/FebInterface.c b/slsDetectorSoftware/eigerDetectorServer/FebInterface.c deleted file mode 100644 index a094bda44..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/FebInterface.c +++ /dev/null @@ -1,210 +0,0 @@ - -/** - * @author Ian Johnson - * @version 1.0 - */ - - - -//#include -//#include -//#include -//#include -//#include -//#include - -#include -#include -#include - -#include "xparameters.h" - -#include "FebInterface.h" - - - - struct LocalLinkInterface ll_local,* ll; - - unsigned int Feb_Interface_nfebs; - unsigned int* Feb_Interface_feb_numb; - - int Feb_Interface_send_ndata; - unsigned int Feb_Interface_send_buffer_size; - unsigned int* Feb_Interface_send_data_raw; - unsigned int* Feb_Interface_send_data; - - int Feb_Interface_recv_ndata; - unsigned int Feb_Interface_recv_buffer_size; - unsigned int* Feb_Interface_recv_data_raw; - unsigned int* Feb_Interface_recv_data; - - -void Feb_Interface_FebInterface(){ - ll = &ll_local; - Feb_Interface_nfebs = 0; - Feb_Interface_feb_numb = 0; - - Feb_Interface_send_ndata = 0; - Feb_Interface_send_buffer_size = 1026; - Feb_Interface_send_data_raw = malloc((Feb_Interface_send_buffer_size+1) * sizeof(unsigned int)); - Feb_Interface_send_data = &Feb_Interface_send_data_raw[1]; - - Feb_Interface_recv_ndata = 0; - Feb_Interface_recv_buffer_size = 1026; - Feb_Interface_recv_data_raw = malloc((Feb_Interface_recv_buffer_size+1) * sizeof(unsigned int)); - Feb_Interface_recv_data = &Feb_Interface_recv_data_raw[1]; - - Local_LocalLinkInterface1(ll,XPAR_PLB_LL_FIFO_AURORA_DUAL_CTRL_FEB_RIGHT_BASEADDR); - -} - - - -void Feb_Interface_SendCompleteList(unsigned int n,unsigned int* list){ - unsigned int i; - if(Feb_Interface_feb_numb) free(Feb_Interface_feb_numb); - Feb_Interface_nfebs = n; - Feb_Interface_feb_numb = malloc(n * sizeof(unsigned int)); - for(i=0;i0xfff) return 0; - -#ifdef MARTIN - cprintf(YELLOW, "FIW ch %d\n", ch); -#endif - - Feb_Interface_send_data_raw[0] = 0x8fff0000; - if(Local_Write(ll,4,Feb_Interface_send_data_raw)!=4) return 0; - - Feb_Interface_send_data_raw[0] = 0x90000000 | (ch<<16); - if(Local_Write(ll,4,Feb_Interface_send_data_raw)!=4) return 0; - - Feb_Interface_send_data_raw[0] = 0xc0000000; - return ((Feb_Interface_send_ndata+1)*4==Local_Write(ll,(Feb_Interface_send_ndata+1)*4,Feb_Interface_send_data_raw)); -} - -int Feb_Interface_ReadFrom(unsigned int ch, unsigned int ntrys){ - unsigned int t; - if(ch>=0xfff) return 0; - - Feb_Interface_recv_data_raw[0] = 0xa0000000 | (ch<<16); - Local_Write(ll,4,Feb_Interface_recv_data_raw); - usleep(20); - - Feb_Interface_recv_ndata=-1; - for(t=0;t0){ - Feb_Interface_recv_ndata--; - break; - } - usleep(1000); - } - - return (Feb_Interface_recv_ndata>=0); -} - - - -int Feb_Interface_SetByteOrder(){ - Feb_Interface_send_data_raw[0] = 0x8fff0000; - if(Local_Write(ll,4,Feb_Interface_send_data_raw)!=4) return 0; - Feb_Interface_send_ndata = 2; - Feb_Interface_send_data[0] = 0; - Feb_Interface_send_data[1] = 0; - unsigned int i; - unsigned int dst = 0xff; - for(i=0;iFeb_Interface_send_buffer_size-2) return 0; - - Feb_Interface_send_ndata = nreads+2; - Feb_Interface_send_data[0] = 0x20000000 | nreads << 14; - - for(i=0;iFeb_Interface_send_buffer_size-2) return 0; - - //cout<<"Write register : "<0){ - n_to_send = ndata_countdownFeb_Interface_send_buffer_size-2) {printf("error herer: nwrites:%d\n",nwrites);return 0;}//*d-1026 - - Feb_Interface_send_ndata = nwrites+2;//*d-1026 - Feb_Interface_send_data[0] = 0xc0000000 | mem_num << 24 | nwrites << 14 | start_address; //cmd -> write to memory, nwrites, mem number, start address - Feb_Interface_send_data[nwrites+1] = 0; - for(i=0;i - -#include "ansi.h" -#include -#include - -/*class LocalLinkInterface: public HardwareIO{ //*/ - - -struct LocalLinkInterface{ - xfs_u32 ll_fifo_base; - unsigned int ll_fifo_ctrl_reg; -}; - - - - int Local_Init(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr); - int Local_Reset1(struct LocalLinkInterface* ll,unsigned int rst_mask); - - int Local_ctrl_reg_write_mask(struct LocalLinkInterface* ll,unsigned int mask, unsigned int val); - void Local_llfifo_print_frame(struct LocalLinkInterface* ll,unsigned char* fbuff, int len); - - - void Local_LocalLinkInterface1(struct LocalLinkInterface* ll,unsigned int ll_fifo_badr); - /* virtual ~LocalLinkInterface();*/ - - unsigned int Local_StatusVector(struct LocalLinkInterface* ll); - int Local_Reset(struct LocalLinkInterface* ll); - int Local_Write(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer); - int Local_Read(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer); - - int Local_Test(struct LocalLinkInterface* ll,unsigned int buffer_len, void *buffer); - - void Local_LocalLinkInterface(struct LocalLinkInterface* ll); - - /* - int FiFoReset(unsigned int numb); - int FifoSend(unsigned int numb, unsigned int frame_len, void *buffer); - int FifoReceive(unsigned int numb, unsigned int frame_len, void *buffer); - int FifoTest(unsigned int numb,unsigned int send_len, char *send_str); - */ - - - - -#endif diff --git a/slsDetectorSoftware/eigerDetectorServer/ansi.h b/slsDetectorSoftware/eigerDetectorServer/ansi.h deleted file mode 120000 index a122db0ad..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/ansi.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/ansi.h \ No newline at end of file diff --git a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServer_developer b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServer_developer deleted file mode 100755 index 1717256ae..000000000 Binary files a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServer_developer and /dev/null differ diff --git a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServer_virtualMaster b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServer_virtualMaster deleted file mode 100755 index 8530be551..000000000 Binary files a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServer_virtualMaster and /dev/null differ diff --git a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServer_virtualSlave b/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServer_virtualSlave deleted file mode 100755 index 18d5d623a..000000000 Binary files a/slsDetectorSoftware/eigerDetectorServer/bin/eigerDetectorServer_virtualSlave and /dev/null differ diff --git a/slsDetectorSoftware/eigerDetectorServer/communication_funcs.c b/slsDetectorSoftware/eigerDetectorServer/communication_funcs.c deleted file mode 120000 index 87a4f95d1..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/communication_funcs.c +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.c \ No newline at end of file diff --git a/slsDetectorSoftware/eigerDetectorServer/communication_funcs.h b/slsDetectorSoftware/eigerDetectorServer/communication_funcs.h deleted file mode 120000 index f220903b2..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/communication_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/eigerDetectorServer/gitInfo.txt b/slsDetectorSoftware/eigerDetectorServer/gitInfo.txt deleted file mode 100644 index 5f27ec24f..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/gitInfo.txt +++ /dev/null @@ -1,9 +0,0 @@ -Path: slsDetectorsPackage/slsDetectorSoftware/eigerDetectorServer -URL: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repository Root: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repsitory UUID: def79807f6f40ed1797b8154240adbc0e35c95e0 -Revision: 352 -Branch: developer -Last Changed Author: Dhanya_Thattil -Last Changed Rev: 4039 -Last Changed Date: 2019-02-07 18:05:28.000000002 +0100 ./xparameters.h diff --git a/slsDetectorSoftware/eigerDetectorServer/gitInfoEiger.h b/slsDetectorSoftware/eigerDetectorServer/gitInfoEiger.h deleted file mode 100644 index 9bfaeb0d0..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/gitInfoEiger.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "git@github.com:slsdetectorgroup/slsDetectorPackage.git" -#define GITREPUUID "def79807f6f40ed1797b8154240adbc0e35c95e0" -#define GITAUTH "Dhanya_Thattil" -#define GITREV 0x4039 -#define GITDATE 0x20190207 -#define GITBRANCH "developer" diff --git a/slsDetectorSoftware/eigerDetectorServer/gitInfoEigerTmp.h b/slsDetectorSoftware/eigerDetectorServer/gitInfoEigerTmp.h deleted file mode 100644 index dfd9bb246..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/gitInfoEigerTmp.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "" -#define GITREPUUID "" -#define GITAUTH "" -#define GITREV "" -#define GITDATE "" -#define GITBRANCH "" diff --git a/slsDetectorSoftware/eigerDetectorServer/sls_detector_defs.h b/slsDetectorSoftware/eigerDetectorServer/sls_detector_defs.h deleted file mode 120000 index c5062e03f..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/sls_detector_defs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/eigerDetectorServer/sls_detector_funcs.h b/slsDetectorSoftware/eigerDetectorServer/sls_detector_funcs.h deleted file mode 120000 index 844b67129..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/sls_detector_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/eigerDetectorServer/sls_receiver_defs.h b/slsDetectorSoftware/eigerDetectorServer/sls_receiver_defs.h deleted file mode 120000 index 1de31caf5..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/sls_receiver_defs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/eigerDetectorServer/sls_receiver_funcs.h b/slsDetectorSoftware/eigerDetectorServer/sls_receiver_funcs.h deleted file mode 120000 index c2ea4ded9..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/sls_receiver_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/eigerDetectorServer/updateAPIVersion.sh b/slsDetectorSoftware/eigerDetectorServer/updateAPIVersion.sh deleted file mode 100755 index 618a9b601..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/updateAPIVersion.sh +++ /dev/null @@ -1,7 +0,0 @@ -SRCFILE=gitInfoEiger.h -DSTFILE=versionAPI.h - -SRCPATTERN=GITDATE -DSTPATTERN=APIEIGER - -awk -v a="$SRCFILE" -v b="$DSTFILE" -v c="$SRCPATTERN" -v d="$DSTPATTERN" 'FNR==NR&&$2==c{x=$3} NR!=FNR{if($2==d){$3="0x"substr(x,5)}print > b}' $SRCFILE $DSTFILE \ No newline at end of file diff --git a/slsDetectorSoftware/eigerDetectorServer/updateGitVersion.sh b/slsDetectorSoftware/eigerDetectorServer/updateGitVersion.sh deleted file mode 100755 index 509bffaf4..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/updateGitVersion.sh +++ /dev/null @@ -1,32 +0,0 @@ -SERVER=eigerDetectorServer -MAINDIR=slsDetectorsPackage -SPECDIR=slsDetectorSoftware/$SERVER -TMPFILE=gitInfoEigerTmp.h -INCLFILE=gitInfoEiger.h - -#evaluate the variables -EVALFILE=../../evalVersionVariables.sh -source $EVALFILE - - -#get modified date -#RDATE1='git log --pretty=format:"%ci" -1' -RDATE1="find ../slsDetectorServer . -type f -exec stat --format '%Y :%y %n' '{}' \; | sort -nr | cut -d: -f2- | egrep -v 'gitInfo|bin|.git|updateGitVersion|.o' | head -n 1" -RDATE=`eval $RDATE1` -NEWDATE=$(sed "s/-//g" <<< $RDATE | awk '{print $1;}') -NEWDATE=${NEWDATE/#/0x} - - -#get old date from INCLFILE -OLDDATE=$(more $INCLFILE | grep '#define GITDATE' | awk '{print $3}') - - -#update INCLFILE if changes -if [ "$OLDDATE" != "$NEWDATE" ]; then - echo Path: ${MAINDIR}/${SPECDIR} $'\n'URL: ${GITREPO} $'\n'Repository Root: ${GITREPO} $'\n'Repsitory UUID: ${REPUID} $'\n'Revision: ${FOLDERREV} $'\n'Branch: ${BRANCH} $'\n'Last Changed Author: ${AUTH1}_${AUTH2} $'\n'Last Changed Rev: ${REV} $'\n'Last Changed Date: ${RDATE} > gitInfo.txt - cd ../../ - ./genVersionHeader.sh $SPECDIR/gitInfo.txt $SPECDIR/$TMPFILE $SPECDIR/$INCLFILE - cd $WD -fi - - diff --git a/slsDetectorSoftware/eigerDetectorServer/versionAPI.h b/slsDetectorSoftware/eigerDetectorServer/versionAPI.h deleted file mode 120000 index d3bf8d6cf..000000000 --- a/slsDetectorSoftware/eigerDetectorServer/versionAPI.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/versionAPI.h \ No newline at end of file diff --git a/slsDetectorSoftware/f90Interface/externPostProcessing.cpp b/slsDetectorSoftware/f90Interface/externPostProcessing.cpp deleted file mode 100644 index 92b83c576..000000000 --- a/slsDetectorSoftware/f90Interface/externPostProcessing.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include "externPostProcessing.h" - - - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - - -using namespace std; - - - - -int externPostProcessing::InitDataset(int *nModules,int *chPerMod,int moduleMask[],int badChans[], double ffcoeff[], double fferr[], double* tDead, double angRadius[], double angOffset[], double angCentre[], double* totalOffset, double* binSize, double *sampleX, double *sampleY) - { - - init_dataset(nModules,chPerMod,moduleMask,badChans,ffcoeff,fferr,tDead,angRadius,angOffset,angCentre,totalOffset,binSize,sampleX,sampleY); - return 0; - - } - -int externPostProcessing::finalizeDataset(double ang[], double val[], double err[], int *np) -{ - finalize_dataset(ang, val, err, np); - return 0; -}; - - -int addFrame(double data[], double *pos, double *IO, double *expTime, const char *filename, int *var) -{ - add_frame(data, pos, i0, expTime, filename, var); - return 0; -}; - -int calculateFlatField(int* nModules, int *chPerMod, int modMask[], int badChanMask[], double data[], double ffCoeff[], double ffErr[]) -{ - calculate_flat_field(nModules, chPerMod, modMask, badChanMask, data, ffCoeff, ffErr); - return 0; -}; diff --git a/slsDetectorSoftware/f90Interface/externPostProcessing.h b/slsDetectorSoftware/f90Interface/externPostProcessing.h deleted file mode 100644 index 9225d66f9..000000000 --- a/slsDetectorSoftware/f90Interface/externPostProcessing.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef EXTERNPOSTPROCESSING_H -#define EXTERNPOSTPROCESSING_H - - -#include "detectorData.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - - - - - - -extern "C" { - - void init_dataset(int *nMod, int *chPerMod, int* modMask, int *badChanMask, double *ffCoeff, double *ffErr, double *tDead, int *dir, double *angRadius, double *angOffset, double *angCenter, double *totalOff, double *binSize, double * sampleX, double* sampleY); -void finalize_dataset(double *outang, double *outval, double *outerr, int *np); - void add_frame(double *data, double *pos, double *i0, double *exptime, char *fn, double *var); -void calculate_flat_field(int *nMod, int *chPerMod, int *modMask,int *badChanMask, double *data, double *ffc, double *fferr); -} - - - -class externPostProcessing - -{ - - public: - externPostProcessing(){}; - virtual ~externPostProcessing(){}; - - - static int InitDataset(int *nModules,int *chPerMod,int moduleMask[],int badChans[], double ffcoeff[], double fferr[], double* tDead, int *dir, double angRadius[], double angOffset[], double angCentre[], double* totalOffset, double* binSize, double *sampleX, double *sampleY); - - - - static int finalizeDataset(double ang[], double val[], double err[], int *np); - - static int addFrame(double data[], double *pos, double *IO, double *expTime, const char *filename, int *var=0); - - static int calculateFlatField(int* nModules, int *chPerMod, int moduleMask[], int badChannelMask[], double ffData[], double ffCoeff[], double ffErr[]); - - - - - }; - - -#endif diff --git a/slsDetectorSoftware/f90Interface/sls_detector_analysis_f.f90 b/slsDetectorSoftware/f90Interface/sls_detector_analysis_f.f90 deleted file mode 100644 index 201371ef4..000000000 --- a/slsDetectorSoftware/f90Interface/sls_detector_analysis_f.f90 +++ /dev/null @@ -1,174 +0,0 @@ -module ax -USE,INTRINSIC :: ISO_C_BINDING -IMPLICIT NONE -integer(C_LONG) :: numberofmodules,totalnumberofchannels -real(C_DOUBLE) :: numberofbins -real(C_DOUBLE) :: bincenter(360000), binvalue(360000), binerror(360000) - -contains - - -subroutine initdataset(nmodules, chpmod, modulemask,badchanmask,ffcoeff,fferr,tdead,angradius,angoffset,angcenter, totaloffset, binsize, samplex, sampley) bind(c, name='init_dataset') -IMPLICIT NONE -integer(C_LONG), intent(IN) :: nmodules, chpmod -integer(C_LONG), intent(IN) :: modulemask(nmodules), badchanmask(nmodules*chpmod) -real(C_DOUBLE), intent(IN) :: ffcoeff(nmodules*chpmod), fferr(nmodules*chpmod) -real(C_DOUBLE), intent(IN) :: tdead, totaloffset,binsize, samplex, sampley -real(C_DOUBLE), intent(IN) :: angradius(nmodules), angoffset(nmodules), angcenter(nmodules) -integer(C_LONG) :: i - -print*,'init dataset' - -numberofmodules=nmodules - -print*,'Number of modules:' -print*,numberofmodules -print*,'Channels per module:' -print*,chpmod - -totalnumberofchannels=nmodules*chpmod - -print*,'Total number of channels:' -print*,totalnumberofchannels - - -print*,'Modulemask:' -do i=1,nmodules - print*,i,modulemask(i) -enddo - -print*,'Badchannelmask:' -do i=1,nmodules*chpmod - print*,i,badchanmask(i) -enddo - -print*,'Flat field coefficients:' -do i=1,nmodules*chpmod - print*,i,ffcoeff(i),'+-',fferr(i) -enddo - -print*,'Tdead:' -print*,tdead - - -print*,'Angular conversion coefficients:' -do i=1,nmodules - print*,i,angradius(i),angoffset(i),angcenter(i) -enddo - - -print*,'Total offset:' -print*,totaloffset - -print*,'Bin size:' -print*,binsize - -numberofbins=360./binsize - - -print*,'Sample displacement:' -print*,samplex, sampley - -end subroutine initdataset - - - -subroutine resetdataset() bind(c, name='resetDataset') -IMPLICIT NONE - -print*,'reset dataset' - - -end subroutine resetdataset - - -subroutine finalizedataset(outang, outval, outerr, outnpoints) bind(c, name='finalize_dataset') -IMPLICIT NONE -integer(C_LONG), intent(OUT) :: outnpoints -real(C_DOUBLE), intent(OUT) :: outang(*), outval(*), outerr(*) -integer(C_LONG) :: i - -print*,'finalize dataset' - -outnpoints=numberofbins - -print*,'returning points:' -do i=1,numberofbins - - outang(i)=i; - outval(i)=i*100; - outerr(i)=i*0.1 - - print*,i,outang(i),outval(i),outerr(i) -enddo - -end subroutine finalizedataset - - - -subroutine addframe(data, pos, i0, exptime, fname, var) bind(c, name='add_frame') -IMPLICIT NONE -real(C_DOUBLE), intent(IN) :: data(totalnumberofchannels) -real(C_DOUBLE), intent(IN) :: pos, i0, exptime, var -character(kind=c_char), dimension(*), intent(IN) :: fname -integer :: l -integer :: i - -l=0 -do - if (fname(l+1) == C_NULL_CHAR) exit - l = l + 1 -end do - - -print*,'add frame' - -print*,'Filename: ' -print*,fname(1:l) - -print*,'Position: ' -print*,pos - -print*,'I0: ' -print*,i0 - -print*,'Exposure time: ' -print*,exptime - -print*,'Var: ' -print*,var - -print*,'Data: ' -print*,data - - -end subroutine addframe - - - -subroutine calculateflatfield(nmodules, chpmod, modulemask, badchanmask,data, ffcoeff,fferr) bind(c, name='calculate_flat_field') - -IMPLICIT NONE -integer(C_LONG), intent(IN) :: nmodules, chpmod -integer(C_LONG), intent(IN) :: modulemask(nmodules), badchanmask(nmodules*chpmod) -real(C_DOUBLE), intent(IN) :: data(nmodules*chpmod) -real(C_DOUBLE), intent(OUT) :: ffcoeff(*),fferr(*) -integer(C_LONG) :: i - -real(C_DOUBLE) :: ave; - -print*,'calculate flat field' - -do i=1,nmodules*chpmod - ffcoeff(i)=data(i)*10. - fferr(i)=i - print*,i,data(i), ffcoeff(i),fferr(i) -enddo - - - - -end subroutine calculateflatfield - - -end module ax diff --git a/slsDetectorSoftware/gitInfo.txt b/slsDetectorSoftware/gitInfo.txt deleted file mode 100644 index e20733686..000000000 --- a/slsDetectorSoftware/gitInfo.txt +++ /dev/null @@ -1,9 +0,0 @@ -Path: slsDetectorsPackage/slsDetectorSoftware -URL: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repository Root: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repsitory UUID: 907d1655d1f6cf2bb8cf6ccd7e91e82f479dd2ca -Revision: 2076 -Branch: developer -Last Changed Author: Dhanya_Thattil -Last Changed Rev: 4101 -Last Changed Date: 2019-02-11 14:35:41.000000002 +0100 ./threadFiles/ThreadPool.o diff --git a/slsDetectorSoftware/gotthardDetectorServer/Makefile b/slsDetectorSoftware/gotthardDetectorServer/Makefile deleted file mode 100755 index f6eacbd00..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/Makefile +++ /dev/null @@ -1,51 +0,0 @@ -# $Id: Makefile,v 1.1.1.1 2006/02/04 03:35:01 freza Exp $ -# first compile -# make cris-axis-linux-gnu - - -CROSS = bfin-uclinux- -CC = $(CROSS)gcc - -CFLAGS += -Wall -DGOTTHARDD -DMCB_FUNCS -DDACS_INT -DDEBUG # -DVERBOSE #-DVERYVERBOSE #-DVIRTUAL #-DDACS_INT_CSERVER - - -PROGS= gotthardDetectorServer -INSTDIR= /tftpboot -INSTMODE= 0777 - - - -BINS = testlib_sharedlibc -SRCS = server.c firmware_funcs.c server_funcs.c communication_funcs.c mcb_funcs.c -OBJS = $(SRCS:%.c=%.o) - - - -all: clean versioning $(PROGS) - -boot: $(OBJS) - -versioning: - @echo `tput setaf 6; ./updateGitVersion.sh; tput sgr0;` - -$(PROGS): $(OBJS) -# echo $(OBJS) - $(CC) $(CFLAGS) -o $@ $^ $(LDLIBS_$@) $(LDFLAGS_$@) - rm gotthardDetectorServer.gdb - - -install: $(PROGS) - $(INSTALL) -d $(INSTDIR) - $(INSTALL) -m $(INSTMODE) $(PROGS) $(INSTDIR) - - -romfs: - $(ROMFSINST) /bin/$(PROGS) - -clean: - rm -rf $(PROGS) *.o *.gdb - - - - - diff --git a/slsDetectorSoftware/gotthardDetectorServer/Makefile.propix b/slsDetectorSoftware/gotthardDetectorServer/Makefile.propix deleted file mode 100755 index 7f40e78a3..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/Makefile.propix +++ /dev/null @@ -1,49 +0,0 @@ -# $Id: Makefile,v 1.1.1.1 2006/02/04 03:35:01 freza Exp $ -# first compile -# make cris-axis-linux-gnu - - -CROSS = bfin-uclinux- -CC = $(CROSS)gcc - -CFLAGS += -Wall -DGOTTHARDD -DPROPIXD -DMCB_FUNCS -DDACS_INT -DDEBUG # -DVERBOSE #-DVERYVERBOSE #-DVIRTUAL #-DDACS_INT_CSERVER - - -PROGS= propixDetectorServer -INSTDIR= /tftpboot -INSTMODE= 0777 - - - -BINS = testlib_sharedlibc -SRCS = server.c server_funcs.c communication_funcs.c firmware_funcs.c mcb_funcs.c -OBJS = $(SRCS:%.c=%.o) - - - -all: clean $(PROGS) - -boot: $(OBJS) - -$(PROGS): $(OBJS) - echo $(OBJS) - @echo `tput setaf 6; ./updateGitVersion.sh; tput sgr0;` - $(CC) $(CFLAGS) -o $@ $^ $(LDLIBS_$@) $(LDFLAGS_$@) - - -install: $(PROGS) - $(INSTALL) -d $(INSTDIR) - $(INSTALL) -m $(INSTMODE) $(PROGS) $(INSTDIR) - - -romfs: - $(ROMFSINST) /bin/$(PROGS) - -clean: - rm -rf $(PROGS) *.o *.gdb - - - - - - diff --git a/slsDetectorSoftware/gotthardDetectorServer/Makefile.virtual b/slsDetectorSoftware/gotthardDetectorServer/Makefile.virtual deleted file mode 100755 index ca9bff23c..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/Makefile.virtual +++ /dev/null @@ -1,30 +0,0 @@ - -DESTDIR ?= ./ - -CC = gcc -CFLAGS += -Wall -DGOTTHARDD -DMCB_FUNCS -DDACS_INT -DDEBUG -DVIRTUAL - - -PROGS= $(DESTDIR)/gotthardDetectorServer_virtual - - -SRCS = server.c server_funcs.c communication_funcs.c firmware_funcs.c mcb_funcs.c -OBJS = $(SRCS:%.c=%.o) - -gotthardVirtualServer = $(PROGS) - -all: clean $(PROGS) - - -$(PROGS): $(OBJS) - $(CC) $(CFLAGS) -o $@ $^ $(LDLIBS_$@) $(LDFLAGS_$@) - - -clean: - rm -rf $(PROGS) *.o *.gdb - - - - - - diff --git a/slsDetectorSoftware/gotthardDetectorServer/ansi.h b/slsDetectorSoftware/gotthardDetectorServer/ansi.h deleted file mode 120000 index a122db0ad..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/ansi.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/ansi.h \ No newline at end of file diff --git a/slsDetectorSoftware/gotthardDetectorServer/communication_funcs.c b/slsDetectorSoftware/gotthardDetectorServer/communication_funcs.c deleted file mode 120000 index 87a4f95d1..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/communication_funcs.c +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.c \ No newline at end of file diff --git a/slsDetectorSoftware/gotthardDetectorServer/communication_funcs.h b/slsDetectorSoftware/gotthardDetectorServer/communication_funcs.h deleted file mode 120000 index f220903b2..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/communication_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/gotthardDetectorServer/firmware_funcs.c b/slsDetectorSoftware/gotthardDetectorServer/firmware_funcs.c deleted file mode 100755 index 261c58da4..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/firmware_funcs.c +++ /dev/null @@ -1,1975 +0,0 @@ - -#include "server_defs.h" -#include "firmware_funcs.h" -#include "mcb_funcs.h" -#include "registers_g.h" - -#include -#include -#include - -#include -#include - - -//for memory mapping -u_int64_t CSP0BASE; - -FILE *debugfp, *datafp; - -int fr; -int wait_time; -int *fifocntrl; - -//int *statusreg; commented out by dhanya -const int nModY=1; -int nModBoard; -int nModX=NMAXMOD; -int dynamicRange=16;//32; -int dataBytes=NMAXMOD*NCHIP*NCHAN*2; -int storeInRAM=0; -int ROI_flag=0; -int adcConfigured=-1; - -int ram_size=0; - -int64_t totalTime=1; -u_int32_t progressMask=0; - -int phase_shift=DEFAULT_PHASE_SHIFT; -int ipPacketSize=DEFAULT_IP_PACKETSIZE; -int udpPacketSize=DEFAULT_UDP_PACKETSIZE; - - -int ififostart, ififostop, ififostep, ififo; - -int masterMode=NO_MASTER, syncMode=NO_SYNCHRONIZATION, timingMode=AUTO_TIMING; - -enum externalSignalFlag signalMode=EXT_SIG_OFF; - - -//for the 25um detectors -int masterflags = NO_MASTER; -int masterdefaultdelay = 62; -int patternphase = 0; -int adcphase = 0; -int slavepatternphase = 0; -int slaveadcphase = 0; -int rsttosw1delay = 2; -int startacqdelay = 1; - -int detectorFirstServer = 1; - - -#ifdef MCB_FUNCS -extern const int nChans; -extern const int nChips; -//extern const int nDacs; -//extern const int nAdcs; -#endif -#ifndef MCB_FUNCS - -const int nChans=NCHAN; -const int nChips=NCHIP; -const int nDacs=NDAC; -const int nAdcs=NADC; -#endif - - - - -/** - ENEt conf structs -*/ -typedef struct mac_header_struct{ - u_int8_t mac_dest_mac2; - u_int8_t mac_dest_mac1; - u_int8_t mac_dummy1; - u_int8_t mac_dummy2; - u_int8_t mac_dest_mac6; - u_int8_t mac_dest_mac5; - u_int8_t mac_dest_mac4; - u_int8_t mac_dest_mac3; - u_int8_t mac_src_mac4; - u_int8_t mac_src_mac3; - u_int8_t mac_src_mac2; - u_int8_t mac_src_mac1; - u_int16_t mac_ether_type; - u_int8_t mac_src_mac6; - u_int8_t mac_src_mac5; -} mac_header; - -typedef struct ip_header_struct { - u_int16_t ip_len; - u_int8_t ip_tos; - u_int8_t ip_ihl:4 ,ip_ver:4; - u_int16_t ip_offset:13,ip_flag:3; - u_int16_t ip_ident; - u_int16_t ip_chksum; - u_int8_t ip_protocol; - u_int8_t ip_ttl; - u_int32_t ip_sourceip; - u_int32_t ip_destip; -} ip_header; - -typedef struct udp_header_struct{ - u_int16_t udp_destport; - u_int16_t udp_srcport; - u_int16_t udp_chksum; - u_int16_t udp_len; -} udp_header; - -typedef struct mac_conf_struct{ - mac_header mac; - ip_header ip; - udp_header udp; - u_int32_t npack; - u_int32_t lpack; - u_int32_t npad; - u_int32_t cdone; -} mac_conf; - -typedef struct tse_conf_struct{ - u_int32_t rev; //0x0 - u_int32_t scratch; - u_int32_t command_config; - u_int32_t mac_0; //0x3 - u_int32_t mac_1; - u_int32_t frm_length; - u_int32_t pause_quant; - u_int32_t rx_section_empty; //0x7 - u_int32_t rx_section_full; - u_int32_t tx_section_empty; - u_int32_t tx_section_full; - u_int32_t rx_almost_empty; //0xB - u_int32_t rx_almost_full; - u_int32_t tx_almost_empty; - u_int32_t tx_almost_full; - u_int32_t mdio_addr0; //0xF - u_int32_t mdio_addr1; -}tse_conf; - - - -int mapCSP0(void) { - printf("Mapping memory\n"); -#ifndef VIRTUAL - int fd; - fd = open("/dev/mem", O_RDWR | O_SYNC, 0); - if (fd == -1) { - printf("\nCan't find /dev/mem!\n"); - return FAIL; - } - printf("/dev/mem opened\n"); - - CSP0BASE = (u_int32_t)mmap(0, MEM_SIZE, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, CSP0); - if (CSP0BASE == (u_int32_t)MAP_FAILED) { - printf("\nCan't map memmory area!!\n"); - return FAIL; - } - printf("CSP0 mapped\n"); - -#endif -#ifdef VIRTUAL - CSP0BASE = malloc(MEM_SIZE); - printf("memory allocated\n"); -#endif -#ifdef SHAREDMEMORY - if ( (res=inism(SMSV))<0) { - printf("error attaching shared memory! %i",res); - return FAIL; - } -#endif - printf("CSPObase is 0x%llx \n",CSP0BASE); - printf("CSPOBASE=from %llx to %llx\n",CSP0BASE,CSP0BASE+MEM_SIZE); - - printf("statusreg=%08x\n",bus_r(STATUS_REG)); - printf("\n\n"); - return OK; -} - -u_int16_t bus_r16(u_int32_t offset){ - volatile u_int16_t *ptr1; - ptr1=(u_int16_t*)(CSP0BASE+offset*2); - return *ptr1; -} - -u_int16_t bus_w16(u_int32_t offset, u_int16_t data) { - volatile u_int16_t *ptr1; - ptr1=(u_int16_t*)(CSP0BASE+offset*2); - *ptr1=data; - return OK; -} - -/** ramType is DARK_IMAGE_REG or GAIN_IMAGE_REG */ -u_int16_t ram_w16(u_int32_t ramType, int adc, int adcCh, int Ch, u_int16_t data) { - unsigned int adr = (ramType | adc << 8 | adcCh << 5 | Ch ); - // printf("Writing to addr:%x\n",adr); - return bus_w16(adr,data); -} - -/** ramType is DARK_IMAGE_REG or GAIN_IMAGE_REG */ -u_int16_t ram_r16(u_int32_t ramType, int adc, int adcCh, int Ch){ - unsigned int adr = (ramType | adc << 8 | adcCh << 5 | Ch ); - // printf("Reading from addr:%x\n",adr); - return bus_r16(adr); -} - -u_int32_t bus_w(u_int32_t offset, u_int32_t data) { - volatile u_int32_t *ptr1; - - ptr1=(u_int32_t*)(CSP0BASE+offset*2); - *ptr1=data; - - return OK; -} - - -u_int32_t bus_r(u_int32_t offset) { - volatile u_int32_t *ptr1; - - ptr1=(u_int32_t*)(CSP0BASE+offset*2); - return *ptr1; -} - - - -void setMasterSlaveConfiguration(){ - -// global master default delay picked from config file - FILE* fd=fopen(CONFIG_FILE,"r"); - if(fd==NULL){ - cprintf(RED,"\nWarning: Could not open file\n"); - return; - } - cprintf(BLUE,"config file %s opened\n", CONFIG_FILE); - - char key[256]; - char value[256]; - char line[256]; - int ival=0; - u_int32_t val=0; - - while (fgets(line, sizeof(line), fd)) { - if(line[0] == '#') - continue; - sscanf(line, "%s %s\n", key, value); - if (!strcasecmp(key,"masterflags")) { - if (!strcasecmp(value,"is_master")) { - masterflags = IS_MASTER; - } - else if (!strcasecmp(value,"is_slave")) { - masterflags = IS_SLAVE; - } - else if (!strcasecmp(value,"no_master")){ - masterflags = NO_MASTER; - } - else { - cprintf(RED,"could not scan masterflags %s value from config file\n",value); - fclose(fd); - exit(EXIT_FAILURE); - } - - if (!detectorFirstServer) { - cprintf(BLUE, "Server has been started up before. Ignoring rest of config file\n"); - fclose(fd); - return; - } - } - else { - if(sscanf(value,"%d",&ival)<=0) { - cprintf(RED,"could not scan patternphase %s value from config file\n",value); - fclose(fd); - exit(EXIT_FAILURE); - } - - if (!strcasecmp(key,"masterdefaultdelay")) - masterdefaultdelay = ival; - else if (!strcasecmp(key,"patternphase")) - patternphase = ival; - else if (!strcasecmp(key,"adcphase")) - adcphase = ival; - else if (!strcasecmp(key,"slavepatternphase")) - slavepatternphase = ival; - else if (!strcasecmp(key,"slaveadcphase")) - slaveadcphase = ival; - else if (!strcasecmp(key,"rsttosw1delay")) - rsttosw1delay = ival; - else if (!strcasecmp(key,"startacqdelay")) - startacqdelay = ival; - else { - cprintf(RED,"could not scan parameter name %s from config file\n",key); - fclose(fd); - exit(EXIT_FAILURE); - } - } - - } - cprintf(BLUE, - "masterflags: %d\n" - "masterdefaultdelay:%d\n" - "patternphase:%d\n" - "adcphase:%d\n" - "slavepatternphase:%d\n" - "slaveadcphase:%d\n" - "rsttosw1delay:%d\n" - "startacqdelay:%d\n", - masterflags, - masterdefaultdelay, - patternphase, - adcphase, - slavepatternphase, - slaveadcphase, - rsttosw1delay, - startacqdelay); - - - - if (masterflags == IS_MASTER) { - // set delay - setDelay(0); - - /* Set pattern phase for the master module */ - val=bus_r(MULTI_PURPOSE_REG); - val = (val & (~(PLL_CLK_SEL_MSK))) | PLL_CLK_SEL_MASTER_VAL; - bus_w(MULTI_PURPOSE_REG,val); - setPhaseShift(patternphase); - /* Set adc phase for the master module */ - val=bus_r(MULTI_PURPOSE_REG); - val = (val & (~(PLL_CLK_SEL_MSK))) | PLL_CLK_SEL_MASTER_ADC_VAL; - bus_w(MULTI_PURPOSE_REG,val); - setPhaseShift(adcphase); - /* Set pattern phase for the slave module */ - val=bus_r(MULTI_PURPOSE_REG); - val = (val & (~(PLL_CLK_SEL_MSK))) | PLL_CLK_SEL_SLAVE_VAL; - bus_w(MULTI_PURPOSE_REG,val); - setPhaseShift(slavepatternphase); - /* Set adc phase for the slave module */ - val=bus_r(MULTI_PURPOSE_REG); - val = (val & (~(PLL_CLK_SEL_MSK))) | PLL_CLK_SEL_SLAVE_ADC_VAL; - bus_w(MULTI_PURPOSE_REG,val); - setPhaseShift(slaveadcphase); - /* Set start acq delay */ - val=bus_r(MULTI_PURPOSE_REG); -#ifdef VERBOSE - printf("Multipurpose reg:0x%x\n",bus_r(MULTI_PURPOSE_REG)); -#endif - val = (val & (~(START_ACQ_DELAY_MSK))) | ((startacqdelay << START_ACQ_DELAY_OFFSET) & (START_ACQ_DELAY_MSK)); - bus_w(MULTI_PURPOSE_REG,val); - printf("Start acq delay set. Multipurpose reg: 0x%x\n",bus_r(MULTI_PURPOSE_REG)); - } - - /* Set RST to SW1 delay */ - val=bus_r(MULTI_PURPOSE_REG); -#ifdef VERBOSE - printf("Multipurpose reg:0x%x\n",bus_r(MULTI_PURPOSE_REG)); -#endif - val = (val & (~(RST_TO_SW1_DELAY_MSK))) | ((rsttosw1delay << RST_TO_SW1_DELAY_OFFSET) & (RST_TO_SW1_DELAY_MSK)); - bus_w(MULTI_PURPOSE_REG,val); - printf("RST to SW1 delay set. Multipurpose reg:0x%x\n",bus_r(MULTI_PURPOSE_REG)); - - fclose(fd); -} - - -int setPhaseShiftOnce(){ - u_int32_t addr, reg; - int i; - addr=MULTI_PURPOSE_REG; - reg=bus_r(addr); -#ifdef VERBOSE - printf("Multipurpose reg:%x\n",reg); -#endif - - //Checking if it is power on(negative number) - // if(((reg&0xFFFF0000)>>16)>0){ - //bus_w(addr,0x0); //clear the reg - - if(reg==0){ - detectorFirstServer = 1; - printf("\nImplementing phase shift of %d\n",phase_shift); - for (i=1;i=0) { - bus_w(CONFIG_REG,d); - } -#ifdef VERBOSE - printf("configuration register is %x", bus_r(CONFIG_REG)); -#endif - return bus_r(CONFIG_REG); -} - -int setToT(int d) { - //int ret=0; - int reg; -#ifdef VERBOSE - printf("Setting ToT to %d\n",d); -#endif - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Before: ToT is %x\n", reg); -#endif - if (d>0) { - bus_w(CONFIG_REG,reg|TOT_ENABLE_BIT); - } else if (d==0) { - bus_w(CONFIG_REG,reg&(~TOT_ENABLE_BIT)); - } - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("ToT is %x\n", reg); -#endif - if (reg&TOT_ENABLE_BIT) - return 1; - else - return 0; -} - -int setContinousReadOut(int d) { - //int ret=0; - int reg; -#ifdef VERBOSE - printf("Setting Continous readout to %d\n",d); -#endif - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Before: Continous readout is %x\n", reg); -#endif - if (d>0) { - bus_w(CONFIG_REG,reg|CONT_RO_ENABLE_BIT); - } else if (d==0) { - bus_w(CONFIG_REG,reg&(~CONT_RO_ENABLE_BIT)); - } - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Continous readout is %x\n", reg); -#endif - if (reg&CONT_RO_ENABLE_BIT) - return 1; - else - return 0; -} - - -int startReceiver(int start) { - u_int32_t addr=CONFIG_REG; -#ifdef VERBOSE - if(start) - printf("Setting up detector to send to Receiver\n"); - else - printf("Setting up detector to send to CPU\n"); -#endif - int reg=bus_r(addr); - //for start recever, write 0 and for stop, write 1 - if (!start) - bus_w(CONFIG_REG,reg|CPU_OR_RECEIVER_BIT); - else - bus_w(CONFIG_REG,reg&(~CPU_OR_RECEIVER_BIT)); - - reg=bus_r(addr); -//#ifdef VERBOSE - printf("Config Reg %x\n", reg); -//#endif - int d =reg&CPU_OR_RECEIVER_BIT; - if(d!=0) d=1; - if(d!=start) - return OK; - else - return FAIL; -} - - -u_int64_t getDetectorNumber() { - char output[255],mac[255]=""; - u_int64_t res=0; - FILE* sysFile = popen("ifconfig eth0 | grep HWaddr | cut -d \" \" -f 11", "r"); - fgets(output, sizeof(output), sysFile); - pclose(sysFile); - //getting rid of ":" - char * pch; - pch = strtok (output,":"); - while (pch != NULL){ - strcat(mac,pch); - pch = strtok (NULL, ":"); - } - sscanf(mac,"%llx",&res); - return res; -} - -u_int32_t getFirmwareVersion() { - return bus_r(FPGA_VERSION_REG); -} - -u_int32_t getFirmwareSVNVersion(){ - return bus_r(FPGA_SVN_REG); -} - - -// for fpga test -u_int32_t testFpga(void) { - printf("Testing FPGA:\n"); - volatile u_int32_t val,addr,val2; - int result=OK,i; - //fixed pattern - val=bus_r(FIX_PATT_REG); - if (val==FIXED_PATT_VAL) { - printf("fixed pattern ok!! %08x\n",val); - } else { - printf("fixed pattern wrong!! %08x\n",val); - result=FAIL; - } - - //dummy register - addr = DUMMY_REG; - for(i=0;i<1000000;i++) - { - val=0x5A5A5A5A-i; - bus_w(addr, val); - val=bus_r(addr); - if (val!=0x5A5A5A5A-i) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of %x \n",i,val,0x5A5A5A5A-i); - result=FAIL; - } - val=(i+(i<<10)+(i<<20)); - bus_w(addr, val); - val2=bus_r(addr); - if (val2!=val) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! read %x instead of %x.\n",i,val2,val); - result=FAIL; - } - val=0x0F0F0F0F; - bus_w(addr, val); - val=bus_r(addr); - if (val!=0x0F0F0F0F) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of 0x0F0F0F0F \n",i,val); - result=FAIL; - } - val=0xF0F0F0F0; - bus_w(addr, val); - val=bus_r(addr); - if (val!=0xF0F0F0F0) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of 0xF0F0F0F0 \n\n",i,val); - result=FAIL; - } - } - if(result==OK) - { - printf("----------------------------------------------------------------------------------------------"); - printf("\nATTEMPT 1000000: FPGA DUMMY REGISTER OK!!!\n"); - printf("----------------------------------------------------------------------------------------------"); - } - printf("\n"); - return result; -} - - -int getNModBoard() { - return nModX; -} - -int setNMod(int n) { - return nModX; -} - - -// fifo test -int testFifos(void) { - printf("Fifo test not implemented!\n"); - bus_w16(CONTROL_REG, START_FIFOTEST_BIT); - bus_w16(CONTROL_REG, 0x0); - return OK; -} - - - -// program dacq settings - -int64_t set64BitReg(int64_t value, int aLSB, int aMSB){ - int64_t v64; - u_int32_t vLSB,vMSB; - if (value!=-1) { - vLSB=value&(0xffffffff); - bus_w(aLSB,vLSB); - v64=value>> 32; - vMSB=v64&(0xffffffff); - bus_w(aMSB,vMSB); - } - return get64BitReg(aLSB, aMSB); - -} - -int64_t get64BitReg(int aLSB, int aMSB){ - int64_t v64; - u_int32_t vLSB,vMSB; - vLSB=bus_r(aLSB); - vMSB=bus_r(aMSB); - v64=vMSB; - v64=(v64<<32) | vLSB; - return v64; -} - -int64_t setFrames(int64_t value){printf("setting frames to %lld\n", (long long int)value); - return set64BitReg(value, SET_FRAMES_LSB_REG, SET_FRAMES_MSB_REG); -} - -int64_t getFrames(){ - return get64BitReg(GET_FRAMES_LSB_REG, GET_FRAMES_MSB_REG); -} - -int64_t setExposureTime(int64_t value){printf("setting exptime to %lld ns\n", (long long int)value); - /* time is in ns */ - if (value!=-1) { - value = (value * 1E-3 * CLK_FREQ ) + 0.5; - } - return (set64BitReg(value,SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG) / - (1E-3 * CLK_FREQ)) + 0.5; -} - -int64_t getExposureTime(){ - return (get64BitReg(GET_EXPTIME_LSB_REG, GET_EXPTIME_MSB_REG) / - (1E-3 * CLK_FREQ)) + 0.5; -} - -int64_t setGates(int64_t value){printf("setting gates to %lld\n", (long long int)value); - return set64BitReg(value, SET_GATES_LSB_REG, SET_GATES_MSB_REG); -} - -int64_t getGates(){ - return get64BitReg(GET_GATES_LSB_REG, GET_GATES_MSB_REG); -} - -int64_t setPeriod(int64_t value){printf("setting period to %lld ns\n", (long long int)value); - /* time is in ns */ - if (value!=-1) { - value = (value * 1E-3 * CLK_FREQ ) + 0.5; - } - return (set64BitReg(value,SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG) / - (1E-3 * CLK_FREQ)) + 0.5; -} - -int64_t getPeriod(){ - return (get64BitReg(GET_PERIOD_LSB_REG, GET_PERIOD_MSB_REG) / - (1E-3 * CLK_FREQ)) + 0.5; -} - -int64_t setDelay(int64_t value){printf("setting delay to %lld ns\n", (long long int)value); - /* time is in ns */ - if (value!=-1) { - if (masterflags == IS_MASTER) { - value += masterdefaultdelay; - cprintf(BLUE,"Actual delay for master: %lld\n", (long long int) value); - } - value = (value * 1E-3 * CLK_FREQ ) + 0.5; - } - int64_t retval = (set64BitReg(value,SET_DELAY_LSB_REG, SET_DELAY_MSB_REG) / - (1E-3 * CLK_FREQ)) + 0.5; - if (masterflags == IS_MASTER) { - cprintf(BLUE,"Actual delay read from master: %lld\n", (long long int) retval); - retval -= masterdefaultdelay; - } - - return retval; -} - -int64_t getDelay(){ - return (get64BitReg(GET_DELAY_LSB_REG, GET_DELAY_MSB_REG) / - (1E-3 * CLK_FREQ)) + 0.5; -} - -int64_t setTrains(int64_t value){printf("setting cycles to %lld\n", (long long int)value); - return set64BitReg(value, SET_TRAINS_LSB_REG, SET_TRAINS_MSB_REG); -} - -int64_t getTrains(){ - return get64BitReg(GET_TRAINS_LSB_REG, GET_TRAINS_MSB_REG); -} - - -int64_t setProbes(int64_t value){ - return 0; -} - - -int64_t setProgress() { - //????? eventually call after setting the registers -return 0; - -} - - -int64_t getProgress() { - //should be done in firmware!!!! - return 0; - -} - -int64_t getActualTime(){ - return (get64BitReg(GET_ACTUAL_TIME_LSB_REG, GET_ACTUAL_TIME_MSB_REG) / - (1E-3 * CLK_FREQ)) + 0.5; -} - -int64_t getMeasurementTime(){ - int64_t v=get64BitReg(GET_MEASUREMENT_TIME_LSB_REG, GET_MEASUREMENT_TIME_MSB_REG); - return (v / (1E-3 * CLK_FREQ)) + 0.5; -} - - - - -int loadImage(int index, short int ImageVals[]){ - u_int32_t address; - switch (index) { - case DARK_IMAGE : - address = DARK_IMAGE_REG; - break; - case GAIN_IMAGE : - address = GAIN_IMAGE_REG; - break; - } - volatile u_int16_t *ptr; - ptr=(u_int16_t*)(CSP0BASE+address*2); -#ifdef VERBOSE - int i; - for(i=0;i<6;i++) - printf("%d:%d\t",i,ImageVals[i]); -#endif - memcpy((char*)ptr,(char*)ImageVals ,dataBytes); -#ifdef VERBOSE - printf("\nLoaded x%08x address with image of index %d\n",(unsigned int)(ptr),index); -#endif - return OK; -} - - - -int64_t getProbes(){ - return 0; -} - - -int setDACRegister(int idac, int val, int imod) { - u_int32_t addr, reg, mask; - int off; -#ifdef VERBOSE - if(val==-1) - printf("Getting dac register%d module %d\n",idac,imod); - else - printf("Setting dac register %d module %d to %d\n",idac,imod,val); -#endif - - switch(idac){ - case 0: - case 1: - case 2: - addr=MOD_DACS1_REG; - break; - case 3: - case 4: - case 5: - addr=MOD_DACS2_REG; - break; - case 6: - case 7: - addr=MOD_DACS3_REG; - break; - default: - printf("weird idac value %d\n",idac); - return -1; - break; - } - //saving only the msb - val=val>>2; - - off=(idac%3)*10; - mask=~((0x3ff)<=0 && val>off)&0x3ff; - //since we saved only the msb - val=val<<2; - - //val=(bus_r(addr)>>off)&0x3ff; - - -#ifdef VERBOSE - printf("Dac %d module %d register is %d\n\n",idac,imod,val); -#endif - return val; -} - - -int getTemperature(int tempSensor, int imod){ - int val; - imod=0;//ignoring more than 1 mod for now - int i,j,repeats=6; - u_int32_t tempVal=0; -#ifdef VERBOSE - char cTempSensor[2][100]={"ADCs/ASICs","VRs/FPGAs"}; - printf("Getting Temperature of module:%d for the %s for tempsensor:%d\n",imod,cTempSensor[tempSensor],tempSensor); -#endif - bus_w(TEMP_IN_REG,(T1_CLK_BIT)|(T1_CS_BIT)|(T2_CLK_BIT)|(T2_CS_BIT));//standby - bus_w(TEMP_IN_REG,((T1_CLK_BIT)&~(T1_CS_BIT))|(T2_CLK_BIT));//high clk low cs - - for(i=0;i<20;i++) { - //repeats is number of register writes for delay - for(j=0;j>1);//fpga - } - } - - bus_w(TEMP_IN_REG,(T1_CLK_BIT)|(T1_CS_BIT)|(T2_CLK_BIT)|(T2_CS_BIT));//standby - val=((int)tempVal)/4.0; - -#ifdef VERBOSE - printf("Temperature of module:%d for the %s is %.2fC\n",imod,cTempSensor[tempSensor],val); -#endif - return val; -} - - - -int initHighVoltage(int val, int imod){ -#ifdef VERBOSE - printf("Setting/Getting High Voltage of module:%d with val:%d\n",imod,val); -#endif - volatile u_int32_t addr=HV_REG; - int writeVal,writeVal2; - switch(val){ - case -1: break; - case 0: writeVal=0x0; writeVal2=0x0; break; - case 90: writeVal=0x0; writeVal2=0x1; break; - case 110:writeVal=0x2; writeVal2=0x3; break; - case 120:writeVal=0x4; writeVal2=0x5; break; - case 150:writeVal=0x6; writeVal2=0x7; break; - case 180:writeVal=0x8; writeVal2=0x9; break; - case 200:writeVal=0xA; writeVal2=0xB; break; - default :printf("Invalid voltage\n");return -2;break; - } - //to set value - if(val!=-1){ - //set value to converted value - bus_w(addr,writeVal); - bus_w(addr,writeVal2); -#ifdef VERBOSE - printf("Value sent is %d and then %d\n",writeVal,writeVal2); -#endif - } - //read value and return the converted value - val=bus_r(addr); -#ifdef VERBOSE - printf("Value read from reg is %d\n",val); -#endif - switch(val){ - case 0x0:val=0;break; - case 0x1:val=90;break; - case 0x3:val=110;break; - case 0x5:val=120;break; - case 0x7:val=150;break; - case 0x9:val=180;break; - case 0xB:val=200;break; - default:printf("Weird value read:%d\n",val);return -3;break; - } -#ifdef VERBOSE - printf("High voltage of module:%d is %d\n",imod,val); -#endif - return val; -} - - - -int initConfGain(int isettings,int val,int imod){ - int retval; - u_int32_t addr=GAIN_REG; - - if(val!=-1){ -#ifdef VERBOSE - printf("Setting Gain of module:%d with val:%d\n",imod,val); -#endif - bus_w(addr,((val<>SETTINGS_OFFSET); -#ifdef VERBOSE - printf("Settings read from reg is %d\n",retval); -#endif - if((isettings!=-1)&&(retval!=isettings)){ - printf("\n\nSettings r\n\n"); - return -1; - } - - return retval; -} - - - -int setADC(int adc){ - int reg,nchips,mask; - - if(adc==-1) ROI_flag=0; - else ROI_flag=1; - - setDAQRegister();//token timing - cleanFifo();//adc sync - - //all adc - if(adc==-1){ - //set packet size - ipPacketSize= DEFAULT_IP_PACKETSIZE; - udpPacketSize=DEFAULT_UDP_PACKETSIZE; - //set channel mask - nchips = NCHIP; - mask = ACTIVE_ADC_MASK; - } - //1 adc - else{ - ipPacketSize= ADC1_IP_PACKETSIZE; - udpPacketSize=ADC1_UDP_PACKETSIZE; - //set channel mask - nchips = NCHIPS_PER_ADC; - mask = 1<mac.mac_dest_mac1 =((macad>>(8*5))&0xFF);// 0x00; //pc7060 - mac_conf_regs->mac.mac_dest_mac2 =((macad>>(8*4))&0xFF);// 0x19; //pc7060 - mac_conf_regs->mac.mac_dest_mac3 =((macad>>(8*3))&0xFF);// 0x99; //pc7060 - mac_conf_regs->mac.mac_dest_mac4 =((macad>>(8*2))&0xFF);// 0x24; //pc7060 - mac_conf_regs->mac.mac_dest_mac5 =((macad>>(8*1))&0xFF);// 0xEB; //pc7060 - mac_conf_regs->mac.mac_dest_mac6 =((macad>>(8*0))&0xFF);// 0xEE; //pc7060 - /* - mac_conf_regs->mac.mac_src_mac1 = 0x00; - mac_conf_regs->mac.mac_src_mac2 = 0xAA; - mac_conf_regs->mac.mac_src_mac3 = 0xBB; - mac_conf_regs->mac.mac_src_mac4 = 0xCC; - mac_conf_regs->mac.mac_src_mac5 = 0xDD; - mac_conf_regs->mac.mac_src_mac6 = 0xEE; - */ - mac_conf_regs->mac.mac_src_mac1 =((detectormacad>>(8*5))&0xFF); - mac_conf_regs->mac.mac_src_mac2 =((detectormacad>>(8*4))&0xFF); - mac_conf_regs->mac.mac_src_mac3 =((detectormacad>>(8*3))&0xFF); - mac_conf_regs->mac.mac_src_mac4 =((detectormacad>>(8*2))&0xFF); - mac_conf_regs->mac.mac_src_mac5 =((detectormacad>>(8*1))&0xFF); - mac_conf_regs->mac.mac_src_mac6 =((detectormacad>>(8*0))&0xFF); - mac_conf_regs->mac.mac_ether_type = 0x0800; //ipv4 - - - mac_conf_regs->ip.ip_ver = 0x4; - mac_conf_regs->ip.ip_ihl = 0x5; - mac_conf_regs->ip.ip_tos = 0x0; - mac_conf_regs->ip.ip_len = ipPacketSize;//0x0522; // was 0x0526; - mac_conf_regs->ip.ip_ident = 0x0000; - mac_conf_regs->ip.ip_flag = 0x2; - mac_conf_regs->ip.ip_offset = 0x00; - mac_conf_regs->ip.ip_ttl = 0x70; - mac_conf_regs->ip.ip_protocol = 0x11; - mac_conf_regs->ip.ip_chksum = 0x0000 ; //6E42 now is automatically computed - mac_conf_regs->ip.ip_sourceip = detipad; //0x8181CA2E;129.129.202.46 - mac_conf_regs->ip.ip_destip = ipad; //CA57 - -#ifdef VERBOSE - printf("mac_dest:%llx %x:%x:%x:%x:%x:%x\n", - macad, - mac_conf_regs->mac.mac_dest_mac1, - mac_conf_regs->mac.mac_dest_mac2, - mac_conf_regs->mac.mac_dest_mac3, - mac_conf_regs->mac.mac_dest_mac4, - mac_conf_regs->mac.mac_dest_mac5, - mac_conf_regs->mac.mac_dest_mac6); - printf("mac_src:%llx %x:%x:%x:%x:%x:%x\n", - detectormacad, - mac_conf_regs->mac.mac_src_mac1, - mac_conf_regs->mac.mac_src_mac2, - mac_conf_regs->mac.mac_src_mac3, - mac_conf_regs->mac.mac_src_mac4, - mac_conf_regs->mac.mac_src_mac5, - mac_conf_regs->mac.mac_src_mac6); - printf("ip_ttl:%x\n",mac_conf_regs->ip.ip_ttl); -#endif - - //checksum - count=sizeof(mac_conf_regs->ip); - addr=&(mac_conf_regs->ip); - while( count > 1 ) { - sum += *addr++; - count -= 2; - } - if( count > 0 ) sum += *addr; // Add left-over byte, if any - while (sum>>16) sum = (sum & 0xffff) + (sum >> 16);// Fold 32-bit sum to 16 bits - checksum = (~sum)&0xffff; - mac_conf_regs->ip.ip_chksum = checksum; - //#ifdef VERBOSE - printf("IP header checksum is 0x%x s\n",(unsigned int)(checksum)); - //#endif - - mac_conf_regs->udp.udp_srcport = 0xE185; - mac_conf_regs->udp.udp_destport = udpport;//0xC351; - mac_conf_regs->udp.udp_len = udpPacketSize;//0x050E; //was 0x0512; - mac_conf_regs->udp.udp_chksum = 0x0000; - -#ifdef VERBOSE - printf("Configuring TSE\n"); -#endif - tse_conf_regs->rev = 0xA00; - tse_conf_regs->scratch = 0xCCCCCCCC; - tse_conf_regs->command_config = 0xB; - tse_conf_regs->mac_0 = 0x17231C00; - tse_conf_regs->mac_1 = 0xCB4A; - tse_conf_regs->frm_length = 0x5DC; //max frame length (1500 bytes) (was 0x41C) - tse_conf_regs->pause_quant = 0x0; - tse_conf_regs->rx_section_empty = 0x7F0; - tse_conf_regs->rx_section_full = 0x10; - tse_conf_regs->tx_section_empty = 0x3F8; //was 0x7F0; - tse_conf_regs->tx_section_full = 0x16; - tse_conf_regs->rx_almost_empty = 0x8; - tse_conf_regs->rx_almost_full = 0x8; - tse_conf_regs->tx_almost_empty = 0x8; - tse_conf_regs->tx_almost_full = 0x3; - tse_conf_regs->mdio_addr0 = 0x12; - tse_conf_regs->mdio_addr1 = 0x0; - mac_conf_regs->cdone = 0xFFFFFFFF; - - - if(ival) - bus_w(addrr, bus_r(addrr) | (INT_RSTN_BIT|ENET_RESETN_BIT|WRITE_BACK_BIT|DIGITAL_TEST_BIT)); //0x2840,write shadow regs.. - else - bus_w(addrr, bus_r(addrr) | (INT_RSTN_BIT|ENET_RESETN_BIT|WRITE_BACK_BIT)); //0x2840,write shadow regs.. - -#ifdef VERBOSE - printf("Value read from Multi-purpose Reg:%x\n",bus_r(addrr)); -#endif - // if(val!=0x2840) return -1; - - usleep(100000); - - bus_w(addrr, bus_r(addrr) &(~WRITE_BACK_BIT)); - - if(ival) - bus_w(addrr, bus_r(addrr) | (INT_RSTN_BIT|ENET_RESETN_BIT|SW1_BIT|DIGITAL_TEST_BIT)); //0x2820,write shadow regs.. - else - bus_w(addrr, bus_r(addrr) | (INT_RSTN_BIT|ENET_RESETN_BIT|SW1_BIT)); //0x2820,write shadow regs.. - -#ifdef VERBOSE - printf("Value read from Multi-purpose Reg:%x\n",bus_r(addrr)); -#endif - // if(val!=0x2820) return -1; - - usleep(1000 * 1000); - - /** send out first image as first packet does not give 0xcacacaca (needed to know if first image - * when switching back and forth between roi and no roi - */ - // remember old parameters - int oldtiming = setTiming(-1); - uint64_t oldframes = setFrames(-1); - uint64_t oldcycles = setTrains(-1); - uint64_t oldPeriod = setPeriod(-1); - uint64_t oldExptime = setExposureTime(-1); - - // set to basic parameters - cprintf(BLUE,"Setting basic parameters\n" - "\tTiming: auto, frames: 1, cycles: 1, period: 1s, exptime: 900ms\n"); - setTiming(AUTO_TIMING); - setFrames(1); - setTrains(1); - setPeriod(1e9); // important to keep this until we have to wait for acquisition to start - setExposureTime(900 * 1000); - - // take an image - if (masterflags == IS_MASTER) - usleep(1 * 1000 * 1000); // required to ensure master starts acquisition only after slave has changed to basic parameters and is waiting - - int loop = 0; - startStateMachine(); - // wait for acquisition to start (trigger from master) - printf(" Waiting for acquisition to start\n"); - while(!runBusy()) { - usleep(0); - ++loop; - } - - cprintf(MAGENTA, "waited %d loops to start\n", loop); - cprintf(BLUE, " Waiting for acquisition to end (frames left: %lld)\n", (long long int)getFrames()); - waitForAcquisitionFinish(); - - // set to previous parameters - cprintf(BLUE,"Setting previous parameters:\n" - "\tTiming: %d, " - "frames: %lld, " - "cycles: %lld, " - "period: %lld ns, " - "exptime:%lld ns\n", - oldtiming, oldframes, oldcycles, oldPeriod, oldExptime); - setTiming(oldtiming); - setFrames(oldframes); - setTrains(oldcycles); - setPeriod(oldPeriod); - setExposureTime(oldExptime); - - return adcConfigured; -} - - -int getAdcConfigured(){ - return adcConfigured; -} - -u_int32_t runBusy(void) { - u_int32_t s = bus_r(STATUS_REG) & RUN_BUSY_BIT; - //printf("runBusy: 0x%08x\n", s); - return s; -} - -u_int32_t dataPresent(void) { - return bus_r(LOOK_AT_ME_REG); -} - -u_int32_t runState(void) { - int s=bus_r(STATUS_REG); -#ifdef SHAREDMEMORY - if (s&RUN_BUSY_BIT) - write_status_sm("Running"); - else - write_status_sm("Stopped"); -#endif -#ifdef VERBOSE - printf("status %04x\n",s); -#endif - -/* if (s==0x62001) - exit(-1);*/ - return s; -} - - -// State Machine - -int startStateMachine(){ - -//#ifdef VERBOSE - cprintf(GREEN,"*******Starting State Machine*******\n"); - cprintf(GREEN,"Number of frames to acquire:%lld\n", (long long int)setFrames(-1)); -//#endif - cleanFifo(); - // fifoReset(); - - bus_w16(CONTROL_REG, START_ACQ_BIT | START_EXPOSURE_BIT); - bus_w16(CONTROL_REG, 0x0); - printf("statusreg=%08x\n",bus_r(STATUS_REG)); - return OK; -} - - - - -int stopStateMachine(){ - -//#ifdef VERBOSE - cprintf(BG_RED,"*******Stopping State Machine*******\n"); -//#endif - bus_w16(CONTROL_REG, STOP_ACQ_BIT); - bus_w16(CONTROL_REG, 0x0); - usleep(500); - // if (!runBusy()) - if(!(bus_r(STATUS_REG)&RUNMACHINE_BUSY_BIT)) - return OK; - else - return FAIL; -} - - -int startReadOut(){ - u_int32_t status; -#ifdef VERBOSE - printf("Starting State Machine Readout\n"); -#endif - status=bus_r(STATUS_REG)&RUN_BUSY_BIT; -#ifdef DEBUG - printf("State machine status is %08x\n",bus_r(STATUS_REG)); -#endif - bus_w16(CONTROL_REG, START_ACQ_BIT |START_READOUT_BIT); // start readout - bus_w16(CONTROL_REG, 0x0); - return OK; -} - - -// fifo routines - -u_int32_t fifoReset(void) { - return -1; -} - - -u_int32_t setNBits(u_int32_t n) { - return -1; -} - -u_int32_t getNBits(){ - return -1; -} - - -u_int32_t fifoReadCounter(int fifonum){ - return -1; -} - -u_int32_t fifoReadStatus() -{ - // reads from the global status register - - return bus_r(STATUS_REG)&(SOME_FIFO_FULL_BIT | ALL_FIFO_EMPTY_BIT); -} - -u_int32_t fifo_full(void) -{ - // checks fifo empty flag returns 1 if fifo is empty - // otherwise 0 - return bus_r(STATUS_REG)&SOME_FIFO_FULL_BIT; -} - - -void waitForAcquisitionFinish(){ - volatile u_int32_t t = bus_r(LOOK_AT_ME_REG); -#ifdef VERBOSE - printf("lookatmereg=x%x\n",t); -#endif - while((t&0x1)==0) { - if (runBusy() == 0) { - t = bus_r(LOOK_AT_ME_REG); - if ((t&0x1)==0) { -#ifdef VERBOSE - printf("no frame found - exiting "); - printf("%08x %08x\n", runState(), bus_r(LOOK_AT_ME_REG)); -#endif - return; - } else { -#ifdef VERBOSE - printf("no frame found %x status %x\n", bus_r(LOOK_AT_ME_REG),runState()); -#endif - break; - } - } - - t = bus_r(LOOK_AT_ME_REG); - } -} - - - - -u_int32_t* decode_data(int *datain) -{ - u_int32_t *dataout; - // const char one=1; - const int bytesize=8; - char *ptr=(char*)datain; - //int nbits=dynamicRange; - int ipos=0, ichan=0;; - //int nch, boff=0; - int ibyte;//, ibit; - char iptr; - -#ifdef VERBOSE - printf("Decoding data for DR %d\n",dynamicRange); -#endif - dataout=malloc(nChans*nChips*nModX*4); - ichan=0; - switch (dynamicRange) { - case 1: - for (ibyte=0; ibyte>(ipos))&0x1; - ichan++; - } - } - break; - case 4: - for (ibyte=0; ibyte>(ipos*4))&0xf; - ichan++; - } - } - break; - case 8: - for (ichan=0; ichan>(23-i))&0x1)< -#include -#include -#include -#include -#include -#include -//#include -#include -#include -#include -#include -#include -#include - - -int mapCSP0(void); - -u_int16_t bus_r16(u_int32_t offset); -u_int16_t bus_w16(u_int32_t offset, u_int16_t data);//aldos function -u_int32_t bus_w(u_int32_t offset, u_int32_t data); -u_int32_t bus_r(u_int32_t offset); - -void setMasterSlaveConfiguration(); -int setPhaseShiftOnce(); -int setPhaseShift(int numphaseshift); -int cleanFifo(); -int setDAQRegister(); - -u_int32_t putout(char *s, int modnum); -u_int32_t readin(int modnum); -u_int32_t setClockDivider(int d); -u_int32_t getClockDivider(); -u_int32_t setSetLength(int d); -u_int32_t getSetLength(); -u_int32_t setWaitStates(int d); -u_int32_t getWaitStates(); -u_int32_t setTotClockDivider(int d); -u_int32_t getTotClockDivider(); -u_int32_t setTotDutyCycle(int d); -u_int32_t getTotDutyCycle(); - -u_int32_t setExtSignal(enum externalSignalFlag mode); -int getExtSignal(); - -u_int32_t setFPGASignal(enum externalSignalFlag mode); -int getFPGASignal(); - -int setTiming(int t); - - -int setConfigurationRegister(int d); -int setToT(int d); -int setContinousReadOut(int d); -int startReceiver(int d); - -int setDACRegister(int idac, int val, int imod); - -int getTemperature(int tempSensor,int imod); -int initHighVoltage(int val,int imod); -int initConfGain(int isettings,int val,int imod); - -int setADC(int adc); -int configureMAC(int ipad, long long int macad, long long int detectormacadd, int detipad, int ival, int udpport); -int getAdcConfigured(); - - -u_int64_t getDetectorNumber(); -u_int32_t getFirmwareVersion(); -u_int32_t getFirmwareSVNVersion(); -int testFifos(void); -u_int32_t testFpga(void); -int testBus(void); -int setDigitalTestBit(int ival); - -int64_t set64BitReg(int64_t value, int aLSB, int aMSB); -int64_t get64BitReg(int aLSB, int aMSB); - -int64_t setFrames(int64_t value); -int64_t getFrames(); - -int64_t setExposureTime(int64_t value); -int64_t getExposureTime(); - -int64_t setGates(int64_t value); -int64_t getGates(); - -int64_t setDelay(int64_t value); -int64_t getDelay(); - -int64_t setPeriod(int64_t value); -int64_t getPeriod(); - -int64_t setTrains(int64_t value); -int64_t getTrains(); - -int64_t setProbes(int64_t value); -int64_t getProbes(); - -int64_t getProgress(); -int64_t setProgress(); - -int64_t getActualTime(); -int64_t getMeasurementTime(); - - -u_int32_t runBusy(void); -u_int32_t runState(void); -u_int32_t dataPresent(void); - - -int startStateMachine(); -int stopStateMachine(); -int startReadOut(); -u_int32_t fifoReset(void); -u_int32_t fifoReadCounter(int fifonum); -u_int32_t fifoReadStatus(); - - -u_int32_t fifo_full(void); - - -void waitForAcquisitionFinish(); - -u_int32_t* decode_data(int* datain); -//u_int32_t move_data(u_int64_t* datain, u_int64_t* dataout); -int setDynamicRange(int dr); -int getDynamicRange(); -int getNModBoard(); -int setNMod(int n); -int setStoreInRAM(int b); - - - - -int setMaster(int f); -int setSynchronization(int s); - -int loadImage(int index, short int ImageVals[]); -int readCounterBlock(int startACQ, short int CounterVals[]); -int resetCounterBlock(int startACQ); - -int calibratePedestal(int frames); - - - -/* - -u_int32_t setNBits(u_int32_t); -u_int32_t getNBits(); -*/ - -/* -//move to mcb_funcs? - -int readOutChan(int *val); -u_int32_t getModuleNumber(int modnum); -int testShiftIn(int imod); -int testShiftOut(int imod); -int testShiftStSel(int imod); -int testDataInOut(int num, int imod); -int testExtPulse(int imod); -int testExtPulseMux(int imod, int ow); -int testDataInOutMux(int imod, int ow, int num); -int testOutMux(int imod); -int testFpgaMux(int imod); -int calibration_sensor(int num, int *values, int *dacs) ; -int calibration_chip(int num, int *values, int *dacs); -*/ - - -#endif diff --git a/slsDetectorSoftware/gotthardDetectorServer/gitInfo.txt b/slsDetectorSoftware/gotthardDetectorServer/gitInfo.txt deleted file mode 100644 index 476188958..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/gitInfo.txt +++ /dev/null @@ -1,9 +0,0 @@ -Path: slsDetectorsPackage/slsDetectorSoftware/gotthardDetectorServer -URL: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repository Root: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repsitory UUID: def79807f6f40ed1797b8154240adbc0e35c95e0 -Revision: 244 -Branch: developer -Last Changed Author: Dhanya_Thattil -Last Changed Rev: 4039 -Last Changed Date: 2019-02-11 11:53:14.000000002 +0100 ./server_funcs.c diff --git a/slsDetectorSoftware/gotthardDetectorServer/gitInfoGotthard.h b/slsDetectorSoftware/gotthardDetectorServer/gitInfoGotthard.h deleted file mode 100644 index 44a6315e3..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/gitInfoGotthard.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "git@github.com:slsdetectorgroup/slsDetectorPackage.git" -#define GITREPUUID "def79807f6f40ed1797b8154240adbc0e35c95e0" -#define GITAUTH "Dhanya_Thattil" -#define GITREV 0x4039 -#define GITDATE 0x20190211 -#define GITBRANCH "developer" diff --git a/slsDetectorSoftware/gotthardDetectorServer/gitInfoGotthardTmp.h b/slsDetectorSoftware/gotthardDetectorServer/gitInfoGotthardTmp.h deleted file mode 100644 index dfd9bb246..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/gitInfoGotthardTmp.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "" -#define GITREPUUID "" -#define GITAUTH "" -#define GITREV "" -#define GITDATE "" -#define GITBRANCH "" diff --git a/slsDetectorSoftware/gotthardDetectorServer/gotthardDetectorServer_developer b/slsDetectorSoftware/gotthardDetectorServer/gotthardDetectorServer_developer deleted file mode 100755 index ec3348fc7..000000000 Binary files a/slsDetectorSoftware/gotthardDetectorServer/gotthardDetectorServer_developer and /dev/null differ diff --git a/slsDetectorSoftware/gotthardDetectorServer/gotthardDetectorServer_virtual b/slsDetectorSoftware/gotthardDetectorServer/gotthardDetectorServer_virtual deleted file mode 100755 index 4f6df8112..000000000 Binary files a/slsDetectorSoftware/gotthardDetectorServer/gotthardDetectorServer_virtual and /dev/null differ diff --git a/slsDetectorSoftware/gotthardDetectorServer/mcb_funcs.c b/slsDetectorSoftware/gotthardDetectorServer/mcb_funcs.c deleted file mode 100755 index 8d73b536f..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/mcb_funcs.c +++ /dev/null @@ -1,2340 +0,0 @@ -#ifdef MCB_FUNCS - -#include -#include -#include -#include -#include -#include "registers_g.h" - -#ifndef PICASSOD -#include "server_defs.h" -#else -#include "picasso_defs.h" -#endif -#include "firmware_funcs.h" -#include "mcb_funcs.h" - -/* global variables */ -#undef DEBUG -#undef DEBUGOUT - -extern int nModX; -//extern int dataBytes; -extern int dynamicRange; -const int nChans=NCHAN; -const int nChips=NCHIP; -const int nDacs=NDAC; -const int nAdcs=NADC; -enum detectorSettings thisSettings; - -int sChan, sChip, sMod, sDac, sAdc; -const int allSelected=-2; -const int noneSelected=-1; - - -sls_detector_module *detectorModules=NULL; -int *detectorChips=NULL; -int *detectorChans=NULL; -int *detectorDacs=NULL; -int *detectorAdcs=NULL; -//int numberOfProbes; - -ROI rois[MAX_ROIS]; -int nROI=0; - - -int initDetector() { - - int imod; - // sls_detector_module *myModule; - int n=getNModBoard(); - nModX=n; - -#ifdef VERBOSE - printf("Board is for %d modules\n",n); -#endif - detectorModules=malloc(n*sizeof(sls_detector_module)); - detectorChips=malloc(n*NCHIP*sizeof(int)); - detectorChans=malloc(n*NCHIP*NCHAN*sizeof(int)); - detectorDacs=malloc(n*NDAC*sizeof(int)); - detectorAdcs=malloc(n*NADC*sizeof(int)); -#ifdef VERBOSE - printf("modules from 0x%x to 0x%x\n",(unsigned int)(detectorModules), (unsigned int)(detectorModules+n)); - printf("chips from 0x%x to 0x%x\n",(unsigned int)(detectorChips), (unsigned int)(detectorChips+n*NCHIP)); - printf("chans from 0x%x to 0x%x\n",(unsigned int)(detectorChans), (unsigned int)(detectorChans+n*NCHIP*NCHAN)); - printf("dacs from 0x%x to 0x%x\n",(unsigned int)(detectorDacs), (unsigned int)(detectorDacs+n*NDAC)); - printf("adcs from 0x%x to 0x%x\n",(unsigned int)(detectorAdcs), (unsigned int)(detectorAdcs+n*NADC)); -#endif - for (imod=0; imoddacs=detectorDacs+imod*NDAC; - (detectorModules+imod)->adcs=detectorAdcs+imod*NADC; - (detectorModules+imod)->chipregs=detectorChips+imod*NCHIP; - (detectorModules+imod)->chanregs=detectorChans+imod*NCHIP*NCHAN; - (detectorModules+imod)->ndac=NDAC; - (detectorModules+imod)->nadc=NADC; - (detectorModules+imod)->nchip=NCHIP; - (detectorModules+imod)->nchan=NCHIP*NCHAN; - (detectorModules+imod)->module=imod; - (detectorModules+imod)->gain=0; - (detectorModules+imod)->offset=0; - (detectorModules+imod)->reg=0; - /* initialize registers, dacs, retrieve sn, adc values etc */ - } - thisSettings=UNINITIALIZED; - sChan=noneSelected; - sChip=noneSelected; - sMod=noneSelected; - sDac=noneSelected; - sAdc=noneSelected; - - /* - setCSregister(ALLMOD); //commented out by dhanya - setSSregister(ALLMOD); - counterClear(ALLMOD); - clearSSregister(ALLMOD); - putout("0000000000000000",ALLMOD); - */ - - /* initialize dynamic range etc. */ - /* dynamicRange=getDynamicRange(); //always 16 not required commented out - nModX=setNMod(-1);*/ - - //dataBytes=nModX*NCHIP*NCHAN*4; - // dynamicRange=32; - // initChip(0, 0,ALLMOD); - //nModX=n; - // - - - return OK; -} - - -int setDefaultDacs() { - printf("Setting Default Dac values\n"); - - int ret = OK; - int i = 0; - int retval[2]={-1,-1}; - const int defaultvals[NDAC] = DEFAULT_DAC_VALS; - - for(i = 0; i < NDAC; ++i) { - // if not already default, set it to default - if (setDACRegister(i, -1, -1) != defaultvals[i]) { - initDACbyIndexDACU(i, defaultvals[i], 0, 0, retval); - if (abs(retval[0] - defaultvals[i])<=3) { - cprintf(RED, "Warning: Setting dac %d failed, wrote %d, read %d\n",i ,defaultvals[i], retval[0]); - ret = FAIL; - } - } - } - - return ret; -} - - - -int copyChannel(sls_detector_channel *destChan, sls_detector_channel *srcChan) { - destChan->chan=srcChan->chan; - destChan->chip=srcChan->chip; - destChan->module=srcChan->module; - destChan->reg=srcChan->reg; - return OK; -} - - -int copyChip(sls_detector_chip *destChip, sls_detector_chip *srcChip) { - - int ichan; - int ret=OK; - if ((srcChip->nchan)>(destChip->nchan)) { - printf("Number of channels of source is larger than number of channels of destination\n"); - return FAIL; - } - - destChip->nchan=srcChip->nchan; - destChip->reg=srcChip->reg; - destChip->chip=srcChip->chip; - destChip->module=srcChip->module; - for (ichan=0; ichan<(srcChip->nchan); ichan++) { - *((destChip->chanregs)+ichan)=*((srcChip->chanregs)+ichan); - } - return ret; -} - - -int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) { - - int ichip, idac, ichan, iadc; - - int ret=OK; - -#ifdef VERBOSE - printf("Copying module %x to module %x\n",(unsigned int)(srcMod),(unsigned int)(destMod)); -#endif - - if (srcMod->module>=0) { -#ifdef VERBOSE - printf("Copying module number %d to module number %d\n",srcMod->module,destMod->module); -#endif - destMod->module=srcMod->module; - } - if (srcMod->serialnumber>=0){ -/* #ifdef VERBOSE */ -/* printf("Copying module serial number %x to module serial number %x\n",srcMod->serialnumber,destMod->serialnumber); */ -/* #endif */ - destMod->serialnumber=srcMod->serialnumber; - } - if ((srcMod->nchip)>(destMod->nchip)) { - printf("Number of chip of source is larger than number of chips of destination\n"); - return FAIL; - } - if ((srcMod->nchan)>(destMod->nchan)) { - printf("Number of channels of source is larger than number of channels of destination\n"); - return FAIL; - } - if ((srcMod->ndac)>(destMod->ndac)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - if ((srcMod->nadc)>(destMod->nadc)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - -#ifdef VERBOSE - printf("DACs: src %d, dest %d\n",srcMod->ndac,destMod->ndac); - printf("ADCs: src %d, dest %d\n",srcMod->nadc,destMod->nadc); - printf("Chips: src %d, dest %d\n",srcMod->nchip,destMod->nchip); - printf("Chans: src %d, dest %d\n",srcMod->nchan,destMod->nchan); - -#endif - - - - destMod->ndac=srcMod->ndac; - destMod->nadc=srcMod->nadc; - destMod->nchip=srcMod->nchip; - destMod->nchan=srcMod->nchan; - if (srcMod->reg>=0) - destMod->reg=srcMod->reg; -#ifdef VERBOSE - printf("Copying register %x (%x)\n",destMod->reg,srcMod->reg ); -#endif - if (srcMod->gain>=0) - destMod->gain=srcMod->gain; - if (srcMod->offset>=0) - destMod->offset=srcMod->offset; - - // printf("copying gain and offset %f %f to %f %f\n",srcMod->gain,srcMod->offset,destMod->gain,destMod->offset); - - for (ichip=0; ichip<(srcMod->nchip); ichip++) { - if (*((srcMod->chipregs)+ichip)>=0) - *((destMod->chipregs)+ichip)=*((srcMod->chipregs)+ichip); - } - for (ichan=0; ichan<(srcMod->nchan); ichan++) { - if (*((srcMod->chanregs)+ichan)>=0) - *((destMod->chanregs)+ichan)=*((srcMod->chanregs)+ichan); - } - for (idac=0; idac<(srcMod->ndac); idac++) { - if (*((srcMod->dacs)+idac)>=0) - *((destMod->dacs)+idac)=*((srcMod->dacs)+idac); - } - for (iadc=0; iadc<(srcMod->nadc); iadc++) { - if (*((srcMod->adcs)+iadc)>=0) - *((destMod->adcs)+iadc)=*((srcMod->adcs)+iadc); - } - return ret; -} - - - -/* Register commands */ - - -int clearDACSregister(int imod) { - - putout("1111111111111111",imod);//reset - putout("1111111111111110",imod);//cs down - - /* commented out by dhanya - putout("0000000001000000",imod); - putout("0000000101000000",imod); - putout("0000000101000000",imod); - putout("0000000001000000",imod); - */ -#ifdef DEBUG - fprintf(stdout, "Clearing DAC shiftregister\n"); -#endif - // sDac=0; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return OK; -} - -int nextDAC(int imod) { - - putout("1111111111111011",imod);//cs up - putout("1111111111111001",imod);//clk down - putout("1111111111111111",imod);//reset - - /*commented out by dhanya - putout("0000000001000000",imod); - putout("0000000001001000",imod); - putout("0000000001000000",imod); - */ -#ifdef DEBUG - fprintf(stdout, "Next DAC\n"); -#endif - // sDac++; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return OK; -} - - -int clearCSregister(int imod) { - - putout("0000000001000000",imod); - putout("0000100001000000",imod); - putout("0000100001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Clearing CS shiftregister\n"); -#endif - /* - sChan=noneSelected; - sMod=noneSelected; - sDac=noneSelected; - sAdc=noneSelected; - */ - sChip=noneSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - //putout("0000000000000000",imod); - return 0; -} - -int setCSregister(int imod){ - - putout("0000000001000000",imod); - putout("0001000001000000",imod); - putout("0001000001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Setting CS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChip=allSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int nextChip(int imod){ - - putout("0000000001000000",imod); - putout("0010000001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Next Chip\n"); -#endif - sChip++; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int firstChip(int imod){ - - putout("0100000001000000",imod); - putout("0110000001000000",imod); - putout("0100000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "First Chip\n"); -#endif - sChip=0; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int clearSSregister(int imod){ - int i; - putout("0000011000000000",imod); - for (i=0; i<10; i++) - putout("0000111000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"Clearing SS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChan=noneSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int setSSregister(int imod){ - int i; - putout("0000011000000000",imod); - for (i=0; i<10; i++) - putout("0001011000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"Setting SS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChan=allSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int nextStrip(int imod){ - putout("0000011000000000",imod); - putout("0010011000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"|-"); -#endif - sChan++; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int selChannel(const int strip,int imod) { - int istrip; - clearSSregister(imod); - nextStrip(imod); - for (istrip=0; istrip=0 && imod=0) - initDAC(ind,val, imod); - - if (imod>=0 && imodndac) - return (detectorDacs[ind+imod*NDAC]); - } - return FAIL; - */ - return setDACRegister(ind, -1, imod); -} - - -int initDAC(int dac_addr, int value, int imod) { -// int i; -#ifdef VERBOSE - printf("Programming dac %d with value %d\n", dac_addr, value); -#endif - clearDACSregister(imod); - program_one_dac(dac_addr,value,imod); - nextDAC(imod); - clearDACSregister(imod); - - return 0; -} - -int getTemperatureByModule(int tempSensor, int imod) -{ - int im; - //for the particular module - if (imod>=0 && imod=0 && imod=0 && imod=0) { -#ifdef VERBOSE - fprintf(stdout, "voltage %d\n", *(v+iaddr)); -#endif - program_one_dac(iaddr, *(v+iaddr),imod); - } - nextDAC(imod); - } - - - clearDACSregister(imod); - - return 0; - -} - - - - -int setSettings(int i, int imod) { -#ifdef VERBOSE - if(i==-1) - printf("\nReading settings of detector...\n"); - else - printf("\ninside set settings wit settings=%d...\n",i); -#endif - int confgain[] = CONF_GAIN; - int isett=-2,retval; - - //reading settings - if(i==GET_SETTINGS){ - retval=initConfGainByModule(i,i,imod); - if(retval==i) - isett=UNDEFINED; - } - //writing settings - else{ - retval=initConfGainByModule(i,confgain[i],imod); - if(retval!=i) - isett=UNDEFINED; - } - //if error while read/writing - if(isett==UNDEFINED) - printf("Error:Weird Value read back from the Gain/Settings Reg\n"); - else{ - //validating the settings read back - if((retval>=HIGHGAIN)&&(retval<=VERYHIGHGAIN)) - isett=retval; - else{ - isett=UNDEFINED; - printf("Error:Wrong Settings Read out:%d\n",retval); - } - } - thisSettings=isett; -//#ifdef VERBOSE - printf("detector settings are %d\n",thisSettings); -//#endif - return thisSettings; -} - - - - -/* Initialization*/ - -int initChannelbyNumber(sls_detector_channel myChan) { - int reg=myChan.reg; - int ft=reg & TRIM_DR; - int cae=(reg>>(NTRIMBITS))&1; - int ae=(reg>>(NTRIMBITS+1))&1; - int coe=(reg>>(NTRIMBITS+2))&1; - int ocoe=(reg>>(NTRIMBITS+3))&1; - int counts=(reg>>(NTRIMBITS+4)); -#ifdef VERBOSE - printf("Initializing channel %d chip %d module %d reg %x\n",myChan.chan,myChan.chip,myChan.module, reg); - printf("trim %d, cae %d, ae %d, coe %d, ocoe %d, counts %d\n",ft, cae, ae, coe, ocoe, counts); -#endif - - if (myChan.chip<0) - setCSregister(myChan.module); - else - selChip(myChan.chip,myChan.module); - - if (myChan.chan<0) - setSSregister(myChan.module); - else - selChannel(myChan.chan,myChan.module); - - initChannel(ft,cae,ae, coe, ocoe, counts,myChan.module); - - setDynamicRange(dynamicRange); - - setCSregister(ALLMOD); - clearSSregister(ALLMOD); - putout("0000000000000000",ALLMOD); - - return myChan.reg; - -} - -int getChannelbyNumber(sls_detector_channel* myChan) { - int imod, ichip, ichan; - imod=myChan->module; - ichip=myChan->chip; - ichan=myChan->chan; - - if (detectorChans) { - if (imod=0) { - if (ichip<(detectorModules+imod)->nchip && ichan<(detectorModules+imod)->nchan/(detectorModules+imod)->nchip) - myChan->reg=detectorChans[imod*NCHAN*NCHIP+ichip*NCHAN+ichan]; - return OK; - } - } - return FAIL; - -} - -int getTrimbit(int imod, int ichip, int ichan) { - if (detectorChans) { - if (imod=0) - if (ichip<(detectorModules+imod)->nchip && ichan<(detectorModules+imod)->nchan/(detectorModules+imod)->nchip) - return (detectorChans[imod*NCHAN*NCHIP+ichip*NCHAN+ichan] & TRIM_DR); - } - - return -1; -} - -int initChannel(int ft,int cae, int ae, int coe, int ocoe, int counts, int imod){ - - int ibit, bit, i, im, ichip, ichan; - int chanmi, chanma, chipmi, chipma, modmi, modma; - - - - sMod=imod; - // printf("initializing module %d\n",sMod); - if (imod==ALLMOD) { - sMod=allSelected; - - // printf("initializing all modules\n"); - } - - if (sChan==allSelected) { - // printf("initializing all channels ft=%d coe=%d\n",ft,coe); - chanmi=0; - chanma=NCHAN; - } else if (sChan==noneSelected || sChan>NCHAN || sChan<0) { - // printf("initializing no channels ft=%d coe=%d\n",ft,coe); - chanmi=0; - chanma=-1; - } else { - // printf("initializing channel %d ft=%d coe=%d\n",sChan, ft,coe); - chanmi=sChan; - chanma=sChan+1; - } - - if (sChip==allSelected) { - // printf("initializing all chips\n"); - chipmi=0; - chipma=NCHIP; - } else if (sChip==noneSelected || sChip>NCHIP || sChip<0) { - // printf("initializing no chips\n"); - chipmi=0; - chipma=-1; - } else { - // printf("initializing chip %d\n",sChip); - chipmi=sChip; - chipma=sChip+1; - } - - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - return 1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorChans) { - for (im=modmi; im63 || ft<0) { - fprintf(stdout,"Fine Threshold is %d while should be between 0 and 63!",ft); - return 1; - } - /*cal_enable*/ - if (cae) { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - } else { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - } - /*n_an_enable*/ - if (ae) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } else { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - putout("0100000000000000",imod); - } - /*trb5*/ - ibit=5; - bit=ft & (1<>1; - int nchan, ichan; - int ft, cae, ae, coe, ocoe, counts, chanreg; - - - - nchan=myChip.nchan; - if (ichip<0) - setCSregister(imod); - else - selChip(ichip,imod); - - clearSSregister(imod); - for (ichan=0; ichan>(NTRIMBITS+1))&1; - ae=(chanreg>>(NTRIMBITS+2))&1; - coe=((chanreg)>>(NTRIMBITS+3))&1; - ocoe=((chanreg)>>(NTRIMBITS+4))&1; - counts=((chanreg)>>(NTRIMBITS+5)); - nextStrip(imod); - initChannel(ft,cae,ae, coe, ocoe, counts,imod); - } - initChip(obe,ow,imod); - return myChip.reg; - -} - -int getChipbyNumber(sls_detector_chip* myChip){ - int imod, ichip; - imod=myChip->module; - ichip=myChip->chip; - - if (detectorChips) { - if (imodnchip) { - myChip->reg=detectorChips[ichip+imod*NCHIP]; - myChip->nchan=NCHAN; - myChip->chanregs=detectorChans+imod*NCHAN*NCHIP+ichip*NCHIP; - return OK; - } - } - return FAIL; - -} - - - -int initChip(int obe, int ow,int imod){ - int i; - int im, ichip; - int chipmi, chipma, modmi, modma; - /* switch (ow) { - case 0:; - case 1: - setDynamicRange(32); - break; - case 2: - setDynamicRange(16); - break; - case 3: - setDynamicRange(8); - break; - case 4: - setDynamicRange(4); - break; - case 5: - setDynamicRange(1); - break; - default: - setDynamicRange(32); - break; - } - */ - -#ifdef DEBUGOUT - printf("Initializing chip\n"); -#endif - putout("0000000000000000",imod); -#ifdef DEBUGOUT - printf("Output mode= %d\n", ow); -#endif - - /* clearing shift in register */ - for (i=0; i<10; i++) - putout("0000100000000000",imod); - putout("0000000000000000",imod); - - if (ow>0) { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - putout("0100000000000000",imod); - for (i=0; i<(OUTMUX_OFFSET-1); i++) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>1) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>2) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>3) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>4) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - } -#ifdef DEBUGOUT - printf("Output buffer enable= %d\n", obe); -#endif - if (obe) { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - putout("0100000000000000",imod); - } else { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - /*}*/ - putout("0000000000000000",imod); - - - - - - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - - - if (sChip==allSelected) { - chipmi=0; - chipma=NCHIP; - } else if (sChip==noneSelected || sChip>NCHIP || sChip<0) { - chipmi=0; - chipma=-1; - } else { - chipmi=sChip; - chipma=sChip+1; - } - - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorChips) { - for (im=modmi; imNCHIP || sChip<0) { - chipmi=0; - chipma=-1; - } else { - chipmi=sChip; - chipma=sChip+1; - } - - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorChips) { - for (im=modmi; imnModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorModules) { - for (im=modmi; imreg)=cm; -#ifdef VERBOSE - printf("imod=%d reg=%d (%x)\n",im,(detectorModules+im)->reg,(unsigned int)((detectorModules+im))); -#endif - } - } - return 0; -} - -int initModulebyNumber(sls_detector_module myMod) { - - printf("\ninside initmoduleynumber..\n"); - - int nchip,nchan;//int ichip, nchip, ichan, nchan; - int im, modmi,modma; - // int ft, cae, ae, coe, ocoe, counts, chanreg; - int imod; - // int obe; - // int ow; - int v[NDAC]; - - - nchip=myMod.nchip; - nchan=(myMod.nchan)/nchip; - - imod=myMod.module; - sMod=imod; - - if (sMod==ALLMOD) - sMod=allSelected; - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {// (sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - - /* - for (idac=0; idacmodule; -#ifdef VERBOSE - printf("Getting module %d\n",imod); -#endif - if (detectorModules) { - copyModule(myMod,detectorModules+imod); - ; - } else - return FAIL; - - return OK; -} - -/* To chips */ -int clearCounter(int imod){ - int i; -#ifdef DEBUG - printf("Clearing counter with contclear\n"); -#endif - putout("0000000000000000",imod); - for (i=0; i<10; i++) - putout("0000000000010000",imod); - putout("0000000000000000",imod); - - return 0; -} - -int clearOutReg(int imod){ - int i; -#ifdef DEBUG - printf("Clearing output register\n"); -#endif - putout("0000010000000000",imod); - for (i=0; i<10; i++) - putout("0000110000000000",imod); - putout("0000010000000000",imod); - return 0; -} -int setOutReg(int imod){ - int i; -#ifdef DEBUG - printf("Setting output register\n"); -#endif - putout("0000010000000000",imod); - for (i=0; i<10; i++) - putout("0001010000000000",imod); - putout("0000010000000000",imod); - return 0; -} - - -int extPulse(int ncal, int imod) { - int ical; -#ifdef DEBUG - printf("Giving a clock pulse to the counter\n"); -#endif - for (ical=0; ical0 && i%2==0) { - printf("Shift in: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, i%2); - result++; - } - if (i%2>0 && (val & 1<0 && (dum & (1<0) { - printf("Shift out: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, (dum &1<0 && i%2==0) { - printf("Shift stsel: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, i%2); - result++; - } - if (i%2>0 && (val & 1<> 1; - - - putout("0000000000000000",ALLMOD); - putout("0010000000000000",ALLMOD); //change mux setting - putout("0000000000000000",ALLMOD); - } - - printf("Test FpgaMux module %d : %d errors\n", imod,result); - if (result) - return 1; - else - return 0; -} - - - - - - - - - -int calibration_sensor(int num, int *v, int *dacs) { - int ich, ichip, imod; - int val[10]; - - - printf("calibrating sensor..."); - for (imod=0; imod=0){ - - //clear rois - for(i=0;i=0) && (adc<=4)); - else { - printf("warning:adc value greater than 5. deleting roi\n"); - adc=-1; - } - } - } - printf("\tGoing to enable adc: %d\n", adc); - - //set rois for just 1 adc - take only 1st roi - if(adc!=-1){ - rois[0].xmin=adc*(NCHAN*NCHIPS_PER_ADC); - rois[0].xmax=(adc+1)*(NCHAN*NCHIPS_PER_ADC)-1; - rois[0].ymin=-1; - rois[0].ymax=-1; - nROI = 1; - printf("\tActual xmin:%d xmax:%d\n",rois[0].xmin,rois[0].xmax); - }else - nROI = 0; - - if((n!=0) && ((arg[0].xmin!=rois[0].xmin)|| - (arg[0].xmax!=rois[0].xmax)|| - (arg[0].ymin!=rois[0].ymin)|| - (arg[0].ymax!=rois[0].ymax))) - *ret=FAIL; - if(n!=nROI) - *ret=FAIL; - - //set adc of interest - setADC(adc); - } - -//#ifdef VERBOSE - if (nROI) { - printf("Rois:\n"); - for( i=0;i -#include - - -extern int sockfd; -extern int phase_shift; - - - -void error(char *msg) -{ - perror(msg); -} - -int main(int argc, char *argv[]) -{ - int portno, b; - char cmd[100]; - int retval=OK; - int sd, fd; - int iarg; - for(iarg=1; iarg - - -// Hardware definitions - -#define NCHAN 128 -#define NCHIP 10 -#define NMAXMODX 1 -#define NMAXMODY 1 -#define NMAXMOD NMAXMODX*NMAXMODY -#define NDAC 8 -#define NADC 5 - -#define NCHANS NCHAN*NCHIP*NMAXMOD -#define NDACS NDAC*NMAXMOD - -#define NTRIMBITS 6 -#define NCOUNTBITS 24 - -#define NCHIPS_PER_ADC 2 - -// for 25 um -#define CONFIG_FILE "config.txt" - - -//#define TRIM_DR ((2**NTRIMBITS)-1) -//#define COUNT_DR ((2**NCOUNTBITS)-1) -#define TRIM_DR (((int)pow(2,NTRIMBITS))-1) -#define COUNT_DR (((int)pow(2,NCOUNTBITS))-1) - - -#define ALLMOD 0xffff -#define ALLFIFO 0xffff - - -#define ADCSYNC_VAL 0x32214 -#define TOKEN_RESTART_DELAY 0x88000000 -#define TOKEN_RESTART_DELAY_ROI 0x1b000000 -#define TOKEN_TIMING_REV1 0x1f16 -#define TOKEN_TIMING_REV2 0x1f10 - -#define DEFAULT_PHASE_SHIFT 120 -#define DEFAULT_IP_PACKETSIZE 0x0522 -#define DEFAULT_UDP_PACKETSIZE 0x050E -#define ADC1_IP_PACKETSIZE (256*2+14+20) -#define ADC1_UDP_PACKETSIZE (256*2+4+8+2) - -#ifdef VIRTUAL -#define DEBUGOUT -#endif - -#define CLK_FREQ 32.007729 - - -#endif diff --git a/slsDetectorSoftware/gotthardDetectorServer/server_funcs.c b/slsDetectorSoftware/gotthardDetectorServer/server_funcs.c deleted file mode 100755 index 3fe6591e5..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/server_funcs.c +++ /dev/null @@ -1,3153 +0,0 @@ -#include "sls_detector_defs.h" -#include "server_funcs.h" -#ifndef PICASSOD -#include "server_defs.h" -#else -#include "picasso_defs.h" -#endif -#include "firmware_funcs.h" -#include "mcb_funcs.h" -#include "registers_g.h" -#include "gitInfoGotthard.h" -#include "AD9257.h" // include "commonServerFunctions.h" -#include "versionAPI.h" - -#define FIFO_DATA_REG_OFF 0x50<<11 -#define CONTROL_REG 0x24<<11 -// Global variables - -int (*flist[256])(int); - -//defined in the detector specific file -#ifdef MYTHEND -const enum detectorType myDetectorType=MYTHEN; -#elif PROPIXD -const enum detectorType myDetectorType=PROPIX; -#elif GOTTHARDD -const enum detectorType myDetectorType=GOTTHARD; -#elif EIGERD -const enum detectorType myDetectorType=EIGER; -#elif PICASSOD -const enum detectorType myDetectorType=PICASSO; -#elif MOENCHD -const enum detectorType myDetectorType=MOENCH; -#else -const enum detectorType myDetectorType=GENERIC; -#endif - - -extern int nModX; -extern int nModY; -extern int dataBytes; -extern int dynamicRange; -extern int storeInRAM; - -extern int lockStatus; -extern char lastClientIP[INET_ADDRSTRLEN]; -extern char thisClientIP[INET_ADDRSTRLEN]; -extern int differentClients; - -/* global variables for optimized readout */ -extern unsigned int *ram_values; -char *dataretval=NULL; -int nframes, iframes, dataret; -char mess[MAX_STR_LENGTH]; - -int digitalTestBit = 0; - - -int init_detector( int b) { - - if (mapCSP0()==FAIL) { - printf("Could not map memory\n"); - exit(-1); - } - - //confirm if it is really gotthard - if (((bus_r(PCB_REV_REG) & DETECTOR_TYPE_MASK)>> DETECTOR_TYPE_OFFSET) == MOENCH_MODULE){ - printf("This is a MOENCH detector. Exiting Gotthard Server.\n\n"); - exit(-1); - } - - if (b) { -#ifdef PROPIXD - printf("***This is a PROPIX detector***\n"); -#else - printf("***This is a GOTTHARD detector with %d chips per module***\n", NCHIP); -#endif - printf("\nBoard Revision:0x%x\n",(bus_r(PCB_REV_REG)&BOARD_REVISION_MASK)); -#ifdef MCB_FUNCS - initDetector(); - printf("Initializing Detector\n"); -#endif - testFpga(); - - //gotthard specific - setPhaseShiftOnce(); - configureADC(); - - setADC(-1); //already does setdaqreg and clean fifo - setSettings(DYNAMICGAIN,-1); - setDefaultDacs(); - - //Initialization - setFrames(1); - setTrains(1); - setExposureTime(1e6); - setPeriod(1e9); - setDelay(0); - setGates(0); - setTiming(GET_EXTERNAL_COMMUNICATION_MODE); - setMaster(GET_MASTER); - setSynchronization(GET_SYNCHRONIZATION_MODE); - startReceiver(1); - setMasterSlaveConfiguration(); - } - strcpy(mess,"dummy message"); - strcpy(lastClientIP,"none"); - strcpy(thisClientIP,"none1"); - lockStatus=0; - return OK; -} - - -int decode_function(int file_des) { - int fnum,n; - int retval=FAIL; -#ifdef VERBOSE - printf( "receive data\n"); -#endif - n = receiveDataOnly(file_des,&fnum,sizeof(fnum)); - if (n <= 0) { -#ifdef VERBOSE - printf("ERROR reading from socket %d, %d %d\n", n, fnum, file_des); -#endif - return FAIL; - } -#ifdef VERBOSE - else - printf("size of data received %d\n",n); -#endif - -#ifdef VERBOSE - printf( "calling function fnum = %d %x\n",fnum,(unsigned int)(flist[fnum])); -#endif - if (fnum<0 || fnum>255) - fnum=255; - retval=(*flist[fnum])(file_des); - if (retval==FAIL) - printf( "Error executing the function = %d \n",fnum); - return retval; -} - - -int function_table() { - int i; - for (i=0;i<256;i++){ - flist[i]=&M_nofunc; - } - flist[F_EXIT_SERVER]=&exit_server; - flist[F_EXEC_COMMAND]=&exec_command; - flist[F_GET_DETECTOR_TYPE]=&get_detector_type; - flist[F_SET_NUMBER_OF_MODULES]=&set_number_of_modules; - flist[F_GET_MAX_NUMBER_OF_MODULES]=&get_max_number_of_modules; - flist[F_SET_EXTERNAL_SIGNAL_FLAG]=&set_external_signal_flag; - flist[F_SET_EXTERNAL_COMMUNICATION_MODE]=&set_external_communication_mode; - flist[F_GET_ID]=&get_id; - flist[F_DIGITAL_TEST]=&digital_test; - flist[F_WRITE_REGISTER]=&write_register; - flist[F_READ_REGISTER]=&read_register; - flist[F_SET_DAC]=&set_dac; - flist[F_GET_ADC]=&get_adc; - flist[F_SET_CHANNEL]=&set_channel; - flist[F_SET_CHIP]=&set_chip; - flist[F_SET_MODULE]=&set_module; - flist[F_GET_CHANNEL]=&get_channel; - flist[F_GET_CHIP]=&get_chip; - flist[F_GET_MODULE]=&get_module; - flist[F_GET_THRESHOLD_ENERGY]=&get_threshold_energy; - flist[F_SET_THRESHOLD_ENERGY]=&set_threshold_energy; - flist[F_SET_SETTINGS]=&set_settings; - flist[F_START_ACQUISITION]=&start_acquisition; - flist[F_STOP_ACQUISITION]=&stop_acquisition; - flist[F_START_READOUT]=&start_readout; - flist[F_GET_RUN_STATUS]=&get_run_status; - flist[F_READ_FRAME]=&read_frame; - flist[F_READ_ALL]=&read_all; - flist[F_START_AND_READ_ALL]=&start_and_read_all; - flist[F_SET_TIMER]=&set_timer; - flist[F_GET_TIME_LEFT]=&get_time_left; - flist[F_SET_DYNAMIC_RANGE]=&set_dynamic_range; - flist[F_SET_ROI]=&set_roi; - flist[F_SET_SPEED]=&set_speed; - flist[F_SET_READOUT_FLAGS]=&set_readout_flags; - flist[F_EXECUTE_TRIMMING]=&execute_trimming; - flist[F_LOCK_SERVER]=&lock_server; - flist[F_SET_PORT]=&set_port; - flist[F_GET_LAST_CLIENT_IP]=&get_last_client_ip; - flist[F_UPDATE_CLIENT]=&update_client; - flist[F_CONFIGURE_MAC]=&configure_mac; - flist[F_LOAD_IMAGE]=&load_image; - flist[F_SET_MASTER]=&set_master; - flist[F_SET_SYNCHRONIZATION_MODE]=&set_synchronization; - flist[F_READ_COUNTER_BLOCK]=&read_counter_block; - flist[F_RESET_COUNTER_BLOCK]=&reset_counter_block; - flist[F_PREPARE_ACQUISITION]=&start_receiver; - flist[F_CLEANUP_ACQUISITION]=&stop_receiver; - flist[F_CALIBRATE_PEDESTAL]=&calibrate_pedestal; - flist[F_WRITE_ADC_REG]=&write_adc_register; - flist[F_CHECK_VERSION]= &check_version; - return OK; -} - - -int M_nofunc(int file_des){ - - int ret=FAIL; - sprintf(mess,"Unrecognized Function\n"); - printf(mess); - - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); - return GOODBYE; -} - - -int exit_server(int file_des) { - int retval=FAIL; - sendDataOnly(file_des,&retval,sizeof(retval)); - printf("closing server."); - sprintf(mess,"closing server"); - sendDataOnly(file_des,mess,sizeof(mess)); - return GOODBYE; -} - -int exec_command(int file_des) { - char cmd[MAX_STR_LENGTH]; - char answer[MAX_STR_LENGTH]; - int retval=OK; - int sysret=0; - int n=0; - - /* receive arguments */ - n = receiveDataOnly(file_des,cmd,MAX_STR_LENGTH); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - - /* execute action if the arguments correctly arrived*/ - if (retval==OK) { -#ifdef VERBOSE - printf("executing command %s\n", cmd); -#endif - if (lockStatus==0 || differentClients==0) - sysret=system(cmd); - - //should be replaced by popen - if (sysret==0) { - sprintf(answer,"Succeeded\n"); - if (lockStatus==1 && differentClients==1) - sprintf(answer,"Detector locked by %s\n", lastClientIP); - } else { - sprintf(answer,"Failed\n"); - retval=FAIL; - } - } else { - sprintf(answer,"Could not receive the command\n"); - } - - /* send answer */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - n = sendDataOnly(file_des,answer,MAX_STR_LENGTH); - if (n < 0) { - sprintf(mess,"Error writing to socket"); - retval=FAIL; - } - - - /*return ok/fail*/ - return retval; - -} - - - -int get_detector_type(int file_des) { - int n=0; - enum detectorType ret; - int retval=OK; - - sprintf(mess,"Can't return detector type\n"); - - - /* receive arguments */ - /* execute action */ - ret=myDetectorType; - -#ifdef VERBOSE - printf("Returning detector type %d\n",ret); -#endif - - /* send answer */ - /* send OK/failed */ - if (differentClients==1) - retval=FORCE_UPDATE; - - n += sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - /*return ok/fail*/ - return retval; - - -} - - -int set_number_of_modules(int file_des) { - int n; - int arg[2], ret=0; - int retval=OK; - int dim, nm; - - sprintf(mess,"Can't set number of modules\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket %d", n); - retval=GOODBYE; - } - if (retval==OK) { - dim=arg[0]; - nm=arg[1]; - - /* execute action */ -#ifdef VERBOSE - printf("Setting the number of modules in dimension %d to %d\n",dim,nm ); -#endif - - //if (nm!=GET_FLAG) { - if (dim!=X && nm!=GET_FLAG) { - retval=FAIL; - sprintf(mess,"Can't change module number in dimension %d\n",dim); - } else { - if (lockStatus==1 && differentClients==1 && nm!=GET_FLAG) { - sprintf(mess,"Detector locked by %s\n", lastClientIP); - retval=FAIL; - } else { - ret=setNMod(nm); - if (nModX==nm || nm==GET_FLAG) { - retval=OK; - if (differentClients==1) - retval=FORCE_UPDATE; - } else - retval=FAIL; - } - } - } - /*} else { - if (dim==Y) { - ret=nModY; - } else if (dim==X) { - ret=setNMod(-1); - } - } - */ - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - /*return ok/fail*/ - return retval; - -} - - -int get_max_number_of_modules(int file_des) { - int n; - int ret; - int retval=OK; - enum dimension arg; - - sprintf(mess,"Can't get max number of modules\n"); - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - /* execute action */ -#ifdef VERBOSE - printf("Getting the max number of modules in dimension %d \n",arg); -#endif - - - switch (arg) { - case X: - ret=getNModBoard(); - break; - case Y: - ret=NMAXMODY; - break; - default: - ret=FAIL; - retval=FAIL; - break; - } -#ifdef VERBOSE - printf("Max number of module in dimension %d is %d\n",arg,ret ); -#endif - - - - if (differentClients==1 && retval==OK) { - retval=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - - /*return ok/fail*/ - return retval; -} - - -//index 0 is in gate -//index 1 is in trigger -//index 2 is out gate -//index 3 is out trigger - -int set_external_signal_flag(int file_des) { - int n; - int arg[2]; - int ret=OK; - int signalindex; - enum externalSignalFlag flag, retval; - - sprintf(mess,"Can't set external signal flag\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - retval=SIGNAL_OFF; - if (ret==OK) { - signalindex=arg[0]; - flag=arg[1]; - /* execute action */ - switch (flag) { - case GET_EXTERNAL_SIGNAL_FLAG: - retval=getExtSignal(signalindex); - break; - - default: - if (lockStatus && differentClients) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n", lastClientIP); - } else if (signalindex > 0) { - ret=FAIL; - sprintf(mess,"Signal index %d is reserved. Only index 0 can be configured.\n", signalindex); - } else { - retval=setExtSignal(flag); - } - } -#ifdef VERBOSE - printf("Setting external signal %d to flag %d\n",signalindex,flag ); - printf("Set to flag %d\n",retval); -#endif - - } - - if (ret==OK && differentClients!=0) - ret=FORCE_UPDATE; - - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - /*return ok/fail*/ - return ret; - -} - - -int set_external_communication_mode(int file_des) { - int n; - enum externalCommunicationMode arg, ret=GET_EXTERNAL_COMMUNICATION_MODE; - int retval=OK; - - sprintf(mess,"Can't set external communication mode\n"); - - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - /* - enum externalCommunicationMode{ - GET_EXTERNAL_COMMUNICATION_MODE, - AUTO, - TRIGGER_EXPOSURE_SERIES, - TRIGGER_EXPOSURE_BURST, - TRIGGER_READOUT, - TRIGGER_COINCIDENCE_WITH_INTERNAL_ENABLE, - GATE_FIX_NUMBER, - GATE_FIX_DURATION, - GATE_WITH_START_TRIGGER, - GATE_COINCIDENCE_WITH_INTERNAL_ENABLE - }; - */ - if (retval==OK) { - /* execute action */ - - ret=setTiming(arg); - - /* switch(arg) { */ - /* default: */ - /* sprintf(mess,"The meaning of single signals should be set\n"); */ - /* retval=FAIL; */ - /* } */ - - -#ifdef VERBOSE - printf("Setting external communication mode to %d\n", arg); -#endif - } else - ret=FAIL; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return retval; -} - - - -int get_id(int file_des) { - // sends back 64 bits! - int64_t retval=-1; - int ret=OK; - int n=0; - enum idMode arg; - - sprintf(mess,"Can't return id\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - -#ifdef VERBOSE - printf("Getting id %d\n", arg); -#endif - - switch (arg) { - case DETECTOR_SERIAL_NUMBER: - retval=getDetectorNumber(); - break; - case DETECTOR_FIRMWARE_VERSION: - retval = (getFirmwareVersion() & 0xFFFFFF); - break; - case DETECTOR_SOFTWARE_VERSION: - retval = (GITDATE & 0xFFFFFF); - break; - case CLIENT_SOFTWARE_API_VERSION: - return APIGOTTHARD; - default: - printf("Required unknown id %d \n", arg); - ret=FAIL; - retval=FAIL; - break; - } - -#ifdef VERBOSE - printf("Id is %llx\n", retval); -#endif - - if (differentClients==1) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - -int digital_test(int file_des) { - - int retval; - int ret=OK; - int imod=-1; - int n=0; - int ibit=0; - int ow; - int ival; - enum digitalTestMode arg; - - sprintf(mess,"Can't send digital test\n"); - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - -#ifdef VERBOSE - printf("Digital test mode %d\n",arg ); -#endif - - switch (arg) { - case CHIP_TEST: - n = receiveDataOnly(file_des,&imod,sizeof(imod)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } -#ifdef VERBOSE - printf("of module %d\n", imod); -#endif - retval=0; -#ifdef MCB_FUNCS - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - break; - } - if (imod >= nModX) { - ret=FAIL; - sprintf(mess,"Module %d disabled\n",imod); - break; - } - if (testShiftIn(imod)) retval|=(1<<(ibit)); - ibit++; - if (testShiftOut(imod)) retval|=(1<<(ibit)); - ibit++; - if (testShiftStSel(imod)) retval|=(1<<(ibit)); - ibit++; - //if ( testDataInOut(0x123456, imod)) retval|=(1<<(ibit++)); - //if ( testExtPulse(imod)) retval|=(1<<(ibit++)); - // for (ow=0; ow<6; ow++) - // ow=1; - //#ifndef PICASSOD - for (ow=0; ow<5; ow++) { - //#endif - if (testDataInOutMux(imod, ow, 0x789abc)) retval|=(1<=getNModBoard()) - ret=FAIL; - if (imod<0) - imod=ALLMOD; - -#ifdef MCB_FUNCS - switch (ind) { - case G_VREF_DS : - idac=VREF_DS; - break; - case G_VCASCN_PB: - idac=VCASCN_PB; - break; - case G_VCASCP_PB: - idac=VCASCP_PB; - break; - case G_VOUT_CM: - idac=VOUT_CM; - break; - case G_VCASC_OUT: - idac=VCASC_OUT; - break; - case G_VIN_CM: - idac=VIN_CM; - break; - case G_VREF_COMP: - idac=VREF_COMP; - break; - case G_IB_TESTC: - idac=IB_TESTC; - break; - case HV_POT: - idac=HIGH_VOLTAGE; - break; - - default: - printf("Unknown DAC index %d\n",ind); - sprintf(mess,"Unknown DAC index %d\n",ind); - ret=FAIL; - break; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else{ - if(idac==HIGH_VOLTAGE){ - retval[0]=initHighVoltageByModule(val,imod); - ret=FAIL; - if(retval[0]==-2) - strcpy(mess,"Invalid Voltage.Valid values are 0,90,110,120,150,180,200"); - else if(retval[0]==-3) - strcpy(mess,"Weird value read back or it has not been set yet\n"); - else - ret=OK; - }else{ - initDACbyIndexDACU(idac,val,imod,mV,retval); - ret=FAIL; - if(mV) - temp = retval[1]; - else - temp = retval[0]; - if ((abs(temp-val)<=3) || val==-1) { - ret=OK; -#ifdef VERBOSE - printf("DAC set to %d in dac units and %d mV\n", retval[0],retval[1]); -#endif - } - } - } - } - -#endif - - - if(ret==FAIL) - printf("Setting dac %d of module %d: wrote %d but read %d\n", ind, imod, val, temp); - else{ - if (differentClients) - ret=FORCE_UPDATE; - } - - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - /*return ok/fail*/ - return ret; - -} - - - -int get_adc(int file_des) { - //default: mod 0 - int retval; - int ret=OK; - int arg[2]; - enum dacIndex ind; - int imod; - int n; - int idac=0; - - sprintf(mess,"Can't read ADC\n"); - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ind=arg[0]; - imod=0;//arg[1]; - -#ifdef VERBOSE - printf("Getting ADC %d of module %d\n", ind, imod); -#endif - - if (imod>=getNModBoard() || imod<0) - ret=FAIL; - -#ifdef MCB_FUNCS - switch (ind) { - case TEMPERATURE_FPGA: - idac=TEMP_FPGA; - break; - case TEMPERATURE_ADC: - idac=TEMP_ADC; - break; - default: - printf("Unknown DAC index %d\n",ind); - sprintf(mess,"Unknown DAC index %d\n",ind); - ret=FAIL; - break; - } - - if (ret==OK) - retval=getTemperatureByModule(idac,imod); -#endif - -#ifdef VERBOSE - printf("ADC is %d V\n", retval); -#endif - if (ret==FAIL) { - printf("Getting adc %d of module %d failed\n", ind, imod); - } - - if (differentClients) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - -int set_channel(int file_des) { - int ret=OK; - sls_detector_channel myChan; - int retval; - int n; - - - sprintf(mess,"Can't set channel\n"); - -#ifdef VERBOSE - printf("Setting channel\n"); -#endif - ret=receiveChannel(file_des, &myChan); - if (ret>=0) - ret=OK; - else - ret=FAIL; -#ifdef VERBOSE - printf("channel number is %d, chip number is %d, module number is %d, register is %lld\n", myChan.chan,myChan.chip, myChan.module, myChan.reg); -#endif - - if (ret==OK) { - if (myChan.module>=getNModBoard()) - ret=FAIL; - if (myChan.chip>=NCHIP) - ret=FAIL; - if (myChan.chan>=NCHAN) - ret=FAIL; - if (myChan.module<0) - myChan.module=ALLMOD; - } - - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef MCB_FUNCS - retval=initChannelbyNumber(myChan); -#endif - } - } - /* Maybe this is done inside the initialization funcs */ - //copyChannel(detectorChans[myChan.module][myChan.chip]+(myChan.chan), &myChan); - - - - if (differentClients==1 && ret==OK) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - /*return ok/fail*/ - return ret; - -} - - - - -int get_channel(int file_des) { - - int ret=OK; - sls_detector_channel retval; - - int arg[3]; - int ichan, ichip, imod; - int n; - - sprintf(mess,"Can't get channel\n"); - - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ichan=arg[0]; - ichip=arg[1]; - imod=arg[2]; - - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod=0 && ichip=0 && ichan=0) - ret=OK; - else - ret=FAIL; -#ifdef VERBOSE - printf("chip number is %d, module number is %d, register is %d, nchan %d\n",myChip.chip, myChip.module, myChip.reg, myChip.nchan); -#endif - - if (ret==OK) { - if (myChip.module>=getNModBoard()) - ret=FAIL; - if (myChip.module<0) - myChip.module=ALLMOD; - if (myChip.chip>=NCHIP) - ret=FAIL; - } - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef MCB_FUNCS - retval=initChipbyNumber(myChip); -#endif - } - /* Maybe this is done inside the initialization funcs */ - //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); - - if (differentClients && ret==OK) - ret=FORCE_UPDATE; - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - return ret; -} - -int get_chip(int file_des) { - - - int ret=OK; - sls_detector_chip retval; - int arg[2]; - int ichip, imod; - int n; - - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ichip=arg[0]; - imod=arg[1]; - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod=0 && ichip=0) - ret=OK; - else - ret=FAIL; - - -#ifdef VERBOSE - printf("module number is %d,register is %d, nchan %d, nchip %d, ndac %d, nadc %d, gain %f, offset %f\n",myModule.module, myModule.reg, myModule.nchan, myModule.nchip, myModule.ndac, myModule.nadc, myModule.gain,myModule.offset); -#endif - - if (ret==OK) { - if (myModule.module>=getNModBoard()) { - ret=FAIL; - printf("Module number is too large %d\n",myModule.module); - } - if (myModule.module<0) - myModule.module=ALLMOD; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef MCB_FUNCS - retval=initModulebyNumber(myModule); -#endif - } - } - - if (differentClients==1 && ret==OK) - ret=FORCE_UPDATE; - - /* Maybe this is done inside the initialization funcs */ - //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - free(myChip); - free(myChan); - free(myDac); - free(myAdc); - - // setDynamicRange(dr); always 16 commented out - - - return ret; -} - - - - -int get_module(int file_des) { - - - int ret=OK; - - - int arg; - int imod; - int n; - - - - sls_detector_module myModule; - int *myChip=malloc(NCHIP*sizeof(int)); - int *myChan=malloc(NCHIP*NCHAN*sizeof(int)); - int *myDac=malloc(NDAC*sizeof(int));/**dhanya*/ - int *myAdc=malloc(NADC*sizeof(int));/**dhanya*/ - - - if (myDac) - myModule.dacs=myDac; - else { - sprintf(mess,"could not allocate dacs\n"); - ret=FAIL; - } - if (myAdc) - myModule.adcs=myAdc; - else { - sprintf(mess,"could not allocate adcs\n"); - ret=FAIL; - } - if (myChip) - myModule.chipregs=myChip; - else { - sprintf(mess,"could not allocate chips\n"); - ret=FAIL; - } - if (myChan) - myModule.chanregs=myChan; - else { - sprintf(mess,"could not allocate chans\n"); - ret=FAIL; - } - - myModule.ndac=NDAC; - myModule.nchip=NCHIP; - myModule.nchan=NCHAN*NCHIP; - myModule.nadc=NADC; - - - - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - imod=arg; - - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod= 0) { - ret=FAIL; - sprintf(mess, "Changing settings of module %d: wrote %d but read %d\n", imod, isett, retval); - printf("Warning: %s",mess); - } - - else { - ret = setDefaultDacs(); - if (ret == FAIL) { - strcpy(mess,"Could change settings, but could not set to default dacs\n"); - cprintf(RED, "Warning: %s", mess); - } - } - } -#endif - } - if (ret==OK && differentClients==1) - ret=FORCE_UPDATE; - - /* send answer */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } else - n += sendDataOnly(file_des,&retval,sizeof(retval)); - - - - return ret; - - -} - -int start_acquisition(int file_des) { - - int ret=OK; - int n; - - - sprintf(mess,"can't start acquisition\n"); - -#ifdef VERBOSE - printf("Starting acquisition\n"); -#endif - - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - ret=startStateMachine(); - } - if (ret==FAIL) - sprintf(mess,"Start acquisition failed\n"); - else if (differentClients) - ret=FORCE_UPDATE; - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - return ret; - -} - -int stop_acquisition(int file_des) { - - int ret=OK; - int n; - - sprintf(mess,"can't stop acquisition\n"); - - cprintf(BG_RED,"Client command received to stop acquisition\n"); - - - - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - ret=stopStateMachine(); - } - - if (ret==FAIL) - sprintf(mess,"Stop acquisition failed\n"); - else if (differentClients) - ret=FORCE_UPDATE; - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - return ret; - - -} - -int start_readout(int file_des) { - - - int ret=OK; - int n; - - - sprintf(mess,"can't start readout\n"); - -#ifdef VERBOSE - printf("Starting readout\n"); -#endif - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - ret=startReadOut(); - } - if (ret==FAIL) - sprintf(mess,"Start readout failed\n"); - else if (differentClients) - ret=FORCE_UPDATE; - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - return ret; - - - -} - -int get_run_status(int file_des) { - - int ret=OK; - int n; - - int retval; - enum runStatus s; - sprintf(mess,"getting run status\n"); - -#ifdef VERBOSE - printf("Getting status\n"); -#endif - - retval= runState(); - printf("STATUS=%08x\n",retval); - - - //stopped (external stop, also maybe fifo full) - if (runState() & STOPPED_BIT){ - printf("-----------------------------------STOPPED--------------------------------------x%0x\n",retval); - s=STOPPED; - - retval= runState(); - printf("reading again STATUS=%08x\n",retval); - if (runState() & STOPPED_BIT){ - printf("-----------------------------------ERROR--------------------------------------x%0x\n",retval); - s=ERROR; - } - } - - - - //error - else if(retval&SOME_FIFO_FULL_BIT){ - printf("-----------------------------------ERROR--------------------------------------x%0x\n",retval); - s=ERROR; - } - - - //runbusy=0 - // else if(!(retval&RUNMACHINE_BUSY_BIT)){ //commented by Anna 24.10.2012 - else if(!(retval&RUN_BUSY_BIT)){ // by Anna 24.10.2012 - - - - //and readbusy=1, its last frame read - if((retval&READMACHINE_BUSY_BIT) ){ // - - - printf("-----------------------------------READ MACHINE BUSY--------------------------\n"); - s=TRANSMITTING; - } else if (retval&ALL_FIFO_EMPTY_BIT) { - printf("-----------------------------------DATA IN FIFO--------------------------\n"); - s=TRANSMITTING; - - } - //and readbusy=0,idle - else if(!(retval&0xffff)){ - //if(!(retval&0x00000001)){ - printf("-----------------------------------IDLE--------------------------------------\n"); - s=IDLE; - } else { - printf("-----------------------------------Unknown status %08x--------------------------------------\n", retval); - s=ERROR; - ret=FAIL; - } - } - //if runbusy=1 - else { - if (retval&WAITING_FOR_TRIGGER_BIT){ - printf("-----------------------------------WAITING-----------------------------------\n"); - s=WAITING; - } - else{ - printf("-----------------------------------RUNNING-----------------------------------\n"); - s=RUNNING; - } - } - - - - - if (ret!=OK) { - printf("get status failed %04x\n",retval); - sprintf(mess, "get status failed %08x\n", retval); - - } else if (differentClients) - ret=FORCE_UPDATE; - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n += sendDataOnly(file_des,&s,sizeof(s)); - } - return ret; - - - -} - -int read_frame(int file_des) { - dataret = FAIL; - strcpy(mess,"wait for read frame failed\n"); - - if (differentClients==1 && lockStatus==1) { - dataret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED,"%s\n",mess); - sendDataOnly(file_des,&dataret,sizeof(dataret)); - sendDataOnly(file_des,mess,sizeof(mess)); - return dataret; - } - - -#ifdef VIRTUAL - dataret = FINISHED; - strcpy(mess,"acquisition successfully finished\n"); -#else - waitForAcquisitionFinish(); - - // set return value and message - if(getFrames()>-2) { - dataret = FAIL; - sprintf(mess,"no data and run stopped: %d frames left\n",(int)(getFrames()+2)); - cprintf(RED,"%s\n",mess); - } else { - dataret = FINISHED; - sprintf(mess,"acquisition successfully finished\n"); - cprintf(GREEN,"%s",mess); - - } -#endif - - if (differentClients) - dataret=FORCE_UPDATE; - - sendDataOnly(file_des,&dataret,sizeof(dataret)); - sendDataOnly(file_des,mess,sizeof(mess)); - return dataret; -} - - - - - - - - -int read_all(int file_des) { - -while(read_frame(file_des)==OK) { - -#ifdef VERBOSE - printf("frame read\n"); -#endif - ; - } -#ifdef VERBOSE - printf("Frames finished\n"); -#endif - return OK; - - -} - -int start_and_read_all(int file_des) { - //int dataret=OK; -#ifdef VERBOSE - printf("Starting and reading all frames\n"); -#endif - - if (differentClients==1 && lockStatus==1) { - dataret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - sendDataOnly(file_des,&dataret,sizeof(dataret)); - sendDataOnly(file_des,mess,sizeof(mess)); - return dataret; - - } - - startStateMachine(); - - /* ret=startStateMachine(); - if (ret!=OK) { - sprintf(mess,"could not start state machine\n"); - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); - - #ifdef VERBOSE - printf("could not start state machine\n"); -#endif -} else {*/ - read_all(file_des); -#ifdef VERBOSE - printf("Frames finished\n"); -#endif - //} - - - return OK; - - -} - -int set_timer(int file_des) { - enum timerIndex ind; - int64_t tns; - int n; - int64_t retval; - int ret=OK; - - - sprintf(mess,"can't set timer\n"); - - n = receiveDataOnly(file_des,&ind,sizeof(ind)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,&tns,sizeof(tns)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret!=OK) { - printf(mess); - } - -#ifdef VERBOSE - printf("setting timer %d to %lld ns\n",ind,tns); -#endif - if (ret==OK) { - - if (differentClients==1 && lockStatus==1 && tns!=-1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - switch(ind) { - case FRAME_NUMBER: - retval=setFrames(tns); - break; - case ACQUISITION_TIME: - retval=setExposureTime(tns); - break; - case FRAME_PERIOD: - retval=setPeriod(tns); - break; - case DELAY_AFTER_TRIGGER: - retval=setDelay(tns); - break; - case GATES_NUMBER: - retval=setGates(tns); - break; - case PROBES_NUMBER: -#ifdef PROPIXD - sprintf(mess,"can't set/get number of probes for propix\n"); -#else - sprintf(mess,"can't set/get number of probes for gotthard\n"); -#endif - - ret=FAIL; - break; - case CYCLES_NUMBER: - retval=setTrains(tns); - break; - default: - ret=FAIL; - sprintf(mess,"timer index unknown %d\n",ind); - break; - } - } - } - if (ret!=OK) { - printf(mess); - if (differentClients) - ret=FORCE_UPDATE; - } - - if (ret!=OK) { - printf(mess); - printf("set timer failed\n"); - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { -#ifdef VERBOSE - printf("returning ok %d\n",(int)(sizeof(retval))); -#endif - - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - - return ret; - -} - - - - - - - - -int get_time_left(int file_des) { - - enum timerIndex ind; - int n; - int64_t retval; - int ret=OK; - - sprintf(mess,"can't get timer\n"); - n = receiveDataOnly(file_des,&ind,sizeof(ind)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - -#ifdef VERBOSE - - printf("getting time left on timer %d \n",ind); -#endif - - if (ret==OK) { - switch(ind) { - case FRAME_NUMBER: - retval=getFrames(); - break; - case ACQUISITION_TIME: - retval=getExposureTime(); - break; - case FRAME_PERIOD: - retval=getPeriod(); - break; - case DELAY_AFTER_TRIGGER: - retval=getDelay(); - break; - case GATES_NUMBER: - retval=getGates(); - break; - case PROBES_NUMBER: - retval=getProbes(); - break; - case CYCLES_NUMBER: - retval=getTrains(); - break; - case PROGRESS: - retval=getProgress(); - break; - case ACTUAL_TIME: - retval=getActualTime(); - break; - case MEASUREMENT_TIME: - retval=getMeasurementTime(); - break; - default: - ret=FAIL; - sprintf(mess,"timer index unknown %d\n",ind); - break; - } - } - - - if (ret!=OK) { - printf("get time left failed\n"); - } else if (differentClients) - ret=FORCE_UPDATE; - -#ifdef VERBOSE - - printf("time left on timer %d is %lld\n",ind, retval); -#endif - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=OK) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } -#ifdef VERBOSE - - printf("data sent\n"); -#endif - - return ret; - - -} - -int set_dynamic_range(int file_des) { - - - - int dr; - int n; - int retval; - int ret=OK; - - - sprintf(mess,"can't set dynamic range\n"); - - - n = receiveDataOnly(file_des,&dr,sizeof(dr)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - - if (differentClients==1 && lockStatus==1 && dr>=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=setDynamicRange(dr); - } - - //if (dr>=0 && retval!=dr) ret=FAIL; - if (ret!=OK) { - sprintf(mess,"set dynamic range failed\n"); - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - -int set_roi(int file_des) { - - int i; - int ret=OK; - int nroi=-1; - int n=0; - int retvalsize=0; - ROI arg[MAX_ROIS]; - ROI* retval=0; - - strcpy(mess,"Could not set/get roi\n"); - - - n = receiveDataOnly(file_des,&nroi,sizeof(nroi)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - -#ifdef PROPIXD - sprintf(mess,"can't set roi for propix\n"); - ret = FAIL; -#endif - if(ret != FAIL){ - if(nroi!=-1){ - n = receiveDataOnly(file_des,arg,nroi*sizeof(ROI)); - if (n != (nroi*sizeof(ROI))) { - sprintf(mess,"Received wrong number of bytes for ROI\n"); - ret=FAIL; - } - //#ifdef VERBOSE - printf("\n\nSetting ROI: nroi=%d\n",nroi); - for( i=0;i=0) { - if (lockStatus==0 || strcmp(lastClientIP,thisClientIP)==0 || strcmp(lastClientIP,"none")==0) - lockStatus=lock; - else { - ret=FAIL; - sprintf(mess,"Server already locked by %s\n", lastClientIP); - } - } - if (differentClients && ret==OK) - ret=FORCE_UPDATE; - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else - n = sendDataOnly(file_des,&lockStatus,sizeof(lockStatus)); - - return ret; - -} - -int set_port(int file_des) { - int n; - int ret=OK; - int sd=-1; - - enum portType p_type; /** data? control? stop? Unused! */ - int p_number; /** new port number */ - - n = receiveDataOnly(file_des,&p_type,sizeof(p_type)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (ptype)\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,&p_number,sizeof(p_number)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (pnum)\n"); - ret=FAIL; - } - if (differentClients==1 && lockStatus==1 ) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - if (p_number<1024) { - sprintf(mess,"Too low port number %d\n", p_number); - printf("\n"); - ret=FAIL; - } - - printf("set port %d to %d\n",p_type, p_number); - - sd=bindSocket(p_number); - } - if (sd>=0) { - ret=OK; - if (differentClients ) - ret=FORCE_UPDATE; - } else { - ret=FAIL; - sprintf(mess,"Could not bind port %d\n", p_number); - printf("Could not bind port %d\n", p_number); - if (sd==-10) { - sprintf(mess,"Port %d already set\n", p_number); - printf("Port %d already set\n", p_number); - - } - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&p_number,sizeof(p_number)); - closeConnection(file_des); - exitServer(sockfd); - sockfd=sd; - - } - - return ret; - -} - -int get_last_client_ip(int file_des) { - int ret=OK; - int n; - if (differentClients ) - ret=FORCE_UPDATE; - n = sendDataOnly(file_des,&ret,sizeof(ret)); - n = sendDataOnly(file_des,lastClientIP,sizeof(lastClientIP)); - - return ret; - -} - - -int send_update(int file_des) { - - int ret=OK; - enum detectorSettings t; - int n;//int thr, n; - //int it; - int64_t retval, tns=-1; - n = sendDataOnly(file_des,lastClientIP,sizeof(lastClientIP)); - n = sendDataOnly(file_des,&nModX,sizeof(nModX)); - n = sendDataOnly(file_des,&nModY,sizeof(nModY)); - n = sendDataOnly(file_des,&dynamicRange,sizeof(dynamicRange)); - n = sendDataOnly(file_des,&dataBytes,sizeof(dataBytes)); - t=setSettings(GET_SETTINGS,-1); - n = sendDataOnly(file_des,&t,sizeof(t)); -/* thr=getThresholdEnergy(); - n = sendDataOnly(file_des,&thr,sizeof(thr));*/ - retval=setFrames(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setExposureTime(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setPeriod(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setDelay(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setGates(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); -/* retval=setProbes(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t));*/ - retval=setTrains(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - - if (lockStatus==0) { - strcpy(lastClientIP,thisClientIP); - } - - return ret; - - -} -int update_client(int file_des) { - - int ret=OK; - - sendDataOnly(file_des,&ret,sizeof(ret)); - return send_update(file_des); - - - -} - - -int configure_mac(int file_des) { - - int ret=OK; - char arg[6][50]; - int n; - - int imod=0;//should be in future sent from client as -1, arg[2] - int ipad; - long long int imacadd; - long long int idetectormacadd; - int udpport; - int detipad; - int retval=-100; - - sprintf(mess,"Can't configure MAC\n"); - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - sscanf(arg[0], "%x", &ipad); - sscanf(arg[1], "%llx", &imacadd); - sscanf(arg[2], "%x", &udpport); - sscanf(arg[3], "%llx", &idetectormacadd); - sscanf(arg[4], "%x", &detipad); - //arg[5] is udpport2 for eiger -//#ifdef VERBOSE - int i; - printf("\ndigital_test_bit in server %d\t",digitalTestBit); - printf("\nipadd %x\t",ipad); - printf("destination ip is %d.%d.%d.%d = 0x%x \n",(ipad>>24)&0xff,(ipad>>16)&0xff,(ipad>>8)&0xff,(ipad)&0xff,ipad); - printf("macad:%llx\n",imacadd); - for (i=0;i<6;i++) - printf("mac adress %d is 0x%x \n",6-i,(unsigned int)(((imacadd>>(8*i))&0xFF))); - printf("udp port:0x%x\n",udpport); - printf("detector macad:%llx\n",idetectormacadd); - for (i=0;i<6;i++) - printf("detector mac adress %d is 0x%x \n",6-i,(unsigned int)(((idetectormacadd>>(8*i))&0xFF))); - printf("detipad %x\n",detipad); - printf("destination ip is %d.%d.%d.%d = 0x%x \n",(detipad>>24)&0xff,(detipad>>16)&0xff,(detipad>>8)&0xff,(detipad)&0xff,detipad); - printf("\n"); -//#endif - - - - if (imod>=getNModBoard()) - ret=FAIL; - if (imod<0) - imod=ALLMOD; - - //#ifdef VERBOSE - printf("Configuring MAC of module %d at port %x\n", imod, udpport); - //#endif -#ifdef MCB_FUNCS - if (ret==OK){ - if(runBusy()){ - ret=stopStateMachine(); - if(ret==FAIL) - strcpy(mess,"could not stop detector acquisition to configure mac"); - } - - if(ret==OK) - configureMAC(ipad,imacadd,idetectormacadd,detipad,digitalTestBit,udpport); - retval=getAdcConfigured(); - } -#endif - if (ret==FAIL) - printf("configuring MAC of mod %d failed\n", imod); - else - printf("Configuremac successful of mod %d and adc %d\n",imod,retval); - - if (differentClients) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval,sizeof(retval)); - /*return ok/fail*/ - return ret; - -} - - - -int load_image(int file_des) { - int retval; - int ret=OK; - int n; - enum imageType index; - short int ImageVals[NCHAN*NCHIP]; - - sprintf(mess,"Loading image failed\n"); - - n = receiveDataOnly(file_des,&index,sizeof(index)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,ImageVals,dataBytes); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - -#ifdef PROPIXD - sprintf(mess,"can't load image for propix\n"); - ret = FAIL; -#endif - - switch (index) { - case DARK_IMAGE : -#ifdef VERBOSE - printf("Loading Dark image\n"); -#endif - break; - case GAIN_IMAGE : -#ifdef VERBOSE - printf("Loading Gain image\n"); -#endif - break; - default: - printf("Unknown index %d\n",index); - sprintf(mess,"Unknown index %d\n",index); - ret=FAIL; - break; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else{ - retval=loadImage(index,ImageVals); - if (retval==-1) - ret = FAIL; - } - } - - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; -} - - - -int set_master(int file_des) { - - enum masterFlags retval=GET_MASTER; - enum masterFlags arg; - int n; - int ret=OK; - // int regret=OK; - - - sprintf(mess,"can't set master flags\n"); - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - -#ifdef VERBOSE - printf("setting master flags to %d\n",arg); -#endif - - if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=setMaster(arg); - - } - if (retval==GET_MASTER) { - ret=FAIL; - } - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - - - - - - -int set_synchronization(int file_des) { - - enum synchronizationMode retval=GET_MASTER; - enum synchronizationMode arg; - int n; - int ret=OK; - //int regret=OK; - - - sprintf(mess,"can't set synchronization mode\n"); - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } -#ifdef VERBOSE - printf("setting master flags to %d\n",arg); -#endif - - if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - //ret=setStoreInRAM(0); - // initChipWithProbes(0,0,0, ALLMOD); - retval=setSynchronization(arg); - } - if (retval==GET_SYNCHRONIZATION_MODE) { - ret=FAIL; - } - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - - - - - - -int read_counter_block(int file_des) { - - int ret=OK; - int n; - int startACQ; - //char *retval=NULL; - short int CounterVals[NCHAN*NCHIP]; - - sprintf(mess,"Read counter block failed\n"); - - n = receiveDataOnly(file_des,&startACQ,sizeof(startACQ)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - -#ifdef PROPIXD - sprintf(mess,"can't read counter block for propix\n"); - ret = FAIL; -#endif - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else{ - ret=readCounterBlock(startACQ,CounterVals); -#ifdef VERBOSE - int i; - for(i=0;i<6;i++) - printf("%d:%d\t",i,CounterVals[i]); -#endif - } - } - - if(ret!=FAIL){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,CounterVals,dataBytes);//1280*2 - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; -} - - - - - -int reset_counter_block(int file_des) { - - int ret=OK; - int n; - int startACQ; - - sprintf(mess,"Reset counter block failed\n"); - - n = receiveDataOnly(file_des,&startACQ,sizeof(startACQ)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else - ret=resetCounterBlock(startACQ); - } - - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - - /*return ok/fail*/ - return ret; -} - - - - - - -int start_receiver(int file_des) { - int ret=OK; - int n=0; - strcpy(mess,"Could not start receiver\n"); - - /* execute action if the arguments correctly arrived*/ -#ifdef MCB_FUNCS - if (lockStatus==1 && differentClients==1){//necessary??? - sprintf(mess,"Detector locked by %s\n", lastClientIP); - ret=FAIL; - } - else - ret = startReceiver(1); - -#endif - - - if(ret==OK && differentClients){ - printf("Force update\n"); - ret=FORCE_UPDATE; - } - - /* send answer */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if(ret==FAIL) - n = sendDataOnly(file_des,mess,sizeof(mess)); - /*return ok/fail*/ - return ret; -} - - - - - - -int stop_receiver(int file_des) { - int ret=OK; - int n=0; - - strcpy(mess,"Could not stop receiver\n"); - - /* execute action if the arguments correctly arrived*/ -#ifdef MCB_FUNCS - if (lockStatus==1 && differentClients==1){//necessary??? - sprintf(mess,"Detector locked by %s\n", lastClientIP); - ret=FAIL; - } - else - ret=startReceiver(0); - -#endif - - - if(ret==OK && differentClients){ - printf("Force update\n"); - ret=FORCE_UPDATE; - } - - /* send answer */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if(ret==FAIL) - n = sendDataOnly(file_des,mess,sizeof(mess)); - /*return ok/fail*/ - return ret; -} - - - - - -int calibrate_pedestal(int file_des){ - - int ret=OK; - int retval=-1; - int n; - int frames; - - sprintf(mess,"Could not calibrate pedestal\n"); - - n = receiveDataOnly(file_des,&frames,sizeof(frames)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else - ret=calibratePedestal(frames); - } - - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval,sizeof(retval)); - - /*return ok/fail*/ - return ret; -} - - - - -int write_adc_register(int file_des) { - int ret=OK; - int n=0; - int retval=-1; - sprintf(mess,"write to adc register failed\n"); - - // receive arguments - int arg[2]={-1,-1}; - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - int addr=arg[0]; - int val=arg[1]; - - // execute action - if (ret == OK) { - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef VERBOSE - printf("writing to register 0x%x data 0x%x\n", addr, val); -#endif - setAdc(addr,val); -#ifdef VERBOSE - printf("Data set to 0x%x\n", retval); -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - } - } - // send ok / fail - n = sendDataOnly(file_des,&ret,sizeof(ret)); - // send return argument - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else - n = sendDataOnly(file_des,&retval,sizeof(retval)); - - // return ok / fail - return ret; -} - - - - -int check_version(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"check version failed\n"); - - - - // receive arguments - int64_t arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT64); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - - // execute action - if (ret == OK) { -#ifdef VERBOSE - printf("Checking versioning compatibility with value %d\n",arg); -#endif - int64_t client_requiredVersion = arg; - int64_t det_apiVersion = APIGOTTHARD; - int64_t det_version = (GITDATE & 0xFFFFFF); - - // old client - if (det_apiVersion > client_requiredVersion) { - ret = FAIL; - sprintf(mess,"Client's detector SW API version: (0x%llx). " - "Detector's SW API Version: (0x%llx). " - "Incompatible, update client!\n", - client_requiredVersion, det_apiVersion); - cprintf(RED, "Warning: %s", mess); - } - - // old software - else if (client_requiredVersion > det_version) { - ret = FAIL; - sprintf(mess,"Detector SW Version: (0x%llx). " - "Client's detector SW API Version: (0x%llx). " - "Incompatible, update detector software!\n", - det_version, client_requiredVersion); - cprintf(RED, "Warning: %s", mess); - } - } - - - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - diff --git a/slsDetectorSoftware/gotthardDetectorServer/server_funcs.h b/slsDetectorSoftware/gotthardDetectorServer/server_funcs.h deleted file mode 100755 index 832ab3602..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/server_funcs.h +++ /dev/null @@ -1,99 +0,0 @@ -#ifndef SERVER_FUNCS_H -#define SERVER_FUNCS_H - - -#include "sls_detector_defs.h" - - -#include -/* -#include -#include -#include -*/ -#include "communication_funcs.h" - - - - -#define GOODBYE -200 - -int sockfd; - -int function_table(); - -int decode_function(int); -int init_detector(int); - -int M_nofunc(int); -int exit_server(int); - - - - -// General purpose functions -int get_detector_type(int); -int set_number_of_modules(int); -int get_max_number_of_modules(int); - - -int exec_command(int); -int set_external_signal_flag(int); -int set_external_communication_mode(int); -int get_id(int); -int digital_test(int); -int write_register(int); -int read_register(int); -int set_dac(int); -int get_adc(int); -int set_channel(int); -int set_chip(int); -int set_module(int); -int get_channel(int); -int get_chip(int); -int get_module(int); - -int get_threshold_energy(int); -int set_threshold_energy(int); -int set_settings(int); -int start_acquisition(int); -int stop_acquisition(int); -int start_readout(int); -int get_run_status(int); -int read_frame(int); -int read_all(int); -int start_and_read_all(int); -int set_timer(int); -int get_time_left(int); -int set_dynamic_range(int); -int set_roi(int); -int get_roi(int); -int set_speed(int); -void configureADC(); -int set_readout_flags(int); -int execute_trimming(int); -int lock_server(int); -int set_port(int); -int get_last_client_ip(int); -int set_master(int); -int set_synchronization(int); - -int update_client(int); -int send_update(int); -int configure_mac(int); - -int load_image(int); -int read_counter_block(int); -int reset_counter_block(int); - -int start_receiver(int); -int stop_receiver(int); - - -int calibrate_pedestal(int); - -int set_roi(int); - -int write_adc_register(int); -int check_version(int); -#endif diff --git a/slsDetectorSoftware/gotthardDetectorServer/sls_detector_defs.h b/slsDetectorSoftware/gotthardDetectorServer/sls_detector_defs.h deleted file mode 120000 index c5062e03f..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/sls_detector_defs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/gotthardDetectorServer/sls_detector_funcs.h b/slsDetectorSoftware/gotthardDetectorServer/sls_detector_funcs.h deleted file mode 120000 index 844b67129..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/sls_detector_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/gotthardDetectorServer/sls_receiver_defs.h b/slsDetectorSoftware/gotthardDetectorServer/sls_receiver_defs.h deleted file mode 120000 index 1de31caf5..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/sls_receiver_defs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/gotthardDetectorServer/sls_receiver_funcs.h b/slsDetectorSoftware/gotthardDetectorServer/sls_receiver_funcs.h deleted file mode 120000 index c2ea4ded9..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/sls_receiver_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/gotthardDetectorServer/stop_server.c b/slsDetectorSoftware/gotthardDetectorServer/stop_server.c deleted file mode 100755 index e3c8ff7e1..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/stop_server.c +++ /dev/null @@ -1,46 +0,0 @@ -/* A simple server in the internet domain using TCP - The port number is passed as an argument */ - - -#include "sls_detector_defs.h" - - -#include "communication_funcs.h" -#include "firmware_funcs.h" - - -int sockfd; - -int main(int argc, char *argv[]) -{ - int portno; - int retval=0; - - portno = DEFAULT_PORTNO; - - - bindSocket(portno); - if (getServerError()) - return -1; - - - - /* waits for connection */ - while(retval!=GOODBYE) { -#ifdef VERBOSE - printf("\n"); -#endif -#ifdef VERY_VERBOSE - printf("Stop server: waiting for client call\n"); -#endif - acceptConnection(); - retval=stopStateMachine(); - closeConnection(); - } - - exitServer(); - printf("Goodbye!\n"); - - return 0; -} - diff --git a/slsDetectorSoftware/gotthardDetectorServer/updateAPIVersion.sh b/slsDetectorSoftware/gotthardDetectorServer/updateAPIVersion.sh deleted file mode 100755 index 2d5d8d04d..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/updateAPIVersion.sh +++ /dev/null @@ -1,7 +0,0 @@ -SRCFILE=gitInfoGotthard.h -DSTFILE=versionAPI.h - -SRCPATTERN=GITDATE -DSTPATTERN=APIGOTTHARD - -awk -v a="$SRCFILE" -v b="$DSTFILE" -v c="$SRCPATTERN" -v d="$DSTPATTERN" 'FNR==NR&&$2==c{x=$3} NR!=FNR{if($2==d){$3="0x"substr(x,5)}print > b}' $SRCFILE $DSTFILE \ No newline at end of file diff --git a/slsDetectorSoftware/gotthardDetectorServer/updateGitVersion.sh b/slsDetectorSoftware/gotthardDetectorServer/updateGitVersion.sh deleted file mode 100755 index 19d9acbcb..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/updateGitVersion.sh +++ /dev/null @@ -1,30 +0,0 @@ -SERVER=gotthardDetectorServer -MAINDIR=slsDetectorsPackage -SPECDIR=slsDetectorSoftware/$SERVER -TMPFILE=gitInfoGotthardTmp.h -INCLFILE=gitInfoGotthard.h - -#evaluate the variables -EVALFILE=../../evalVersionVariables.sh -source $EVALFILE - - -#get modified date -#RDATE1='git log --pretty=format:"%ci" -1' -RDATE1="find . -type f -exec stat --format '%Y :%y %n' '{}' \; | sort -nr | cut -d: -f2- | egrep -v 'gitInfo|.git|updateGitVersion|.o' | head -n 1" -RDATE=`eval $RDATE1` -NEWDATE=$(sed "s/-//g" <<< $RDATE | awk '{print $1;}') -NEWDATE=${NEWDATE/#/0x} - - -#get old date from INCLFILE -OLDDATE=$(more $INCLFILE | grep '#define GITDATE' | awk '{print $3}') - - -#update INCLFILE if changes -if [ "$OLDDATE" != "$NEWDATE" ]; then - echo Path: ${MAINDIR}/${SPECDIR} $'\n'URL: ${GITREPO} $'\n'Repository Root: ${GITREPO} $'\n'Repsitory UUID: ${REPUID} $'\n'Revision: ${FOLDERREV} $'\n'Branch: ${BRANCH} $'\n'Last Changed Author: ${AUTH1}_${AUTH2} $'\n'Last Changed Rev: ${REV} $'\n'Last Changed Date: ${RDATE} > gitInfo.txt - cd ../../ - ./genVersionHeader.sh $SPECDIR/gitInfo.txt $SPECDIR/$TMPFILE $SPECDIR/$INCLFILE - cd $WD -fi \ No newline at end of file diff --git a/slsDetectorSoftware/gotthardDetectorServer/versionAPI.h b/slsDetectorSoftware/gotthardDetectorServer/versionAPI.h deleted file mode 120000 index d3bf8d6cf..000000000 --- a/slsDetectorSoftware/gotthardDetectorServer/versionAPI.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/versionAPI.h \ No newline at end of file diff --git a/slsDetectorSoftware/include/SharedMemory.h b/slsDetectorSoftware/include/SharedMemory.h new file mode 100755 index 000000000..8a6bb92b5 --- /dev/null +++ b/slsDetectorSoftware/include/SharedMemory.h @@ -0,0 +1,304 @@ +#pragma once +/************************************************ + * @file SharedMemory.h + * @short functions basic implemenation of + * shared memory + ***********************************************/ +/** + *@short functions basic implemenation of shared memory + */ + +#include "ansi.h" +#include "logger.h" +#include "sls_detector_exceptions.h" + +#include "stdlib.h" +#include // errno +#include // strerror +#include // O_CREAT, O_TRUNC.. +#include +#include +#include // printf +#include // shared memory +#include // fstat +#include + +#define SHM_MULTI_PREFIX "/slsDetectorPackage_multi_" +#define SHM_SLS_PREFIX "_sls_" +#define SHM_ENV_NAME "SLSDETNAME" + +#include +#include + +namespace sls { + +template +class SharedMemory { + + public: + /** + * Constructor + * creates the single/multi detector shared memory name + * @param multiId multi detector id + * @param slsId sls detector id, -1 if a multi detector shared memory + */ + SharedMemory(int multiId, int slsId) { + name = ConstructSharedMemoryName(multiId, slsId); + } + + /** + * Delete the copy constructor and copy assignment since we don't want two + * objects managing the same resource + */ + SharedMemory(const SharedMemory &) = delete; + SharedMemory &operator=(const SharedMemory &other) = delete; + + //Move constructor + SharedMemory(SharedMemory &&other) : name(other.name), + fd(other.fd), + shmSize(other.shmSize), + shared_struct(other.shared_struct) { + + other.fd = -1; + other.shared_struct = nullptr; + other.shmSize = 0; + } + + //Move assignment + SharedMemory &operator=(SharedMemory &&other) { + name = other.name; + if (fd) { + close(fd); + } + fd = other.fd; + other.fd = -1; + + if (shared_struct != nullptr) { + UnmapSharedMemory(); + } + shared_struct = other.shared_struct; + other.shared_struct = nullptr; + + shmSize = other.shmSize; + other.shmSize = 0; + return *this; + } + + ~SharedMemory() { + if (fd >= 0) + close(fd); + + if (shared_struct) { + UnmapSharedMemory(); + } + } + + /** + * Verify if it exists + * @param name of shared memory + * @return true if exists, else false + */ + bool IsExisting() { + bool ret = true; + int tempfd = shm_open(name.c_str(), O_RDWR, 0); + if ((tempfd < 0) && (errno == ENOENT)) { + ret = false; + } + close(tempfd); + return ret; + } + + /** + * Get shared memory name + */ + std::string GetName() const { + return name; + } + + size_t size() const { + return shmSize; + } + + /** + * Create Shared memory and call MapSharedMemory to map it to an address + * throws a SharedMemoryError exception on failure to create, ftruncate or map + * @param sz of shared memory + */ + void CreateSharedMemory() { + fd = shm_open(name.c_str(), O_CREAT | O_TRUNC | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); + if (fd < 0) { + std::string msg = "Create shared memory " + name + " failed: " + strerror(errno); + FILE_LOG(logERROR) << msg; + throw SharedMemoryError(msg); + } + + if (ftruncate(fd, sizeof(T)) < 0) { + std::string msg = "Create shared memory " + name + " failed at ftruncate: " + strerror(errno); + FILE_LOG(logERROR) << msg; + close(fd); + RemoveSharedMemory(); + throw SharedMemoryError(msg); + } + + shared_struct = MapSharedMemory(); + FILE_LOG(logINFO) << "Shared memory created " << name; + } + + /** + * Open existing Shared memory and call MapSharedMemory to map it to an address + * throws a SharedMemoryError exception on failure to open or map + * @param sz of shared memory + */ + void OpenSharedMemory() { + fd = shm_open(name.c_str(), O_RDWR, 0); + if (fd < 0) { + std::string msg = "Open existing shared memory " + name + " failed: " + strerror(errno); + FILE_LOG(logERROR) << msg; + throw SharedMemoryError(msg); + } + + shared_struct = MapSharedMemory(); + } + + /** + * Unmap shared memory from an address + * throws a SharedMemoryError exception on failure + */ + void UnmapSharedMemory() { + if (shared_struct != nullptr) { + if (munmap(shared_struct, shmSize) < 0) { + std::string msg = "Unmapping shared memory " + name + " failed: " + strerror(errno); + FILE_LOG(logERROR) << msg; + close(fd); + throw SharedMemoryError(msg); + } + shared_struct = nullptr; + } + } + + /** + * Remove existing Shared memory + */ + void RemoveSharedMemory() { + UnmapSharedMemory(); + if (shm_unlink(name.c_str()) < 0) { + // silent exit if shm did not exist anyway + if (errno == ENOENT) + return; + std::string msg = "Free Shared Memory " + name + " Failed: " + strerror(errno); + FILE_LOG(logERROR) << msg; + throw SharedMemoryError(msg); + } + FILE_LOG(logINFO) << "Shared memory deleted " << name; + } + + /** + * Maximum length of name as from man pages + */ + static const int NAME_MAX_LENGTH = 255; + + /** + *Using the call operator to access the pointer + */ + T *operator()() { + return shared_struct; + } + + /** + *Using the call operator to access the pointer, const overload + */ + const T *operator()() const { + return shared_struct; + } + + private: + /** + * Create Shared memory name + * throws exception if name created is longer than required 255(manpages) + * @param multiId multi detector id + * @param slsId sls detector id, -1 if a multi detector shared memory + * @returns shared memory name + */ + std::string ConstructSharedMemoryName(int multiId, int slsId) { + + // using environment path + std::string sEnvPath = ""; + char *envpath = getenv(SHM_ENV_NAME); + if (envpath != nullptr) { + sEnvPath.assign(envpath); + sEnvPath.insert(0, "_"); + } + + std::stringstream ss; + if (slsId < 0) + ss << SHM_MULTI_PREFIX << multiId << sEnvPath; + else + ss << SHM_MULTI_PREFIX << multiId << SHM_SLS_PREFIX << slsId << sEnvPath; + + std::string temp = ss.str(); + if (temp.length() > NAME_MAX_LENGTH) { + std::string msg = "Shared memory initialization failed. " + temp + " has " + std::to_string(temp.length()) + " characters. \n" + "Maximum is " + std::to_string(NAME_MAX_LENGTH) + ". Change the environment variable " + SHM_ENV_NAME; + FILE_LOG(logERROR) << msg; + throw SharedMemoryError(msg); + } + return temp; + } + + /** + * Map shared memory to an address + * throws a SharedMemoryException exception on failure + * @param sz of shared memory + */ + + T *MapSharedMemory() { + void *addr = mmap(nullptr, sizeof(T), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (addr == MAP_FAILED) { + std::string msg = "Mapping shared memory " + name + " failed: " + strerror(errno); + FILE_LOG(logERROR) << msg; + close(fd); + throw SharedMemoryError(msg); + } + shmSize = sizeof(T); + close(fd); + return (T *)addr; + } + + /** + * Verify if existing shared memory size matches expected size + * @param expectedSize expected size of shared memory, replaced with smaller size if size does not match + * @return 0 for success, 1 for fail + */ + int VerifySizeMatch(size_t expectedSize) { + struct stat sb; + // could not fstat + if (fstat(fd, &sb) < 0) { + std::string msg = "Could not verify existing shared memory " + name + " size match " + "(could not fstat): " + strerror(errno); + FILE_LOG(logERROR) << msg; + close(fd); + throw SharedMemoryError(msg); + } + + //size does not match + auto sz = static_cast(sb.st_size); + if (sz != expectedSize) { + std::string msg = "Existing shared memory " + name + " size does not match" + "Expected " + std::to_string(expectedSize) + ", found " + std::to_string(sz); + FILE_LOG(logERROR) << msg; + throw SharedMemoryError(msg); + return 1; + } + return 0; + } + + /** Shared memory name */ + std::string name; + + /** File descriptor */ + int fd{-1}; + + /** shm size */ + size_t shmSize{0}; + + T *shared_struct{nullptr}; +}; + +} // namespace sls diff --git a/slsDetectorSoftware/include/detectorData.h b/slsDetectorSoftware/include/detectorData.h deleted file mode 120000 index 44205ed04..000000000 --- a/slsDetectorSoftware/include/detectorData.h +++ /dev/null @@ -1 +0,0 @@ -../slsDetectorAnalysis/detectorData.h \ No newline at end of file diff --git a/slsDetectorSoftware/include/detectorData.h b/slsDetectorSoftware/include/detectorData.h new file mode 100755 index 000000000..4b91aeba1 --- /dev/null +++ b/slsDetectorSoftware/include/detectorData.h @@ -0,0 +1,49 @@ + +#include +#include +#ifndef DETECTOR_DATA_H +#define DETECTOR_DATA_H +/** + @short data structure to hold the detector data after postprocessing (e.g. to plot, store in a root tree etc.) + */ +class detectorData { + public: + /** @short The constructor + \param f_ind file index + \param fname file name to which the data are saved + \param np number of points in x coordinate defaults to the number of detector channels (1D detector) or dimension in x (2D detector) + \param ny dimension in y (2D detector) + \param cval pointer to data in char* format + \param dbytes number of bytes of image pointed to by cval pointer + \param dr dynamic range or bits per pixel + \param file_ind file index + */ + detectorData(double f_ind=-1, + const char *fname="", int np=-1, int ny=1, char *cval=NULL, int dbytes=0, int dr=0, + long long int file_ind=-1) : + progressIndex(f_ind), + npoints(np), npy(ny), cvalues(cval), databytes(dbytes), + dynamicRange(dr), dgainvalues(NULL), fileIndex(file_ind) { + strcpy(fileName,fname); + }; + + /** + @short The destructor + deletes also the arrays pointing to data/errors/angles if not NULL + cvalues are deleted by caller + */ + ~detectorData() {if(dgainvalues) delete [] dgainvalues;}; + //private: + double progressIndex;/**< @short file index */ + char fileName[1000];/**< @short file name */ + int npoints;/**< @short number of points */ + int npy;/**< @short dimensions in y coordinate*/ + char* cvalues; /**< @short pointer to the data as char arary */ + int databytes; /**< @short number of bytes of data. Used with cvalues */ + int dynamicRange; /**< @short dynamic range */ + double* dgainvalues; /**< @short pointer to gain data as double array for Jungfrau only in show gain mode */ + long long int fileIndex; /**< @short file index */ +}; + + +#endif diff --git a/slsDetectorSoftware/include/multiSlsDetector.h b/slsDetectorSoftware/include/multiSlsDetector.h new file mode 100755 index 000000000..57af13111 --- /dev/null +++ b/slsDetectorSoftware/include/multiSlsDetector.h @@ -0,0 +1,2139 @@ +#pragma once + +#include "SharedMemory.h" +#include "error_defs.h" +#include "logger.h" +#include "sls_detector_defs.h" + + +class slsDetector; +class ZmqSocket; +class detectorData; + +#include +#include +#include +#include +#include +#include + +#define MULTI_SHMVERSION 0x181002 +#define SHORT_STRING_LENGTH 50 +#define DATE_LENGTH 30 + +/** + * @short structure allocated in shared memory to store detector settings + * for IPC and cache + */ +struct sharedMultiSlsDetector { + + /* FIXED PATTERN FOR STATIC FUNCTIONS. DO NOT CHANGE, ONLY APPEND + * ------*/ + + /** shared memory version */ + int shmversion; + + /** last process id accessing the shared memory */ + pid_t lastPID; + + /** last user name accessing the shared memory */ + char lastUser[SHORT_STRING_LENGTH]; + + /** last time stamp when accessing the shared memory */ + char lastDate[SHORT_STRING_LENGTH]; + + /** number of sls detectors in shared memory */ + int numberOfDetectors; + + /** END OF FIXED PATTERN + * -----------------------------------------------*/ + + /** Number of detectors operated at once */ + int numberOfDetector[2]; + + /** online flag - is set if the detector is connected, unset if socket + * connection is not possible */ + int onlineFlag; + + /** stopped flag - is set if an acquisition error occurs or the detector + * is stopped manually. Is reset to 0 at the start of the acquisition */ + int stoppedFlag; + + /** size of the data that are transfered from all detectors */ + int dataBytes; + + /** data bytes including gap pixels transferred from all detectors */ + int dataBytesInclGapPixels; + + /** total number of channels for all detectors */ + int numberOfChannels; + + /** total number of channels for all detectors in one dimension*/ + int numberOfChannel[2]; + + /** total number of channels including gap pixels in one dimension */ + int numberOfChannelInclGapPixels[2]; + + /** total number of channels for all detectors */ + int maxNumberOfChannels; + + /** max number of channels for all detectors in one dimension*/ + int maxNumberOfChannel[2]; + + /** max number of channels including gap pixels for all detectors in + * one dimension*/ + int maxNumberOfChannelInclGapPixels[2]; + + /** max number of channels allowed for the complete set of detectors in + * one dimension */ + int maxNumberOfChannelsPerDetector[2]; + + /** timer values */ + int64_t timerValue[slsDetectorDefs::timerIndex::MAX_TIMERS]; + + /** flag for acquiring */ + bool acquiringFlag; + + /** receiver online flag - is set if the receiver is connected, + * unset if socket connection is not possible */ + int receiverOnlineFlag; + + /** data streaming (up stream) enable in receiver */ + bool receiver_upstream; +}; + +class multiSlsDetector : public virtual slsDetectorDefs { + public: + /** + * Constructor + * @param id multi detector id + * @param verify true to verify if shared memory version matches existing + * one + * @param update true to update last user pid, date etc + */ + explicit multiSlsDetector(int multi_id = 0, + bool verify = true, + bool update = true); + + /** + * Destructor + */ + virtual ~multiSlsDetector(); + + /** + * Creates/open shared memory, initializes detector structure and members + * Called by constructor/ set hostname / read config file + * @param verify true to verify if shared memory version matches existing + * one + * @param update true to update last user pid, date etc + */ + void setupMultiDetector(bool verify = true, + bool update = true); + + /** + * Loop through the detectors serially and return the result as a vector + */ + template + struct NonDeduced { using type = CT; }; + template + std::vector serialCall(RT (slsDetector::*somefunc)(CT...), + typename NonDeduced::type... Args); + + /** + * Loop through the detectors serially and return the result as a vector + * Const qualified version + */ + template + std::vector serialCall(RT (slsDetector::*somefunc)(CT...) const, + typename NonDeduced::type... Args) const; + + /** + * Loop through the detectors in parallel and return the result as a vector + */ + template + std::vector parallelCall(RT (slsDetector::*somefunc)(CT...), + typename NonDeduced::type... Args); + + /** + * Loop through the detectors in parallel and return the result as a vector + * Const qualified version + */ + template + std::vector parallelCall(RT (slsDetector::*somefunc)(CT...) const, + typename NonDeduced::type... Args) const; + + + template + void parallelCall(void (slsDetector::*somefunc)(CT...), typename NonDeduced::type... Args); + + template + void parallelCall(void (slsDetector::*somefunc)(CT...) const, typename NonDeduced::type... Args) const; + + + /** + * Decodes which detector and the corresponding channel numbers for it + * Mainly useful in a multi detector setROI (Gotthard, Mythen?) + * @param offsetX channel number or total channel offset in x direction + * @param offsetY channel number or total channel offset in y direction + * @param channelX channel number from detector offset in x direction + * @param channelY channel number from detector offset in x direction + * @returns detector id or -1 if channel number out of range + */ + int decodeNChannel(int offsetX, int offsetY, int &channelX, int &channelY); + + /** + * Set acquiring flag in shared memory + * @param b acquiring flag + */ + void setAcquiringFlag(bool flag); + + /** + * Get acquiring flag from shared memory + * @returns acquiring flag + */ + bool getAcquiringFlag() const; + + /** + * Check if acquiring flag is set, set error if set + * @returns FAIL if not ready, OK if ready + */ + bool isAcquireReady(); + + /** + * Check version compatibility with detector software + * (if hostname/rx_hostname has been set/ sockets created) + * @param p port type control port or receiver port + * @param detPos -1 for all detectors in list or specific detector position + * @returns FAIL for incompatibility, OK for compatibility + */ + int checkDetectorVersionCompatibility(int detPos = -1); + /** + * Check version compatibility with receiver software + * (if hostname/rx_hostname has been set/ sockets created) + * @param p port type control port or receiver port + * @param detPos -1 for all detectors in list or specific detector position + * @returns FAIL for incompatibility, OK for compatibility + */ + int checkReceiverVersionCompatibility(int detPos = -1); + + /** + * Get ID or version numbers + * @param mode version type + * @param detPos -1 for all detectors in list or specific detector position + * @returns Id or version number of that type + */ + int64_t getId(idMode mode, int detPos = -1); + + /** + * Get Client Software version + * @returns client software version + */ + int64_t getClientSoftwareVersion() const; + + /** + * Get Receiver software version + * @return receiver software version + */ + int64_t getReceiverSoftwareVersion(int detPos = -1) const; + + std::vector getDetectorNumber(); + /** + * Free shared memory from the command line + * avoiding creating the constructor classes and mapping + * @param multiId multi detector Id + * @param detPos -1 for all detectors in list or specific detector position + */ + static void freeSharedMemory(int multiId, int detPos = -1); + + /** + * Free shared memory and delete shared memory structure + * occupied by the sharedMultiSlsDetector structure + * Clears all the vectors and bring + * object back to state before object creation amap + * @param detPos -1 for all detectors in list or specific detector position + */ + void freeSharedMemory(int detPos = -1); + + /** + * Get user details of shared memory + * @returns string with user details + */ + std::string getUserDetails(); + + /** + * Sets the hostname of all sls detectors in shared memory + * Connects to them to set up online flag + * @param name concatenated hostname of all the sls detectors + * @param detPos -1 for all detectors in list or specific detector position + */ + void setHostname(const char *name, int detPos = -1); + + /** + * Gets the hostname of detector at particular position + * or concatenated hostnames of all the sls detectors + * @param detPos -1 for all detectors in list or specific detector position + * @returns concatenated hostnames of all detectors or hostname of specific + * one + */ + std::string getHostname(int detPos = -1) const; + + /** + * Appends detectors to the end of the list in shared memory + * Connects to them to set up online flag + * @param name concatenated hostname of the sls detectors to be appended to + * the list + */ + void addMultipleDetectors(const char *name); + + /** + * Get Detector type for a particular sls detector or get the first one + * @param detPos -1 for all detectors in list or specific detector position + * @returns detector type of sls detector in position pos, if -1, returns + * the first det type + */ + detectorType getDetectorTypeAsEnum(int detPos = -1); + + /** + * Concatenates string types of all sls detectors or + * returns the detector type of the first sls detector + * @param detPos -1 for all detectors in list or specific detector position + * @returns detector type of sls detector in position pos, if -1, + * concatenates + */ + std::string getDetectorTypeAsString(int detPos = -1); + + /** + * Returns the number of detectors in the multidetector structure + * @returns number of detectors + */ + int getNumberOfDetectors() const; + + /** + * Returns number of detectors in dimension d + * @param d dimension d + * @returns number of detectors in dimension d + */ + int getNumberOfDetectors(dimension d) const; + + /** + * Returns the number of detectors in each direction + @param nx number of detectors in x direction + @param ny number of detectors in y direction + */ + void getNumberOfDetectors(int &nx, int &ny) const; + + /** + * Returns the total number of channels of all sls detectors from shared + * memory + * @param detPos -1 for all detectors in list or specific detector position + * @returns the total number of channels of all sls detectors + */ + int getTotalNumberOfChannels(int detPos = -1); + + /** + * Returns the total number of channels of all sls detectors in dimension d + * from shared memory + * @param d dimension d + * @param detPos -1 for all detectors in list or specific detector position + * @returns the total number of channels of all sls detectors in dimension d + */ + int getTotalNumberOfChannels(dimension d, int detPos = -1); + + /** + * Returns the total number of channels of all sls detectors in dimension d + * including gap pixels from shared memory + * @param d dimension d + * @param detPos -1 for all detectors in list or specific detector position + * @returns the total number of channels of all sls detectors in dimension d + * including gap pixels + */ + int getTotalNumberOfChannelsInclGapPixels(dimension d, int detPos = -1); + + /** + * Returns the maximum number of channels of all sls detectors in each + * dimension d from shared memory. multi detector shared memory variable to + * calculate offsets for each sls detector + * @param d dimension d + * @returns the maximum number of channels of all sls detectors in dimension + * d + */ + int getMaxNumberOfChannelsPerDetector(dimension d); + + /** + * Sets the maximum number of channels of all sls detectors in each + * dimension d from shared memory, multi detector shared memory variable to + * calculate offsets for each sls detector + * @param d dimension d + * @param i maximum number of channels for multi structure in dimension d + * @returns the maximum number of channels of all sls detectors in dimension + * d + */ + int setMaxNumberOfChannelsPerDetector(dimension d, int i); + + /** + * Get Detector offset from shared memory in dimension d + * @param d dimension d + * @param detPos -1 for all detectors in list or specific detector position + * @returns offset in dimension d, -1 if pos is not an actual position in + * list + */ + int getDetectorOffset(dimension d, int detPos = -1); + + /** + * Set Detector offset in shared memory in dimension d + * @param d dimension d + * @param off offset for detector + * @param detPos -1 for all detectors in list or specific detector position + */ + void setDetectorOffset(dimension d, int off, int detPos = -1); + + /** + * Updates the channel offsets in X and Y dimension for all the sls + * detectors It is required for decodeNMod and setting ROI + */ + void updateOffsets(); + + /** + * Checks if the multi detectors are online and sets the online flag + * @param online if GET_ONLINE_FLAG, only returns shared memory online flag, + * else sets the detector in online/offline state + * if OFFLINE_FLAG, (i.e. no communication to the detector - using only + * local structure - no data acquisition possible!); if ONLINE_FLAG, + * detector in online state (i.e. communication to the detector updating the + * local structure) + * @param detPos -1 for all detectors in list or specific detector position + * @returns online/offline status + */ + int setOnline(int value = GET_ONLINE_FLAG, int detPos = -1); + + /** + * Checks if each of the detectors are online/offline + * @param detPos -1 for all detectors in list or specific detector position + * @returns empty string if they are all online, + * else returns concatenation of strings of all detectors that are offline + */ + std::string checkOnline(int detPos = -1); + + /** + * Set/Gets TCP Port of the detector + * @param port_number (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns port number + */ + int setControlPort(int port_number = -1, int detPos = -1); + + /** + * Set/Gets TCP STOP Port of the detector + * @param port_number (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns port number + */ + int setStopPort(int port_number = -1, int detPos = -1); + + /** + * Set/Gets TCP Port of the receiver + * @param port_number (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns port number + */ + int setReceiverPort(int port_number = -1, int detPos = -1); + + std::vector getReceiverPort() const; + + /** + * Lock server for this client IP + * @param p 0 to unlock, 1 to lock + * @param detPos -1 for all detectors in list or specific detector position + * @returns 1 for locked or 0 for unlocked + */ + int lockServer(int p = -1, int detPos = -1); + + /** + * Get last client IP saved on detector server + * @param detPos -1 for all detectors in list or specific detector position + * @returns last client IP saved on detector server + */ + std::string getLastClientIP(int detPos = -1); + + /** + * Exit detector server + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int exitServer(int detPos = -1); + + /** + * Execute a command on the detector server + * @param cmd command + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int execCommand(const std::string &cmd, int detPos); + + /** + * Load configuration from a configuration File + * @param fname configuration file name + */ + void readConfigurationFile(const std::string &fname); + + /** + * Write current configuration to a file + * @param fname configuration file name + * @returns OK or FAIL + */ + int writeConfigurationFile(const std::string &fname); + + /** + * Get detector settings + * @param detPos -1 for all detectors in list or specific detector position + * @returns current settings + */ + detectorSettings getSettings(int detPos = -1); + + /** + * Load detector settings from the settings file picked from the + * trimdir/settingsdir Eiger only stores in shared memory ( a get will + * overwrite this) For Eiger, one must use threshold + * @param isettings settings + * @param detPos -1 for all detectors in list or specific detector position + * @returns current settings + */ + detectorSettings setSettings(detectorSettings isettings, int detPos = -1); + + /** + * Get threshold energy (Eiger) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current threshold value for imod in ev (-1 failed) + */ + int getThresholdEnergy(int detPos = -1); + + /** + * Set threshold energy (Eiger) + * @param e_eV threshold in eV + * @param isettings ev. change settings + * @param tb 1 to include trimbits, 0 to exclude + * @param detPos -1 for all detectors in list or specific detector position + * @returns current threshold value for imod in ev (-1 failed) + */ + int setThresholdEnergy(int e_eV, detectorSettings isettings = GET_SETTINGS, + int tb = 1, int detPos = -1); + + /** + * Returns the detector trimbit/settings directory + * @param detPos -1 for all detectors in list or specific detector position + * @returns the trimbit/settings directory + */ + std::string getSettingsDir(int detPos = -1); + + /** + * Sets the detector trimbit/settings directory + * @param s trimbits/settings directory + * @param detPos -1 for all detectors in list or specific detector position + * @returns the trimbit/settings directory + */ + std::string setSettingsDir(const std::string &directory, int detPos = -1); + + /** + * Loads the modules settings/trimbits reading from a specific file + * file name extension is automatically generated. + * @param fname specific settings/trimbits file + * @param detPos -1 for all detectors in list or specific detector position + * returns OK or FAIL + */ + int loadSettingsFile(const std::string &fname, int detPos = -1); + + /** + * Saves the modules settings/trimbits to a specific file + * file name extension is automatically generated. + * @param fname specific settings/trimbits file + * @param detPos -1 for all detectors in list or specific detector position + * returns OK or FAIL + */ + int saveSettingsFile(const std::string &fname, int detPos = -1); + + /** + * Get Detector run status + * @param detPos -1 for all detectors in list or specific detector position + * @returns status + */ + runStatus getRunStatus(int detPos = -1); + + /** + * Prepares detector for acquisition (Eiger) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK if all detectors are ready for acquisition, FAIL otherwise + */ + int prepareAcquisition(int detPos = -1); + + /** + * Start detector acquisition (Non blocking) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL if even one does not start properly + */ + int startAcquisition(int detPos = -1); + + /** + * Stop detector acquisition + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int stopAcquisition(int detPos = -1); + + /** + * Give an internal software trigger to the detector (Eiger only) + * @param detPos -1 for all detectors in list or specific detector position + * @return OK or FAIL + */ + int sendSoftwareTrigger(int detPos = -1); + + /** + * Start detector acquisition and read all data (Blocking until end of + * acquisition) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int startAndReadAll(int detPos = -1); + + /** + * Start readout (without exposure or interrupting exposure) (Eiger store in + * ram) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int startReadOut(int detPos = -1); + + /** + * Requests and receives all data from the detector (Eiger store in ram) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int readAll(int detPos = -1); + + /** + * Configures in detector the destination for UDP packets + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int configureMAC(int detPos = -1); + + /** + * Set/get timer value (not all implemented for all detectors) + * @param index timer index + * @param t time in ns or number of...(e.g. frames, gates, probes) + * @param detPos -1 for all detectors in list or specific detector position + * @returns timer set value in ns or number of...(e.g. frames, gates, + * probes) + */ + int64_t setTimer(timerIndex index, int64_t t = -1, int detPos = -1); + + /** + * Set/get exposure time + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns exposure time in ns, or s if specified + */ + double setExposureTime(double t = -1, bool inseconds = false, + int detPos = -1); + + /** + * Set/get exposure period + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns exposure period in ns, or s if specified + */ + double setExposurePeriod(double t = -1, bool inseconds = false, + int detPos = -1); + + /** + * Set/get delay after trigger (Gotthard, Jungfrau(not for this release)) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns delay after trigger in ns, or s if specified + */ + double setDelayAfterTrigger(double t = -1, bool inseconds = false, + int detPos = -1); + + /** + * (Advanced users) + * Set/get sub frame exposure time (Eiger in 32 bit mode) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns sub frame exposure time in ns, or s if specified + */ + double setSubFrameExposureTime(double t = -1, bool inseconds = false, + int detPos = -1); + + /** + * (Advanced users) + * Set/get sub frame dead time (Eiger in 32 bit mode) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns sub frame dead time in ns, or s if specified + */ + double setSubFrameExposureDeadTime(double t = -1, bool inseconds = false, + int detPos = -1); + + /** + * Set/get number of frames + * @param t number of frames (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of frames + */ + int64_t setNumberOfFrames(int64_t t = -1, int detPos = -1); + + /** + * Set/get number of cycles + * @param t number of cycles (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of cycles + */ + int64_t setNumberOfCycles(int64_t t = -1, int detPos = -1); + + /** + * Set/get number of gates (none of the detectors at the moment) + * @param t number of gates (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of gates + */ + int64_t setNumberOfGates(int64_t t = -1, int detPos = -1); + + /** + * Set/get number of additional storage cells (Jungfrau) + * @param t number of additional storage cells. Default is 0. (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of additional storage cells + */ + int64_t setNumberOfStorageCells(int64_t t = -1, int detPos = -1); + + /** + * Get measured period between previous two frames (EIGER) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns sub frame dead time in ns, or s if specified + */ + double getMeasuredPeriod(bool inseconds = false, int detPos = -1); + + /** + * Get sub period between previous two sub frames in 32 bit mode (EIGER) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns sub frame dead time in ns, or s if specified + */ + double getMeasuredSubFramePeriod(bool inseconds = false, int detPos = -1); + + /** + * Set/get timer value left in acquisition (not all implemented for all + * detectors) + * @param index timer index + * @param t time in ns or number of...(e.g. frames, gates, probes) + * @param detPos -1 for all detectors in list or specific detector position + * @returns timer set value in ns or number of...(e.g. frames, gates, + * probes) + */ + int64_t getTimeLeft(timerIndex index, int detPos = -1); + + /** + * Set speed + * @param sp speed type (clkdivider option for Jungfrau and Eiger, + * adcphase for Gotthard, others for CTB & Moench) + * @param value (clkdivider 0,1,2 for full, half and quarter speed). Other + * values check manual + * @param detPos -1 for all detectors in list or specific detector position + * @returns value of speed set + */ + int setSpeed(speedVariable index, int value = -1, int mode = 0, int detPos = -1); + + /** + * Set/get dynamic range and updates the number of dataBytes + * (Eiger: If i is 32, also sets clkdivider to 2, if 16, sets clkdivider to + * 1) + * @param i dynamic range (-1 get) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current dynamic range + */ + int setDynamicRange(int dr = -1, int detPos = -1); + + /** + * Recalculated number of data bytes for multi detector + * @param detPos -1 for all detectors in list or specific detector position + * @returns tota number of data bytes for multi detector + */ + int getDataBytes(int detPos = -1); + + /** + * Set/get dacs value + * @param val value (in V) + * @param index DAC index + * @param mV 0 in dac units or 1 in mV + * @param detPos -1 for all detectors in list or specific detector position + * @returns current DAC value + */ + int setDAC(int val, dacIndex index, int mV, int detPos = -1); + + /** + * Get adc value + * @param index adc(DAC) index + * @param detPos -1 for all detectors in list or specific detector position + * @returns current adc value (temperature for eiger and jungfrau in + * millidegrees) + */ + int getADC(dacIndex index, int detPos = -1); + + /** + * Set/get timing mode + * @param pol timing mode (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current timing mode + */ + externalCommunicationMode setExternalCommunicationMode( + externalCommunicationMode pol = GET_EXTERNAL_COMMUNICATION_MODE, + int detPos = -1); + + /** + * Set/get external signal flags (to specify triggerinrising edge etc) + * (Gotthard, Mythen) + * @param pol external signal flag (-1 gets) + * @param signalindex singal index (0 - 3) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current timing mode + */ + externalSignalFlag + setExternalSignalFlags(externalSignalFlag pol = GET_EXTERNAL_SIGNAL_FLAG, + int signalindex = 0, int detPos = -1); + + /** + * Set/get readout flags (Eiger, Mythen) + * @param flag readout flag (Eiger options: parallel, nonparallel, safe + * etc.) (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns readout flag + */ + int setReadOutFlags(readOutFlags flag = GET_READOUT_FLAGS, int detPos = -1); + + /** + * Write in a register. For Advanced users + * @param addr address of register + * @param val value to write into register + * @param detPos -1 for all detectors in list or specific detector position + * @returns value read after writing + */ + uint32_t writeRegister(uint32_t addr, uint32_t val, int detPos = -1); + + /** + * Read from a register. For Advanced users + * @param addr address of register + * @param detPos -1 for all detectors in list or specific detector position + * @returns value read from register + */ + uint32_t readRegister(uint32_t addr, int detPos = -1); + + /** + * Set bit in a register. For Advanced users + * @param addr address of register + * @param n nth bit + * @param detPos -1 for all detectors in list or specific detector position + * @returns value read from register + */ + uint32_t setBit(uint32_t addr, int n, int detPos = -1); + + /** + * Clear bit in a register. For Advanced users + * @param addr address of register + * @param n nth bit + * @param detPos -1 for all detectors in list or specific detector position + * @returns value read from register + */ + uint32_t clearBit(uint32_t addr, int n, int detPos = -1); + + /** + * Validates the format of the detector MAC address and sets it + * @param detectorMAC detector MAC address + * @param detPos -1 for all detectors in list or specific detector position + * @returns the detector MAC address + */ + std::string setDetectorMAC(const std::string &detectorMAC, int detPos = -1); + + /** + * Returns the detector MAC address + * @param detPos -1 for all detectors in list or specific detector position + * @returns the detector MAC address + */ + std::string getDetectorMAC(int detPos = -1); + + /** + * Validates the format of the detector MAC address (bottom half) and sets it (Jungfrau only) + * @param detectorMAC detector MAC address (bottom half) + * @param detPos -1 for all detectors in list or specific detector position + * @returns the detector MAC address (bottom half) + */ + std::string setDetectorMAC2(const std::string &detectorMAC, int detPos = -1); + + /** + * Returns the detector MAC address (bottom half) Jungfrau only + * @param detPos -1 for all detectors in list or specific detector position + * @returns the detector MAC address (bottom half) + */ + std::string getDetectorMAC2(int detPos = -1); + + /** + * Validates the format of the detector IP address and sets it + * @param detectorIP detector IP address + * @param detPos -1 for all detectors in list or specific detector position + * @returns the detector IP address + */ + std::string setDetectorIP(const std::string &detectorIP, int detPos = -1); + + /** + * Returns the detector IP address + * @param detPos -1 for all detectors in list or specific detector position + * @returns the detector IP address + */ + std::string getDetectorIP(int detPos = -1) const; + + /** + * Validates the format of the detector IP address (bottom half) and sets it (Jungfrau only) + * @param detectorIP detector IP address (bottom half) + * @param detPos -1 for all detectors in list or specific detector position + * @returns the detector IP address (bottom half) + */ + std::string setDetectorIP2(const std::string &detectorIP, int detPos = -1); + + /** + * Returns the detector IP address (bottom half) Jungfrau only + * @param detPos -1 for all detectors in list or specific detector position + * @returns the detector IP address (bottom half) + */ + std::string getDetectorIP2(int detPos = -1) const; + + /** + * Validates and sets the receiver. + * Also updates the receiver with all the shared memory parameters significant for the receiver + * Also configures the detector to the receiver as UDP destination + * @param receiver receiver hostname or IP address + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver IP address from shared memory + */ + std::string setReceiverHostname(const std::string &receiver, int detPos = -1); + + /** + * Returns the receiver IP address + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver IP address + */ + std::string getReceiverHostname(int detPos = -1) const; + + /** + * Validates the format of the receiver UDP IP address and sets it + * @param udpip receiver UDP IP address + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver UDP IP address + */ + std::string setReceiverUDPIP(const std::string &udpip, int detPos = -1); + + /** + * Returns the receiver UDP IP address + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver UDP IP address + */ + std::string getReceiverUDPIP(int detPos = -1) const; + + /** + * Validates the format of the receiver UDP IP address (bottom half) and sets it(Jungfrau only) + * @param udpip receiver UDP IP address (bottom half) + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver UDP IP address (bottom half) + */ + std::string setReceiverUDPIP2(const std::string &udpip, int detPos = -1); + + /** + * Returns the receiver UDP IP address (bottom half) Jungfrau only + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver UDP IP address (bottom half) + */ + std::string getReceiverUDPIP2(int detPos = -1) const; + + /** + * Validates the format of the receiver UDP MAC address and sets it + * @param udpmac receiver UDP MAC address + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver UDP MAC address + */ + std::string setReceiverUDPMAC(const std::string &udpmac, int detPos = -1); + + /** + * Returns the receiver UDP MAC address + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver UDP MAC address + */ + std::string getReceiverUDPMAC(int detPos = -1) const; + + /** + * Validates the format of the receiver UDP MAC address (bottom half) and sets it (Jungfrau only) + * @param udpmac receiver UDP MAC address (bottom half) + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver UDP MAC address (bottom half) + */ + std::string setReceiverUDPMAC2(const std::string &udpmac, int detPos = -1); + + /** + * Returns the receiver UDP MAC address (bottom half) Jungfrau only + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver UDP MAC address (bottom half) + */ + std::string getReceiverUDPMAC2(int detPos = -1) const; + + /** + * Sets the receiver UDP port + * @param udpport receiver UDP port + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver UDP port + */ + int setReceiverUDPPort(int udpport, int detPos = -1); + + /** + * Returns the receiver UDP port + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver UDP port + */ + int getReceiverUDPPort(int detPos = -1) const; + + /** + * Sets the receiver UDP port 2 (Eiger and Jungfrau only) + * @param udpport receiver UDP port 2 + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver UDP port 2 + */ + int setReceiverUDPPort2(int udpport, int detPos = -1); + + /** + * Returns the receiver UDP port 2 of same interface (Eiger and Jungfrau only) + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver UDP port 2 of same interface + */ + int getReceiverUDPPort2(int detPos = -1) const; + + /** + * Sets the number of UDP interfaces to stream data from detector (Jungfrau only) + * @param n number of interfaces. Options 1 or 2. + * @param detPos -1 for all detectors in list or specific detector position + * @returns the number of interfaces + */ + int setNumberofUDPInterfaces(int n, int detPos = -1); + + /** + * Returns the number of UDP interfaces to stream data from detector (Jungfrau only) + * @param detPos -1 for all detectors in list or specific detector position + * @returns the number of interfaces + */ + int getNumberofUDPInterfaces(int detPos = -1) const; + + /** + * Selects the UDP interfaces to stream data from detector. Effective only when number of interfaces is 1. (Jungfrau only) + * @param n selected interface. Options 1 or 2. + * @param detPos -1 for all detectors in list or specific detector position + * @returns the interface selected + */ + int selectUDPInterface(int n, int detPos = -1); + + /** + * Returns the UDP interfaces to stream data from detector. Effective only when number of interfaces is 1. (Jungfrau only) + * @param detPos -1 for all detectors in list or specific detector position + * @returns the interface selected + */ + int getSelectedUDPInterface(int detPos = -1) const; + + /** + * (advanced users) + * Set/Get client streaming in ZMQ port and restarts client sockets + * @param i sets, -1 gets + * If detPos is -1(multi module), port calculated (increments) for all the + * individual detectors using i + * @param detPos -1 for all detectors in list or specific detector position + */ + void setClientDataStreamingInPort(int i = -1, int detPos = -1); + + /** + * Returns the client zmq port + * If detPos is -1(multi module), port returns client streaming port of first module + * @param detPos -1 for all detectors in list or specific detector position + * @returns the client zmq port + */ + int getClientStreamingPort(int detPos = -1); + + /** + * (advanced users) + * Set/Get receiver streaming out ZMQ port and restarts receiver sockets + * @param i sets, -1 gets + * If detPos is -1(multi module), port calculated (increments) for all the + * individual detectors using i + * @param detPos -1 for all detectors in list or specific detector position + */ + void setReceiverDataStreamingOutPort(int i = -1, int detPos = -1); + + /** + * Returns the receiver zmq port + * If detPos is -1(multi module), port returns receiver streaming port of first module + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver zmq port + */ + int getReceiverStreamingPort(int detPos = -1); + + /** + * (advanced users) + * Set/Get client streaming in ZMQ IP and restarts client sockets + * @param i sets, empty string gets + * By default, it is the IP of receiver hostname + * @param detPos -1 for all detectors in list or specific detector position + */ + void setClientDataStreamingInIP(const std::string &ip = "", + int detPos = -1); + + /** + * Returns the client zmq ip + * If detPos is -1(multi module), ip returns concatenation of all client streaming ip + * @param detPos -1 for all detectors in list or specific detector position + * @returns the client zmq ip + */ + std::string getClientStreamingIP(int detPos = -1); + + /** + * (advanced users) + * Set/Get receiver streaming out ZMQ IP and restarts receiver sockets + * @param i sets, empty string gets + * By default, it is the IP of receiver hostname + * @param detPos -1 for all detectors in list or specific detector position + */ + void setReceiverDataStreamingOutIP(const std::string &ip = "", + int detPos = -1); + + /** + * Returns the receiver zmq ip + * If detPos is -1(multi module), ip returns concatenation of all receiver streaming ip + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver zmq ip + */ + std::string getReceiverStreamingIP(int detPos = -1); + + /** + * Sets the transmission delay for left, right or entire frame + * (Eiger, Jungfrau(only entire frame)) + * @param index type of delay + * @param delay delay + * @param detPos -1 for all detectors in list or specific detector position + * @returns transmission delay + */ + int setDetectorNetworkParameter(networkParameter index, int delay, int detPos = -1); + + /** + * Sets the additional json header + * @param jsonheader additional json header + * @param detPos -1 for all detectors in list or specific detector position + * @returns additional json header, default is empty + */ + std::string setAdditionalJsonHeader(const std::string &jsonheader, int detPos = -1); + + /** + * Returns the additional json header + * @param detPos -1 for all detectors in list or specific detector position + * @returns the additional json header, default is empty + */ + std::string getAdditionalJsonHeader(int detPos = -1); + + /** + * Sets the value for the additional json header parameter if found, else append it + * @param key additional json header parameter + * @param value additional json header parameter value (cannot be empty) + * @param detPos -1 for all detectors in list or specific detector position + * @returns the additional json header parameter value, + * empty if no parameter found in additional json header + */ + std::string setAdditionalJsonParameter(const std::string &key, const std::string &value, int detPos = -1); + + /** + * Returns the additional json header parameter value + * @param key additional json header parameter + * @param detPos -1 for all detectors in list or specific detector position + * @returns the additional json header parameter value, + * empty if no parameter found in additional json header + */ + std::string getAdditionalJsonParameter(const std::string &key, int detPos = -1); + + /** + * Sets the detector minimum/maximum energy threshold in processor (for Moench only) + * @param index 0 for emin, antyhing else for emax + * @param v value to set (-1 gets) + * @returns detector minimum/maximum energy threshold (-1 for not found or error in computing json parameter value) + */ + int setDetectorMinMaxEnergyThreshold(const int index, int value, int detPos = -1); + + /** + * Sets the frame mode in processor (Moench only) + * @param value frameModeType (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns frame mode (-1 for not found or error in computing json parameter value) + */ + int setFrameMode(frameModeType value, int detPos = -1); + + /** + * Sets the detector mode in processor (Moench only) + * @param value detectorModetype (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns detector mode (-1 for not found or error in computing json parameter value) + */ + int setDetectorMode(detectorModeType value, int detPos = -1); + + /** + * Sets the receiver UDP socket buffer size + * @param udpsockbufsize additional json header + * @param detPos -1 for all detectors in list or specific detector position + * @returns receiver udp socket buffer size + */ + int64_t setReceiverUDPSocketBufferSize(int64_t udpsockbufsize = -1, int detPos = -1); + + /** + * Returns the receiver UDP socket buffer size + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver UDP socket buffer size + */ + int64_t getReceiverUDPSocketBufferSize(int detPos = -1); + + /** + * Returns the receiver real UDP socket buffer size + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver real UDP socket buffer size + */ + int64_t getReceiverRealUDPSocketBufferSize(int detPos = -1); + + /** (users only) + * Set 10GbE Flow Control (Eiger) + * @param enable 1 to set, 0 to unset, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns 10GbE flow Control + */ + int setFlowControl10G(int enable = -1, int detPos = -1); + + /** + * Execute a digital test (Gotthard) + * @param mode testmode type + * @param value 1 to set or 0 to clear the digital test bit + * @param detPos -1 for all detectors in list or specific detector position + * @returns result of test + */ + int digitalTest(digitalTestMode mode, int ival = -1, int detPos = -1); + + /** + * Load dark or gain image to detector (Gotthard) + * @param index image type + * @param fname file name from which to load image + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int loadImageToDetector(imageType index, const std::string &fname, + int detPos = -1); + + /** + * Writes the counter memory block from the detector (Gotthard) + * @param fname file name to load data from + * @param startACQ is 1 to start acquisition after reading counter + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int writeCounterBlockFile(const std::string &fname, int startACQ = 0, + int detPos = -1); + + /** + * Resets counter in detector (Gotthard) + * @param startACQ is 1 to start acquisition after resetting counter + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int resetCounterBlock(int startACQ = 0, int detPos = -1); + + /** + * Set/get counter bit in detector (Gotthard) + * @param i is -1 to get, 0 to reset and any other value to set the counter + * bit + * @param detPos -1 for all detectors in list or specific detector position + * @returns the counter bit in detector + */ + int setCounterBit(int i = -1, int detPos = -1); + + /** + * Ensures that min is less than max in both dimensions (Gotthard) + * @param n number of rois + * @param r array of rois + */ + void verifyMinMaxROI(int n, ROI r[]); + + /** + * Set ROI (Gotthard) + * At the moment only one set allowed + * @param n number of rois + * @param roiLimits array of roi + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int setROI(int n = -1, ROI roiLimits[] = nullptr, int detPos = -1); + + /** + * Get ROI from each detector and convert it to the multi detector scale + * (Gotthard) + * @param n number of rois + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + const ROI *getROI(int &n, int detPos = -1); + + /** + * Write to ADC register (Gotthard, Jungfrau, ChipTestBoard). For expert + * users + * @param addr address of adc register + * @param val value + * @param detPos -1 for all detectors in list or specific detector position + * @returns return value (mostly -1 as it can't read adc register) + */ + int writeAdcRegister(int addr, int val, int detPos = -1); + + /** + * Activates/Deactivates the detector (Eiger only) + * @param enable active (1) or inactive (0), -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns 0 (inactive) or 1 (active)for activate mode + */ + int activate(int const enable = -1, int detPos = -1); + + /** + * Set deactivated Receiver padding mode (Eiger only) + * @param padding padding option for deactivated receiver. Can be 1 + * (padding), 0 (no padding), -1 (gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns 1 (padding), 0 (no padding), -1 (inconsistent values) for + * padding option + */ + int setDeactivatedRxrPaddingMode(int padding = -1, int detPos = -1); + + /** + * Returns the enable if data will be flipped across x or y axis (Eiger) + * @param d axis across which data is flipped + * @param detPos -1 for all detectors in list or specific detector position + * @returns 1 for flipped, else 0 + */ + int getFlippedData(dimension d = X, int detPos = -1); + + /** + * Sets the enable which determines if + * data will be flipped across x or y axis (Eiger) + * @param d axis across which data is flipped + * @param value 0 or 1 to reset/set or -1 to get value + * @param detPos -1 for all detectors in list or specific detector position + * @returns enable flipped data across x or y axis + */ + int setFlippedData(dimension d = X, int value = -1, int detPos = -1); + + /** + * Sets all the trimbits to a particular value (Eiger) + * @param val trimbit value + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int setAllTrimbits(int val, int detPos = -1); + + /** + * Enable gap pixels, only for Eiger and for 8,16 and 32 bit mode. (Eiger) + * 4 bit mode gap pixels only in gui call back + * @param val 1 sets, 0 unsets, -1 gets + * @returns gap pixel enable or -1 for error + */ + int enableGapPixels(int val = -1, int detPos = -1); + + /** + * Sets the number of trim energies and their value (Eiger) + * + * @param nen number of energies + * @param en array of energies + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of trim energies + */ + int setTrimEn(std::vector energies, int detPos = -1); + + /** + * Returns the number of trim energies and their value (Eiger) + * + * @param detPos -1 for all detectors in list or specific detector position + * @returns vector of trim energies + */ + std::vector getTrimEn(int detPos = -1); + + /** + * Pulse Pixel (Eiger) + * @param n is number of times to pulse + * @param x is x coordinate + * @param y is y coordinate + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int pulsePixel(int n = 0, int x = 0, int y = 0, int detPos = -1); + + /** + * Pulse Pixel and move by a relative value (Eiger) + * @param n is number of times to pulse + * @param x is relative x value + * @param y is relative y value + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int pulsePixelNMove(int n = 0, int x = 0, int y = 0, int detPos = -1); + + /** + * Pulse Chip (Eiger) + * @param n is number of times to pulse + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int pulseChip(int n = 0, int detPos = -1); + + /** + * Set/gets threshold temperature (Jungfrau) + * @param val value in millidegrees, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns threshold temperature in millidegrees + */ + int setThresholdTemperature(int val = -1, int detPos = -1); + + /** + * Enables/disables temperature control (Jungfrau) + * @param val value, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns temperature control enable + */ + int setTemperatureControl(int val = -1, int detPos = -1); + + /** + * Resets/ gets over-temperature event (Jungfrau) + * @param val value, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns over-temperature event + */ + int setTemperatureEvent(int val = -1, int detPos = -1); + + /** + * Set storage cell that stores first acquisition of the series (Jungfrau) + * @param value storage cell index. Value can be 0 to 15. (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns the storage cell that stores the first acquisition of the series + */ + int setStoragecellStart(int pos = -1, int detPos = -1); + + /** + * Programs FPGA with pof file (Not Eiger) + * @param fname file name + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int programFPGA(const std::string &fname, int detPos = -1); + + /** + * Resets FPGA (Not Eiger) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int resetFPGA(int detPos = -1); + + /** + * Copies detector server from tftp and changes respawn server (Not Eiger) + * @param fname name of detector server binary + * @param hostname name of pc to tftp from + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int copyDetectorServer(const std::string &fname, const std::string &hostname, int detPos = -1); + + /** + * Reboot detector controller (Not Eiger) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int rebootController(int detPos = -1); + + /** + * Updates the firmware, detector server and then reboots detector controller blackfin. (Not Eiger) + * @param sname name of detector server binary + * @param hostname name of pc to tftp from + * @param fname programming file name + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int update(const std::string &sname, const std::string &hostname, const std::string &fname, int detPos = -1); + + /** + * Power on/off Chip (Jungfrau) + * @param ival on is 1, off is 0, -1 to get + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int powerChip(int ival = -1, int detPos = -1); + + /** + * Automatic comparator disable (Jungfrau) + * @param ival on is 1, off is 0, -1 to get + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int setAutoComparatorDisableMode(int ival = -1, int detPos = -1); + + /** + * Returns the trimbits from the detector's shared memmory (Mythen, Eiger) + * @param retval is the array with the trimbits + * @param detPos -1 for all detectors in list or specific detector position + * @returns total number of channels for the detector + */ + int getChanRegs(double *retval, int detPos = -1); + + /** + * Set Rate correction ( Eiger) + * @param t dead time in ns - if 0 disable correction, + * if >0 set dead time to t, if < 0 set deadtime to default dead time + * for current settings + * @param detPos -1 for all detectors in list or specific detector position + * @returns 0 if rate correction disabled, >0 otherwise + */ + int setRateCorrection(int64_t t = 0, int detPos = -1); + + /** + * Get rate correction ( Eiger) + * @param detPos -1 for all detectors in list or specific detector position + * @returns 0 if rate correction disabled, > 0 otherwise (ns) + */ + int64_t getRateCorrection(int detPos = -1); + + /** + * Prints receiver configuration + * @param level print level + * @param detPos -1 for all detectors in list or specific detector position + */ + void printReceiverConfiguration(TLogLevel level = logINFO, int detPos = -1); + + /** + * Sets up receiver socket if online and sets the flag + * @param online online/offline flag (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns online/offline flag + */ + int setReceiverOnline(int value = GET_ONLINE_FLAG, int detPos = -1); + + /** + * Checks if the receiver is really online + * @param detPos -1 for all detectors in list or specific detector position + * @returns empty string if all online, else concatenates hostnames of all + * detectors that are offline + */ + std::string checkReceiverOnline(int detPos = -1); + + /** + * Locks/Unlocks the connection to the receiver + * @param lock sets (1), usets (0), gets (-1) the lock + * @param detPos -1 for all detectors in list or specific detector position + * @returns lock status of the receiver + */ + int lockReceiver(int lock = -1, int detPos = -1); + + /** + * Returns the IP of the last client connecting to the receiver + * @param detPos -1 for all detectors in list or specific detector position + * @returns IP of last client connecting to receiver + */ + std::string getReceiverLastClientIP(int detPos = -1); + + /** + * Turns off the receiver server! + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int exitReceiver(int detPos = -1); + + /** + * Executes a system command on the receiver server + * e.g. mount an nfs disk, reboot and returns answer etc. + * @param cmd command to be executed + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int execReceiverCommand(const std::string &cmd, int detPos = -1); + + /** + * Returns output file directory + * @param detPos -1 for all detectors in list or specific detector position + * @returns output file directory + */ + std::string getFilePath(int detPos = -1); + + /** + * Sets up the file directory + * @param detPos -1 for all detectors in list or specific detector position + * @param s file directory + * @returns file dir + */ + std::string setFilePath(const std::string &path, int detPos = -1); + + /** + * Returns file name prefix + * @param detPos -1 for all detectors in list or specific detector position + * @returns file name prefix + */ + std::string getFileName(int detPos = -1); + + /** + * Sets up the file name prefix + * @param detPos -1 for all detectors in list or specific detector position + * @param s file name prefix + * @returns file name prefix + */ + std::string setFileName(const std::string &fname, int detPos = -1); + + /** + * Sets the max frames per file in receiver + * @param f max frames per file + * @param detPos -1 for all detectors in list or specific detector position + * @returns max frames per file in receiver + */ + int setFramesPerFile(int f = -1, int detPos = -1); + + /** + * Gets the max frames per file in receiver + * @param detPos -1 for all detectors in list or specific detector position + * @returns max frames per file in receiver + */ + int getFramesPerFile(int detPos = -1) const; + + /** + * Sets the frames discard policy in receiver + * @param f frames discard policy + * @param detPos -1 for all detectors in list or specific detector position + * @returns frames discard policy set in receiver + */ + frameDiscardPolicy setReceiverFramesDiscardPolicy( + frameDiscardPolicy f = GET_FRAME_DISCARD_POLICY, int detPos = -1); + + /** + * Sets the partial frames padding enable in receiver + * @param f partial frames padding enable + * @param detPos -1 for all detectors in list or specific detector position + * @returns partial frames padding enable in receiver + */ + int setPartialFramesPadding(bool padding, int detPos = -1); + + int getPartialFramesPadding(int detPos = -1) const; + + /** + * Returns file format + * @param detPos -1 for all detectors in list or specific detector position + * @returns file name + */ + fileFormat getFileFormat(int detPos = -1); + + /** + * Sets up the file format + * @param f file format + * @param detPos -1 for all detectors in list or specific detector position + * @returns file format + */ + fileFormat setFileFormat(fileFormat f, int detPos = -1); + + /** + * Returns file index + * @param detPos -1 for all detectors in list or specific detector position + * @returns file index + */ + int getFileIndex(int detPos = -1); + + /** + * Sets up the file index + * @param i file index + * @param detPos -1 for all detectors in list or specific detector position + * @returns file index + */ + int setFileIndex(int i, int detPos = -1); + + int getFileIndex(int detPos = -1) const; + + /** + * increments file index + * @param detPos -1 for all detectors in list or specific detector position + * @returns the file index + */ + int incrementFileIndex(int detPos = -1); + + /** + * Receiver starts listening to packets + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int startReceiver(int detPos = -1); + + /** + * Stops the listening mode of receiver + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int stopReceiver(int detPos = -1); + + /** + * Gets the status of the listening mode of receiver + * @param detPos -1 for all detectors in list or specific detector position + * @returns status + */ + runStatus getReceiverStatus(int detPos = -1); + + /** + * Gets the number of frames caught by receiver + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of frames caught by receiver + */ + int getFramesCaughtByReceiver(int detPos = -1); + + /** + * Gets the current frame index of receiver + * @param detPos -1 for all detectors in list or specific detector position + * @returns current frame index of receiver + */ + int getReceiverCurrentFrameIndex(int detPos = -1); + + /** + * Resets framescaught in receiver + * Use this when using startAcquisition instead of acquire + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int resetFramesCaught(int detPos = -1); + + /** + * Create Receiving Data Sockets + * @param destroy is true to destroy all the sockets + * @returns OK or FAIL + */ + int createReceivingDataSockets(const bool destroy = false); + + /** + * Reads frames from receiver through a constant socket + * Called during acquire() when call back registered or when using gui + */ + void readFrameFromReceiver(); + + /** + * Sets/Gets receiver file write enable + * @param enable 1 or 0 to set/reset file write enable + * @param detPos -1 for all detectors in list or specific detector position + * @returns file write enable + */ + int setFileWrite(bool value, int detPos = -1); + int getFileWrite(int detPos = -1) const; + + /** + * Sets/Gets file overwrite enable + * @param enable 1 or 0 to set/reset file overwrite enable + * @param detPos -1 for all detectors in list or specific detector position + * @returns file overwrite enable + */ + int setFileOverWrite(bool enable, int detPos = -1); + int getFileOverWrite(int detPos = -1) const; + + /** + * (previously setReadReceiverFrequency) + * Sets the receiver streaming frequency + * @param freq nth frame streamed out, if 0, streamed out at a timer of 200 + * ms + * @param detPos -1 for all detectors in list or specific detector position + * @returns receiver streaming frequency + */ + int setReceiverStreamingFrequency(int freq = -1, int detPos = -1); + + /** + * (previously setReceiverReadTimer) + * Sets the receiver streaming timer + * If receiver streaming frequency is 0, then this timer between each + * data stream is set. Default is 200 ms. + * @param time_in_ms timer between frames + * @param detPos -1 for all detectors in list or specific detector position + * @returns receiver streaming timer in ms + */ + int setReceiverStreamingTimer(int time_in_ms = 500, int detPos = -1); + + /** + * Enable data streaming to client + * @param enable 0 to disable, 1 to enable, -1 to get the value + * @returns data streaming to client enable + */ + int enableDataStreamingToClient(int enable = -1); + + /** + * Enable or disable streaming data from receiver to client + * @param enable 0 to disable 1 to enable -1 to only get the value + * @param detPos -1 for all detectors in list or specific detector position + * @returns data streaming from receiver enable + */ + int enableDataStreamingFromReceiver(int enable = -1, int detPos = -1); + + /** + * Enable/disable or 10Gbe + * @param i is -1 to get, 0 to disable and 1 to enable + * @param detPos -1 for all detectors in list or specific detector position + * @returns if 10Gbe is enabled + */ + int enableTenGigabitEthernet(int i = -1, int detPos = -1); + + /** + * Set/get receiver fifo depth + * @param i is -1 to get, any other value to set the fifo deph + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver fifo depth + */ + int setReceiverFifoDepth(int i = -1, int detPos = -1); + + /** + * Set/get receiver silent mode + * @param i is -1 to get, 0 unsets silent mode, 1 sets silent mode + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver silent mode enable + */ + int setReceiverSilentMode(int i = -1, int detPos = -1); + + /** + * Opens pattern file and sends pattern to CTB + * @param fname pattern file to open + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK/FAIL + */ + int setPattern(const std::string &fname, int detPos = -1); + + /** + * Writes a pattern word to the CTB + * @param addr address of the word, -1 is I/O control register, + * -2 is clk control register + * @param word 64bit word to be written, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns actual value + */ + uint64_t setPatternWord(int addr, uint64_t word = -1, int detPos = -1); + + /** + * Sets the pattern or loop limits in the CTB + * @param level -1 complete pattern, 0,1,2, loop level + * @param start start address if >=0 + * @param stop stop address if >=0 + * @param n number of loops (if level >=0) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK/FAIL + */ + int setPatternLoops(int level, int &start, int &stop, int &n, + int detPos = -1); + + /** + * Sets the wait address in the CTB + * @param level 0,1,2, wait level + * @param addr wait address, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns actual value + */ + int setPatternWaitAddr(int level, int addr = -1, int detPos = -1); + + /** + * Sets the wait time in the CTB + * @param level 0,1,2, wait level + * @param t wait time, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns actual value + */ + uint64_t setPatternWaitTime(int level, uint64_t t = -1, int detPos = -1); + + /** + * Sets the mask applied to every pattern + * @param mask mask to be applied + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int setPatternMask(uint64_t mask, int detPos = -1); + + /** + * Gets the mask applied to every pattern + * @param detPos -1 for all detectors in list or specific detector position + * @returns mask set + */ + uint64_t getPatternMask(int detPos = -1); + + /** + * Selects the bits that the mask will be applied to for every pattern + * @param mask mask to select bits + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int setPatternBitMask(uint64_t mask, int detPos = -1); + + /** + * Gets the bits that the mask will be applied to for every pattern + * @param detPos -1 for all detectors in list or specific detector position + * @returns mask of bits selected + */ + uint64_t getPatternBitMask(int detPos = -1); + + /** + * Set LED Enable (Moench, CTB only) + * @param enable 1 to switch on, 0 to switch off, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns LED enable + */ + int setLEDEnable(int enable = -1, int detPos = -1); + + /** + * Set Digital IO Delay (Moench, CTB only) + * @param digital IO mask to select the pins + * @param delay delay in ps(1 bit=25ps, max of 775 ps) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int setDigitalIODelay(uint64_t pinMask, int delay, int detPos = -1); + + /** + * Loads the detector setup from file + * @param fname file to read from + * @param level if 2 reads also reads trimbits, angular conversion + * coefficients etc. from files with default extensions as generated by + * dumpDetectorSetup + * @returns OK or FAIL + */ + int retrieveDetectorSetup(const std::string &fname, int level = 0); + + /** + * Saves the detector setup to file + * @param fname file to write to + * @param level if 2 reads also trimbits, flat field, angular correction + * etc. and writes them to files with automatically added extension + * @returns OK or FAIL + */ + int dumpDetectorSetup(const std::string &fname, int level = 0); + + /** + * register callback for accessing acquisition final data + * @param func function to be called at the end of the acquisition. + * gets detector status and progress index as arguments + * @param pArg argument + */ + void registerAcquisitionFinishedCallback(int (*func)(double, int, void *), + void *pArg); + + /** + * register callback for accessing measurement final data + * @param func function to be called at the end of the acquisition. + * gets detector status and progress index as arguments + * @param pArg argument + */ + void registerMeasurementFinishedCallback(int (*func)(int, int, void *), + void *pArg); + + /** + * register callback for accessing detector progress + * @param func function to be called at the end of the acquisition. + * gets detector status and progress index as arguments + * @param pArg argument + */ + void registerProgressCallback(int (*func)(double, void *), void *pArg); + + /** + * register calbback for accessing detector final data, + * also enables data streaming in client and receiver + * @param userCallback function for plotting/analyzing the data. + * Its arguments are + * the data structure d and the frame number f, + * s is for subframe number for eiger for 32 bit mode + * @param pArg argument + */ + void registerDataCallback(int (*userCallback)(detectorData *, int, int, + void *), + void *pArg); + + /** + * Performs a complete acquisition + * resets frames caught in receiver, starts receiver, starts detector, + * blocks till detector finished acquisition, stop receiver, increments file + * index, loops for measurements, calls required call backs. + * @returns OK or FAIL depending on if it already started + */ + int acquire(); + + /** + * Combines data from all readouts and gives it to the gui + * or just gives progress of acquisition by polling receivers + */ + void processData(); + + void addSlsDetector(std::unique_ptr det); + + private: + /** + * Initialize (open/create) shared memory for the sharedMultiDetector + * structure + * @param verify true to verify if shm size matches existing one + * @param update true to update last user pid, date etc + * @returns true if shared memory was created in this call, else false + */ + void initSharedMemory(bool verify = true); + + /** + * Initialize detector structure for the shared memory just created + */ + void initializeDetectorStructure(); + + /** + * Initialize class members (and from parent classes) + * @param verify true to verify if shm size matches existing one + */ + void initializeMembers(bool verify = true); + + /** + * Update user details in detector structure + */ + void updateUserdetails(); + + /** + * Execute in command line and return result + * @param cmd command + * @returns result + */ + std::string exec(const char *cmd); + + /** + * Add sls detector + * @param s hostname of the single detector + */ + void addSlsDetector(const std::string &hostname); + + + + /** + * add gap pixels to the image (only for Eiger in 4 bit mode) + * @param image pointer to image without gap pixels + * @param gpImage poiner to image with gap pixels, if NULL, allocated + * inside function + * @returns number of data bytes of image with gap pixels + */ + int processImageWithGapPixels(char *image, char *&gpImage); + + /** + * Set total progress (total number of frames/images in an acquisition) + * @returns total progress + */ + int setTotalProgress(); + + /** + * Get progress in current acquisition + * @returns current progress + */ + double getCurrentProgress(); + + /** + * Increment progress by one + */ + void incrementProgress(); + + /** + * Set current progress to argument + * @param i current progress + */ + void setCurrentProgress(int i = 0); + + /** + * Start data processing thread + */ + void startProcessingThread(); + + /** + * Check if processing thread is ready to join main thread + * @returns true if ready, else false + */ + bool getJoinThreadFlag() const; + + /** + * Main thread sets if the processing thread should join it + * @param v true if it should join, else false + */ + void setJoinThreadFlag(bool value); + + /** + * Listen to key event to stop acquiring + * when using acquire command + */ + int kbhit(); + + /** + * Convert raw file + * @param fname name of pof file + * @param fpgasrc pointer in memory to read pof to + * @returns file size + */ + std::vector readPofFile(const std::string &fname); + + + /** Multi detector Id */ + const int multiId{0}; + + /** Shared Memory object */ + sls::SharedMemory multi_shm{0, -1}; + + /** pointers to the slsDetector structures */ + std::vector> detectors; + + /** data streaming (down stream) enabled in client (zmq sckets created) */ + bool client_downstream{false}; + + /** ZMQ Socket - Receiver to Client */ + std::vector> zmqSocket; + + /** semaphore to let postprocessing thread continue for next + * scan/measurement */ + sem_t sem_newRTAcquisition; + + /** semaphore to let main thread know it got all the dummy packets (also + * from ext. process) */ + sem_t sem_endRTAcquisition; + + /** Total number of frames/images for next acquisition */ + int totalProgress{0}; + + /** Current progress or frames/images processed in current acquisition */ + int progressIndex{0}; + + /** mutex to synchronize main and data processing threads */ + mutable std::mutex mp; + + /** mutex to synchronizedata processing and plotting threads */ + mutable std::mutex mg; + + /** sets when the acquisition is finished */ + bool jointhread{false}; + + /** the data processing thread */ + // pthread_t dataProcessingThread; + std::thread dataProcessingThread; + + /** detector data packed for the gui */ + detectorData *thisData{nullptr}; + + int (*acquisition_finished)(double, int, void *){nullptr}; + void *acqFinished_p{nullptr}; + + int (*measurement_finished)(int, int, void *){nullptr}; + void *measFinished_p{nullptr}; + + int (*progress_call)(double, void *){nullptr}; + void *pProgressCallArg{nullptr}; + + int (*dataReady)(detectorData *, int, int, void *){nullptr}; + void *pCallbackArg{nullptr}; +}; + diff --git a/slsDetectorSoftware/include/multiSlsDetectorClient.h b/slsDetectorSoftware/include/multiSlsDetectorClient.h new file mode 100755 index 000000000..fba5f71f6 --- /dev/null +++ b/slsDetectorSoftware/include/multiSlsDetectorClient.h @@ -0,0 +1,105 @@ +#pragma once +#include +#include + +#include "CmdLineParser.h" +#include "container_utils.h" +#include "string_utils.h" +#include "multiSlsDetector.h" +#include "slsDetectorCommand.h" +#include "sls_detector_exceptions.h" + +#include +#include + +using sls::RuntimeError; + +inline int dummyCallback(detectorData *d, int p, void *) { + std::cout << "got data " << p << std::endl; + return 0; +}; + +class multiSlsDetectorClient { + public: + multiSlsDetectorClient(int argc, char *argv[], int action, multiSlsDetector *myDetector = nullptr): + action_(action), + detPtr(myDetector){ + parser.Parse(argc, argv); + runCommand(); + + } + multiSlsDetectorClient(const std::string& args, int action, multiSlsDetector *myDetector = nullptr): + action_(action), + detPtr(myDetector){ + parser.Parse(args); + runCommand(); + } + private: + int action_; + CmdLineParser parser; + multiSlsDetector* detPtr = nullptr; + + void runCommand(){ + bool verify = true; + bool update = true; + if (action_ == slsDetectorDefs::PUT_ACTION && parser.n_arguments() == 0) { + std::cout << "Wrong usage - should be: " << parser.executable() << "[id-][pos:]channel arg" << std::endl; + std::cout << std::endl; + return; + }; + if (action_ == slsDetectorDefs::GET_ACTION && parser.command().empty()) { + std::cout << "Wrong usage - should be: " << parser.executable() << "[id-][pos:]channel arg" << std::endl; + std::cout << std::endl; + return; + }; + + if (action_ == slsDetectorDefs::READOUT_ACTION && parser.detector_id() != -1) { + std::cout << "detector_id: " << parser.detector_id() << " ,readout of individual detectors is not allowed!" << std::endl; + return; + } + + // special commands + if (parser.command() == "free") { + multiSlsDetector::freeSharedMemory(parser.multi_id(), parser.detector_id()); + return; + } // get user details without verify sharedMultiSlsDetector version + else if ((parser.command() == "user") && (action_ == slsDetectorDefs::GET_ACTION)) { + verify = false; + update = false; + } + + //std::cout<<"id:"< localDet; + if (detPtr == nullptr) { + try { + localDet = sls::make_unique(parser.multi_id(), verify, update); + detPtr = localDet.get(); + } catch (const RuntimeError &e) { + /*std::cout << e.GetMessage() << std::endl;*/ + return; + } catch (...) { + std::cout << " caught exception\n"; + return; + } + } + if (parser.detector_id() >= detPtr->getNumberOfDetectors()) { + std::cout << "position is out of bounds.\n"; + return; + } + + // call multi detector command line + slsDetectorCommand myCmd(detPtr); + std::string answer = myCmd.executeLine(parser.n_arguments()+1, parser.argv().data(), action_, parser.detector_id()); + + if (parser.multi_id()!=0) + std::cout << parser.multi_id() << '-'; + if (parser.detector_id() != -1) + std::cout << parser.detector_id() << ':'; + + if (action_ != slsDetectorDefs::READOUT_ACTION) { + std::cout << parser.command() << " "; + } + std::cout << answer << std::endl; + } +}; diff --git a/slsDetectorSoftware/include/slsDetector.h b/slsDetectorSoftware/include/slsDetector.h new file mode 100755 index 000000000..b778372b1 --- /dev/null +++ b/slsDetectorSoftware/include/slsDetector.h @@ -0,0 +1,1847 @@ +#pragma once + +#include "ClientSocket.h" +#include "SharedMemory.h" +#include "error_defs.h" +#include "logger.h" +#include "sls_detector_defs.h" +#include "network_utils.h" +class ClientInterface; + +#include +#include + +class multiSlsDetector; +class ServerInterface; +class MySocketTCP; + +#define SLS_SHMVERSION 0x181005 +#define NCHIPSMAX 10 +#define NCHANSMAX 65536 +#define NDACSMAX 16 +/** + * parameter list that has to be initialized depending on the detector type + */ +struct detParameters { + int nChanX; + int nChanY; + int nChipX; + int nChipY; + int nDacs; + int dynamicRange; + int nGappixelsX; + int nGappixelsY; +}; + +/** + * @short structure allocated in shared memory to store detector settings for IPC and cache + */ +struct sharedSlsDetector { + + /* FIXED PATTERN FOR STATIC FUNCTIONS. DO NOT CHANGE, ONLY APPEND ------*/ + + /** shared memory version */ + int shmversion; + + /** online flag - is set if the detector is connected, unset if socket + * connection is not possible */ + int onlineFlag; + + /** stopped flag - is set if an acquisition error occurs or the detector + * is stopped manually. Is reset to 0 at the start of the acquisition */ + int stoppedFlag; + + /** is the hostname (or IP address) of the detector. needs to be set + * before starting the communication */ + char hostname[MAX_STR_LENGTH]; + + /** detector type \ see :: detectorType*/ + slsDetectorDefs::detectorType myDetectorType; + + /** END OF FIXED PATTERN -----------------------------------------------*/ + + /** Detector offset in the X & Y direction in the multi detector structure */ + int offset[2]; + + /** Number of detectors in multi list in x dir and y dir */ + int multiSize[2]; + + /** is the port used for control functions */ + int controlPort; + + /** is the port used to stop the acquisition */ + int stopPort; + + /** path of the trimbits/settings files */ + char settingsDir[MAX_STR_LENGTH]; + + /** number of energies at which the detector has been trimmed */ + int nTrimEn; + + /** list of the energies at which the detector has been trimmed */ + int trimEnergies[MAX_TRIMEN]; + + /** number of channels per chip */ + int nChans; + + /** number of channels per chip in one direction */ + int nChan[2]; + + /** number of chips per module*/ + int nChips; + + /** number of chips per module in one direction */ + int nChip[2]; + + /** number of dacs per module*/ + int nDacs; + + /** dynamic range of the detector data */ + int dynamicRange; + + /** size of the data that are transfered from the detector */ + int dataBytes; + + /** number of rois defined */ + int nROI; + + /** list of rois */ + slsDetectorDefs::ROI roiLimits[MAX_ROIS]; + + /** readout flags */ + slsDetectorDefs::readOutFlags roFlags; + + /** detector settings (standard, fast, etc.) */ + slsDetectorDefs::detectorSettings currentSettings; + + /** detector threshold (eV) */ + int currentThresholdEV; + + /** timer values */ + int64_t timerValue[slsDetectorDefs::timerIndex::MAX_TIMERS]; + + /** ip address/hostname of the receiver for client control via TCP */ + char receiver_hostname[MAX_STR_LENGTH]; + + /** is the TCP port used to communicate between client and the receiver */ + int receiverTCPPort; + + /** is the UDP port used to send data from detector to receiver */ + int receiverUDPPort; + + /** is the port used to communicate between second half module of + * Eiger/ Jungfrau detector and the receiver*/ + int receiverUDPPort2; + + /** ip address of the receiver for the detector to send packets to**/ + sls::IpAddr receiverUDPIP; + + /** ip address of the receiver for the 2nd interface of the detector to send packets to**/ + sls::IpAddr receiverUDPIP2; + + /** mac address of receiver for the detector to send packets to **/ + sls::MacAddr receiverUDPMAC; + + /** mac address of receiver for the 2nd interface of the detector to send packets to **/ + sls::MacAddr receiverUDPMAC2; + + /** mac address of the detector **/ + sls::MacAddr detectorMAC; + + /** mac address of the 2nd interface of the detector **/ + sls::MacAddr detectorMAC2; + + /** ip address of the detector **/ + sls::IpAddr detectorIP; + + /** ip address of the 2nd interface of the detector **/ + sls::IpAddr detectorIP2; + + /** number of udp interface */ + int numUDPInterfaces; + + /** selected udp interface */ + int selectedUDPInterface; + + /** online flag - is set if the receiver is connected, + * unset if socket connection is not possible */ + int receiverOnlineFlag; + + /** 10 Gbe enable*/ + int tenGigaEnable; + + /** flipped data across x or y axis */ + int flippedData[2]; + + /** tcp port from gui/different process to receiver (only data) */ + int zmqport; + + /** tcp port from receiver to gui/different process (only data) */ + int receiver_zmqport; + + /** data streaming (up stream) enable in receiver */ + bool receiver_upstream; + + /* Receiver read frequency */ + int receiver_read_freq; + + /** zmq tcp src ip address in client (only data) **/ + char zmqip[MAX_STR_LENGTH]; + + /** zmq tcp src ip address in receiver (only data) **/ + char receiver_zmqip[MAX_STR_LENGTH]; + + /** gap pixels enable */ + int gappixels; + + /** gap pixels in each direction */ + int nGappixels[2]; + + /** data bytes including gap pixels */ + int dataBytesInclGapPixels; + + /** additional json header */ + char receiver_additionalJsonHeader[MAX_STR_LENGTH]; + + /** detector control server software API version */ + int64_t detectorControlAPIVersion; + + /** detector stop server software API version */ + int64_t detectorStopAPIVersion; + + /** receiver server software API version */ + int64_t receiverAPIVersion; + + /** receiver frames discard policy */ + slsDetectorDefs::frameDiscardPolicy receiver_frameDiscardMode; + + /** receiver partial frames padding enable */ + bool rxFramePadding; + + /** activated receiver */ + bool activated; + + /** padding enable in deactivated receiver */ + bool receiver_deactivatedPaddingEnable; + + /** silent receiver */ + bool receiver_silentMode; + + /** path of the output files */ + char receiver_filePath[MAX_STR_LENGTH]; + + /** file name prefix */ + char receiver_fileName[MAX_STR_LENGTH]; + + /** file index */ + int rxFileIndex; + + /** file format */ + slsDetectorDefs::fileFormat rxFileFormat; + + /** frames per file */ + int rxFramesPerFile; + + /** filewriteenable */ + bool rxFileWrite; + + /** overwriteenable */ + bool rxFileOverWrite; +}; + +class slsDetector : public virtual slsDetectorDefs{ + public: + /** + * Constructor called when creating new shared memory + * @param type detector type + * @param multi_id multi detector shared memory id + * @param id sls detector id (position in detectors list) + * @param verify true to verify if shared memory version matches existing one + */ + explicit slsDetector(detectorType type, + int multi_id = 0, + int det_id = 0, + bool verify = true); + + /** + * Constructor called when opening existing shared memory + * @param multi_id multi detector shared memory id + * @param id sls detector id (position in detectors list) + * @param verify true to verify if shared memory version matches existing one + */ + explicit slsDetector(int multi_id = 0, + int det_id = 0, + bool verify = true); + + /** + * Destructor + */ + virtual ~slsDetector(); + + /** + * Check version compatibility with receiver software + * (if hostname/rx_hostname has been set/ sockets created) + * @param p port type control port or receiver port + * @returns FAIL for incompatibility, OK for compatibility + */ + int checkReceiverVersionCompatibility(); + + /** + * Check version compatibility with detector software + * @returns FAIL for incompatibility, OK for compatibility + */ + int checkDetectorVersionCompatibility(); + + /** + * Get ID or version numbers + * @param mode version type + * @returns Id or version number of that type + */ + int64_t getId(idMode mode); + + + int64_t getReceiverSoftwareVersion() const; + + /** + * Free shared memory without creating objects + * If this is called, must take care to update + * multiSlsDetectors thisMultiDetector->numberofDetectors + * avoiding creating the constructor classes and mapping + * @param multi_id multi detector Id + * @param slsId slsDetectorId or position of slsDetector in detectors list + */ + static void freeSharedMemory(int multi_id, int slsId); + + /** + * Free shared memory and delete shared memory structure + * occupied by the sharedSlsDetector structure + * Is only safe to call if one deletes the slsDetector object afterward + * and frees multi shared memory/updates thisMultiDetector->numberOfDetectors + */ + void freeSharedMemory(); + + /** + * Sets the hostname, if online flag is set connects to update the detector + * @param name hostname + */ + void setHostname(const std::string &hostname); + + /** + * Gets the hostname of detector + * @returns hostname + */ + std::string getHostname() const; + + /** + * Get detector type by connecting to the detector + * @returns detector tpe or GENERIC if failed + */ + static detectorType getTypeFromDetector(const std::string &hostname, int cport = DEFAULT_PORTNO); + + /** + * Get Detector type from shared memory variable + * @returns detector type from shared memory variable + */ + detectorType getDetectorTypeAsEnum() const; + + /** + * Gets string version of detector type from shared memory variable + * @returns string version of detector type from shared memory variable + */ + std::string getDetectorTypeAsString() const; + + /** + * Gets detector type from detector and set it in receiver + * @param type the detector type + * @returns detector type in receiver + */ + int setDetectorType(detectorType type = GET_DETECTOR_TYPE); + + /** + * Returns the total number of channels from shared memory + * @returns the total number of channels + */ + int getTotalNumberOfChannels() const; + + /** + * Update total number of channels (chiptestboard or moench) + * depending on the number of samples, roi, readout flags(ctb) + */ + void updateTotalNumberOfChannels(); + + /** + * Returns the total number of channels in dimension d from shared memory + * @param d dimension d + * @returns the total number of channels in dimension d + */ + int getTotalNumberOfChannels(dimension d) const; + + /** + * Returns the total number of channels of in dimension d including gap pixels + * from shared memory + * @param d dimension d + * @returns the total number of channels including gap pixels in dimension d + * including gap pixels + */ + int getTotalNumberOfChannelsInclGapPixels(dimension d) const; + + /** + * returns the number of channels per chip from shared memory (Mythen) + * @returns number of channels per chip + */ + int getNChans() const; + + /** + * returns the number of channels per chip in dimension d from shared memory (Mythen) + * @param d dimension d + * @returns number of channels per chip in dimension d + */ + int getNChans(dimension d) const; + + /** + * returns the number of chips per module from shared memory (Mythen) + * @returns number of chips per module + */ + int getNChips() const; + + /** + * returns the number of chips per module in dimension d from shared memory (Mythen) + * @param d dimension d + * @returns number of chips per module in dimension d + */ + int getNChips(dimension d) const; + + /** + * Get Detector offset from shared memory in dimension d + * @param d dimension d + * @returns offset in dimension d + */ + int getDetectorOffset(dimension d) const; + + /** + * Set Detector offset in shared memory in dimension d + * @param d dimension d + * @param off offset for detector + */ + void setDetectorOffset(dimension d, int off); + + /** + * Set Detector offset in shared memory in dimension d + * @param detx number of detectors in X dir in multi list + * @param dety number of detectors in Y dir in multi list + */ + void updateMultiSize(int detx, int dety); + + /** + * Checks if the detector is online and sets the online flag + * @param online if GET_ONLINE_FLAG, only returns shared memory online flag, + * else sets the detector in online/offline state + * if OFFLINE_FLAG, (i.e. no communication to the detector - using only local structure - no data acquisition possible!); + * if ONLINE_FLAG, detector in online state (i.e. communication to the detector updating the local structure) + * @returns online/offline status + */ + int setOnline(int value = GET_ONLINE_FLAG); + + /** + * Returns the online flag + */ + int getOnlineFlag() const; + + /** + * Checks if each of the detector is online/offline + * @returns empty string if it is online + * else returns hostname if it is offline + */ + std::string checkOnline(); + + int setControlPort(int port_number); + + /** + * Returns the detector TCP control port \sa sharedSlsDetector + * @returns the detector TCP control port + */ + int getControlPort() const; + + int setStopPort(int port_number); + + /** + * Returns the detector TCP stop port \sa sharedSlsDetector + * @returns the detector TCP stop port + */ + int getStopPort() const; + + int setReceiverPort(int port_number); + + /** + * Returns the receiver TCP port \sa sharedSlsDetector + * @returns the receiver TCP port + */ + int getReceiverPort() const; + + /** + * Lock server for this client IP + * @param p 0 to unlock, 1 to lock (-1 gets) + * @returns 1 for locked or 0 for unlocked + */ + int lockServer(int lock = -1); + + /** + * Get last client IP saved on detector server + * @returns last client IP saved on detector server + */ + std::string getLastClientIP(); + + /** + * Exit detector server + * @returns OK or FAIL + */ + int exitServer(); + + /** + * Executes a system command on the detector server + * e.g. mount an nfs disk, reboot and returns answer etc. + * @param cmd command to be executed + * @returns OK or FAIL + */ + int execCommand(const std::string &cmd); + + /** + * Updates some of the shared memory receiving the data from the detector + * @returns OK + */ + int updateDetectorNoWait(sls::ClientSocket &client); + + /** + * Updates some of the shared memory receiving the data from the detector + * calls updateDetectorNoWait + * @returns OK or FAIL or FORCE_RET + */ + int updateDetector(); + + /** + * Write current configuration to a file + * calls writeConfigurationFile giving it a stream to write to + * @param fname configuration file name + * @param m multiSlsDetector reference to parse commands + * @returns OK or FAIL + */ + int writeConfigurationFile(const std::string &fname, multiSlsDetector *m); + + /** + * Write current configuration to a stream + * @param outfile outstream + * @param m multiSlsDetector reference to parse commands + * @returns OK or FAIL + */ + int writeConfigurationFile(std::ofstream &outfile, multiSlsDetector *m); + + /** + * Get detector settings + * @returns current settings + */ + detectorSettings getSettings(); + + /** + * Load detector settings from the settings file picked from the trimdir/settingsdir + * Eiger only stores in shared memory ( a get will overwrite this) + * For Eiger, one must use threshold + * Gotthard, Propix, Jungfrau and Moench only sends the settings enum to the detector + * @param isettings settings + * @returns current settings + */ + detectorSettings setSettings(detectorSettings isettings); + + /** + * Send detector settings only (set only for Jungfrau, Gotthard, Moench, get for all) + * Only the settings enum is sent to the detector, where it will + * initialize al the dacs already hard coded in the detector server + * @param isettings settings + * @returns current settings + */ + detectorSettings sendSettingsOnly(detectorSettings isettings); + + /** + * Get threshold energy (Mythen and Eiger) + * @returns current threshold value in ev (-1 failed) + */ + int getThresholdEnergy(); + + /** + * Set threshold energy (Mythen and Eiger) + * For Eiger, calls setThresholdEneryAndSettings + * @param e_eV threshold in eV + * @param isettings ev. change settings + * @param tb 1 to include trimbits, 0 to exclude + * @returns current threshold value in ev (-1 failed) + */ + int setThresholdEnergy(int e_eV, detectorSettings isettings = GET_SETTINGS, int tb = 1); + + /** + * Set threshold energy and settings (Eiger only) + * @param e_eV threshold in eV + * @param isettings ev. change settings + * @param tb 1 to include trimbits, 0 to exclude + * @returns OK if successful, else FAIL + */ + int setThresholdEnergyAndSettings(int e_eV, detectorSettings isettings, int tb = 1); + + /** + * Returns the detector trimbit/settings directory \sa sharedSlsDetector + * @returns the trimbit/settings directory + */ + std::string getSettingsDir(); + + /** + * Sets the detector trimbit/settings directory \sa sharedSlsDetector + * @param s trimbits/settings directory + * @returns the trimbit/settings directory + */ + std::string setSettingsDir(const std::string &dir); + + /** + * Loads the modules settings/trimbits reading from a specific file + * file name extension is automatically generated. + * @param fname specific settings/trimbits file + * returns OK or FAIL + */ + int loadSettingsFile(const std::string &fname); + + /** + * Saves the modules settings/trimbits to a specific file + * file name extension is automatically generated. + * @param fname specific settings/trimbits file + * returns OK or FAIL + */ + int saveSettingsFile(const std::string &fname); + + /** + * Get run status of the detector + * @returns the status of the detector + */ + runStatus getRunStatus(); + + /** + * Prepares detector for acquisition (Eiger) + * @returns OK or FAIL + */ + int prepareAcquisition(); + + /** + * Start detector acquisition (Non blocking) + * @returns OK or FAIL if even one does not start properly + */ + int startAcquisition(); + + /** + * Stop detector acquisition + * @returns OK or FAIL + */ + int stopAcquisition(); + + /** + * Give an internal software trigger to the detector (Eiger only) + * @return OK or FAIL + */ + int sendSoftwareTrigger(); + + /** + * Start detector acquisition and read all data (Blocking until end of acquisition) + * @returns OK or FAIL + */ + int startAndReadAll(); + + /** + * Start readout (without exposure or interrupting exposure) (Eiger store in ram) + * @returns OK or FAIL + */ + int startReadOut(); + + /** + * Requests and receives all data from the detector (Eiger store in ram) + * @returns OK or FAIL + */ + int readAll(); + + /** + * Configures in detector the destination for UDP packets + * @returns OK or FAIL + */ + int configureMAC(); + + /** + * Set/get timer value (not all implemented for all detectors) + * @param index timer index + * @param t time in ns or number of...(e.g. frames, gates, probes) + * @returns timer set value in ns or number of...(e.g. frames, gates, probes) + */ + int64_t setTimer(timerIndex index, int64_t t = -1); + + /** + * Set/get timer value left in acquisition (not all implemented for all detectors) + * @param index timer index + * @param t time in ns or number of...(e.g. frames, gates, probes) + * @returns timer set value in ns or number of...(e.g. frames, gates, probes) + */ + int64_t getTimeLeft(timerIndex index); + + /** + * Set speed + * @param sp speed type (clkdivider option for Jungfrau and Eiger, + * adcphase for Gotthard, others for CTB & Moench) + * @param value (clkdivider 0,1,2 for full, half and quarter speed). Other values check manual + * @returns value of speed set + */ + int setSpeed(speedVariable sp, int value = -1, int mode = 0); + + /** + * Set/get dynamic range and updates the number of dataBytes + * (Eiger: If i is 32, also sets clkdivider to 2, if 16, sets clkdivider to 1) + * @param i dynamic range (-1 get) + * @returns current dynamic range + * \sa sharedSlsDetector + */ + int setDynamicRange(int n = -1); + + /** + * Recalculated number of data bytes + * @returns tota number of data bytes + */ + int getDataBytes(); + + /** + * Recalculated number of data bytes including gap pixels + * @returns tota number of data bytes including gap pixels + */ + int getDataBytesInclGapPixels(); + + /** + * Set/get dacs value + * @param val value (in V) + * @param index DAC index + * @param mV 0 in dac units or 1 in mV + * @returns current DAC value + */ + int setDAC(int val, dacIndex index, int mV); + + /** + * Get adc value + * @param index adc(DAC) index + * @returns current adc value (temperature for eiger and jungfrau in millidegrees) + */ + int getADC(dacIndex index); + + /** + * Set/get timing mode + * @param pol timing mode (-1 gets) + * @returns current timing mode + */ + externalCommunicationMode setExternalCommunicationMode(externalCommunicationMode pol = GET_EXTERNAL_COMMUNICATION_MODE); + + /** + * Set/get external signal flags (to specify triggerinrising edge etc) (Gotthard, Mythen) + * @param pol external signal flag (-1 gets) + * @param signalindex singal index (0 - 3) + * @returns current timing mode + */ + externalSignalFlag setExternalSignalFlags(externalSignalFlag pol = GET_EXTERNAL_SIGNAL_FLAG, int signalindex = 0); + + /** + * Set/get readout flags (Eiger, Mythen) + * @param flag readout flag (Eiger options: parallel, nonparallel, safe etc.) (-1 gets) + * @returns readout flag + */ + int setReadOutFlags(readOutFlags flag = GET_READOUT_FLAGS); + + /** + * Write in a register. For Advanced users + * @param addr address of register + * @param val value to write into register + * @returns value read after writing + */ + uint32_t writeRegister(uint32_t addr, uint32_t val); + + /** + * Read from a register. For Advanced users + * @param addr address of register + * @returns value read from register + */ + uint32_t readRegister(uint32_t addr); + + /** + * Set bit in a register. For Advanced users + * @param addr address of register + * @param n nth bit + * @returns value read from register + */ + uint32_t setBit(uint32_t addr, int n); + + /** + * Clear bit in a register. For Advanced users + * @param addr address of register + * @param n nth bit + * @returns value read from register + */ + uint32_t clearBit(uint32_t addr, int n); + + /** + * Validates the format of the detector MAC address and sets it \sa sharedSlsDetector + * @param detectorMAC detector MAC address + * @returns the detector MAC address + */ + std::string setDetectorMAC(const std::string &detectorMAC); + + /** + * Returns the detector MAC address\sa sharedSlsDetector + * @returns the detector MAC address + */ + sls::MacAddr getDetectorMAC(); + + /** + * Validates the format of the detector MAC address (bottom half) and sets it (Jungfrau only) + * @param detectorMAC detector MAC address (bottom half) + * @returns the detector MAC address (bottom half) + */ + std::string setDetectorMAC2(const std::string &detectorMAC); + + /** + * Returns the detector MAC address (bottom half) Jungfrau only + * @returns the detector MAC address (bottom half) + */ + sls::MacAddr getDetectorMAC2(); + + /** + * Validates the format of the detector IP address and sets it \sa sharedSlsDetector + * @param detectorIP detector IP address + * @returns the detector IP address + */ + std::string setDetectorIP(const std::string &detectorIP); + + /** + * Returns the detector IP address\sa sharedSlsDetector + * @returns the detector IP address + */ + sls::IpAddr getDetectorIP() const; + + /** + * Validates the format of the detector IP address (bottom half) and sets it (Jungfrau only) + * @param detectorIP detector IP address (bottom half) + * @returns the detector IP address (bottom half) + */ + std::string setDetectorIP2(const std::string &detectorIP); + + /** + * Returns the detector IP address (bottom half) Jungfrau only + * @returns the detector IP address (bottom half) + */ + sls::IpAddr getDetectorIP2() const; + + /** + * Validates and sets the receiver. + * Also updates the receiver with all the shared memory parameters significant for the receiver + * Also configures the detector to the receiver as UDP destination + * @param receiver receiver hostname or IP address + * @returns the receiver IP address from shared memory + */ + std::string setReceiverHostname(const std::string &receiver); + + /** + * Returns the receiver IP address\sa sharedSlsDetector + * @returns the receiver IP address + */ + std::string getReceiverHostname() const; + + /** + * Validates the format of the receiver UDP IP address and sets it \sa sharedSlsDetector + * @param udpip receiver UDP IP address + * @returns the receiver UDP IP address + */ + std::string setReceiverUDPIP(const std::string &udpip); + + /** + * Returns the receiver UDP IP address\sa sharedSlsDetector + * @returns the receiver UDP IP address + */ + sls::IpAddr getReceiverUDPIP() const; + + /** + * Validates the format of the receiver UDP IP address (bottom half) and sets it(Jungfrau only) + * @param udpip receiver UDP IP address (bottom half) + * @returns the receiver UDP IP address (bottom half) + */ + std::string setReceiverUDPIP2(const std::string &udpip); + + /** + * Returns the receiver UDP IP address (bottom half) Jungfrau only + * @returns the receiver UDP IP address (bottom half) + */ + sls::IpAddr getReceiverUDPIP2() const; + + /** + * Validates the format of the receiver UDP MAC address and sets it \sa sharedSlsDetector + * @param udpmac receiver UDP MAC address + * @returns the receiver UDP MAC address + */ + std::string setReceiverUDPMAC(const std::string &udpmac); + + /** + * Returns the receiver UDP MAC address\sa sharedSlsDetector + * @returns the receiver UDP MAC address + */ + sls::MacAddr getReceiverUDPMAC() const; + + /** + * Validates the format of the receiver UDP MAC address (bottom half) and sets it (Jungfrau only) + * @param udpmac receiver UDP MAC address (bottom half) + * @returns the receiver UDP MAC address (bottom half) + */ + std::string setReceiverUDPMAC2(const std::string &udpmac); + + /** + * Returns the receiver UDP MAC address (bottom half) Jungfrau only + * @returns the receiver UDP MAC address (bottom half) + */ + sls::MacAddr getReceiverUDPMAC2() const; + + /** + * Sets the receiver UDP port\sa sharedSlsDetector + * @param udpport receiver UDP port + * @returns the receiver UDP port + */ + int setReceiverUDPPort(int udpport); + + /** + * Returns the receiver UDP port\sa sharedSlsDetector + * @returns the receiver UDP port + */ + int getReceiverUDPPort() const; + + /** + * Sets the receiver UDP port 2\sa sharedSlsDetector (Eiger and Jungfrau only) + * @param udpport receiver UDP port 2 + * @returns the receiver UDP port 2 + */ + int setReceiverUDPPort2(int udpport); + + /** + * Returns the receiver UDP port 2 of same interface\sa sharedSlsDetector (Eiger and Jungfrau only) + * @returns the receiver UDP port 2 of same interface + */ + int getReceiverUDPPort2() const; + + /** + * Sets the number of UDP interfaces to stream data from detector (Jungfrau only) + * @param n number of interfaces. Options 1 or 2. + * @returns the number of interfaces + */ + int setNumberofUDPInterfaces(int n); + + /** + * Returns the number of UDP interfaces to stream data from detector (Jungfrau only) + * @returns the number of interfaces + */ + int getNumberofUDPInterfaces() const; + + /** + * Selects the UDP interfaces to stream data from detector. Effective only when number of interfaces is 1. (Jungfrau only) + * @param n selected interface. Options 1 or 2. + * @returns the interface selected + */ + int selectUDPInterface(int n); + + /** + * Returns the UDP interfaces to stream data from detector. Effective only when number of interfaces is 1. (Jungfrau only) + * @returns the interface selected + */ + int getSelectedUDPInterface() const; + + /** + * Sets the client zmq port\sa sharedSlsDetector + * @param port client zmq port + */ + void setClientStreamingPort(int port); + + /** + * Returns the client zmq port \sa sharedSlsDetector + * @returns the client zmq port + */ + int getClientStreamingPort(); + + /** + * Sets the receiver zmq port\sa sharedSlsDetector + * @param port receiver zmq port + */ + void setReceiverStreamingPort(int port); + + /** + * Returns the receiver zmq port \sa sharedSlsDetector + * @returns the receiver zmq port + */ + int getReceiverStreamingPort(); + + /** + * Sets the client zmq ip\sa sharedSlsDetector + * @param sourceIP client zmq ip + */ + void setClientStreamingIP(const std::string &sourceIP); + + /** + * Returns the client zmq ip \sa sharedSlsDetector + * @returns the client zmq ip, returns "none" if default setting and no custom ip set + */ + std::string getClientStreamingIP(); + + /** + * Sets the receiver zmq ip\sa sharedSlsDetector + * @param sourceIP receiver zmq ip. If empty, uses rx_hostname + */ + void setReceiverStreamingIP(std::string sourceIP); + + /** + * Returns the receiver zmq ip \sa sharedSlsDetector + * @returns the receiver zmq ip, returns "none" if default setting and no custom ip set + */ + std::string getReceiverStreamingIP(); + + /** + * Sets the transmission delay for left, right or entire frame + * (Eiger, Jungfrau(only entire frame)) + * @param index type of delay + * @param delay delay + * @returns transmission delay + */ + int setDetectorNetworkParameter(networkParameter index, int delay); + + /** + * Sets the additional json header\sa sharedSlsDetector + * @param jsonheader additional json header + * @returns additional json header, returns "none" if default setting and no custom ip set + */ + std::string setAdditionalJsonHeader(const std::string &jsonheader); + + /** + * Returns the additional json header \sa sharedSlsDetector + * @returns the additional json header, returns "none" if default setting and no custom ip set + */ + std::string getAdditionalJsonHeader(); + + /** + * Sets the value for the additional json header parameter if found, else append it + * @param key additional json header parameter + * @param value additional json header parameter value (cannot be empty) + * @returns the additional json header parameter value, + * empty if no parameter found in additional json header + */ + std::string setAdditionalJsonParameter(const std::string &key, const std::string &value); + + /** + * Returns the additional json header parameter value + * @param key additional json header parameter + * @returns the additional json header parameter value, + * empty if no parameter found in additional json header + */ + std::string getAdditionalJsonParameter(const std::string &key); + + /** + * Sets the receiver UDP socket buffer size + * @param udpsockbufsize additional json header + * @returns receiver udp socket buffer size + */ + int64_t setReceiverUDPSocketBufferSize(int64_t udpsockbufsize = -1); + + /** + * Returns the receiver UDP socket buffer size\sa sharedSlsDetector + * @returns the receiver UDP socket buffer size + */ + int64_t getReceiverUDPSocketBufferSize(); + + /** + * Returns the receiver real UDP socket buffer size\sa sharedSlsDetector + * @returns the receiver real UDP socket buffer size + */ + int64_t getReceiverRealUDPSocketBufferSize(); + + /** + * Execute a digital test (Gotthard, Mythen) + * @param mode testmode type + * @param value 1 to set or 0 to clear the digital test bit + * @returns result of test + */ + int digitalTest(digitalTestMode mode, int ival = -1); + + /** + * Load dark or gain image to detector (Gotthard) + * @param index image type, 0 for dark image and 1 for gain image + * @param fname file name from which to load image + * @returns OK or FAIL + */ + int loadImageToDetector(imageType index, const std::string &fname); + + /** + * Called from loadImageToDetector to send the image to detector + * @param index image type, 0 for dark image and 1 for gain image + * @param imageVals image + * @returns OK or FAIL + */ + int sendImageToDetector(imageType index, int16_t imageVals[]); + + /** + * Writes the counter memory block from the detector (Gotthard) + * @param fname file name to load data from + * @param startACQ is 1 to start acquisition after reading counter + * @returns OK or FAIL + */ + int writeCounterBlockFile(const std::string &fname, int startACQ = 0); + + /** + * Gets counter memory block in detector (Gotthard) + * @param image counter memory block from detector + * @param startACQ 1 to start acquisition afterwards, else 0 + * @returns OK or FAIL + */ + int getCounterBlock(int16_t image[], int startACQ = 0); + + /** + * Resets counter in detector + * @param startACQ is 1 to start acquisition after resetting counter + * @returns OK or FAIL + */ + int resetCounterBlock(int startACQ = 0); + + /** + * Set/get counter bit in detector (Gotthard) + * @param i is -1 to get, 0 to reset and any other value to set the counter bit + * @returns the counter bit in detector + */ + int setCounterBit(int i = -1); + + /** + * send ROI to processor (moench only) + * @returns OK or FAIL + */ + int sendROIToProcessor(); + + /** + * Set ROI (Gotthard) + * At the moment only one set allowed + * @param n number of rois + * @param roiLimits array of roi + * @returns OK or FAIL + */ + int setROI(int n = -1, ROI roiLimits[] = nullptr); + + /** + * Get ROI from each detector and convert it to the multi detector scale (Gotthard) + * @param n number of rois + * @returns OK or FAIL + */ + const slsDetectorDefs::ROI * getROI(int &n); + + /** + * Returns number of rois + * @returns number of ROIs + */ + int getNRoi(); + + /** + * Send ROI to the detector after calculating + * from setROI + * @param n number of ROIs (-1 to get) + * @param roiLimits ROI + * @returns OK or FAIL + */ + int sendROI(int n = -1, ROI roiLimits[] = nullptr); + + /** + * Write to ADC register (Gotthard, Jungfrau, ChipTestBoard). For expert users + * @param addr address of adc register + * @param val value + * @returns return value (mostly -1 as it can't read adc register) + */ + int writeAdcRegister(int addr, int val); + + /** + * Activates/Deactivates the detector (Eiger only) + * @param enable active (1) or inactive (0), -1 gets + * @returns 0 (inactive) or 1 (active)for activate mode + */ + int activate(int const enable = -1); + + /** + * Set deactivated Receiver padding mode (Eiger only) + * @param padding padding option for deactivated receiver. Can be 1 (padding), 0 (no padding), -1 (gets) + * @returns 1 (padding), 0 (no padding), -1 (inconsistent values) for padding option + */ + int setDeactivatedRxrPaddingMode(int padding = -1); + + /** + * Returns the enable if data will be flipped across x or y axis (Eiger) + * @param d axis across which data is flipped + * @returns 1 for flipped, else 0 + */ + int getFlippedData(dimension d = X) const; + + /** + * Sets the enable which determines if + * data will be flipped across x or y axis (Eiger) + * @param d axis across which data is flipped + * @param value 0 or 1 to reset/set or -1 to get value + * @returns enable flipped data across x or y axis + */ + int setFlippedData(dimension d = X, int value = -1); + + /** + * Sets all the trimbits to a particular value (Eiger) + * @param val trimbit value + * @returns OK or FAIL + */ + int setAllTrimbits(int val); + + /** + * Enable gap pixels, only for Eiger and for 8,16 and 32 bit mode. (Eiger) + * 4 bit mode gap pixels only in gui call back + * @param val 1 sets, 0 unsets, -1 gets + * @returns gap pixel enable or -1 for error + */ + int enableGapPixels(int val = -1); + + /** + * Sets the number of trim energies and their value (Eiger) + * \sa sharedSlsDetector + * @param nen number of energies + * @param vector os trimmed energies + * @returns number of trim energies + */ + int setTrimEn(std::vector energies={}); + + /** + * Returns a vector with the trimmed energies (Eiger) + * \sa sharedSlsDetector + * @returns vector with the trimmed energies + */ + std::vector getTrimEn(); + + /** + * Pulse Pixel (Eiger) + * @param n is number of times to pulse + * @param x is x coordinate + * @param y is y coordinate + * @returns OK or FAIL + */ + int pulsePixel(int n = 0, int x = 0, int y = 0); + + /** + * Pulse Pixel and move by a relative value (Eiger) + * @param n is number of times to pulse + * @param x is relative x value + * @param y is relative y value + * @returns OK or FAIL + */ + int pulsePixelNMove(int n = 0, int x = 0, int y = 0); + + /** + * Pulse Chip (Eiger) + * @param n is number of times to pulse + * @returns OK or FAIL + */ + int pulseChip(int n = 0); + + /** + * Set/gets threshold temperature (Jungfrau) + * @param val value in millidegrees, -1 gets + * @returns threshold temperature in millidegrees + */ + int setThresholdTemperature(int val = -1); + + /** + * Enables/disables temperature control (Jungfrau) + * @param val value, -1 gets + * @returns temperature control enable + */ + int setTemperatureControl(int val = -1); + + /** + * Resets/ gets over-temperature event (Jungfrau) + * @param val value, -1 gets + * @returns over-temperature event + */ + int setTemperatureEvent(int val = -1); + + /** + * Set storage cell that stores first acquisition of the series (Jungfrau) + * @param value storage cell index. Value can be 0 to 15. (-1 gets) + * @returns the storage cell that stores the first acquisition of the series + */ + int setStoragecellStart(int pos = -1); + + /** + * Programs FPGA with pof file (Jungfrau, CTB, Moench) + * @param buffer programming file in memory + * @returns OK or FAIL + */ + int programFPGA(std::vector buffer); + + /** + * Resets FPGA (Jungfrau) + * @returns OK or FAIL + */ + int resetFPGA(); + + /** + * Copies detector server from tftp and changes respawn server (Not Eiger) + * @param fname name of detector server binary + * @param hostname name of pc to tftp from + * @returns OK or FAIL + */ + int copyDetectorServer(const std::string &fname, const std::string &hostname); + + /** + * Reboot detector controller (blackfin/ powerpc) + * @returns OK or FAIL + */ + int rebootController(); + + /** + * Power on/off Chip (Jungfrau) + * @param ival on is 1, off is 0, -1 to get + * @returns OK or FAIL + */ + int powerChip(int ival = -1); + + /** + * Automatic comparator disable (Jungfrau) + * @param ival on is 1, off is 0, -1 to get + * @returns OK or FAIL + */ + int setAutoComparatorDisableMode(int ival = -1); + + /** + * Returns the trimbits from the detector's shared memmory (Eiger) + * @param retval is the array with the trimbits + * @returns total number of channels for the detector + */ + int getChanRegs(double *retval); + + /** + * Configure Module (Eiger) + * Called for loading trimbits and settings settings to the detector + * @param module module to be set - must contain correct module number and + * also channel and chip registers + * @param tb 1 to include trimbits, 0 to exclude (used for eiger) + * @returns ok or fail + * \sa ::sls_detector_module + */ + int setModule(sls_detector_module module, int tb = 1); + + /** + * Get module structure from detector (all detectors) + * @returns pointer to module structure (which has been created and must then be deleted) + */ + sls_detector_module *getModule(); + + /** + * Set Rate correction (Mythen, Eiger) + * @param t dead time in ns - if 0 disable correction, + * if >0 set dead time to t, if < 0 set deadtime to default dead time + * for current settings + * @returns 0 if rate correction disabled, >0 otherwise + */ + int setRateCorrection(int64_t t = 0); + + /** + * Get rate correction Eiger) + * @returns 0 if rate correction disabled, > 0 otherwise + */ + int64_t getRateCorrection(); + + /** + * Prints receiver configuration + * @param level print level + */ + void printReceiverConfiguration(TLogLevel level = logINFO); + + /** + * Checks if receiver is online and set flag + * Also initializes the data socekt + * @param online 1 to set online, 0 to set offline, -1 gets + * @returns online, offline (from shared memory) + */ + int setReceiverOnline(int value = GET_ONLINE_FLAG); + + int getReceiverOnline() const; + + /** + * Checks if the receiver is really online + * @returns empty string if online, else returns receiver hostname + */ + std::string checkReceiverOnline(); + + /** + * Locks/Unlocks the connection to the receiver + * @param lock sets (1), usets (0), gets (-1) the lock + * @returns lock status of the receiver + */ + int lockReceiver(int lock = -1); + + /** + * Returns the IP of the last client connecting to the receiver + * @returns the IP of the last client connecting to the receiver + */ + std::string getReceiverLastClientIP(); + + /** + * Exits the receiver TCP server + * @retutns OK or FAIL + */ + int exitReceiver(); + + /** + * Executes a system command on the receiver server + * e.g. mount an nfs disk, reboot and returns answer etc. + * @param cmd command to be executed + * @returns OK or FAIL + */ + int execReceiverCommand(const std::string &cmd); + + /** + updates the shared memory receiving the data from the detector (without asking and closing the connection + /returns OK + */ + // int updateReceiverNoWait(sls::ClientSocket &receiver); + + /** + * Updates the shared memory receiving the data from the detector + * @returns OK or FAIL + */ + int updateCachedReceiverVariables() const; + + /** + * Send the multi detector size to the detector + * @param detx number of detectors in x dir + * @param dety number of detectors in y dir + */ + void sendMultiDetectorSize(); + + /** + * Send the detector pos id to the receiver + * for various file naming conventions for multi detectors in receiver + */ + void setDetectorId(); + + /** + * Send the detector host name to the receiver + * for various handshaking required with the detector + */ + void setDetectorHostname(); + + /** + * Returns output file directory + * @returns output file directory + */ + std::string getFilePath(); + + /** + * Sets up the file directory + * @param s file directory + * @returns file dir + */ + std::string setFilePath(const std::string &path); + + /** + * Returns file name prefix + * @returns file name prefix + */ + std::string getFileName(); + + /** + * Sets up the file name prefix + * @param s file name prefix + * @returns file name prefix + */ + std::string setFileName(const std::string &fname); + + /** + * Sets the max frames per file in receiver + * @param f max frames per file + * @returns max frames per file in receiver + */ + int setFramesPerFile(int frames); + + int getFramesPerFile() const; + + /** + * Sets the frames discard policy in receiver + * @param f frames discard policy + * @returns frames discard policy set in receiver + */ + frameDiscardPolicy setReceiverFramesDiscardPolicy(frameDiscardPolicy f = GET_FRAME_DISCARD_POLICY); + + /** + * Sets the partial frames padding enable in receiver + * @param f partial frames padding enable + * @returns partial frames padding enable in receiver + */ + bool setPartialFramesPadding(bool padding); + bool getPartialFramesPadding() const; + + /** + * Returns file format + * @returns file format + */ + fileFormat getFileFormat() const; + + /** + * Sets up the file format + * @param f file format + * @returns file format + */ + fileFormat setFileFormat(fileFormat f); + + /** + * Returns file index + * @returns file index + */ + int getFileIndex(); + + /** + * Sets up the file index + * @param i file index + * @returns file index + */ + int setFileIndex(int i); + + /** + * Gets the file index + * @returns file index + */ + + int getFileIndex() const; + /** + * increments file index + * @returns the file index + */ + int incrementFileIndex(); + + /** + * Receiver starts listening to packets + * @returns OK or FAIL + */ + int startReceiver(); + + /** + * Stops the listening mode of receiver + * @returns OK or FAIL + */ + int stopReceiver(); + + /** + * Gets the status of the listening mode of receiver + * @returns status + */ + runStatus getReceiverStatus(); + + /** + * Gets the number of frames caught by receiver + * @returns number of frames caught by receiver + */ + int getFramesCaughtByReceiver(); + + /** + * Gets the current frame index of receiver + * @returns current frame index of receiver + */ + int getReceiverCurrentFrameIndex(); + + /** + * Resets framescaught in receiver + * Use this when using startAcquisition instead of acquire + * @returns OK or FAIL + */ + int resetFramesCaught(); + + /** + * Sets/Gets receiver file write enable + * @param enable 1 or 0 to set/reset file write enable + * @returns file write enable + */ + bool setFileWrite(bool value); + + bool getFileWrite() const; + + /** + * Sets file overwrite in the receiver + * @param enable true or false to set/reset file overwrite enable + * @returns file overwrite enable + */ + bool setFileOverWrite(bool value); + + /** + * Gets file overwrite in the receiver + * @returns file overwrite enable + */ + bool getFileOverWrite() const; + + /** + * (previously setReadReceiverFrequency) + * Sets the receiver streaming frequency + * @param freq nth frame streamed out, if 0, streamed out at a timer of 200 ms + * @param detPos -1 for all detectors in list or specific detector position + * @returns receiver streaming frequency + */ + int setReceiverStreamingFrequency(int freq = -1); + + /** + * (previously setReceiverReadTimer) + * Sets the receiver streaming timer + * If receiver streaming frequency is 0, then this timer between each + * data stream is set. Default is 200 ms. + * @param time_in_ms timer between frames + * @returns receiver streaming timer in ms + */ + int setReceiverStreamingTimer(int time_in_ms = 500); + + /** + * Enable or disable streaming data from receiver to client + * @param enable 0 to disable 1 to enable -1 to only get the value + * @returns data streaming from receiver enable + */ + bool enableDataStreamingFromReceiver(int enable = -1); + + /** + * Enable/disable or 10Gbe + * @param i is -1 to get, 0 to disable and 1 to enable + * @returns if 10Gbe is enabled + */ + int enableTenGigabitEthernet(int i = -1); + + /** + * Set/get receiver fifo depth + * @param i is -1 to get, any other value to set the fifo deph + * @returns the receiver fifo depth + */ + int setReceiverFifoDepth(int i = -1); + + /** + * Set/get receiver silent mode + * @param i is -1 to get, 0 unsets silent mode, 1 sets silent mode + * @returns the receiver silent mode enable + */ + bool setReceiverSilentMode(int i = -1); + + /** + * If data streaming in receiver is enabled, + * restream the stop dummy packet from receiver + * Used usually for Moench, + * in case it is lost in network due to high data rate + * @returns OK if success else FAIL + */ + int restreamStopFromReceiver(); + + /** + * Opens pattern file and sends pattern to CTB + * @param fname pattern file to open + * @returns OK/FAIL + */ + int setPattern(const std::string &fname); + + /** + * Writes a pattern word to the CTB + * @param addr address of the word, -1 is I/O control register, -2 is clk control register + * @param word 64bit word to be written, -1 gets + * @returns actual value + */ + uint64_t setPatternWord(uint64_t addr, uint64_t word = -1); + + /** + * Sets the pattern or loop limits in the CTB + * @param level -1 complete pattern, 0,1,2, loop level + * @param start start address if >=0 + * @param stop stop address if >=0 + * @param n number of loops (if level >=0) + * @returns OK/FAIL + */ + int setPatternLoops(int level, int &start, int &stop, int &n); + + /** + * Sets the wait address in the CTB + * @param level 0,1,2, wait level + * @param addr wait address, -1 gets + * @returns actual value + */ + int setPatternWaitAddr(uint64_t level, uint64_t addr = -1); + + /** + * Sets the wait time in the CTB + * @param level 0,1,2, wait level + * @param t wait time, -1 gets + * @returns actual value + */ + uint64_t setPatternWaitTime(uint64_t level, uint64_t t = -1); + + /** + * Sets the mask applied to every pattern + * @param mask mask to be applied + * @returns OK or FAIL + */ + int setPatternMask(uint64_t mask); + + /** + * Gets the mask applied to every pattern + * @returns mask set + */ + uint64_t getPatternMask(); + + /** + * Selects the bits that the mask will be applied to for every pattern + * @param mask mask to select bits + * @returns OK or FAIL + */ + int setPatternBitMask(uint64_t mask); + + /** + * Gets the bits that the mask will be applied to for every pattern + * @returns mask of bits selected + */ + uint64_t getPatternBitMask(); + + /** + * Set LED Enable (Moench, CTB only) + * @param enable 1 to switch on, 0 to switch off, -1 gets + * @returns LED enable + */ + int setLEDEnable(int enable = -1); + + /** + * Set Digital IO Delay (Moench, CTB only) + * @param digital IO mask to select the pins + * @param delay delay in ps(1 bit=25ps, max of 775 ps) + * @returns OK or FAIL + */ + int setDigitalIODelay(uint64_t pinMask, int delay); + + private: + /** + * Get Detector Type from Shared Memory (opening shm without verifying size) + * @param multi_id multi detector Id + * @param verify true to verify if shm size matches existing one + * @returns detector type + */ + detectorType getDetectorTypeFromShm(int multi_id, bool verify = true); + + /** + * Initialize shared memory + * @param created true if shared memory must be created, else false to open + * @param type type of detector + * @param multi_id multi detector Id + * @param verify true to verify if shm size matches existing one + * @returns true if the shared memory was created now + */ + void initSharedMemory(detectorType type, int multi_id, bool verify = true); + + /** + * Sets detector parameters depending detector type + * @param type detector type + * @param list structure of parameters to initialize depending on detector type + */ + void setDetectorSpecificParameters(detectorType type, detParameters &list); + + /** + * Initialize detector structure to defaults + * Called when new shared memory is created + * @param type type of detector + */ + void initializeDetectorStructure(detectorType type); + + /** + * Allocates the memory for a sls_detector_module structure and initializes it + * Uses current detector type + * @returns myMod the pointer to the allocate memory location + */ + sls_detector_module *createModule(); + + /** + * Allocates the memory for a sls_detector_module structure and initializes it + * Has detector type + * @param type detector type + * @returns myMod the pointer to the allocate dmemory location + */ + sls_detector_module *createModule(detectorType type); + + /** + * Frees the memory for a sls_detector_module structure + * @param myMod the pointer to the memory to be freed + */ + void deleteModule(sls_detector_module *myMod); + + /** + * Send a sls_detector_module structure over socket + * @param myMod module structure to send + * @returns number of bytes sent to the detector + */ + int sendModule(sls_detector_module *myMod, sls::ClientSocket& client); + + /** + * Receive a sls_detector_module structure over socket + * @param myMod module structure to receive + * @returns number of bytes received from the detector + */ + int receiveModule(sls_detector_module *myMod, sls::ClientSocket& client); + + /** + * Get MAC from the receiver using udpip and + * set up UDP connection in detector + * @returns Ok or FAIL + */ + int setUDPConnection(); + + /* + * Template function to do linear interpolation between two points (Eiger only) + */ + template + V linearInterpolation(const E x, const E x1, const E x2, const V y1, const V y2) { + double k = static_cast(y2 - y1) / (x2 - x1); + double m = y1 - k * x1; + int y = round(k * x + m); + return static_cast(y); + } + + /** + * interpolates dacs and trimbits between 2 trim files + * @param a first module structure + * @param b second module structure + * @param energy energy to trim at + * @param e1 reference trim value + * @param e2 reference trim value + * @param tb 1 to include trimbits, 0 to exclude (used for eiger) + * @returns the pointer to the module structure with interpolated values or NULL if error + */ + sls_detector_module *interpolateTrim( + sls_detector_module *a, sls_detector_module *b, const int energy, + const int e1, const int e2, int tb = 1); + + /** + * reads a trim/settings file + * @param fname name of the file to be read + * @param myMod pointer to the module structure which has to be set.
+ * If it is NULL a new module structure will be created + * @param tb 1 to include trimbits, 0 to exclude (used for eiger) + * @returns the pointer to myMod or NULL if reading the file failed + */ + + sls_detector_module *readSettingsFile(const std::string &fname, sls_detector_module *myMod = nullptr, int tb = 1); + + /** + * writes a trim/settings file + * @param fname name of the file to be written + * @param mod module structure which has to be written to file + * @returns OK or FAIL if the file could not be written + */ + int writeSettingsFile(const std::string &fname, sls_detector_module& mod); + + /** slsDetector Id or position in the detectors list */ + const int detId; + + /** Shared Memory object */ + mutable sls::SharedMemory detector_shm{0,0}; + +}; + diff --git a/slsDetectorSoftware/include/slsDetectorCommand.h b/slsDetectorSoftware/include/slsDetectorCommand.h new file mode 100755 index 000000000..2a4117d9c --- /dev/null +++ b/slsDetectorSoftware/include/slsDetectorCommand.h @@ -0,0 +1,170 @@ + +#ifndef SLS_DETECTOR_COMMAND_H +#define SLS_DETECTOR_COMMAND_H + + +#include "sls_detector_defs.h" + +class multiSlsDetector; + + + +/** @short This class handles the command line I/Os, help etc. of the text clients */ + + +class slsDetectorCommand : public virtual slsDetectorDefs { + + public: + + + slsDetectorCommand(multiSlsDetector *det); + + + /* + * Executes a set of string arguments according to a given format. + * It is used to read/write configuration file, dump and retrieve detector + * settings and for the command line interface command parsing + * @param narg number of arguments + * @param args array of string arguments + * @param action can be PUT_ACTION or GET_ACTION(from text client even READOUT_ACTION for acquisition) + * @param detPos -1 for all detectors in multi detector list or position of a specific detector in list + */ + std::string executeLine(int narg, char *args[], int action, int detPos = -1); + + /* /\** */ + /* returns the help for the executeLine command */ + /* \param os output stream to return the help to */ + /* \param action can be PUT_ACTION or GET_ACTION (from text client even READOUT_ACTION for acquisition) */ + /* *\/ */ + std::string helpLine(int narg, char *args[], int action=HELP_ACTION, int detPos = -1); + static std::string helpAcquire(int action); + static std::string helpData(int action); + static std::string helpStatus(int action); + static std::string helpDataStream(int action); + static std::string helpFree(int action); + static std::string helpHostname(int action); + static std::string helpUser(int action); + static std::string helpExitServer(int action); + static std::string helpSettingsDir(int action); + static std::string helpTrimEn(int action); + static std::string helpOutDir(int action); + static std::string helpFileName(int action); + static std::string helpFileIndex(int action); + static std::string helpRateCorr(int action); + static std::string helpThreaded(int action); + static std::string helpNetworkParameter(int action); + static std::string helpPort(int action); + static std::string helpLock(int action); + static std::string helpLastClient(int action); + static std::string helpOnline(int action); + static std::string helpConfigureMac(int action); + static std::string helpDetectorSize(int action); + static std::string helpSettings(int action); + static std::string helpSN(int action); + static std::string helpDigiTest(int action); + static std::string helpRegister(int action); + static std::string helpDAC(int action); + static std::string helpTimer(int action); + static std::string helpTiming(int action); + static std::string helpTimeLeft(int action); + static std::string helpSpeed(int action); + static std::string helpAdvanced(int action); + static std::string helpConfiguration(int action); + static std::string helpImage(int action); + static std::string helpCounter(int action); + static std::string helpADC(int action); + static std::string helpTempControl(int action); + static std::string helpEnablefwrite(int action); + static std::string helpOverwrite(int action); + static std::string helpReceiver(int action); + static std::string helpPattern(int action); + static std::string helpPulse(int action); + static std::string helpProcessor(int action); + + + + + + + + + + + + private: + + + multiSlsDetector *myDet; + + std::string cmdUnderDevelopment(int narg, char *args[], int action, int detPos = -1); + std::string cmdUnknown(int narg, char *args[], int action, int detPos = -1); + std::string cmdAcquire(int narg, char *args[], int action, int detPos = -1); + std::string cmdData(int narg, char *args[], int action, int detPos = -1); + std::string cmdStatus(int narg, char *args[], int action, int detPos = -1); + std::string cmdDataStream(int narg, char *args[], int action, int detPos = -1); + std::string cmdFree(int narg, char *args[], int action, int detPos = -1); + std::string cmdHostname(int narg, char *args[], int action, int detPos = -1); + std::string cmdUser(int narg, char *args[], int action, int detPos = -1); + std::string cmdHelp(int narg, char *args[], int action, int detPos = -1); + std::string cmdExitServer(int narg, char *args[], int action, int detPos = -1); + std::string cmdSettingsDir(int narg, char *args[], int action, int detPos = -1); + std::string cmdTrimEn(int narg, char *args[], int action, int detPos = -1); + std::string cmdOutDir(int narg, char *args[], int action, int detPos = -1); + std::string cmdFileName(int narg, char *args[], int action, int detPos = -1); + std::string cmdFileIndex(int narg, char *args[], int action, int detPos = -1); + std::string cmdRateCorr(int narg, char *args[], int action, int detPos = -1); + // std::string cmdThreaded(int narg, char *args[], int action, int detPos = -1); + std::string cmdNetworkParameter(int narg, char *args[], int action, int detPos = -1); + std::string cmdPort(int narg, char *args[], int action, int detPos = -1); + std::string cmdLock(int narg, char *args[], int action, int detPos = -1); + std::string cmdLastClient(int narg, char *args[], int action, int detPos = -1); + std::string cmdOnline(int narg, char *args[], int action, int detPos = -1); + std::string cmdConfigureMac(int narg, char *args[], int action, int detPos = -1); + std::string cmdDetectorSize(int narg, char *args[], int action, int detPos = -1); + std::string cmdSettings(int narg, char *args[], int action, int detPos = -1); + std::string cmdSN(int narg, char *args[], int action, int detPos = -1); + std::string cmdDigiTest(int narg, char *args[], int action, int detPos = -1); + std::string cmdRegister(int narg, char *args[], int action, int detPos = -1); + std::string cmdDAC(int narg, char *args[], int action, int detPos = -1); + std::string cmdTiming(int narg, char *args[], int action, int detPos = -1); + std::string cmdTimer(int narg, char *args[], int action, int detPos = -1); + std::string cmdTimeLeft(int narg, char *args[], int action, int detPos = -1); + std::string cmdSpeed(int narg, char *args[], int action, int detPos = -1); + std::string cmdAdvanced(int narg, char *args[], int action, int detPos = -1); + std::string cmdConfiguration(int narg, char *args[], int action, int detPos = -1); + std::string cmdImage(int narg, char *args[], int action, int detPos = -1); + std::string cmdCounter(int narg, char *args[], int action, int detPos = -1); + std::string cmdADC(int narg, char *args[], int action, int detPos = -1); + std::string cmdTempControl(int narg, char *args[], int action, int detPos = -1); + std::string cmdEnablefwrite(int narg, char *args[], int action, int detPos = -1); + std::string cmdOverwrite(int narg, char *args[], int action, int detPos = -1); + std::string cmdReceiver(int narg, char *args[], int action, int detPos = -1); + std::string cmdPattern(int narg, char *args[], int action, int detPos = -1); + std::string cmdPulse(int narg, char *args[], int action, int detPos = -1); + std::string cmdProcessor(int narg, char *args[], int action, int detPos = -1); + + int numberOfCommands; + std::string cmd; + + typedef std::string (slsDetectorCommand::*MemFuncGetter)(int narg, char *args[], int action, int detPos); + + + struct FuncTable + { + std::string m_pFuncName; + MemFuncGetter m_pFuncPtr; + }; + + + + FuncTable descrToFuncMap[1000]; + + + + +}; + + + +#endif + diff --git a/slsDetectorSoftware/include/slsDetectorUsers.h b/slsDetectorSoftware/include/slsDetectorUsers.h deleted file mode 120000 index 51e196881..000000000 --- a/slsDetectorSoftware/include/slsDetectorUsers.h +++ /dev/null @@ -1 +0,0 @@ -../slsDetector/slsDetectorUsers.h \ No newline at end of file diff --git a/slsDetectorSoftware/include/slsDetectorUsers.h b/slsDetectorSoftware/include/slsDetectorUsers.h new file mode 100755 index 000000000..7675bf113 --- /dev/null +++ b/slsDetectorSoftware/include/slsDetectorUsers.h @@ -0,0 +1,946 @@ +#ifndef SLS_DETECTOR_USERS_H +#define SLS_DETECTOR_USERS_H + + + +/** + * + * + * + * @author Anna Bergamaschi + * @version 0.1alpha + */ + + + +class detectorData; +#include "multiSlsDetector.h" + +#include +#include + + + + + +/* + \mainpage +

API for SLS detectors data acquisition

+
+ */ +/** + \mainpage + + +

API for SLS detectors data acquisition

+ +
+ + Although the SLS detectors group delvelops several types of detectors (1/2D, counting/integrating etc.) it is common interest of the group to use a common platfor for data acquisition + + The architecture of the acquisitions system is intended as follows: + \li A socket server running on the detector (or more than one in some special cases) + \li C++ classes common to all detectors for client-server communication. These can be supplied to users as libraries and embedded also in acquisition systems which are not developed by the SLS + \li the possibility of using a Qt-based graphical user interface (with eventually root analisys capabilities) + \li the possibility of running all commands from command line. In order to ensure a fast operation of this so called "text client" the detector parameters should not be re-initialized everytime. For this reason a shared memory block is allocated where the main detector flags and parameters are stored + \li a Root library for data postprocessing and detector calibration (energy, angle). + + +slsDetectorUsers is a class to control the detector which should be instantiated by the users in their acquisition software (EPICS, spec etc.). A callback for dislaying the data can be registered. +More advanced configuration functions are not implemented and can be written in a configuration file tha can be read/written. + +slsReceiverUsers is a class to receive the data for detectors with external data receiver (e.g. GOTTHARD). Callbacks can be registered to process the data or save them in specific formats. + +detectorData is a structure containing the data and additional information which is used to return the data e.g. to the GUI for displaying them. + + +You can find examples of how this classes can be instatiated in mainClient.cpp and mainReceiver.cpp + +Different values from different detectors will give a -1 (return value is integer), a concatenation of all values (return value is a string) or a FAIL (return value is OK or FAIL) + + + \authors Anna Bergamaschi, Dhanya Thattil + @version 3.0 +

Currently supported detectors

+\li GOTTHARD +\li EIGER +\li JUNGFRAU + + + + */ + +/** + @short The slsDetectorUsers class is a minimal interface class which should be instantiated by the users in their acquisition software (EPICS, spec etc.). More advanced configuration functions are not implemented and can be written in a configuration or parameters file that can be read/written. + + Class for detector functionalities to embed the detector controls in the users custom interface e.g. EPICS, Lima etc. + + */ + + +class slsDetectorUsers +{ + +public: + + /** + * Constructor + * @param ret address of return value. 0 for success or 1 for failure + * @param id multi detector id + */ + slsDetectorUsers(int multi_id):detector(multi_id){}; + + /** + * Destructor + */ + virtual ~slsDetectorUsers() = default; + + /** + * Returns the number of detectors in the multidetector structure + * @returns number of detectors + */ + int getNumberOfDetectors() const; + + /** + * Returns the maximum number of channels of all detectors + * (provided by user in config file using detsizechan command) + * Offsets are calculated according to these dimensions + * @param nx number of channels in horizontal + * @param ny number of channels in vertical + * @returns the maximum number of channels of all detectors + */ + int getMaximumDetectorSize(int &nx, int &ny); + + /** + * Returns the size and offsets of detector/multi detector + * @param x horizontal position origin in channel number + * @param y vertical position origin in channel number + * @param nx number of channels in horiziontal + * @param ny number of channels in vertical + * @param detPos -1 for all detectors in list or specific detector position + * @returns the total number of channels of all sls detectors + */ + int getDetectorSize(int &x, int &y, int &nx, int &ny, int detPos = -1); + + /** + * Gets detector type + * @param detPos -1 for all detectors in list or specific detector position + * @returns detector type (EIGER, JUNGFRAU, GOTTHARD) slsDetectorDefs + */ + std::string getDetectorType(int detPos = -1); + + /** + * Sets/Checks the detectors in multi detector list to online/offline + * Must be called before communicating with detector + * @param online 1 to set detector online, 0 to set it offline, -1 to get + * @param detPos -1 for all detectors in list or specific detector position + * @returns (1)online/(0)offline status + */ + int setOnline(int const online = -1, int detPos = -1); + + /** + * Sets/Checks the receivers in multi detector list to online/offline + * Must be called before communicating with receiver + * @param online 1 to set receiver online, 0 to set it receiver, -1 to get + * @param detPos -1 for all detectors in list or specific detector position + * @returns (1)online/(0)offline status + */ + int setReceiverOnline(int const online = -1, int detPos = -1); + + /** + * Load configuration from a configuration File (for one time detector setup) + * @param fname configuration file name + * @return OK or FAIL + */ + int readConfigurationFile(const std::string& fname); + + /** + * Write current configuration to a file (for one time detector setup) + * @param fname configuration file name + * @returns OK or FAIL + */ + int writeConfigurationFile(const std::string& fname); + + /** + * Loads the detector setup from file (current measurement setup) + * @param fname file to read from + * @returns OK or FAIL + */ + int retrieveDetectorSetup(const std::string& fname); + + /** + * Saves the detector setup to file (currentmeasurement setup) + * @param fname file to write to + * @returns OK or FAIL + */ + int dumpDetectorSetup(const std::string& fname); + + /** + * Get detector firmware version + * @param detPos -1 for all detectors in list or specific detector position + * @returns detector firmware version + */ + int64_t getDetectorFirmwareVersion(int detPos = -1); + + /** + * Get detector serial number or MAC + * @param detPos -1 for all detectors in list or specific detector position + * @returns detector serial number or MAC + */ + int64_t getDetectorSerialNumber(int detPos = -1); + + /** + * Get on-board detector server software version + * @param detPos -1 for all detectors in list or specific detector position + * @returns on-board detector server software version + */ + int64_t getDetectorSoftwareVersion(int detPos = -1); + + /** + * (previously getThisSoftwareVersion) + * Get client software version + * @returns client software version + */ + int64_t getClientSoftwareVersion(); + + /** + * Get receiver software version + * @param detPos -1 for all detectors in list or specific detector position + * @returns receiver software version + */ + int64_t getReceiverSoftwareVersion(int detPos = -1); + + /** + * Check Detector Version Compatibility + * @param detPos -1 for all detectors in list or specific detector position + * @returns true if compatible, else false + */ + bool isDetectorVersionCompatible(int detPos = -1); + + /** + * Check Receiver Version Compatibility + * @param detPos -1 for all detectors in list or specific detector position + * @returns true if compatible, else false + */ + bool isReceiverVersionCompatible(int detPos = -1); + + /** + * Performs a complete acquisition + * resets frames caught in receiver, starts receiver, starts detector, + * blocks till detector finished acquisition, stop receiver, increments file index, + * loops for measurements, calls required call backs. + * @returns OK or FAIL depending on if it already started + */ + int startMeasurement(); + + /** + * Stop detector acquisition + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int stopMeasurement(int detPos = -1); + + /** + * Get Detector run status + * @param detPos -1 for all detectors in list or specific detector position + * @returns status + */ + int getDetectorStatus(int detPos = -1); + + /** + * (Advanced user, included in startMeasurement) + * Start detector acquisition (Non blocking) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL if even one does not start properly + */ + int startAcquisition(int detPos = -1); + + /** + * Stop detector acquisition (Same as stopMeasurement) + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int stopAcquisition(int detPos = -1); + + /** + * (Only in non blocking acquire mode) + * Give an internal software trigger to the detector (Eiger) + * @param detPos -1 for all detectors in list or specific detector position + * @return OK or FAIL + */ + int sendSoftwareTrigger(int detPos = -1); + + /** + * Set Rate correction ( Eiger) + * @param t (1) enable rate correction to default dead time, + * (0) disable rate correction, (-1) gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns rate correction tau + */ + int enableCountRateCorrection(int i = -1, int detPos = -1); + + /** + * Set/get dynamic range + * @param i dynamic range (-1 get) + * Options: Eiger(4, 8, 16, 32), Jungfrau(16), Gotthard(16) + * Background operation: + * (Eiger: If i is 32, also sets clkdivider to 2, if 16, sets clkdivider to 1) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current dynamic range + */ + int setBitDepth(int i = -1, int detPos = -1); + + /** + * Set detector settings + * (Eiger only stores in shared memory. A get will overwrite this. One must use set threshold energy) + * @param isettings settings (-1 gets) + * Options: (slsDetectorDefs::detectorSettings) + * Eiger (STANDARD, HIGHGAIN, LOWGAIN, VERYHIGHGAIN, VERYLOWGAIN) + * Jungfrau (DYNAMICGAIN, DYNAMICHG0, FIXGAIN1, FIXGAIN2, FORCESWITCHG1, FORCESWITCHG2) + * Gotthard (DYNAMICGAIN, HIGHGAIN, LOWGAIN, MEDIUMGAIN, VERYHIGHGAIN) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current settings (can also return UNDEFINED, UNINITIALIZED) + */ + int setSettings(int isettings = -1, int detPos = -1); + + /** + * Get threshold energy (Eiger) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current threshold value + */ + int getThresholdEnergy(int detPos = -1); + + /** + * Set threshold energy (Eiger) + * @param e_eV threshold in eV + * @param tb 1 to load trimbits, 0 to exclude trimbits + * @param isettings settings (-1 current settings) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current threshold value + */ + int setThresholdEnergy(int e_ev, int tb = 1, int isettings = -1, int detPos = -1); + + /** + * Set/get exposure time + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns exposure time in ns, or s if specified + */ + double setExposureTime(double t = -1, bool inseconds = false, int detPos = -1); + + /** + * Set/get exposure period + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns exposure period in ns, or s if specified + */ + double setExposurePeriod(double t = -1, bool inseconds = false, int detPos = -1); + + /** + * Set/get delay after trigger (Gotthard, Jungfrau(not for this release)) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns delay after trigger in ns, or s if specified + */ + double setDelayAfterTrigger(double t = -1, bool inseconds = false, int detPos = -1); + + /** + * (Advanced users) + * Set/get sub frame exposure time (Eiger in 32 bit mode) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns sub frame exposure time in ns, or s if specified + */ + double setSubFrameExposureTime(double t = -1, bool inseconds = false, int detPos = -1); + + /** + * (Advanced users) + * Set/get sub frame dead time (Eiger in 32 bit mode) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns sub frame dead time in ns, or s if specified + */ + double setSubFrameExposureDeadTime(double t = -1, bool inseconds = false, int detPos = -1); + + /** + * Set/get number of frames + * @param t number of frames (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of frames + */ + int64_t setNumberOfFrames(int64_t t = -1, int detPos = -1); + + /** + * Set/get number of cycles + * @param t number of cycles (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of cycles + */ + int64_t setNumberOfCycles(int64_t t = -1, int detPos = -1); + + /** + * Set/get number of gates (none of the detectors at the moment) + * @param t number of gates (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of gates + */ + int64_t setNumberOfGates(int64_t t = -1, int detPos = -1); + + /** + * Set/get number of additional storage cells (Jungfrau) + * @param t number of additional storage cells. Default is 0. (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns number of additional storage cells + */ + int64_t setNumberOfStorageCells(int64_t t = -1, int detPos = -1); + + /** + * Get measured period between previous two frames (EIGER) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns sub frame dead time in ns, or s if specified + */ + double getMeasuredPeriod(bool inseconds = false, int detPos = -1); + + /** + * Get sub period between previous two sub frames in 32 bit mode (EIGER) + * @param t time (-1 gets) + * @param inseconds true if the value is in s, else ns + * @param detPos -1 for all detectors in list or specific detector position + * @returns sub frame dead time in ns, or s if specified + */ + double getMeasuredSubFramePeriod(bool inseconds = false, int detPos = -1); + + /** + * Set/get timing mode + * @param pol timing mode (-1 gets) + * Options (slsDetectorDefs::externalCommunicationMode) + * (Eiger: AUTO_TIMING, TRIGGER_EXPOSURE, BURST_TRIGGER, GATE_FIX_NUMBER) + * (Jungfrau: AUTO_TIMING, TRIGGER_EXPOSURE) + * (Gotthard: AUTO_TIMING, TRIGGER_EXPOSURE) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current timing mode + */ + int setTimingMode(int pol = -1, int detPos = -1); + + /** + * Sets clock speed of the detector (Eiger, Jungfrau) + * (Jungfrau also writes adcphase to recommended default) + * (Eiger: 0(full speed not for 32 bit mode), 1 (half speed), 2(quarter speed)) + * (Jungfrau: 0(full speed not implemented), 1(half speed), 2(quarter speed)) + * @param detPos -1 for all detectors in list or specific detector position + * @returns clock speed + */ + int setClockDivider(int value, int detPos = -1); + + /** + * Set parallel readout mode (Eiger) + * @param value readout mode (-1 gets) + * Options: slsDetectorDefs::readOutFlags + * (PARALLEL, NONPARALLEL (Default), SAFE) + * @param detPos -1 for all detectors in list or specific detector position + * @returns mode register, + * result must be ANDED with PARALLEL/NONPARALLEL/SAFE to get mode + */ + int setParallelMode(int value, int detPos = -1); + + /** + * Set overflow readout mode (Eiger in 32 bit) + * @param value readout mode (-1 gets) + * Options: 1(SHOW_OVERFLOW), 0(NOOVERFLOW) (Default) + * @param detPos -1 for all detectors in list or specific detector position + * @returns 1 if overflow mode else 0 + */ + int setOverflowMode(int value, int detPos = -1); + + /** + * (Advanced user) + * Sets all the trimbits to a particular value (Eiger) + * @param val trimbit value + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int setAllTrimbits(int val, int detPos = -1); + + /** + * (Advanced user) + * Set/get dacs value + * @param val value (in V) (-1 gets) + * @param index DAC index + * Options: slsDetectorDefs::dacIndex + * (Eiger: E_SvP up to IO_DELAY, THRESHOLD, HIGH_VOLTAGE) + * (Jungfrau: 0-7) + * (Gotthard: G_VREF_DS up to G_IB_TESTC, HIGH_VOLTAGE) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current DAC value + */ + int setDAC(int val, int index , int detPos = -1); + + /** + * Get adc value + * @param index adc(DAC) index + * Options: slsDetectorDefs::dacIndex + * (Eiger: TEMPERATURE_FPGA, TEMPERATURE_FPGAEXT upto TEMPERATURE_FPGA3) + * (Jungfrau: TEMPERATURE_FPGA) + * (Gotthard: TEMPERATURE_ADC, TEMPERATURE_FPGA) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current adc value (temperature for eiger and jungfrau in millidegrees) + */ + int getADC(int index, int detPos = -1); + + /** + * Enable/disable or 10Gbe (Eiger) + * @param i is -1 to get, 0 to disable and 1 to enable + * @param detPos -1 for all detectors in list or specific detector position + * @returns if 10Gbe is enabled + */ + int setTenGigabitEthernet(int i = -1, int detPos = -1); + + /** + * Set storage cell that stores first acquisition of the series (Jungfrau) + * @param value storage cell index. Value can be 0 to 15. (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns the storage cell that stores the first acquisition of the series + */ + int setStoragecellStart(int pos=-1, int detPos = -1); + + /** + * set high voltage (Gotthard, Jungfrau, Eiger) + * @param i > 0 sets, 0 unsets, (-1 gets) + * (Eiger: ) + * (Jungfrau: ) + * (Gotthard: ) + * @returns high voltage + */ + int setHighVoltage(int i = -1, int detPos = -1); + + /** + * Set 10GbE Flow Control (Eiger) + * @param enable 1 to set, 0 to unset, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns 10GbE flow Control + */ + int setFlowControl10G(int enable = -1, int detPos = -1); + + /** + * Set ROI (Gotthard) (>= 1 roi, but max 1 roi per module) + * At the moment only one set allowed + * @param n number of rois + * @param roiLimits array of roi + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int setROI(int n=-1, slsDetectorDefs::ROI roiLimits[]=NULL, int detPos = -1); + + /** + * Get ROI from each detector and convert it to the multi detector scale (Gotthard) + * >= 1 roi, but max 1 roi per module + * @param n number of rois + * @param detPos -1 for all detectors in list or specific detector position + * @returns pointer to array of ROI structure + */ + const slsDetectorDefs::ROI* getROI(int &n, int detPos = -1); + + + + /************************************************************************ + + RECEIVER FUNCTIONS + + *********************************************************************/ + + /** + * (Advanced user, included in startMeasurement) + * Receiver starts listening to packets + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int startReceiver(int detPos = -1); + + /** + * (Advanced user, included in startMeasurement) + * Stops the listening mode of receiver + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int stopReceiver(int detPos = -1); + + /** + * Set/get receiver silent mode + * @param i is -1 to get, 0 unsets silent mode, 1 sets silent mode + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver silent mode enable + */ + int setReceiverSilentMode(int i = -1, int detPos = -1); + + /** + * (Advanced user, included in startMeasurement) + * Resets framescaught in receiver + * Use this when using startAcquisition instead of acquire + * @param detPos -1 for all detectors in list or specific detector position + * @returns OK or FAIL + */ + int resetFramesCaughtInReceiver(int detPos = -1); + + /** + * (Advanced user) + * Set/get receiver fifo depth + * @param i is -1 to get, any other value to set the fifo deph + * @param detPos -1 for all detectors in list or specific detector position + * @returns the receiver fifo depth + */ + int setReceiverFifoDepth(int i = -1, int detPos = -1); + + /** + * Returns output file directory + * @param detPos -1 for all detectors in list or specific detector position + * @returns output file directory + */ + std::string getFilePath(int detPos = -1); + + /** + * Sets up the file directory + * @param detPos -1 for all detectors in list or specific detector position + * @param s file directory + * @returns file dir + */ + std::string setFilePath(const std::string& s, int detPos = -1); + + /** + * Returns file name prefix + * @param detPos -1 for all detectors in list or specific detector position + * @returns file name prefix + */ + std::string getFileName(int detPos = -1); + + /** + * Sets up the file name prefix + * @param detPos -1 for all detectors in list or specific detector position + * @param s file name prefix + * @returns file name prefix + */ + std::string setFileName(const std::string& s, int detPos = -1); + + /** + * Returns file index + * @param detPos -1 for all detectors in list or specific detector position + * @returns file index + */ + int getFileIndex(int detPos = -1); + + /** + * Sets up the file index + * @param i file index + * @param detPos -1 for all detectors in list or specific detector position + * @returns file index + */ + int setFileIndex(int i, int detPos = -1); + + /** + * Sets/Gets receiver file write enable + * @param enable 1 or 0 to set/reset file write enable + * @param detPos -1 for all detectors in list or specific detector position + * @returns file write enable + */ + int enableWriteToFile(int enable = -1, int detPos = -1); + + /** + * Sets/Gets file overwrite enable + * @param enable 1 or 0 to set/reset file overwrite enable + * @param detPos -1 for all detectors in list or specific detector position + * @returns file overwrite enable + */ + int enableOverwriteFile(int enable = -1, int detPos = -1); + + /** + * (previously setReceiverMode) + * Sets the receiver streaming frequency + * @param freq nth frame streamed out, if 0, streamed out at a timer of 200 ms + * frames in between are not streamed + * @param detPos -1 for all detectors in list or specific detector position + * @returns receiver streaming frequency + */ + int setReceiverStreamingFrequency(int freq = -1, int detPos = -1); + + /** + * Sets the receiver streaming timer + * If receiver streaming frequency is 0, then this timer between each + * data stream is set. Default is 200 ms. + * @param time_in_ms timer between frames + * @param detPos -1 for all detectors in list or specific detector position + * @returns receiver streaming timer in ms + */ + int setReceiverStreamingTimer(int time_in_ms=500, int detPos = -1); + + /** + * Enable data streaming to client (data call back in client processing thread) + * @param enable 0 to disable, 1 to enable, -1 to get the value + * @returns data streaming to client enable + */ + int enableDataStreamingToClient(int enable=-1); + + /** + * Enable or disable streaming data from receiver (starts streaming threads) + * @param enable 0 to disable 1 to enable -1 to only get the value + * @param detPos -1 for all detectors in list or specific detector position + * @returns data streaming from receiver enable + */ + int enableDataStreamingFromReceiver(int enable=-1, int detPos = -1); + + /** + * (advanced users) + * Set/Get receiver streaming out ZMQ port and restarts receiver sockets + * @param i sets, -1 gets + * If detPos is -1(multi module), port calculated (increments) for all the individual detectors using i + * @param detPos -1 for all detectors in list or specific detector position + * @returns receiver streaming out ZMQ port (if multiple, of first receiver socket) + */ + int setReceiverDataStreamingOutPort(int i = -1, int detPos = -1); + + /** + * (advanced users) + * Set/Get client streaming in ZMQ port and restarts client sockets + * @param i sets, -1 gets + * If detPos is -1(multi module), port calculated (increments) for all the individual detectors using i + * @param detPos -1 for all detectors in list or specific detector position + * @returns receiver streaming out ZMQ port (if multiple, of first receiver socket) + */ + int setClientDataStreamingInPort(int i = -1, int detPos = -1); + + /** + * (advanced users) + * Set/Get receiver streaming out ZMQ IP and restarts receiver sockets + * @param i sets, empty string gets + * By default, it is the IP of receiver hostname + * @param detPos -1 for all detectors in list or specific detector position + * @returns receiver streaming out ZMQ IP + */ + std::string setReceiverDataStreamingOutIP(const std::string& ip="", int detPos = -1); + + /** + * (advanced users) + * Set/Get client streaming in ZMQ IP and restarts client sockets + * @param i sets, empty string gets + * By default, it is the IP of receiver hostname + * @param detPos -1 for all detectors in list or specific detector position + * @returns client streaming in ZMQ IP + */ + std::string setClientDataStreamingInIP(const std::string& ip = "", int detPos = -1); + + /** + * Enable gap pixels in receiver (Eiger for 8,16 and 32 bit mode) + * 4 bit mode gap pixels only in data call back in client + * @param val 1 sets, 0 unsets, -1 gets + * @param detPos -1 for all detectors in list or specific detector position + * @returns gap pixel enable + */ + int enableGapPixels(int val=-1, int detPos = -1); + + /** + * Sets the frame discard policy in receiver + * @param f frame discard policy (-1 gets) + * Options: (slsDetectorDefs::frameDiscardPolicy) + * (NO_DISCARD (default), DISCARD_EMPTY_FRAMES, DISCARD_PARTIAL_FRAMES (fastest)) + * @param detPos -1 for all detectors in list or specific detector position + * @returns current frame discard policy + */ + int setReceiverFramesDiscardPolicy(int f = -1, int detPos = -1); + + /** + * Sets the frame padding in receiver + * @param f 0 does not partial frames, 1 pads partial frames (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns partial frames padding enable + */ + int setReceiverPartialFramesPadding(int f = -1, int detPos = -1); + + /** + * Sets the frames per file in receiver + * @param f frames per file, 0 is infinite ie. every frame in same file (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns frames per file + */ + int setReceiverFramesPerFile(int f = -1, int detPos = -1); + + /** + * Sets the detector minimum/maximum energy threshold in processor (for Moench only) + * @param index 0 for emin, antyhing else for emax + * @param v value to set (-1 gets) + * @param detPos -1 for all detectors in list or specific detector position + * @returns detector minimum/maximum energy threshold + */ + int setDetectorMinMaxEnergyThreshold(const int index, int v, int detPos = -1); + + /** + * Sets the frame mode in processor (Moench only) + * @param value frame mode value (-1 gets) + * Options (slsDetectorDefs::frameModeType) + * PEDESTAL, NEW_PEDESTAL, FLATFIELD, NEW_FLATFIELD + * @param detPos -1 for all detectors in list or specific detector position + * @returns frame mode (-1 for not found or error in computing json parameter value) + */ + int setFrameMode(int value, int detPos = -1); + + /** + * Sets the detector mode in processor (Moench only) + * @param value detector mode value (-1 gets) + * Options (slsDetectorDefs::detectorModeType) + * COUNTING, INTERPOLATING, ANALOG + * @param detPos -1 for all detectors in list or specific detector position + * @returns detector mode (-1 for not found or error in computing json parameter value) + */ + int setDetectorMode(int value, int detPos = -1); + + /************************************************************************ + + CALLBACKS & COMMAND LINE PARSING + + *********************************************************************/ + + /** + * register callback for accessing detector final data in client, + * also enables data streaming in client and receiver + * @param userCallback function for plotting/analyzing the data. + * Its arguments are + * the data structure d and the frame number f, + * s is for subframe number for eiger for 32 bit mode + * @param pArg argument + */ + + void registerDataCallback(int( *userCallback)(detectorData* d, int f, int s, void*), void *pArg); + + /** + * register callback for accessing acquisition final data in client, + * @param func function to be called at the end of the acquisition. + * gets detector status and progress index as arguments + * @param pArg argument + */ + void registerAcquisitionFinishedCallback(int( *func)(double,int, void*), void *pArg); + + /** + * register callback for accessing measurement final data in client, + * @param func function to be called at the end of the acquisition. + * gets detector status and progress index as arguments + * @param pArg argument + */ + void registerMeasurementFinishedCallback(int( *func)(int,int, void*), void *pArg); + + /** + * register callback for accessing detector progress in client, + * @param func function to be called at the end of the acquisition. + * gets detector status and progress index as arguments + * @param pArg argument + */ + void registerProgressCallback(int( *func)(double,void*), void *pArg); + + /** + @short [usage strongly discouraged] sets parameters trough command line interface http://www.psi.ch/detectors/UsersSupportEN/slsDetectorClientHowTo.pdf + \param command string as it would be written on the command line + \returns void + */ + void putCommand(const std::string& command); + + + + + + /************************************************************************ + + STATIC FUNCTIONS + + *********************************************************************/ + + /** @short returns std::string from run status index + \param s run status index + \returns std::string error, waiting, running, data, finished or unknown when wrong index + */ + static std::string runStatusType(int s){ \ + switch (s) { \ + case 0: return std::string("idle"); \ + case 1: return std::string("error"); \ + case 2: return std::string("waiting"); \ + case 3: return std::string("finished"); \ + case 4: return std::string("data"); \ + case 5: return std::string("running"); \ + case 6: return std::string("stopped"); \ + default: return std::string("unknown"); \ + }}; + + + + /** @short returns detector settings std::string from index + \param s can be standard, fast, highgain, dynamicgain, lowgain, mediumgain, veryhighgain + \returns setting index (-1 unknown std::string) + */ + + static int getDetectorSettings(std::string s){ \ + if (s=="standard") return 0; \ + if (s=="fast") return 1; \ + if (s=="highgain") return 2; \ + if (s=="dynamicgain") return 3; \ + if (s=="lowgain") return 4; \ + if (s=="mediumgain") return 5; \ + if (s=="veryhighgain") return 6; \ + return -1; }; + + /** @short returns detector settings std::string from index + \param s settings index + \returns standard, fast, highgain, dynamicgain, lowgain, mediumgain, veryhighgain, undefined when wrong index + */ + static std::string getDetectorSettings(int s){\ + switch(s) { \ + case 0: return std::string("standard");\ + case 1: return std::string("fast");\ + case 2: return std::string("highgain");\ + case 3: return std::string("dynamicgain"); \ + case 4: return std::string("lowgain"); \ + case 5: return std::string("mediumgain"); \ + case 6: return std::string("veryhighgain"); \ + default: return std::string("undefined"); \ + }}; + + + + /** + @short returns external communication mode std::string from index + \param f index for communication mode + \returns auto, trigger, ro_trigger, gating, triggered_gating, unknown when wrong mode + */ + + static std::string getTimingMode(int f){ \ + switch(f) { \ + case 0: return std::string( "auto"); \ + case 1: return std::string("trigger"); \ + case 2: return std::string("ro_trigger"); \ + case 3: return std::string("gating"); \ + case 4: return std::string("triggered_gating"); \ + case 5: return std::string("burst_trigger"); \ + default: return std::string( "unknown"); \ + } }; + + /** + @short returns external communication mode std::string from index + \param s index for communication mode + \returns auto, trigger, ro_trigger, gating, triggered_gating, unknown when wrong mode + */ + + static int getTimingMode(std::string s){ \ + if (s== "auto") return 0; \ + if (s== "trigger") return 1; \ + if (s== "ro_trigger") return 2; \ + if (s== "gating") return 3; \ + if (s== "triggered_gating") return 4; \ + return -1; }; + + +private: + multiSlsDetector detector; +}; + +#endif diff --git a/slsDetectorSoftware/include/slsReceiverUsers.h b/slsDetectorSoftware/include/slsReceiverUsers.h deleted file mode 120000 index c8727f200..000000000 --- a/slsDetectorSoftware/include/slsReceiverUsers.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/slsReceiverUsers.h \ No newline at end of file diff --git a/slsDetectorSoftware/jctbDetectorServer/AD9257.h b/slsDetectorSoftware/jctbDetectorServer/AD9257.h deleted file mode 100755 index a716af64c..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/AD9257.h +++ /dev/null @@ -1,141 +0,0 @@ -#ifndef AD9257_H -#define AD9257_H - -#include "ansi.h" - -#include "commonServerFunctions.h" -#include - -/* AD9257 ADC DEFINES */ -#define AD9257_ADC_NUMBITS (24) - -#define AD9257_DEV_IND_2_REG (0x04) -#define AD9257_CHAN_H_OFST (0) -#define AD9257_CHAN_H_MSK (0x00000001 << AD9257_CHAN_H_OFST) -#define AD9257_CHAN_G_OFST (1) -#define AD9257_CHAN_G_MSK (0x00000001 << AD9257_CHAN_G_OFST) -#define AD9257_CHAN_F_OFST (2) -#define AD9257_CHAN_F_MSK (0x00000001 << AD9257_CHAN_F_OFST) -#define AD9257_CHAN_E_OFST (3) -#define AD9257_CHAN_E_MSK (0x00000001 << AD9257_CHAN_E_OFST) - -#define AD9257_DEV_IND_1_REG (0x05) -#define AD9257_CHAN_D_OFST (0) -#define AD9257_CHAN_D_MSK (0x00000001 << AD9257_CHAN_D_OFST) -#define AD9257_CHAN_C_OFST (1) -#define AD9257_CHAN_C_MSK (0x00000001 << AD9257_CHAN_C_OFST) -#define AD9257_CHAN_B_OFST (2) -#define AD9257_CHAN_B_MSK (0x00000001 << AD9257_CHAN_B_OFST) -#define AD9257_CHAN_A_OFST (3) -#define AD9257_CHAN_A_MSK (0x00000001 << AD9257_CHAN_A_OFST) -#define AD9257_CLK_CH_DCO_OFST (4) -#define AD9257_CLK_CH_DCO_MSK (0x00000001 << AD9257_CLK_CH_DCO_OFST) -#define AD9257_CLK_CH_IFCO_OFST (5) -#define AD9257_CLK_CH_IFCO_MSK (0x00000001 << AD9257_CLK_CH_IFCO_OFST) - -#define AD9257_POWER_MODE_REG (0x08) -#define AD9257_POWER_INTERNAL_OFST (0) -#define AD9257_POWER_INTERNAL_MSK (0x00000003 << AD9257_POWER_INTERNAL_OFST) -#define AD9257_INT_RESET_VAL (0x3) -#define AD9257_INT_CHIP_RUN_VAL (0x0) -#define AD9257_POWER_EXTERNAL_OFST (5) -#define AD9257_POWER_EXTERNAL_MSK (0x00000001 << AD9257_POWER_EXTERNAL_OFST) -#define AD9257_EXT_FULL_POWER_VAL (0x0) -#define AD9257_EXT_STANDBY_VAL (0x1) - -#define AD9257_OUT_MODE_REG (0x14) -#define AD9257_OUT_FORMAT_OFST (0) -#define AD9257_OUT_FORMAT_MSK (0x00000001 << AD9257_OUT_FORMAT_OFST) -#define AD9257_OUT_BINARY_OFST_VAL (0) -#define AD9257_OUT_TWOS_COMPL_VAL (1) -#define AD9257_OUT_LVDS_OPT_OFST (6) -#define AD9257_OUT_LVDS_OPT_MSK (0x00000001 << AD9257_OUT_LVDS_OPT_OFST) -#define AD9257_OUT_LVDS_ANSI_VAL (0) -#define AD9257_OUT_LVDS_IEEE_VAL (1) - -#define AD9257_OUT_PHASE_REG (0x16) -#define AD9257_OUT_CLK_OFST (0) -#define AD9257_OUT_CLK_MSK (0x0000000F << AD9257_OUT_CLK_OFST) -#define AD9257_OUT_CLK_60_VAL (0x1) -#define AD9257_IN_CLK_OFST (4) -#define AD9257_IN_CLK_MSK (0x00000007 << AD9257_IN_CLK_OFST) -#define AD9257_IN_CLK_0_VAL (0x0) - -#define AD9257_VREF_REG (0x18) -#define AD9257_VREF_OFST (0) -#define AD9257_VREF_MSK (0x00000003 << AD9257_VREF_OFST) -#define AD9257_VREF_1_33_VAL (0x2) - -#define AD9257_TEST_MODE_REG (0x0D) -#define AD9257_OUT_TEST_OFST (0) -#define AD9257_OUT_TEST_MSK (0x0000000F << AD9257_OUT_TEST_OFST) -#define AD9257_NONE_VAL (0x0) -#define AD9257_MIXED_BIT_FREQ_VAL (0xC) -#define AD9257_TEST_RESET_SHORT_GEN (4) -#define AD9257_TEST_RESET_LONG_GEN (5) -#define AD9257_USER_IN_MODE_OFST (6) -#define AD9257_USER_IN_MODE_MSK (0x00000003 << AD9257_USER_IN_MODE_OFST) - - -void setAdc(int addr, int val) { - - u_int32_t codata; - codata = val + (addr << 8); - printf(" Setting ADC SPI Register. Wrote 0x%04x at 0x%04x\n", val, addr); - serializeToSPI(ADC_SPI_REG, codata, ADC_SERIAL_CS_OUT_MSK, AD9257_ADC_NUMBITS, - ADC_SERIAL_CLK_OUT_MSK, ADC_SERIAL_DATA_OUT_MSK, ADC_SERIAL_DATA_OUT_OFST); -} - -void prepareADC(){ - printf("\n\nPreparing ADC ... \n"); - - //power mode reset - printf("power mode reset:\n"); - setAdc(AD9257_POWER_MODE_REG, - (AD9257_INT_RESET_VAL << AD9257_POWER_INTERNAL_OFST) & AD9257_POWER_INTERNAL_MSK); - - //power mode chip run - printf("power mode chip run:\n"); - setAdc(AD9257_POWER_MODE_REG, - (AD9257_INT_CHIP_RUN_VAL << AD9257_POWER_INTERNAL_OFST) & AD9257_POWER_INTERNAL_MSK); - - //output clock phase - printf("output clock phase:\n"); - setAdc(AD9257_OUT_PHASE_REG, - (AD9257_OUT_CLK_60_VAL << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK); - - // lvds-iee reduced , binary offset - printf("lvds-iee reduced, binary offset:\n"); - setAdc(AD9257_OUT_MODE_REG, - (AD9257_OUT_LVDS_IEEE_VAL << AD9257_OUT_LVDS_OPT_OFST) & AD9257_OUT_LVDS_OPT_MSK); - - // all devices on chip to receive next command - printf("all devices on chip to receive next command:\n"); - setAdc(AD9257_DEV_IND_2_REG, - AD9257_CHAN_H_MSK | AD9257_CHAN_G_MSK | AD9257_CHAN_F_MSK | AD9257_CHAN_E_MSK); - setAdc(AD9257_DEV_IND_1_REG, - AD9257_CHAN_D_MSK | AD9257_CHAN_C_MSK | AD9257_CHAN_B_MSK | AD9257_CHAN_A_MSK | - AD9257_CLK_CH_DCO_MSK | AD9257_CLK_CH_IFCO_MSK); - - // vref 1.33 - printf("vref 1.33:\n"); - setAdc(AD9257_VREF_REG, - (AD9257_VREF_1_33_VAL << AD9257_VREF_OFST) & AD9257_VREF_MSK); - - // no test mode - printf("no test mode:\n"); - setAdc(AD9257_TEST_MODE_REG, - (AD9257_NONE_VAL << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK); - -#ifdef TESTADC - printf("***************************************** *******\n"); - printf("******* PUTTING ADC IN TEST MODE!!!!!!!!! *******\n"); - printf("***************************************** *******\n"); - // mixed bit frequency test mode - printf("mixed bit frequency test mode:\n"); - setAdc(AD9257_TEST_MODE_REG, - (AD9257_MIXED_BIT_FREQ_VAL << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK); -#endif -} - -#endif //AD9257_H diff --git a/slsDetectorSoftware/jctbDetectorServer/Makefile b/slsDetectorSoftware/jctbDetectorServer/Makefile deleted file mode 100644 index fe60da6f6..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/Makefile +++ /dev/null @@ -1,55 +0,0 @@ -# $Id: Makefile,v 1.1.1.1 2006/02/04 03:35:01 freza Exp $ -# first compile -# make cris-axis-linux-gnu - - -CROSS = bfin-uclinux- -CC = $(CROSS)gcc - -CFLAGS += -Wall -DMOENCHD -DMCB_FUNCS -DDACS_INT -DDEBUG -DV1 -DCTB - - -PROGS= jctbDetectorServer -INSTDIR= /tftpboot -INSTMODE= 0777 - - - -BINS = testlib_sharedlibc -SRCS = server.c server_funcs.c communication_funcs.c firmware_funcs.c slow_adc.c blackfin.c -#mcb_funcs.c sharedmemory.c -OBJS = $(SRCS:%.c=%.o) - - - -all: clean versioning $(PROGS) - -test: clean jungfrauADCTest - -boot: $(OBJS) - -versioning: - @echo `tput setaf 6; ./updateGitVersion.sh; tput sgr0;` - -jctbDetectorServer: $(OBJS) - echo $(OBJS) - $(CC) $(CFLAGS) -o $@ $^ $(LDLIBS_$@) $(LDFLAGS_$@) - -jungfrauADCTest: $(OBJS) - echo $(OBJS) - $(CC) $(CFLAGS) -o $@ $^ $(LDLIBS_$@) $(LDFLAGS_$@) -DTESTADC - - - - -install: $(PROGS) - $(INSTALL) -d $(INSTDIR) - $(INSTALL) -m $(INSTMODE) $(PROGS) $(INSTDIR) - - -romfs: - $(ROMFSINST) /bin/$(PROGS) - -clean: - rm -rf $(PROGS) *.o *.gdb - diff --git a/slsDetectorSoftware/jctbDetectorServer/ansi.h b/slsDetectorSoftware/jctbDetectorServer/ansi.h deleted file mode 120000 index a122db0ad..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/ansi.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/ansi.h \ No newline at end of file diff --git a/slsDetectorSoftware/jctbDetectorServer/bf_init.sh b/slsDetectorSoftware/jctbDetectorServer/bf_init.sh deleted file mode 100644 index 88eccadb4..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/bf_init.sh +++ /dev/null @@ -1 +0,0 @@ -export PATH=/afs/psi.ch/project/sls_det_firmware/jungfrau_software/uClinux-2010_64bit/bfin-uclinux/bin:$PATH diff --git a/slsDetectorSoftware/jctbDetectorServer/blackfin.c b/slsDetectorSoftware/jctbDetectorServer/blackfin.c deleted file mode 100644 index 9a560ea81..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/blackfin.c +++ /dev/null @@ -1,171 +0,0 @@ -#include "blackfin.h" - - #include - #include - - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include -#include "server_defs.h" -#include "registers_m.h" - -//for memory mapping -u_int64_t CSP0BASE; - -u_int16_t volatile *values; - -int mapCSP0(void) { - printf("Mapping memory\n"); -#ifndef VIRTUAL - int fd; - fd = open("/dev/mem", O_RDWR | O_SYNC, 0); - if (fd == -1) { - printf("\nCan't find /dev/mem!\n"); - return FAIL; - } - printf("/dev/mem opened\n"); - - CSP0BASE = mmap(0, MEM_SIZE, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, CSP0); - if (CSP0BASE == MAP_FAILED) { - printf("\nCan't map memmory area!!\n"); - return FAIL; - } - printf("CSP0 mapped\n"); - -#endif -#ifdef VIRTUAL - CSP0BASE = malloc(MEM_SIZE); - printf("memory allocated\n"); -#endif -#ifdef SHAREDMEMORY - if ( (res=inism(SMSV))<0) { - printf("error attaching shared memory! %i",res); - return FAIL; - } -#endif - printf("CSPObase is 0x%08llx \n",CSP0BASE); - printf("CSPOBASE=from %08llx to %08llx\n",CSP0BASE,CSP0BASE+MEM_SIZE); - - u_int32_t address; - address = FIFO_DATA_REG;//_OFF; - //values=(u_int32_t*)(CSP0BASE+address*2); - values=(u_int16_t*)(CSP0BASE+address*2); - printf("statusreg=%08x\n",bus_r(STATUS_REG)); - printf("\n\n"); - return OK; -} - - - - -u_int16_t a_bus_r16(u_int32_t offset){ - volatile u_int16_t *ptr1; - ptr1=(u_int16_t*)(CSP0BASE+offset*2); - return *ptr1; -} - -u_int16_t bus_r16(u_int32_t offset){ - u_int16_t r= a_bus_r16(offset); -/* #ifndef OLDVERSION */ -/* while (r!=a_bus_r16(offset)) */ -/* r=a_bus_r16(offset); */ -/* #endif */ - return r; -} - -u_int16_t bus_w16(u_int32_t offset, u_int16_t data) { - volatile u_int16_t *ptr1; - ptr1=(u_int16_t*)(CSP0BASE+offset*2); - *ptr1=data; - return OK; -} - - -u_int32_t bus_w(u_int32_t offset, u_int32_t data) { - volatile u_int32_t *ptr1; - - ptr1=(u_int32_t*)(CSP0BASE+offset*2); - *ptr1=data; - - return OK; -} - - -u_int32_t a_bus_r(u_int32_t offset) { - volatile u_int32_t *ptr1; - ptr1=(u_int32_t*)(CSP0BASE+offset*2); - return *ptr1; -} - -u_int32_t bus_r(u_int32_t offset){ - u_int32_t r= a_bus_r(offset); -/* #ifndef OLDVERSION */ -/* while (r!=a_bus_r(offset)) */ -/* r=a_bus_r(offset); */ -/* #endif */ - return r; -} - -// program dacq settings - -int64_t set64BitReg(int64_t value, int aLSB, int aMSB){ - int64_t v64; - u_int32_t vLSB,vMSB; - if (value!=-1) { - vLSB=value&(0xffffffff); - bus_w(aLSB,vLSB); - v64=value>> 32; - vMSB=v64&(0xffffffff); - bus_w(aMSB,vMSB); - // printf("Wreg64(%x,%x) %08x %08x %016llx\n", aLSB>>11, aMSB>>11, vLSB, vMSB, value); - } - return get64BitReg(aLSB, aMSB); - -} - -int64_t get64BitReg(int aLSB, int aMSB){ - int64_t v64; - u_int32_t vLSB,vMSB; - vLSB=bus_r(aLSB); - vMSB=bus_r(aMSB); - v64=vMSB; - v64=(v64<<32) | vLSB; - - // printf("reg64(%x,%x) %x %x %llx\n", aLSB, aMSB, vLSB, vMSB, v64); - - return v64; -} - -/* /\** */ -/* /\** ramType is DARK_IMAGE_REG or GAIN_IMAGE_REG *\/ */ -/* u_int16_t ram_w16(u_int32_t ramType, int adc, int adcCh, int Ch, u_int16_t data) { */ -/* unsigned int adr = (ramType | adc << 8 | adcCh << 5 | Ch ); */ -/* // printf("Writing to addr:%x\n",adr); */ -/* return bus_w16(adr,data); */ -/* } */ - -/* /\** ramType is DARK_IMAGE_REG or GAIN_IMAGE_REG *\/ */ -/* u_int16_t ram_r16(u_int32_t ramType, int adc, int adcCh, int Ch){ */ -/* unsigned int adr = (ramType | adc << 8 | adcCh << 5 | Ch ); */ -/* // printf("Reading from addr:%x\n",adr); */ -/* return bus_r16(adr); */ -/* } */ -/* **\/ */ diff --git a/slsDetectorSoftware/jctbDetectorServer/blackfin.h b/slsDetectorSoftware/jctbDetectorServer/blackfin.h deleted file mode 100644 index c7ef2cda2..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/blackfin.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef BLACKFIN_H -#define BLACKFIN_H - -#define CSP0 0x20200000 -#define MEM_SIZE 0x100000 -#ifndef OLDVERSION -#define MEM_MAP_SHIFT 1 -#endif -#ifdef OLDVERSION -#define MEM_MAP_SHIFT 11 -#endif -#include - -int mapCSP0(void); - -u_int16_t bus_r16(u_int32_t offset); -u_int16_t bus_w16(u_int32_t offset, u_int16_t data);//aldos function -u_int32_t bus_w(u_int32_t offset, u_int32_t data); -u_int32_t bus_r(u_int32_t offset); - -int64_t set64BitReg(int64_t value, int aLSB, int aMSB); -int64_t get64BitReg(int aLSB, int aMSB); - - -#endif diff --git a/slsDetectorSoftware/jctbDetectorServer/commonServerFunctions.h b/slsDetectorSoftware/jctbDetectorServer/commonServerFunctions.h deleted file mode 100755 index 55d30b8c4..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/commonServerFunctions.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef COMMON_SERVER_FUNCTIONS_H -#define COMMON_SERVER_FUNCTIONS_H - -#ifndef GOTTHARDD //gotthard already had bus_w etc defined in its firmware_funcs.c (not yet made with common files) -#include "blackfin.h" -#endif - -/* global variables */ - -void SPIChipSelect (u_int32_t* valw, u_int32_t addr, u_int32_t csmask) { - - // start point - (*valw) = 0xffffffff; // old board compatibility (not using specific bits) - bus_w (addr, (*valw)); - - // chip sel bar down - (*valw) &= ~csmask; /* todo with test: done a bit different, not with previous value */ - bus_w (addr, (*valw)); -} - - -void SPIChipDeselect (u_int32_t* valw, u_int32_t addr, u_int32_t csmask, u_int32_t clkmask) { - // chip sel bar up - (*valw) |= csmask; /* todo with test: not done for spi */ - bus_w (addr, (*valw)); - - //clk down - (*valw) &= ~clkmask; - bus_w (addr, (*valw)); - - // stop point = start point of course - (*valw) = 0xffffffff; // old board compatibility (not using specific bits) - bus_w (addr, (*valw)); -} - -void sendDataToSPI (u_int32_t* valw, u_int32_t addr, u_int32_t val, int numbitstosend, u_int32_t clkmask, u_int32_t digoutmask, int digofset) { - int i = 0; - for (i = 0; i < numbitstosend; ++i) { - - // clk down - (*valw) &= ~clkmask; - bus_w (addr, (*valw)); - - // write data (i) - (*valw) = (((*valw) & ~digoutmask) + // unset bit - (((val >> (numbitstosend - 1 - i)) & 0x1) << digofset)); // each bit from val starting from msb - bus_w (addr, (*valw)); - - // clk up - (*valw) |= clkmask ; - bus_w (addr, (*valw)); - } -} - - -void serializeToSPI(u_int32_t addr, u_int32_t val, u_int32_t csmask, int numbitstosend, u_int32_t clkmask, u_int32_t digoutmask, int digofset) { -#ifdef VERBOSE - if (numbitstosend == 16) - printf("Writing to SPI Register: 0x%04x\n",val); - else - printf("Writing to SPI Register: 0x%08x\n", val); -#endif - - u_int32_t valw; - - SPIChipSelect (&valw, addr, csmask); - - sendDataToSPI(&valw, addr, val, numbitstosend, clkmask, digoutmask, digofset); - - SPIChipDeselect(&valw, addr, csmask, clkmask); -} - -#endif //COMMON_SERVER_FUNCTIONS_H diff --git a/slsDetectorSoftware/jctbDetectorServer/communication_funcs.c b/slsDetectorSoftware/jctbDetectorServer/communication_funcs.c deleted file mode 120000 index 87a4f95d1..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/communication_funcs.c +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.c \ No newline at end of file diff --git a/slsDetectorSoftware/jctbDetectorServer/communication_funcs.h b/slsDetectorSoftware/jctbDetectorServer/communication_funcs.h deleted file mode 120000 index f220903b2..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/communication_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/jctbDetectorServer/convert_pof_to_raw.c b/slsDetectorSoftware/jctbDetectorServer/convert_pof_to_raw.c deleted file mode 100644 index 661ab2bd9..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/convert_pof_to_raw.c +++ /dev/null @@ -1,58 +0,0 @@ -// Converts POF files into RAW files for flashing - -#include -#include - -// Warning: This program is for testing only. -// It makes some assumptions regarding the pof file and the flash size that might be wrong. -// It also overwrites the destination file without any hesitation. -// Handle with care. - -int main(int argc, char* argv[]) -{ - FILE* src; - FILE* dst; - int x; - int y; - int i; - int filepos; - - if (argc < 3) - { - printf("%s Sourcefile Destinationfile\n",argv[0]); - return -1; - } - - src = fopen(argv[1],"rb"); - dst = fopen(argv[2],"wb"); - - // Remove header (0...11C) - for (filepos=0; filepos < 0x11C; filepos++) - fgetc(src); - - // Write 0x80 times 0xFF (0...7F) - for (filepos=0; filepos < 0x80; filepos++) - fputc(0xFF,dst); - - // Swap bits and write to file - for (filepos=0x80; filepos < 0x1000000; filepos++) - { - x = fgetc(src); - if (x < 0) break; - - y=0; - for (i=0; i < 8; i++) - y=y| ( (( x & (1<> i) << (7-i) ); // This swaps the bits - - fputc(y,dst); - } - if (filepos < 0x1000000) - printf("ERROR: EOF before end of flash\n"); - - printf("To flash the file in Linux do:\n"); - printf(" cat /proc/mtd (to findout the right mtd)\n"); - printf(" flash_eraseall /dev/mtdX\n"); - printf(" cat file > /dev/mtdX\n"); - - return 0; -} diff --git a/slsDetectorSoftware/jctbDetectorServer/firmware_funcs.c b/slsDetectorSoftware/jctbDetectorServer/firmware_funcs.c deleted file mode 100755 index 0b014f617..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/firmware_funcs.c +++ /dev/null @@ -1,4041 +0,0 @@ -//#define TESTADC -#define TESTADC1 - - -//#define TIMEDBG -#include "server_defs.h" -#include "firmware_funcs.h" -#include "mcb_funcs.h" -#include "slow_adc.h" -#include "registers_m.h" -#define ADC_SPI_REG ADC_WRITE_REG - -#define ADC_SERIAL_CLK_OUT_OFST (0) -#define ADC_SERIAL_CLK_OUT_MSK (0x00000001 << ADC_SERIAL_CLK_OUT_OFST) -#define ADC_SERIAL_DATA_OUT_OFST (1) -#define ADC_SERIAL_DATA_OUT_MSK (0x00000001 << ADC_SERIAL_DATA_OUT_OFST) -#define ADC_SERIAL_CS_OUT_OFST (2) -#define ADC_SERIAL_CS_OUT_MSK (0x0000000F << ADC_SERIAL_CS_OUT_OFST) - -#include "AD9257.h" - -//#define VERBOSE -//#define VERYVERBOSE - - -#ifdef SHAREDMEMORY -#include "sharedmemory.h" -#endif - -#include -#include -#include - -#include -#include -#include /* exit() */ -#include /* memset(), memcpy() */ -#include /* uname() */ -#include -#include /* socket(), bind(), - listen(), accept() */ -#include -#include -#include -#include -#include /* fork(), write(), close() */ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "blackfin.h" -typedef struct ip_header_struct { - u_int16_t ip_len; - u_int8_t ip_tos; - u_int8_t ip_ihl:4 ,ip_ver:4; - u_int16_t ip_offset:13,ip_flag:3; - u_int16_t ip_ident; - u_int16_t ip_chksum; - u_int8_t ip_protocol; - u_int8_t ip_ttl; - u_int32_t ip_sourceip; - u_int32_t ip_destip; -} ip_header; - - -struct timeval tss,tse,tsss; //for timing - -#define MAXDAC 32 -u_int32_t dac[MAXDAC]; - -FILE *debugfp, *datafp; - -int fr; -int wait_time; -int *fifocntrl; - -//int *statusreg; commented out by dhanya -const int nModY=1; -int nModBoard; -int nModX=NMAXMOD; -int dynamicRange=16;//32; -int nSamples=1; - -int dataBytes=NMAXMOD*NCHIP*NCHAN*2; - -int storeInRAM=0; -int ROI_flag=0; -int adcConfigured=-1; -u_int16_t *ram_values=NULL; -char volatile *now_ptr=NULL; -//u_int32_t volatile *values; -extern u_int16_t volatile *values; -int ram_size=0; - -int64_t totalTime=1; -u_int32_t progressMask=0; - -int phase_shift=0;//DEFAULT_PHASE_SHIFT; -int ipPacketSize=DEFAULT_IP_PACKETSIZE; -int udpPacketSize=DEFAULT_UDP_PACKETSIZE; - - -#ifndef NEW_PLL_RECONFIG -u_int32_t clkDivider[4]={32,16,16,16}; -#else -u_int32_t clkDivider[4]={40,20,20,200}; -#endif -int32_t clkPhase[4]={0,0,0,0}; - -u_int32_t adcDisableMask=0; - -int ififostart, ififostop, ififostep, ififo; - -int masterMode=NO_MASTER, syncMode=NO_SYNCHRONIZATION, timingMode=AUTO_TIMING; - -enum externalSignalFlag signals[4]={EXT_SIG_OFF, EXT_SIG_OFF, EXT_SIG_OFF, EXT_SIG_OFF}; - -int withGotthard = 0; - -/**is not const because this value will change after initDetector, is removed from mcb_funcs.c cuz its not used anywhere - * why is this used anywhere instead of macro*/ -int nChans=NCHAN; -int nChips=NCHIP; -//int nDacs;//=NDAC; -//int nAdcs=NADC; - -extern enum detectorType myDetectorType; -/** for jungfrau reinitializing macro later in server_funcs.c in initDetector*/ - extern int N_CHAN; - extern int N_CHIP; - extern int N_DAC; - extern int N_ADC; - extern int N_CHANS; - - -int analogEnable=1; -int digitalEnable=0; - - -int vLimit=-100; - -int nDacs; -int nAdcs; - -char mtdvalue[10]; - -int initDetector() { - - int imod; - // sls_detector_module *myModule; - int n=getNModBoard(); - nModX=n; - -#ifdef VERBOSE - printf("Board is for %d modules\n",n); -#endif - - - // nChans=N_CHAN; - // nChips=N_CHIP; - nDacs=N_DAC; - // nAdcs=N_ADC; - -/* detectorModules=malloc(n*sizeof(sls_detector_module)); */ -/* detectorDacs=malloc(n*N_DAC*sizeof(int)); */ -/* detectorAdcs=malloc(n*N_ADC*sizeof(int)); */ -/* detectorChips=NULL; */ -/* detectorChans=NULL; */ -/* detectorAdcs=NULL; */ -/* if(myDetectorType != JUNGFRAU){ */ -/* detectorChips=malloc(n*N_CHIP*sizeof(int)); */ -/* detectorChans=malloc(n*N_CHIP*N_CHAN*sizeof(int)); */ -/* } */ - -/* #ifdef VERBOSE */ -/* printf("modules from 0x%x to 0x%x\n",(unsigned int)(detectorModules), (unsigned int)(detectorModules+n)); */ -/* printf("dacs from 0x%x to 0x%x\n",(unsigned int)(detectorDacs), (unsigned int)(detectorDacs+n*N_DAC)); */ -/* printf("adcs from 0x%x to 0x%x\n",(unsigned int)(detectorAdcs), (unsigned int)(detectorAdcs+n*N_ADC)); */ -/* if(myDetectorType != JUNGFRAU){ */ -/* printf("chips from 0x%x to 0x%x\n",(unsigned int)(detectorChips), (unsigned int)(detectorChips+n*N_CHIP)); */ -/* printf("chans from 0x%x to 0x%x\n",(unsigned int)(detectorChans), (unsigned int)(detectorChans+n*N_CHIP*N_CHAN)); */ -/* } */ -/* #endif */ - - -/* for (imod=0; imoddacs=detectorDacs+imod*N_DAC; */ -/* (detectorModules+imod)->adcs=detectorAdcs+imod*N_ADC; */ -/* if(myDetectorType != JUNGFRAU){ */ -/* (detectorModules+imod)->chipregs=detectorChips+imod*N_CHIP; */ -/* (detectorModules+imod)->chanregs=detectorChans+imod*N_CHIP*N_CHAN; */ -/* } */ -/* (detectorModules+imod)->ndac=N_DAC; */ -/* (detectorModules+imod)->nadc=N_ADC; */ -/* (detectorModules+imod)->nchip=N_CHIP; */ -/* (detectorModules+imod)->nchan=N_CHIP*N_CHAN; */ -/* (detectorModules+imod)->module=imod; */ -/* (detectorModules+imod)->gain=0; */ -/* (detectorModules+imod)->offset=0; */ -/* (detectorModules+imod)->reg=0; */ -/* /\* initialize registers, dacs, retrieve sn, adc values etc *\/ */ -/* } */ -/* thisSettings=UNINITIALIZED; */ -/* sChan=noneSelected; */ -/* sChip=noneSelected; */ -/* sMod=noneSelected; */ -/* sDac=noneSelected; */ -/* sAdc=noneSelected; */ - -/* /\* */ -/* setCSregister(ALLMOD); //commented out by dhanya */ -/* setSSregister(ALLMOD); */ -/* counterClear(ALLMOD); */ -/* clearSSregister(ALLMOD); */ -/* putout("0000000000000000",ALLMOD); */ -/* *\/ */ - -/* /\* initialize dynamic range etc. *\/ */ -/* /\* dynamicRange=getDynamicRange(); //always 16 not required commented out */ -/* nModX=setNMod(-1);*\/ */ - -/* // dynamicRange=32; */ -/* // initChip(0, 0,ALLMOD); */ -/* //nModX=n; */ -/* // */ - allocateRAM(); - - return OK; -} - - - - - -int cleanFifo(){ -/* u_int32_t addr, reg, val, adc_sync; */ -/* printf("Cleaning FIFO\n"); */ -/* addr=ADC_SYNC_REG; */ - -/* if(withGotthard) */ -/* adc_sync = GOTTHARD_ADCSYNC_VAL; */ -/* else */ -/* adc_sync = ADCSYNC_VAL; */ - - -/* reg = bus_r(addr) & CLEAN_FIFO_MASK; */ - -/* //only for start up */ -/* if(!reg) reg = adc_sync; */ - -/* // 88 3 02111 */ -/* if (ROI_flag==0) { */ -/* val=reg | ADCSYNC_CLEAN_FIFO_BITS | TOKEN_RESTART_DELAY; */ -/* bus_w(addr,val); */ -/* // 88 0 02111 */ -/* val=reg | TOKEN_RESTART_DELAY; */ -/* bus_w(addr,val); */ -/* } */ -/* else { */ -/* //1b332214 */ -/* val=reg | ADCSYNC_CLEAN_FIFO_BITS | TOKEN_RESTART_DELAY_ROI; */ -/* bus_w(addr,val); */ -/* //1b032214 */ -/* val=reg | TOKEN_RESTART_DELAY_ROI; */ -/* bus_w(addr,val); */ - -/* } */ -/* reg=bus_r(addr); */ -/* //#ifdef DDEBUG */ -/* printf("ADC SYNC reg 0x19:%x\n",reg); */ -/* //#endif */ - return OK; -} - - -int setDAQRegister() -{ -/* u_int32_t addr, reg, val; */ -/* addr=DAQ_REG; */ - -/* //depended on adcval */ -/* int packetlength=0x7f; */ -/* if(!ROI_flag) packetlength=0x13f; */ - -/* //depended on pcb rev */ -/* int tokenTiming = TOKEN_TIMING_REV2; */ -/* if((bus_r(PCB_REV_REG)&BOARD_REVISION_MASK)==1) */ -/* tokenTiming= TOKEN_TIMING_REV1; */ - - -/* val = (packetlength<<16) + tokenTiming; */ -/* //val=34+(42<<8)+(packetlength<<16); */ - -/* reg=bus_r(addr); */ -/* bus_w(addr,val); */ -/* reg=bus_r(addr); */ -/* //#ifdef VERBOSE */ -/* printf("DAQ reg 0x15:%x\n",reg); */ -/* //#endif */ - - return OK; -} - - -// direct pattern output -u_int32_t putout(char *s, int modnum) { - int i; - u_int32_t pat; - int addr; - - if (strlen(s)<16) { - fprintf(stdout," *** putout error: incorrect pattern length ***\n"); - fprintf(stdout," %s \n",s); - return FAIL; - } - - pat=0; - for (i=0;i<16;i++) { - if (s[i]=='1') pat=pat+(1<<(15-i)); - } - //addr=DAC_REG+(modnum<<4); - addr=DAC_REG;//+(modnum<3) - return -1; - - if (val>65535 || val<-65535) - return clkPhase[i]; - - // printf("PLL reconfig reset\N"); bus_w(PLL_CNTRL_REG,(1<0) { - inv=0; - phase=val&0xffff; - } else { - inv=0; - val=-1*val; - phase=(~val)&0xffff; - } - - - vv=phase | (i<<16);// | (inv<<21); - - setPllReconfigReg(PLL_PHASE_SHIFT_REG,vv,0); - - clkPhase[i]=val; - return clkPhase[i]; -} - - -int configureFrequency(int val, int i) { - - - u_int32_t l=0x0c; - u_int32_t h=0x0d; - u_int32_t vv; - int32_t phase=0, inv=0; - - u_int32_t tot; - u_int32_t odd=1;//0; - printf("Want to configure frequency of counter %d to %d\n",i,val); - // printf("PLL reconfig reset\N"); bus_w(PLL_CNTRL_REG,(1<3) { - printf("wrong counter number %d\n",i); - return -1; - } - - if (val<=0) { - - printf("get value %d %d \n",i,clkDivider[i]); - return clkDivider[i]; - } - if (i==adc_clk_c){ - if (val>40) - { - printf("Too high frequency %d MHz for these ADCs!\n", val); - return clkDivider[i]; - } - } - - tot= PLL_VCO_FREQ_MHZ/val; - l=tot/2; - h=l; - if (tot>2*l) { - h=l+1; - odd=1; - } - else - { - odd=0; - } - - printf("Counter %d: Low is %d, High is %d\n",i, l,h); - - - vv= (i<<18)| (odd<<17) | l | (h<<8); - - printf("Counter %d, val: %08x\n", i, vv); - setPllReconfigReg(PLL_C_COUNTER_REG, vv,0); - /* // usleep(20); */ - /* //change sync at the same time as */ - /* if (i>0) { */ - /* val= (2<<18)| (odd<<17) | l | (h<<8); */ - - /* printf("Counter %d, val: %08x\n", i, val); */ - /* setPllReconfigReg(PLL_C_COUNTER_REG, val,0); */ - - /* } */ - - - usleep(10000); - - printf("reset pll\n"); - bus_w(PLL_CNTRL_REG,((1<2) */ -/* return -1; */ - -/* if (ic==2) { */ -/* printf("dbit clock is the same as adc clk\n"); */ -/* ic=1; */ - -/* } */ - -/* if (ic==1 && d>40) */ -/* return -1; */ - -/* if (d>160) */ -/* return -1; */ - -/* if (tot>510) */ -/* return -1; */ - -/* if (tot<1) */ -/* return -1; */ - - - -/* clkDivider[ic]=d; */ -/* configurePll(ic); */ - - - -/* return clkDivider[ic]; */ -/* } */ - - -/* int phaseStep(int st){ */ - -/* if (st>65535 || st<-65535) */ -/* return clkPhase[0]; */ -/* #ifdef NEW_PLL_RECONFIG */ -/* printf("reset pll\n"); */ -/* bus_w(PLL_CNTRL_REG,((1<=0 && i<4) - return clkPhase[i]; - else - return -1; - -}; - - - -/* int getDbitPhase() { */ - -/* printf("dbit clock is the same as adc clk\n"); */ -/* return getPhase(); */ - -/* }; */ - - -/* u_int32_t getClockDivider(int ic) { */ - -/* if (ic>2) */ -/* return -1; */ - -/* if (ic==2) { */ -/* printf("dbit clock is the same as adc clk\n"); */ -/* ic=1; */ - -/* } */ -/* return clkDivider[ic]; */ - - -/* /\* int ic=0; *\/ */ -/* /\* u_int32_t val; *\/ */ -/* /\* u_int32_t l,h; *\/ */ - -/* /\* printf("get clk divider\n"); *\/ */ - - -/* /\* setPllReconfigReg(PLL_MODE_REG,1,0); *\/ */ -/* /\* getPllReconfigReg(PLL_MODE_REG,0); *\/ */ - -/* /\* u_int32_t addr=0xa; //c0 *\/ */ -/* /\* if (ic>0) *\/ */ -/* /\* addr=0xb; //c1 *\/ */ - -/* /\* val=getPllReconfigReg(PLL_N_COUNTER_REG,0); *\/ */ -/* /\* printf("Getting N counter %08x\n",val); *\/ */ - -/* /\* l=val&0xff; *\/ */ -/* /\* h=(val>>8)&0xff; *\/ */ - -/* /\* //getPllReconfigReg(PLL_STATUS_REG,0); *\/ */ -/* /\* val=getPllReconfigReg(addr,0); *\/ */ -/* /\* printf("Getting C counter %08x\n",val); *\/ */ - - - -/* /\* return 800/(l+h); *\/ */ - -/* } */ - - -u_int32_t adcPipeline(int d) { - u_int32_t v; - if (d>=0) { - v=bus_r(ADC_PIPELINE_REG)&0x00ff0000; - bus_w(ADC_PIPELINE_REG, d|v); - } - return bus_r(ADC_PIPELINE_REG)&0xff; -} - - -u_int32_t dbitPipeline(int d) { - u_int32_t v; - if (d>=0) { - v=bus_r(ADC_PIPELINE_REG)&0x000000ff; - bus_w(ADC_PIPELINE_REG, v|(d<<16)); - - } - v=bus_r(ADC_PIPELINE_REG)>>16; - return v&0xff; -} - - -u_int32_t setSetLength(int d) { - return 0; -} - -u_int32_t getSetLength() { - return 0; -} - -u_int32_t setOversampling(int d) { - return 0; - /* if (d>=0 && d<=255) */ - /* bus_w(OVERSAMPLING_REG, d); */ - - /* return bus_r(OVERSAMPLING_REG); */ -} - - -u_int32_t setWaitStates(int d1) { - return 0; -} - -u_int32_t getWaitStates() { - return 0; -} - - - -u_int32_t setExtSignal(int d, enum externalSignalFlag mode) { - - //int modes[]={EXT_SIG_OFF, EXT_GATE_IN_ACTIVEHIGH, EXT_GATE_IN_ACTIVELOW,EXT_TRIG_IN_RISING,EXT_TRIG_IN_FALLING,EXT_RO_TRIG_IN_RISING, EXT_RO_TRIG_IN_FALLING,EXT_GATE_OUT_ACTIVEHIGH, EXT_GATE_OUT_ACTIVELOW, EXT_TRIG_OUT_RISING, EXT_TRIG_OUT_FALLING, EXT_RO_TRIG_OUT_RISING, EXT_RO_TRIG_OUT_FALLING}; - // int off=d*SIGNAL_OFFSET; - - u_int32_t c; - c=bus_r(EXT_SIGNAL_REG); - - if (d>=0 && d<4) { - signals[d]=mode; -#ifdef VERBOSE - printf("settings signal variable number %d to value %04x\n", d, signals[d]); -#endif - - // if output signal, set it! - - switch (mode) { - case GATE_IN_ACTIVE_HIGH: - case GATE_IN_ACTIVE_LOW: - if (timingMode==GATE_FIX_NUMBER || timingMode==GATE_WITH_START_TRIGGER) - setFPGASignal(d,mode); - else - setFPGASignal(d,SIGNAL_OFF); - break; - case TRIGGER_IN_RISING_EDGE: - case TRIGGER_IN_FALLING_EDGE: - if (timingMode==TRIGGER_EXPOSURE || timingMode==GATE_WITH_START_TRIGGER) - setFPGASignal(d,mode); - else - setFPGASignal(d,SIGNAL_OFF); - break; - case RO_TRIGGER_IN_RISING_EDGE: - case RO_TRIGGER_IN_FALLING_EDGE: - if (timingMode==TRIGGER_READOUT) - setFPGASignal(d,mode); - else - setFPGASignal(d,SIGNAL_OFF); - break; - case MASTER_SLAVE_SYNCHRONIZATION: - setSynchronization(syncMode); - break; - default: - setFPGASignal(d,mode); - break; - } - - setTiming(GET_EXTERNAL_COMMUNICATION_MODE); - } - - -// if (mode<=RO_TRIGGER_OUT_FALLING_EDGE && mode>=0) -// bus_w(EXT_SIGNAL_REG,((modes[mode])<=0) { -#ifdef VERBOSE - printf("writing signal register number %d mode %04x\n",d, modes[mode]); -#endif - bus_w(EXT_SIGNAL_REG,((modes[mode])<>off); - - if (mode=0 && d<4) { -#ifdef VERBOSE - printf("gettings signal variable number %d value %04x\n", d, signals[d]); -#endif - return signals[d]; - } else - return -1; - - -} - - -int getFPGASignal(int d) { - - int modes[]={SIGNAL_OFF, GATE_IN_ACTIVE_HIGH, GATE_IN_ACTIVE_LOW,TRIGGER_IN_RISING_EDGE, TRIGGER_IN_FALLING_EDGE,RO_TRIGGER_IN_RISING_EDGE, RO_TRIGGER_IN_FALLING_EDGE, GATE_OUT_ACTIVE_HIGH, GATE_OUT_ACTIVE_LOW, TRIGGER_OUT_RISING_EDGE, TRIGGER_OUT_FALLING_EDGE, RO_TRIGGER_OUT_RISING_EDGE,RO_TRIGGER_OUT_FALLING_EDGE}; - - int off=d*SIGNAL_OFFSET; - int mode=((bus_r(EXT_SIGNAL_REG)&(SIGNAL_MASK<>off); - - if (mode<=RO_TRIGGER_OUT_FALLING_EDGE) { - if (modes[mode]!=SIGNAL_OFF && signals[d]!=MASTER_SLAVE_SYNCHRONIZATION) - signals[d]=modes[mode]; -#ifdef VERYVERBOSE - printf("gettings signal register number %d value %04x\n", d, modes[mode]); -#endif - return modes[mode]; - } else - return -1; - -} - - - - - -/* -enum externalCommunicationMode{ - GET_EXTERNAL_COMMUNICATION_MODE, - AUTO, - TRIGGER_EXPOSURE_SERIES, - TRIGGER_EXPOSURE_BURST, - TRIGGER_READOUT, - TRIGGER_COINCIDENCE_WITH_INTERNAL_ENABLE, - GATE_FIX_NUMBER, - GATE_FIX_DURATION, - GATE_WITH_START_TRIGGER, - GATE_COINCIDENCE_WITH_INTERNAL_ENABLE -}; -*/ - - -int setTiming(int ti) { - - - int ret=GET_EXTERNAL_COMMUNICATION_MODE; - int val; - int g=-1, t=-1, rot=-1; - - int i; - - val=bus_r(EXT_SIGNAL_REG); - switch (ti) { - case AUTO_TIMING: - bus_w(EXT_SIGNAL_REG,val&~(0x1)); - break; - - case TRIGGER_EXPOSURE: - bus_w(EXT_SIGNAL_REG,val|(0x1)); - break; - - - default: - break; - - } - - if (bus_r(EXT_SIGNAL_REG)&0x1) - ret=TRIGGER_EXPOSURE; - else - ret=AUTO_TIMING; - - - - // timingMode=ret; - - return ret; - -} - - - -int setConfigurationRegister(int d) { -#ifdef VERBOSE - printf("Setting configuration register to %x",d); -#endif - if (d>=0) { - bus_w(CONFIG_REG,d); - } -#ifdef VERBOSE - printf("configuration register is %x", bus_r(CONFIG_REG)); -#endif - return bus_r(CONFIG_REG); -} - -int setToT(int d) { - //int ret=0; - int reg; -#ifdef VERBOSE - printf("Setting ToT to %d\n",d); -#endif - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Before: ToT is %x\n", reg); -#endif - if (d>0) { - bus_w(CONFIG_REG,reg|TOT_ENABLE_BIT); - } else if (d==0) { - bus_w(CONFIG_REG,reg&(~TOT_ENABLE_BIT)); - } - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("ToT is %x\n", reg); -#endif - if (reg&TOT_ENABLE_BIT) - return 1; - else - return 0; -} - -/* int setOutputMode(int d) { */ -/* //int ret=0; */ -/* int reg; */ -/* int v; */ -/* //#ifdef VERBOSE */ -/* printf("Setting readout flags to to %d\n",d); */ -/* //#endif */ -/* reg=bus_r(CONFIG_REG); */ -/* //#ifdef VERBOSE */ -/* printf("Before: config reg is %x\n", reg); */ -/* //#endif */ -/* if (d>=0) { */ -/* reg=reg & ~(3<<8); */ -/* if (d==DIGITAL_ONLY) */ -/* reg=reg | (3<<8); */ -/* else if (d==ANALOG_AND_DIGITAL) */ -/* reg=reg | (2<<8); */ - -/* bus_w(CONFIG_REG,reg); */ - -/* } */ - -/* reg=bus_r(CONFIG_REG); */ -/* //#ifdef VERBOSE */ -/* printf("After: config reg is %x\n", reg); */ -/* //#endif */ -/* if ((reg&(2<<8))) { */ -/* if (reg&(1<<8)) { */ -/* digitalEnable=1; */ -/* analogEnable=0; */ -/* return DIGITAL_ONLY; */ -/* } else { */ -/* digitalEnable=1; */ -/* analogEnable=0; */ -/* return ANALOG_AND_DIGITAL; */ -/* } */ -/* } else */ -/* if (reg&(1<<8)) */ -/* return -1; */ -/* else */ -/* return NORMAL_READOUT; */ - - -/* } */ - -int setContinousReadOut(int d) { - //int ret=0; - int reg; -#ifdef VERBOSE - printf("Setting Continous readout to %d\n",d); -#endif - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Before: Continous readout is %x\n", reg); -#endif - - - - if (d>0) { - bus_w(CONFIG_REG,reg|CONT_RO_ENABLE_BIT); - } else if (d==0) { - bus_w(CONFIG_REG,reg&(~CONT_RO_ENABLE_BIT)); - } - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Continous readout is %x\n", reg); -#endif - if (reg&CONT_RO_ENABLE_BIT) - return 1; - else - return 0; -} - - -int startReceiver(int start) { - u_int32_t addr=CONFIG_REG; - //#ifdef VERBOSE - if(start) - printf("Setting up detector to send to Receiver\n"); - else - printf("Setting up detector to send to CPU\n"); - //#endif - int reg=bus_r(addr); - //for start recever, write 0 and for stop, write 1 - if (!start) - bus_w(CONFIG_REG,reg&(~GB10_NOT_CPU_BIT)); - else - bus_w(CONFIG_REG,reg|GB10_NOT_CPU_BIT); - - reg=bus_r(addr); -//#ifdef VERBOSE - printf("Config Reg %x\n", reg); -//#endif - int d =reg&GB10_NOT_CPU_BIT; - if(d!=0) d=1; - - printf("Value is %d expected %d\n", d, start); - - if(d!=start) - return FAIL; - else - return OK; -} - - -u_int64_t getDetectorNumber() { - char output[255],mac[255]=""; - u_int64_t res=0; - FILE* sysFile = popen("ifconfig eth0 | grep HWaddr | cut -d \" \" -f 11", "r"); - fgets(output, sizeof(output), sysFile); - pclose(sysFile); - //getting rid of ":" - char * pch; - pch = strtok (output,":"); - while (pch != NULL){ - strcat(mac,pch); - pch = strtok (NULL, ":"); - } - sscanf(mac,"%llx",&res); - return res; -} - -u_int32_t getFirmwareVersion() { - return bus_r(FPGA_VERSION_REG); -} - -u_int32_t getFirmwareSVNVersion(){ - return bus_r(FPGA_VERSION_REG);//(FPGA_SVN_REG); -} - - -// for fpga test -u_int32_t testFpga(void) { - printf("Testing FPGA:\n"); - volatile u_int32_t val,addr,val2; - int result=OK,i; - //fixed pattern - val=bus_r(FIX_PATT_REG); - if (val==FIXED_PATT_VAL) { - printf("fixed pattern ok!! %08x\n",val); - } else { - printf("fixed pattern wrong!! %08x\n",val); - result=FAIL; - } - - //dummy register - addr = DUMMY_REG; - for(i=0;i<1000000;i++) - { - val=0x5A5A5A5A-i; - bus_w(addr, val); - val=bus_r(addr); - if (val!=0x5A5A5A5A-i) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of %x \n",i,val,0x5A5A5A5A-i); - result=FAIL; - } - val=(i+(i<<10)+(i<<20)); - bus_w(addr, val); - val2=bus_r(addr); - if (val2!=val) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! read %x instead of %x.\n",i,val2,val); - result=FAIL; - } - val=0x0F0F0F0F; - bus_w(addr, val); - val=bus_r(addr); - if (val!=0x0F0F0F0F) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of 0x0F0F0F0F \n",i,val); - result=FAIL; - } - val=0xF0F0F0F0; - bus_w(addr, val); - val=bus_r(addr); - if (val!=0xF0F0F0F0) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of 0xF0F0F0F0 \n\n",i,val); - result=FAIL; - } - } - if(result==OK) - { - printf("----------------------------------------------------------------------------------------------"); - printf("\nATTEMPT 1000000: FPGA DUMMY REGISTER OK!!!\n"); - printf("----------------------------------------------------------------------------------------------"); - } - printf("\n"); - return result; -} - - -// for fpga test -u_int32_t testRAM(void) { - int result=OK; - - printf("TestRAM not implemented\n"); - -/* int i=0; - allocateRAM(); - // while(i<100000) { - memcpy(ram_values, values, dataBytes); - printf ("Testing RAM:\t%d: copied fifo %x to memory %x size %d\n",i++, (unsigned int)(values), (unsigned int)(ram_values), dataBytes); - // } - * -*/ - return result; -} - - -int getNModBoard() { - - return 1; -} - -int setNMod(int n) { - -/* printf("Writin ADC disable register %08x\n",n); */ -/* bus_w(ADC_LATCH_DISABLE_REG,n); */ - return getNMod(); -} - -int getNMod() { -/* u_int32_t reg; */ -/* int i; */ -/* reg=bus_r(ADC_LATCH_DISABLE_REG); */ - -/* printf("Read ADC disable register %08x\n",reg); */ -/* nModX=32; */ -/* for (i=0; i<32; i++) { */ -/* if (reg & (1<=0) { - nSamples=value; - bus_w(NSAMPLES_REG,nSamples); - } - getDynamicRange(); - allocateRAM(); - //printf("Setting dataBytes to %d: dr %d; samples %d\n",dataBytes, dynamicRange, nSamples); - return nSamples; -} - -int64_t setDelay(int64_t value){ - /* time is in ns */ - if (value!=-1) { - value*=(1E-3*clkDivider[1]);//(1E-9*CLK_FREQ); - } - return set64BitReg(value,SET_DELAY_LSB_REG, SET_DELAY_MSB_REG)/(1E-3*clkDivider[1]);//(1E-9*CLK_FREQ); -} - -int64_t getDelay(){ - return get64BitReg(GET_DELAY_LSB_REG, GET_DELAY_MSB_REG)/(1E-3*clkDivider[1]);//(1E-9*CLK_FREQ); -} - -int64_t setTrains(int64_t value){ - printf("Set cycles %lld\n",value); - return set64BitReg(value, SET_CYCLES_LSB_REG, SET_CYCLES_MSB_REG); -} - -int64_t getTrains(){ - return get64BitReg(GET_CYCLES_LSB_REG, GET_CYCLES_MSB_REG); -} - - -int64_t setProbes(int64_t value){ - return 0; -} - - -int64_t setProgress() { - - //????? eventually call after setting the registers - -return 0; - -} - - -int64_t getProgress() { - - - //should be done in firmware!!!! - - return 0; - -} - -int64_t getActualTime(){ - return get64BitReg(GET_ACTUAL_TIME_LSB_REG, GET_ACTUAL_TIME_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t getMeasurementTime(){ - int64_t v=get64BitReg(GET_MEASUREMENT_TIME_LSB_REG, GET_MEASUREMENT_TIME_MSB_REG); - // int64_t mask=0x8000000000000000; - // if (v & mask ) { - //#ifdef VERBOSE - // printf("no measurement time left\n"); - //#endif - // return -1E+9; - // } else - return v/(1E-9*CLK_FREQ); -} - -int64_t getFramesFromStart(){ - int64_t v=get64BitReg(FRAMES_FROM_START_LSB_REG, FRAMES_FROM_START_MSB_REG); - int64_t v1=get64BitReg(FRAMES_FROM_START_PG_LSB_REG, FRAMES_FROM_START_PG_MSB_REG); - - printf("Frames from start data streaming %lld\n",v); - printf("Frames from start run control %lld\n",v1); - - // int64_t mask=0x8000000000000000; - // if (v & mask ) { - //#ifdef VERBOSE - // printf("no measurement time left\n"); - //#endif - // return -1E+9; - // } else - return v; -} - - -int setROI(int nroi,ROI* arg,int *retvalsize, int *ret) { - - - - // ROI retval[MAX_ROIS]; - int i, ich; - adcDisableMask=0xffffffff; - - printf("Setting ROI\n"); - if (nroi>=0) { - if (nroi==0) { - adcDisableMask=0; - } else { - for (i=0; i=0 && ichMAX_ROIS) { - *retvalsize-=1; - break; - } - arg[*retvalsize-1].xmin=ich; - arg[*retvalsize-1].xmax=ich; - } - else { - if ((adcDisableMask)&(1<<(ich-1))) { - *retvalsize+=1; - if (*retvalsize>MAX_ROIS) { - *retvalsize-=1; - break; - } - arg[*retvalsize-1].xmin=ich; - } - arg[*retvalsize-1].xmax=ich; - } - } - } - - for (ich=0; ich<*retvalsize; ich++) { - printf("%d xmin %d xmax %d\n", ich, arg[ich].xmin, arg[ich].xmax); - } - - getDynamicRange(); - return *retvalsize;/*warning: function returns address of local variable*/ - -} - - -int loadImage(int index, short int ImageVals[]){ - - printf("loadImage Not implemented yet\n"); - - /* - u_int32_t address; - switch (index) { - case DARK_IMAGE : - address = DARK_IMAGE_REG; - break; - case GAIN_IMAGE : - address = GAIN_IMAGE_REG; - break; - } - volatile u_int16_t *ptr; - ptr=(u_int16_t*)(CSP0BASE+address*2); -#ifdef VERBOSE - int i; - for(i=0;i<6;i++) - printf("%d:%d\t",i,ImageVals[i]); -#endif - memcpy(ptr,ImageVals ,dataBytes); -#ifdef VERBOSE - printf("\nLoaded x%08x address with image of index %d\n",(unsigned int)(ptr),index); -#endif - */ - - return OK; -} - - - -int64_t getProbes(){ - return 0; -} - - -int setDACRegister(int idac, int val, int imod) { -/* u_int32_t addr, reg, mask; */ -/* int off; */ -/* #ifdef VERBOSE */ -/* if(val==-1) */ -/* printf("Getting dac register%d module %d\n",idac,imod); */ -/* else */ -/* printf("Setting dac register %d module %d to %d\n",idac,imod,val); */ -/* #endif */ - -/* switch(idac){ */ -/* case 0: */ -/* case 1: */ -/* case 2: */ -/* addr=MOD_DACS1_REG; */ -/* break; */ -/* case 3: */ -/* case 4: */ -/* case 5: */ -/* addr=MOD_DACS2_REG; */ -/* break; */ -/* case 6: */ -/* case 7: */ -/* addr=MOD_DACS3_REG; */ -/* break; */ -/* default: */ -/* printf("weird idac value %d\n",idac); */ -/* return -1; */ -/* break; */ -/* } */ -/* //saving only the msb */ -/* val=val>>2; */ - -/* off=(idac%3)*10; */ -/* mask=~((0x3ff)<=0 && val>off)&0x3ff; */ -/* //since we saved only the msb */ -/* val=val<<2; */ - -/* //val=(bus_r(addr)>>off)&0x3ff; */ - - -/* #ifdef VERBOSE */ -/* printf("Dac %d module %d register is %d\n\n",idac,imod,val); */ -/* #endif */ -/* return val; */ -} - - -int getTemperature(int tempSensor){ - int val; - int imod=0;//ignoring more than 1 mod for now - int i,j,repeats=6; - u_int32_t tempVal=0; -#ifdef VERBOSE - char cTempSensor[2][100]={"ADCs/ASICs","VRs/FPGAs"}; - printf("Getting Temperature of module:%d for the %s for tempsensor:%d\n",imod,cTempSensor[tempSensor],tempSensor); -#endif - bus_w(TEMP_IN_REG,(T1_CLK_BIT)|(T1_CS_BIT)|(T2_CLK_BIT)|(T2_CS_BIT));//standby - bus_w(TEMP_IN_REG,((T1_CLK_BIT)&~(T1_CS_BIT))|(T2_CLK_BIT));//high clk low cs - - for(i=0;i<20;i++) { - //repeats is number of register writes for delay - for(j=0;j>1);//fpga - } - } - - bus_w(TEMP_IN_REG,(T1_CLK_BIT)|(T1_CS_BIT)|(T2_CLK_BIT)|(T2_CS_BIT));//standby - val=((int)tempVal)/4.0; - -#ifdef VERBOSE - printf("Temperature of module:%d for the %s is %.2fC\n",imod,cTempSensor[tempSensor],val); -#endif - return val; -} - - - -int initHighVoltage(int val, int imod){ - - - u_int32_t offw,codata; - u_int16_t valw, dacvalue=-1; - int i,ddx,csdx,cdx;//iru, - float alpha=0.55;//, fval=val; - - offw=DAC_REG; - - if (val!=-1) { - if (val<0) { - printf("val is %d: should switch the relais!\n", val); - val=-100; - dacvalue=0; - } else if (val==0) { - dacvalue=0; - val=0; - } else if (val<60) { - dacvalue=0; - val=60; - } else if (val>=200) { - dacvalue=0x1; - val=200; - } else { - dacvalue=1.+(200.-val)/alpha; - val=200.-(dacvalue-1)*alpha; - } - printf ("****************************** setting val %d, dacval %d\n",val, dacvalue); - - // if (dacvalue>=0) { - - - ddx=8; csdx=10; cdx=9; - codata=((dacvalue)&0xff); - - - valw=(bus_r(offw) & 0x7fff) | 0x00ff; - - bus_w(offw,(valw)); // start point - valw=((valw&(~(0x1<>(7-i))&0x1)<=0) { - valw=bus_r(offw) | 0x8000;; //switch on HV - printf("switch on HV in CTB4 %x\n"); - } else { - valw=bus_r(offw) & 0x7fff;//switch off HV - printf("switch off HV in CTB4\n"); - } - - - bus_w(offw,(valw)); // stop point =start point of course */ - printf("Writing %d in HVDAC \n",dacvalue); - - bus_w(HV_REG,val); - - - //added for CTB5! - - // valw=bus_r(POWER_ON_REG); - if (val>=0) { - i=bus_r(POWER_ON_REG) | 0x80000000;; //switch on HV - printf("switch on HV in CTB5 %08x\n", i); - } else { - i=bus_r(POWER_ON_REG) & 0x7fffffff;//switch off HV - printf("switch off HV in CTB5 %08x\n", i); - } - - bus_w(POWER_ON_REG,i); - - - - // } - } - - - - return (int16_t)bus_r(HV_REG); - - - - // return val; -} - - - -int initConfGain(int isettings,int val,int imod){ - int retval; -/* u_int32_t addr=CONFGAIN_REG; */ - -/* if(isettings!=-1){ */ -/* #ifdef VERBOSE */ -/* printf("Setting Gain of module:%d with val:%d\n",imod,val); */ -/* #endif */ -/* bus_w(addr,val); */ -/* } */ -/* retval=(bus_r(addr)); */ -/* #ifdef VERBOSE */ -/* printf("Value read from Gain reg is %d\n",retval); */ -/* #endif */ - return retval; -} - - - -/* int setADC(int adc){ */ -/* /\* int reg,nchips,mask,nchans; *\/ */ - -/* /\* if(adc==-1) ROI_flag=0; *\/ */ -/* /\* else ROI_flag=1; *\/ */ - -/* /\* // setDAQRegister();//token timing *\/ */ -/* /\* cleanFifo();//adc sync *\/ */ - -/* /\* //with gotthard module *\/ */ -/* /\* if(withGotthard){ *\/ */ -/* /\* //set packet size *\/ */ -/* /\* ipPacketSize= DEFAULT_IP_PACKETSIZE; *\/ */ -/* /\* udpPacketSize=DEFAULT_UDP_PACKETSIZE; *\/ */ -/* /\* //set channel mask *\/ */ -/* /\* nchips = GOTTHARDNCHIP; *\/ */ -/* /\* nchans = GOTTHARDNCHAN; *\/ */ -/* /\* mask = ACTIVE_ADC_MASK; *\/ */ -/* /\* } *\/ */ - -/* /\* //with moench module all adc *\/ */ -/* /\* else{/\\* if(adc==-1){*\\/ *\/ */ -/* /\* //set packet size *\/ */ -/* /\* ipPacketSize= DEFAULT_IP_PACKETSIZE; *\/ */ -/* /\* udpPacketSize=DEFAULT_UDP_PACKETSIZE; *\/ */ -/* /\* //set channel mask *\/ */ -/* /\* nchips = N_CHIP; *\/ */ -/* /\* nchans = N_CHANS; *\/ */ -/* /\* mask = ACTIVE_ADC_MASK; *\/ */ -/* /\* }/\\* *\/ */ -/* /\* //with moench module 1 adc -- NOT IMPLEMENTED *\/ */ -/* /\* else{ *\/ */ -/* /\* ipPacketSize= ADC1_IP_PACKETSIZE; *\/ */ -/* /\* udpPacketSize=ADC1_UDP_PACKETSIZE; *\/ */ -/* /\* //set channel mask *\/ */ -/* /\* nchips = NCHIPS_PER_ADC; *\/ */ -/* /\* nchans = GOTTHARDNCHAN; *\/ */ -/* /\* mask = 1< 1 ) { - sum += *addr++; - count -= 2; - } - if( count > 0 ) sum += *addr; // Add left-over byte, if any - while (sum>>16) sum = (sum & 0xffff) + (sum >> 16);// Fold 32-bit sum to 16 bits - checksum = (~sum)&0xffff; - - printf("IP checksum is 0x%lx\n",checksum); - - return checksum; -} - - - -#ifdef NEW_GBE_INTERFACE -int writeGbeReg(int ivar, uint32_t val, int addr, int interface) { -/* #define GBE_CTRL_WSTROBE 0 */ -/* #define GBE_CTRL_VAR_OFFSET 16 */ -/* #define GBE_CTRL_VAR_MASK 0XF */ -/* #define GBE_CTRL_RAMADDR_OFFSET 24 */ -/* #define GBE_CTRL_RAMADDR_MASK 0X3F */ -/* #define GBE_CTRL_INTERFACE 23 */ - uint32_t ctrl=((ivar&GBE_CTRL_VAR_MASK)<>32)&0xFFFFFFFF; - vals[IPCHECKSUM_ADDR]=checksum; - vals[GBE_DELAY_ADDR]=0; - vals[GBE_RESERVED1_ADDR]=sourceport; - vals[GBE_RESERVED2_ADDR]=interface; - vals[DETECTOR_MAC_L_ADDR]=(sourcemac)&0xFFFFFFFF; - vals[DETECTOR_MAC_H_ADDR]=(sourcemac>>32)&0xFFFFFFFF; - vals[DETECTOR_IP_ADDR]=sourceip; - - for (ivar=0; ivar>32)&0xFFFFFFFF);//rx_udpmacH_AReg_c - bus_w(RX_UDPMACL_AREG,(destmac)&0xFFFFFFFF);//rx_udpmacL_AReg_c - bus_w(DETECTORMACH_AREG,(sourcemac>>32)&0xFFFFFFFF);//detectormacH_AReg_c - bus_w(DETECTORMACL_AREG,(sourcemac)&0xFFFFFFFF);//detectormacL_AReg_c - bus_w(UDPPORTS_AREG,((sourceport&0xFFFF)<<16)+(destport&0xFFFF));//udpports_AReg_c - bus_w(IPCHKSUM_AREG,(checksum&0xFFFF));//ipchksum_AReg_c - - -#endif - - bus_w(CONTROL_REG,GB10_RESET_BIT); - sleep(1); - bus_w(CONTROL_REG,0); - usleep(10000); - bus_w(CONFIG_REG,conf | GB10_NOT_CPU_BIT); - printf("System status register is %08x\n",bus_r(SYSTEM_STATUS_REG)); - -return 0; //any value doesnt matter - dhanya - -} - - - - - - - - - - - -int configureMAC(uint32_t destip,uint64_t destmac,uint64_t sourcemac,int sourceip,int ival,uint32_t destport) { -//int configureMAC(int ipad,long long int macad,long long int detectormacad, int detipad, int ival, int udpport){ - - uint32_t sourceport = 0x7e9a; // 0xE185; - int interface=0; - int ngb; -volatile u_int32_t conf= bus_r(CONFIG_REG); - - - - - -#ifdef NEW_GBE_INTERFACE - ngb=2; - printf("--------- New XGB interface\n"); -#else - ngb=1; - printf("********* Old XGB interface\n"); -#endif - - for (interface=0; interface >17)&1); - now_ptr+=8; - - } - // bus_w16(DUMMY_REG,0); // - /* #ifdef TIMEDBG */ - - /* gettimeofday(&tss,NULL); */ - /* printf("read data loop = %ld usec\n",(tss.tv_usec) - (tse.tv_usec)); */ - -/* #endif */ -//#ifdef VERBOSE - // printf("*"); - //#endif - // printf("\n"); - return ram_values; -} - - - -u_int16_t* fifo_read_frame() -{ -#ifdef TIMEDBG - gettimeofday(&tsss,NULL); -#endif - - // u_int16_t *dum; - int ns=0; - now_ptr=(char*)ram_values; - while(ns>(ipos))&0x1; - ichan++; - } - } - break; - case 4: - for (ibyte=0; ibyte>(ipos*4))&0xf; - ichan++; - } - } - break; - case 8: - for (ichan=0; ichan0) { - dynamicRange=16; - } - getDynamicRange(); - allocateRAM(); - printf("Setting dataBytes to %d: dr %d; samples %d\n",dataBytes, dynamicRange, nSamples); - return getDynamicRange(); -} - - - - - - -int getDynamicRange() { - if(myDetectorType == JUNGFRAU){ - dynamicRange=16; - return dynamicRange; - } - - nSamples=bus_r(NSAMPLES_REG); - getChannels(); - dataBytes=nModX*N_CHIP*getChannels()*2*nSamples; - printf("data bytes is:%d\n",dataBytes); - return dynamicRange;//nSamples; -} - -int testBus() { - u_int32_t j; - u_int64_t i, n, nt; - // char cmd[100]; - u_int32_t val=0x0; - int ifail=OK; - // printf("%s\n",cmd); - // system(cmd); - i=0; - - n=1000000; - nt=n/100; - printf("testing bus %d times\n",(int)n); - while (i0) - storeInRAM=1; - else - storeInRAM=0; - return allocateRAM(); -} - -int getChannels() { - int nch=0; - int i; - - if (analogEnable) { - nch+=32; - for (i=0; i1) { - - clearRAM(); - ram_values=malloc(size); - // ram_values=realloc(ram_values,size)+2; - // if (ram_values) - // break; - // nSamples--; - //} - - if (ram_values) { - now_ptr=(char*)ram_values; - - //#ifdef VERBOSE - printf("ram allocated 0x%x of size %d to %x\n",(int)now_ptr,(unsigned int) size,(unsigned int)(now_ptr+size)); - //#endif - ram_size=size; - return OK; - } - - - printf("Fatal error: there must be a memory leak somewhere! You can't allocate even one frame!\n"); - return FAIL; - - - - -} - - -int writeADC(int addr, int val) { - setAdc(addr,val); - return OK; - /* u_int32_t valw,codata,csmask; */ - /* int i,cdx,ddx; */ - /* cdx=0; ddx=1; */ - /* csmask=0xfc; // 1111100 */ - - /* codata=val + (addr<< 8); */ - /* printf("***** ADC SPI WRITE TO REGISTER %04X value %04X\n",addr,val); */ - /* // start point */ - /* valw=0xff; */ - /* bus_w16(ADC_WRITE_REG,(valw)); */ - - /* //chip sel bar down */ - /* valw=((0xffffffff&(~csmask))); */ - /* bus_w16(ADC_WRITE_REG,valw); */ - - /* for (i=0;i<24;i++) { */ - /* //cldwn */ - /* valw=valw&(~(0x1<>(23-i))&0x1)<=MAX_PATTERN_LENGTH) - return -1; - - - printf("read %x\n",addr); - cntrl= (addr&APATTERN_MASK) << PATTERN_CTRL_ADDR_OFFSET; - bus_w(PATTERN_CNTRL_REG, cntrl); - usleep(1000); - bus_w(PATTERN_CNTRL_REG, cntrl | (1<< PATTERN_CTRL_READ_BIT) ); - usleep(1000); - printf("reading\n"); - word=get64BitReg(PATTERN_OUT_LSB_REG,PATTERN_OUT_MSB_REG); - printf("read %llx\n", word); - usleep(1000); - bus_w(PATTERN_CNTRL_REG, cntrl); - printf("done\n"); - - return word; -} - -uint64_t writePatternWord(int addr, uint64_t word) { - - - int cntrl=0; - if (addr>=MAX_PATTERN_LENGTH) - return -1; - - printf("write %x %llx\n",addr, word); - if (word!=-1){ - - set64BitReg(word,PATTERN_IN_REG_LSB,PATTERN_IN_REG_MSB); - - - cntrl= (addr&APATTERN_MASK) << PATTERN_CTRL_ADDR_OFFSET; - bus_w(PATTERN_CNTRL_REG, cntrl); - usleep(1000); - bus_w(PATTERN_CNTRL_REG, cntrl | (1<< PATTERN_CTRL_WRITE_BIT) ); - usleep(1000); - bus_w(PATTERN_CNTRL_REG, cntrl); - return word; - } else - return readPatternWord(addr); -} -uint64_t writePatternIOControl(uint64_t word) { - uint64_t c=0xffffffffffffffffULL; - if (word!=c) { /*warning: integer constant is too large for ‘long’ type*/ - // printf("%llx %llx %lld",get64BitReg(PATTERN_IOCTRL_REG_LSB,PATTERN_IOCTRL_REG_MSB),word); - set64BitReg(word,PATTERN_IOCTRL_REG_LSB,PATTERN_IOCTRL_REG_MSB); - // printf("************ write IOCTRL (%x)\n",PATTERN_IOCTRL_REG_MSB); - } - return get64BitReg(PATTERN_IOCTRL_REG_LSB,PATTERN_IOCTRL_REG_MSB); - -} -uint64_t writePatternClkControl(uint64_t word) { - uint64_t c=0xffffffffffffffffULL; - if (word!=c) set64BitReg(word,PATTERN_IOCLKCTRL_REG_LSB,PATTERN_IOCLKCTRL_REG_MSB);/*warning: integer constant is too large for ‘long’ type*/ - return get64BitReg(PATTERN_IOCLKCTRL_REG_LSB,PATTERN_IOCLKCTRL_REG_MSB); - -} - -int setPatternLoop(int level, int *start, int *stop, int *n) { - int ret=OK; - int lval=0; - - int nreg; - int areg; - - switch (level ) { - case 0: - nreg=PATTERN_N_LOOP0_REG; - areg=PATTERN_LOOP0_AREG; - break; - case 1: - nreg=PATTERN_N_LOOP1_REG; - areg=PATTERN_LOOP1_AREG; - break; - case 2: - nreg=PATTERN_N_LOOP2_REG; - areg=PATTERN_LOOP2_AREG; - break; - case -1: - nreg=-1; - areg=PATTERN_LIMITS_AREG; - break; - default: - return FAIL; - } - - printf("level %d start %x stop %x nl %d\n",level, *start, *stop, *n); - if (nreg>=0) { - if ((*n)>=0) bus_w(nreg, *n); - printf ("n %d\n",*n); - *n=bus_r(nreg); - printf ("n %d\n",*n); - - } - - printf("level %d start %x stop %x nl %d\n",level, *start, *stop, *n); - lval=bus_r(areg); -/* printf("l=%x\n",bus_r16(areg)); */ -/* printf("m=%x\n",bus_r16_m(areg)); */ - - - - - - printf("lval %x\n",lval); - if (*start==-1) *start=(lval>> ASTART_OFFSET) & APATTERN_MASK; - printf("start %x\n",*start); - - - if (*stop==-1) *stop=(lval>> ASTOP_OFFSET) & APATTERN_MASK; - printf("stop %x\n",*stop); - - lval= ((*start & APATTERN_MASK) << ASTART_OFFSET) | ((*stop & APATTERN_MASK) << ASTOP_OFFSET); - printf("lval %x\n",lval); - - bus_w(areg,lval); - printf("lval %x\n",lval); - - - return ret; -} - - -int setPatternWaitAddress(int level, int addr) { - int reg; - - switch (level) { - case 0: - reg=PATTERN_WAIT0_AREG; - break; - case 1: - reg=PATTERN_WAIT1_AREG; - break; - case 2: - reg=PATTERN_WAIT2_AREG; - break; - default: - return -1; - }; - // printf("BEFORE *********PATTERN IOCTRL IS %llx (%x)\n",writePatternIOControl(-1), PATTERN_IOCTRL_REG_MSB); - - // printf ("%d addr %x (%x)\n",level,addr,reg); - if (addr>=0) bus_w(reg, addr); - // printf ("%d addr %x %x (%x) \n",level,addr, bus_r(reg), reg); - - // printf("AFTER *********PATTERN IOCTRL IS %llx (%x)\n",writePatternIOControl(-1), PATTERN_IOCTRL_REG_MSB); - - return bus_r(reg); -} - - -uint64_t setPatternWaitTime(int level, uint64_t t) { - int reglsb; - int regmsb; - - - switch (level) { - case 0: - reglsb=PATTERN_WAIT0_TIME_REG_LSB; - regmsb=PATTERN_WAIT0_TIME_REG_MSB; - break; - case 1: - reglsb=PATTERN_WAIT1_TIME_REG_LSB; - regmsb=PATTERN_WAIT1_TIME_REG_MSB; - break; - case 2: - reglsb=PATTERN_WAIT2_TIME_REG_LSB; - regmsb=PATTERN_WAIT2_TIME_REG_MSB; - break; - default: - return -1; - } - - - if (t>=0) set64BitReg(t,reglsb,regmsb); - return get64BitReg(reglsb,regmsb); - -} - - -void initDac(int dacnum) { - - - u_int32_t offw,codata; - u_int16_t valw; - int i,ddx,csdx,cdx; - - - - //setting int reference - offw=DAC_REG; - - - ddx=0; cdx=1; - csdx=dacnum/8+2; - - - printf("data bit=%d, clkbit=%d, csbit=%d",ddx,cdx,csdx); - codata=(((0x6)<<4)|((0xf)<<16)|((0x0<<4)&0xfff0)); - - valw=0x00ff|(bus_r(offw)&0xff00); - bus_w(offw,(valw)); // start point - valw=((valw&(~(0x1<>(24-i))&0x1)<>(24-i))&0x1)); - valw=((valw&(~(0x1<>16)&0xffff; */ -/* else */ -/* return retval&0xffff; */ - -} - - - - -int setPower(int ind, int val) { - int dacindex=-1; - int dacval=-1; - int pwrindex=-1; - int retval=-1; - int retval1=-1; - - u_int32_t preg; - - int vchip=2700-(getDacRegister(19)*1000)/4095; - int vmax=vchip-200; - int vmin=600; - - printf("---------------------------------------------Current V_Chip is %d mV\n",vchip); - - switch (ind) { - - case V_POWER_CHIP: - dacindex=19; - pwrindex=-1; - break; - case V_POWER_A: - dacindex=22; - pwrindex=1; - break; - case V_POWER_B: - dacindex=21; - pwrindex=2; - break; - case V_POWER_C: - dacindex=20; - pwrindex=3; - break; - case V_POWER_D: - dacindex=18; - pwrindex=4; - break; - case V_POWER_IO: - dacindex=23; - pwrindex=0; - break; - case V_LIMIT: - dacindex=-1; - pwrindex=-1; - break; - default: - pwrindex=-1; - dacindex=-1; - } - - if (val==-1) { - printf("get\n"); - dacval=-1; - } else { - if (pwrindex>=0) { - printf("vpower\n"); - dacval=((vmax-val)*4095)/(vmax-vmin); - if (dacval<0) - dacval=0; - if (dacval>4095) - dacval=-100; - if (val==-100) - dacval=-100; - - - } else if (dacindex>=0) { - printf("vchip\n"); - dacval=((2700-val)*4095)/1000; - if (dacval<0) - dacval=0; - if (dacval>4095) - dacval=4095; - - } else { - vLimit=val; - printf("vlimit %d\n",vLimit ); - } - - } - - if (pwrindex>=0 && val!=-1) { - preg=bus_r(POWER_ON_REG); - printf("power reg is %08x\n",bus_r(POWER_ON_REG)); - printf("Switching off power %d\n", pwrindex); - bus_w(POWER_ON_REG,preg&(~(1<<(16+pwrindex)))); - setDac(dacindex,-100); - printf("power reg is %08x\n",bus_r(POWER_ON_REG)); - retval=0; - } - - if (dacindex>0 && dacval!=-100) { - - printf("Setting power %d to %d mV\n",ind,val); - printf("Setting DAC %d to value %d\n",dacindex,dacval); - retval=setDac(dacindex,dacval); - if (pwrindex>=0 && dacval>=0 ) { - preg=bus_r(POWER_ON_REG); - printf("power reg is %08x\n",bus_r(POWER_ON_REG)); - printf("Switching on power %d\n", pwrindex); - bus_w(POWER_ON_REG,preg|((1<<(16+pwrindex)))); - printf("power reg is %08x\n",bus_r(POWER_ON_REG)); - } - } - - if (pwrindex>=0) { - if (bus_r(POWER_ON_REG)&(1<<(16+pwrindex))){ - vmax=2700-(getDacRegister(19)*1000)/4095-200; - printf("Vchip id %d mV\n",vmax+200); - retval1=vmax-(retval*(vmax-vmin))/4095; - printf("Vdac id %d mV\n",retval1); - if (retval1>vmax) - retval1=vmax; - if (retval1=0) { - if (retval>=0) { - retval1=2700-(retval*1000)/4095; - printf("Vchip is %d mV\n",vmax); - } else - retval1=-1; - } else { - printf("Get vlimit %d\n",vLimit); - retval=vLimit; - retval1=vLimit; - } - - /* switch (ind) { */ -/* case V_POWER_A: */ -/* break; */ -/* case V_POWER_B: */ -/* break; */ -/* case V_POWER_C: */ -/* break; */ -/* case V_POWER_D: */ -/* break; */ -/* case V_POWER_IO: */ -/* break; */ -/* case V_POWER_CHIP: */ -/* break; */ -/* default: */ -/* retval1=retval; */ -/* } */ - - - return retval1; - - -} - - -void defineGPIOpins(){ - //define the gpio pins - system("echo 7 > /sys/class/gpio/export"); - system("echo 9 > /sys/class/gpio/export"); - //define their direction - system("echo in > /sys/class/gpio/gpio7/direction"); - system("echo out > /sys/class/gpio/gpio9/direction"); -} - -void resetFPGA(){ - cprintf(BLUE,"\n*** Reseting FPGA ***\n"); - FPGAdontTouchFlash(); - FPGATouchFlash(); - usleep(250*1000); -} - -void FPGAdontTouchFlash(){ - //tell FPGA to not touch flash - system("echo 0 > /sys/class/gpio/gpio9/value"); - //usleep(100*1000); -} - -void FPGATouchFlash(){ - //tell FPGA to touch flash to program itself - system("echo 1 > /sys/class/gpio/gpio9/value"); -} - - -int startWritingFPGAprogram(FILE** filefp){ -#ifdef VERY_VERBOSE - printf("\n at startWritingFPGAprogram \n"); -#endif - - //getting the drive - char output[255]; - FILE* fp = popen("awk \'$4== \"\\\"bitfile(spi)\\\"\" {print $1}\' /proc/mtd", "r"); - fgets(output, sizeof(output), fp); - pclose(fp); - strcpy(mtdvalue,"/dev/"); - char* pch = strtok(output,":"); - if(pch == NULL){ - cprintf(RED,"Could not get mtd value\n"); - return FAIL; - } - strcat(mtdvalue,pch); - printf ("\nFlash drive found: %s\n",mtdvalue); - - - FPGAdontTouchFlash(); - - //writing the program to flash - *filefp = fopen(mtdvalue, "w"); - if(*filefp == NULL){ - cprintf(RED,"Unable to open %s in write mode\n",mtdvalue); - return FAIL; - } - printf("flash ready for writing\n"); - - return OK; -} - - -void eraseFlash(){ -#ifdef VERY_VERBOSE - printf("\n at eraseFlash \n"); -#endif - - char command[255]; - sprintf(command,"flash_eraseall %s",mtdvalue); - system(command); - printf("flash erased\n"); -} - -int stopWritingFPGAprogram(FILE* filefp){ -#ifdef VERY_VERBOSE - printf("\n at stopWritingFPGAprogram \n"); -#endif - - int wait = 0; - if(filefp!= NULL){ - fclose(filefp); - wait = 1; - } - - //touch and program - FPGATouchFlash(); - - if(wait){ -#ifdef VERY_VERBOSE - printf("Waiting for FPGA to program from flash\n"); -#endif - //waiting for success or done - char output[255]; - int res=0; - while(res == 0){ - FILE* sysFile = popen("cat /sys/class/gpio/gpio7/value", "r"); - fgets(output, sizeof(output), sysFile); - pclose(sysFile); - sscanf(output,"%d",&res); -#ifdef VERY_VERBOSE - printf("gpi07 returned %d\n",res); -#endif - } - } - printf("FPGA has picked up the program from flash\n\n"); - - - return OK; -} - -int writeFPGAProgram(char* fpgasrc, size_t fsize, FILE* filefp){ -#ifdef VERY_VERBOSE - printf("\n at writeFPGAProgram \n"); - cprintf(BLUE,"address of fpgasrc:%p\n",(void *)fpgasrc); - cprintf(BLUE,"fsize:%d\n",fsize); - cprintf(BLUE,"pointer:%p\n",(void*)filefp); -#endif - - if(fwrite((void*)fpgasrc , sizeof(char) , fsize , filefp )!= fsize){ - cprintf(RED,"Could not write FPGA source to flash\n"); - return FAIL; - } -#ifdef VERY_VERBOSE - cprintf(BLUE,"program written to flash\n"); -#endif - return OK; -} - - - - -int powerChip(int arg) { - //#ifndef CTB - - u_int32_t preg=bus_r(POWER_ON_REG); - if (myDetectorType!=JUNGFRAUCTB) { - printf("This is not a JCTB!\n"); - if (arg>=0) { - if (arg) - bus_w(POWER_ON_REG,preg|0xffff0000); - else - bus_w(POWER_ON_REG,preg&0x0000ffff); - preg=bus_r(POWER_ON_REG); - } - } - printf("Power register is %08x\n",preg); - if (preg&0xffff0000) - return 1; - else - return 0; -} - - - -int vLimitCompliant(int val_mV) { - int ret=0; - - if (vLimit>0) { - if (val_mV<=vLimit) ret=1; - } else ret=1; - - return ret; - - -} - - -int dacSPI(int codata) { - u_int32_t offw; - int valw, vv; - int i, ddx,cdx; - - ddx=0; cdx=1; - - offw=DAC_REG; - valw=bus_r(offw); - // codata=((cmd&0xf)<=0) { - - cmd=0x3; - - } else if (dacvalue==-100) { - - cmd=0x4; - - } - codata=cmd<>(24-i)))&0x1); */ - /* valw=(valw&(~(0x1<>(24-i))&0x1)<>(24-i))&0x1)); */ - - - /* valw=((valw)|(0x1<>8)&0x3) { - case 0: - analogEnable=1; - digitalEnable=0; - v1=NORMAL_READOUT; - break; - case 3: - analogEnable=0; - digitalEnable=1; - v1=DIGITAL_ONLY; - break; - case 2: - analogEnable=1; - digitalEnable=1; - v1=ANALOG_AND_DIGITAL; - break; - default: - printf("Unknown readout mode for analog and digital fifos %d\n",(bus_r(CONFIG_REG)>>8)&0x3); - v1=GET_READOUT_FLAGS; - } - getDynamicRange(); - allocateRAM(); - printf("dataBytes is %d\n",dataBytes); - return v1; - -} - - -int writePowerI2C(int val, int nbit) { - - int nc=nbit/8; - int ic, ib, ii; - int ack; - int bsd=PWR_I2C_SDA_BIT, bsc=PWR_I2C_SCL_BIT,esd=PWR_I2C_SDA_EN_BIT, esc=PWR_I2C_SCL_EN_BIT; - - u_int16_t co; - - printf("Write power I2C\n"); - co=(1<>ib)&1)<>ib)&1)); - } - printf("\n"); - co=co&(~(1<>ib)&1)<>ib)&1)); - } - printf("\n"); - co=co&(~(1< -#include -#include -#include -#include -#include -#include -//#include -#include -#include -#include -#include -#include -#include - - -int mapCSP0(void); - -u_int16_t bus_r16(u_int32_t offset); -u_int16_t bus_w16(u_int32_t offset, u_int16_t data);//aldos function -u_int32_t bus_w(u_int32_t offset, u_int32_t data); -u_int32_t bus_r(u_int32_t offset); - -//int setPhaseShiftOnce(); -//int phaseStep(int st); -//int dbitPhaseStep(int st); -//int getDbitPhase(); -int getPhase(int i); -int cleanFifo(); -int setDAQRegister(); -int configurePhase(int val, int i); -int configureFrequency(int val, int i); - -u_int32_t putout(char *s, int modnum); -u_int32_t readin(int modnum); -//u_int32_t setClockDivider(int d, int ic); -//u_int32_t getClockDivider(int ic); - -void resetPLL(); -u_int32_t setPllReconfigReg(u_int32_t reg, u_int32_t val, int trig); -u_int32_t getPllReconfigReg(u_int32_t reg, int trig); - -u_int32_t setSetLength(int d); -u_int32_t getSetLength(); -u_int32_t setWaitStates(int d); -u_int32_t getWaitStates(); -//u_int32_t setTotClockDivider(int d); -//u_int32_t getTotClockDivider(); -//u_int32_t setTotDutyCycle(int d); -//u_int32_t getTotDutyCycle(); -u_int32_t setOversampling(int d); -u_int32_t adcPipeline(int d); -u_int32_t dbitPipeline(int d); - -u_int32_t setExtSignal(int d, enum externalSignalFlag mode); -int getExtSignal(int d); - -u_int32_t setFPGASignal(int d, enum externalSignalFlag mode); -int getFPGASignal(int d); - -int setTiming(int t); - - -int setConfigurationRegister(int d); -int setToT(int d); -int setContinousReadOut(int d); -int startReceiver(int d); - -int setDACRegister(int idac, int val, int imod); -int getDacRegister(int dacnum); - - -int getTemperature(int tempSensor); -int initHighVoltage(int val,int imod); -int initConfGain(int isettings,int val,int imod); - -//int setADC(int adc); -//int configureMAC(int ipad, long long int macad, long long int detectormacadd, int detipad, int ival, int udpport); -int configureMAC(uint32_t destip,uint64_t destmac,uint64_t sourcemac,int detipad,int ival,uint32_t destport); -int getAdcConfigured(); - - -u_int64_t getDetectorNumber(); -u_int32_t getFirmwareVersion(); -u_int32_t getFirmwareSVNVersion(); - -int testFifos(void); -u_int32_t testFpga(void); -u_int32_t testRAM(void); -int testBus(void); -int setDigitalTestBit(int ival); - -int64_t set64BitReg(int64_t value, int aLSB, int aMSB); -int64_t get64BitReg(int aLSB, int aMSB); - -int64_t setFrames(int64_t value); -int64_t getFrames(); - -int64_t setExposureTime(int64_t value); -int64_t getExposureTime(); - -int64_t setGates(int64_t value); -int64_t getGates(); - -int64_t setDelay(int64_t value); -int64_t getDelay(); - -int64_t setPeriod(int64_t value); -int64_t getPeriod(); - -int64_t setTrains(int64_t value); -int64_t getTrains(); - -int64_t setProbes(int64_t value); -int64_t getProbes(); - -int64_t getProgress(); -int64_t setProgress(); - -int64_t getActualTime(); -int64_t getMeasurementTime(); -int64_t getFramesFromStart(); - -u_int32_t runBusy(void); -u_int32_t runState(void); -u_int32_t dataPresent(void); - - -int startStateMachine(); -int stopStateMachine(); -int startReadOut(); -u_int32_t fifoReset(void); -u_int32_t fifoReadCounter(int fifonum); -u_int32_t fifoReadStatus(); - - -u_int32_t fifo_full(void); - - - -u_int16_t* fifo_read_event(int ns); -u_int16_t* fifo_read_frame(); -u_int32_t* decode_data(int* datain); -//u_int32_t move_data(u_int64_t* datain, u_int64_t* dataout); -int setDynamicRange(int dr); -int getDynamicRange(); -int getNModBoard(); -int setNMod(int n); -int getNMod(); - -int setStoreInRAM(int b); -int allocateRAM(); - - -int writeADC(int addr, int val); -//int prepareADC(); - - - -int clearRAM(); - - -int setMaster(int f); -int setSynchronization(int s); - -int loadImage(int index, short int ImageVals[]); -int readCounterBlock(int startACQ, short int CounterVals[]); -int resetCounterBlock(int startACQ); - -int calibratePedestal(int frames); - -uint64_t writePatternWord(int addr, uint64_t word); -uint64_t writePatternIOControl(uint64_t word); -uint64_t writePatternClkControl(uint64_t word); -int setPatternLoop(int level, int *start, int *stop, int *n); -int setPatternWaitAddress(int level, int addr); -uint64_t setPatternWaitTime(int level, uint64_t t); - - -void initDac(int dacnum); -int setDac(int dacnum,int dacvalue); - -int setPower(int ind, int val); - -int setROI(int nroi,ROI* arg,int *retvalsize, int *ret); -int getChannels(); - -int getCurrent(int idac); -int getVoltage(int idac); - -void defineGPIOpins(); -void resetFPGA(); -void FPGAdontTouchFlash(); -void FPGATouchFlash(); - -int startWritingFPGAprogram(FILE** filefp); -int stopWritingFPGAprogram(FILE* filefp); -int writeFPGAProgram(char* fpgasrc, size_t fsize, FILE* filefp); -void eraseFlash(); - - - -/* - -u_int32_t setNBits(u_int32_t); -u_int32_t getNBits(); -*/ - -/* -//move to mcb_funcs? - -int readOutChan(int *val); -u_int32_t getModuleNumber(int modnum); -int testShiftIn(int imod); -int testShiftOut(int imod); -int testShiftStSel(int imod); -int testDataInOut(int num, int imod); -int testExtPulse(int imod); -int testExtPulseMux(int imod, int ow); -int testDataInOutMux(int imod, int ow, int num); -int testOutMux(int imod); -int testFpgaMux(int imod); -int calibration_sensor(int num, int *values, int *dacs) ; -int calibration_chip(int num, int *values, int *dacs); -*/ - -int64_t setSamples(int64_t value); -//int setOutputMode(int d); -int setReadOutMode(int arg); -int vLimitCompliant(int val_mV) - -#endif diff --git a/slsDetectorSoftware/jctbDetectorServer/get_server.sh b/slsDetectorSoftware/jctbDetectorServer/get_server.sh deleted file mode 100755 index b66a7ac2a..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/get_server.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/sh -serv="pc8498" -f="jungfrauDetectorServerTest" -if [ "$#" -gt 0 ]; then - f=$1 -fi -if [ "$#" -gt 1 ]; then - serv=$2 -fi -tftp $serv -r $f -g -chmod a+xrw $f - diff --git a/slsDetectorSoftware/jctbDetectorServer/gitInfo.txt b/slsDetectorSoftware/jctbDetectorServer/gitInfo.txt deleted file mode 100644 index 430dc823b..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/gitInfo.txt +++ /dev/null @@ -1,9 +0,0 @@ -Path: slsDetectorsPackage/slsDetectorSoftware/jctbDetectorServer -URL: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repository Root: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repsitory UUID: 9e5ec6a57bf206fe9384260fc4040867a9bbd71c -Revision: 33 -Branch: developer -Last Changed Author: Erik_Frojdh -Last Changed Rev: 4065 -Last Changed Date: 2019-01-30 17:38:35.000000002 +0100 ./firmware_funcs.c diff --git a/slsDetectorSoftware/jctbDetectorServer/gitInfoMoench.h b/slsDetectorSoftware/jctbDetectorServer/gitInfoMoench.h deleted file mode 100644 index 4a97bf6f0..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/gitInfoMoench.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "git@github.com:slsdetectorgroup/slsDetectorPackage.git" -#define GITREPUUID "9e5ec6a57bf206fe9384260fc4040867a9bbd71c" -#define GITAUTH "Erik_Frojdh" -#define GITREV 0x4065 -#define GITDATE 0x20190130 -#define GITBRANCH "developer" diff --git a/slsDetectorSoftware/jctbDetectorServer/gitInfoMoenchTmp.h b/slsDetectorSoftware/jctbDetectorServer/gitInfoMoenchTmp.h deleted file mode 100644 index dfd9bb246..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/gitInfoMoenchTmp.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "" -#define GITREPUUID "" -#define GITAUTH "" -#define GITREV "" -#define GITDATE "" -#define GITBRANCH "" diff --git a/slsDetectorSoftware/jctbDetectorServer/jctbDetectorServer_developer b/slsDetectorSoftware/jctbDetectorServer/jctbDetectorServer_developer deleted file mode 100755 index 4815259a6..000000000 Binary files a/slsDetectorSoftware/jctbDetectorServer/jctbDetectorServer_developer and /dev/null differ diff --git a/slsDetectorSoftware/jctbDetectorServer/mcb_funcs.c b/slsDetectorSoftware/jctbDetectorServer/mcb_funcs.c deleted file mode 100755 index 695c31688..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/mcb_funcs.c +++ /dev/null @@ -1,2696 +0,0 @@ -#ifdef MCB_FUNCS - -#include -#include -#include -#include -#include -#include "registers_m.h" - -#ifndef PICASSOD -#include "server_defs.h" -#else -#include "picasso_defs.h" -#endif -#include "firmware_funcs.h" -#include "mcb_funcs.h" - - -/* global variables */ -#undef DEBUG -#undef DEBUGOUT - -extern int nModX; -//extern int dataBytes; -extern int dynamicRange; -enum detectorSettings thisSettings; - -int sChan, sChip, sMod, sDac, sAdc; -const int allSelected=-2; -const int noneSelected=-1; - - -sls_detector_module *detectorModules=NULL; -int *detectorChips=NULL; -int *detectorChans=NULL; -int *detectorDacs=NULL; -int *detectorAdcs=NULL; -//int numberOfProbes; - -ROI rois[MAX_ROIS]; -int nROI=0; -extern enum detectorType myDetectorType; - -/** for jungfrau reinitializing macro later in server_funcs.c in initDetector*/ -extern int N_CHAN; -extern int N_CHIP; -extern int N_DAC; -extern int N_ADC; -extern int N_CHANS; - -extern int nChans; -extern int nChips; -int nDacs; -int nAdcs; - -int initDetector() { - - int imod; - // sls_detector_module *myModule; - int n=getNModBoard(); - nModX=n; - -#ifdef VERBOSE - printf("Board is for %d modules\n",n); -#endif - - - // nChans=N_CHAN; - // nChips=N_CHIP; - nDacs=N_DAC; - // nAdcs=N_ADC; - - detectorModules=malloc(n*sizeof(sls_detector_module)); - detectorDacs=malloc(n*N_DAC*sizeof(int)); - detectorAdcs=malloc(n*N_ADC*sizeof(int)); - detectorChips=NULL; - detectorChans=NULL; - detectorAdcs=NULL; - if(myDetectorType != JUNGFRAU){ - detectorChips=malloc(n*N_CHIP*sizeof(int)); - detectorChans=malloc(n*N_CHIP*N_CHAN*sizeof(int)); - } - -#ifdef VERBOSE - printf("modules from 0x%x to 0x%x\n",(unsigned int)(detectorModules), (unsigned int)(detectorModules+n)); - printf("dacs from 0x%x to 0x%x\n",(unsigned int)(detectorDacs), (unsigned int)(detectorDacs+n*N_DAC)); - printf("adcs from 0x%x to 0x%x\n",(unsigned int)(detectorAdcs), (unsigned int)(detectorAdcs+n*N_ADC)); - if(myDetectorType != JUNGFRAU){ - printf("chips from 0x%x to 0x%x\n",(unsigned int)(detectorChips), (unsigned int)(detectorChips+n*N_CHIP)); - printf("chans from 0x%x to 0x%x\n",(unsigned int)(detectorChans), (unsigned int)(detectorChans+n*N_CHIP*N_CHAN)); - } -#endif - - - for (imod=0; imoddacs=detectorDacs+imod*N_DAC; - (detectorModules+imod)->adcs=detectorAdcs+imod*N_ADC; - if(myDetectorType != JUNGFRAU){ - (detectorModules+imod)->chipregs=detectorChips+imod*N_CHIP; - (detectorModules+imod)->chanregs=detectorChans+imod*N_CHIP*N_CHAN; - } - (detectorModules+imod)->ndac=N_DAC; - (detectorModules+imod)->nadc=N_ADC; - (detectorModules+imod)->nchip=N_CHIP; - (detectorModules+imod)->nchan=N_CHIP*N_CHAN; - (detectorModules+imod)->module=imod; - (detectorModules+imod)->gain=0; - (detectorModules+imod)->offset=0; - (detectorModules+imod)->reg=0; - /* initialize registers, dacs, retrieve sn, adc values etc */ - } - thisSettings=UNINITIALIZED; - sChan=noneSelected; - sChip=noneSelected; - sMod=noneSelected; - sDac=noneSelected; - sAdc=noneSelected; - - /* - setCSregister(ALLMOD); //commented out by dhanya - setSSregister(ALLMOD); - counterClear(ALLMOD); - clearSSregister(ALLMOD); - putout("0000000000000000",ALLMOD); - */ - - /* initialize dynamic range etc. */ - /* dynamicRange=getDynamicRange(); //always 16 not required commented out - nModX=setNMod(-1);*/ - - // dynamicRange=32; - // initChip(0, 0,ALLMOD); - //nModX=n; - // - allocateRAM(); - - return OK; -} - - - - -int copyChannel(sls_detector_channel *destChan, sls_detector_channel *srcChan) { - destChan->chan=srcChan->chan; - destChan->chip=srcChan->chip; - destChan->module=srcChan->module; - destChan->reg=srcChan->reg; - return OK; -} - - -int copyChip(sls_detector_chip *destChip, sls_detector_chip *srcChip) { - - int ichan; - int ret=OK; - if ((srcChip->nchan)>(destChip->nchan)) { - printf("Number of channels of source is larger than number of channels of destination\n"); - return FAIL; - } - - destChip->nchan=srcChip->nchan; - destChip->reg=srcChip->reg; - destChip->chip=srcChip->chip; - destChip->module=srcChip->module; - for (ichan=0; ichan<(srcChip->nchan); ichan++) { - *((destChip->chanregs)+ichan)=*((srcChip->chanregs)+ichan); - } - return ret; -} - - -int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) { - - int ichip, idac, ichan, iadc; - - int ret=OK; - -#ifdef VERBOSE - printf("Copying module %x to module %x\n",(unsigned int)(srcMod),(unsigned int)(destMod)); -#endif - - if (srcMod->module>=0) { -#ifdef VERBOSE - printf("Copying module number %d to module number %d\n",srcMod->module,destMod->module); -#endif - destMod->module=srcMod->module; - } - if (srcMod->serialnumber>=0){ -/* #ifdef VERBOSE */ -/* printf("Copying module serial number %x to module serial number %x\n",srcMod->serialnumber,destMod->serialnumber); */ -/* #endif */ - destMod->serialnumber=srcMod->serialnumber; - } - if ((srcMod->nchip)>(destMod->nchip)) { - printf("Number of chip of source is larger than number of chips of destination\n"); - return FAIL; - } - if ((srcMod->nchan)>(destMod->nchan)) { - printf("Number of channels of source is larger than number of channels of destination\n"); - return FAIL; - } - if ((srcMod->ndac)>(destMod->ndac)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - if ((srcMod->nadc)>(destMod->nadc)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - -#ifdef VERBOSE - printf("DACs: src %d, dest %d\n",srcMod->ndac,destMod->ndac); - printf("ADCs: src %d, dest %d\n",srcMod->nadc,destMod->nadc); - printf("Chips: src %d, dest %d\n",srcMod->nchip,destMod->nchip); - printf("Chans: src %d, dest %d\n",srcMod->nchan,destMod->nchan); - -#endif - - - - destMod->ndac=srcMod->ndac; - destMod->nadc=srcMod->nadc; - destMod->nchip=srcMod->nchip; - destMod->nchan=srcMod->nchan; - if (srcMod->reg>=0) - destMod->reg=srcMod->reg; -#ifdef VERBOSE - printf("Copying register %x (%x)\n",destMod->reg,srcMod->reg ); -#endif - if (srcMod->gain>=0) - destMod->gain=srcMod->gain; - if (srcMod->offset>=0) - destMod->offset=srcMod->offset; - - // printf("copying gain and offset %f %f to %f %f\n",srcMod->gain,srcMod->offset,destMod->gain,destMod->offset); - - if(myDetectorType != JUNGFRAU){ - for (ichip=0; ichip<(srcMod->nchip); ichip++) { - if (*((srcMod->chipregs)+ichip)>=0) - *((destMod->chipregs)+ichip)=*((srcMod->chipregs)+ichip); - } - for (ichan=0; ichan<(srcMod->nchan); ichan++) { - if (*((srcMod->chanregs)+ichan)>=0) - *((destMod->chanregs)+ichan)=*((srcMod->chanregs)+ichan); - } - } - - for (idac=0; idac<(srcMod->ndac); idac++) { - if (*((srcMod->dacs)+idac)>=0) - *((destMod->dacs)+idac)=*((srcMod->dacs)+idac); - } - - for (iadc=0; iadc<(srcMod->nadc); iadc++) { - if (*((srcMod->adcs)+iadc)>=0) - *((destMod->adcs)+iadc)=*((srcMod->adcs)+iadc); - } - - return ret; -} - - - -/* Register commands */ - - -/* int clearDACSregister(int imod) { */ - -/* putout("1111111111111111",imod);//reset */ -/* putout("1111111111111110",imod);//cs down */ - -/* /\* commented out by dhanya */ -/* putout("0000000001000000",imod); */ -/* putout("0000000101000000",imod); */ -/* putout("0000000101000000",imod); */ -/* putout("0000000001000000",imod); */ -/* *\/ */ -/* #ifdef DEBUG */ -/* fprintf(stdout, "Clearing DAC shiftregister\n"); */ -/* #endif */ -/* // sDac=0; */ -/* sMod=imod; */ -/* if (imod==ALLMOD) */ -/* sMod=allSelected; */ -/* return OK; */ -/* } */ - -/* int nextDAC(int imod) { */ - -/* putout("1111111111111011",imod);//cs up */ -/* putout("1111111111111001",imod);//clk down */ -/* putout("1111111111111111",imod);//reset */ - -/* /\*commented out by dhanya */ -/* putout("0000000001000000",imod); */ -/* putout("0000000001001000",imod); */ -/* putout("0000000001000000",imod); */ -/* *\/ */ -/* #ifdef DEBUG */ -/* fprintf(stdout, "Next DAC\n"); */ -/* #endif */ -/* // sDac++; */ -/* sMod=imod; */ -/* if (imod==ALLMOD) */ -/* sMod=allSelected; */ -/* return OK; */ -/* } */ - - -int clearCSregister(int imod) { - - putout("0000000001000000",imod); - putout("0000100001000000",imod); - putout("0000100001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Clearing CS shiftregister\n"); -#endif - /* - sChan=noneSelected; - sMod=noneSelected; - sDac=noneSelected; - sAdc=noneSelected; - */ - sChip=noneSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - //putout("0000000000000000",imod); - return 0; -} - -int setCSregister(int imod){ - - putout("0000000001000000",imod); - putout("0001000001000000",imod); - putout("0001000001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Setting CS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChip=allSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int nextChip(int imod){ - - putout("0000000001000000",imod); - putout("0010000001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Next Chip\n"); -#endif - sChip++; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int firstChip(int imod){ - - putout("0100000001000000",imod); - putout("0110000001000000",imod); - putout("0100000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "First Chip\n"); -#endif - sChip=0; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int clearSSregister(int imod){ - int i; - putout("0000011000000000",imod); - for (i=0; i<10; i++) - putout("0000111000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"Clearing SS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChan=noneSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int setSSregister(int imod){ - int i; - putout("0000011000000000",imod); - for (i=0; i<10; i++) - putout("0001011000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"Setting SS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChan=allSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int nextStrip(int imod){ - putout("0000011000000000",imod); - putout("0010011000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"|-"); -#endif - sChan++; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int selChannel(const int strip,int imod) { - int istrip; - clearSSregister(imod); - nextStrip(imod); - for (istrip=0; istrip=0 && imod=0) */ -/* initDAC(ind,val, imod); */ - -/* if (imod>=0 && imodgain,(detectorModules+imod)->offset); */ -/* #endif */ -/* if ((detectorModules+imod)->gain>0) */ -/* myg=(detectorModules+imod)->gain; */ -/* else { */ -/* if (thisSettings>=0 && thisSettings<3) */ -/* myg=g[thisSettings]; */ -/* // else */ -/* //myg=-1; */ -/* } */ - -/* if ((detectorModules+imod)->offset>0) */ -/* myo=(detectorModules+imod)->offset; */ -/* else { */ -/* if (thisSettings>=0 && thisSettings<3) */ -/* myo=o[thisSettings]; */ -/* // else */ -/* //myo=-1; */ -/* } */ - -/* if (myg>0 && myo>0) { */ -/* //ethr=(myo-detectorDacs[VTHRESH+imod*N_DAC])*1000/myg; */ - -/* ethr=(myo-setDACRegister(VDAC0,-1,imod))*1000/myg;//edited by dhanya */ -/* // else */ -/* // ethr=-1; */ - -/* } */ -/* #ifdef VERBOSE */ -/* //printf("module=%d gain=%f, offset=%f, dacu=%f\n",imod, myg, myo, detectorDacs[VTHRESH+imod*N_DAC]); */ -/* printf("module=%d gain=%f, offset=%f, dacu=%d\n",imod, myg, myo,(int)(setDACRegister(VDAC0,-1,imod)));//edited by dhanya */ -/* printf("Threshold energy of module %d is %d eV\n", imod, ethr); */ -/* #endif */ - -/* if (imod==0) */ -/* ret=ethr; */ -/* else { */ -/* if (ethr>(ret+100) || ethr<(ret-100)) */ -/* return FAIL; */ -/* } */ -/* } */ -/* } */ -/* return ret; */ -/* } */ - -/* int setThresholdEnergy(int ethr) { */ -/* double g[3]=DEFAULTGAIN; */ -/* double o[3]=DEFAULTOFFSET; */ -/* double myg=-1, myo=-1; */ -/* int dacu; */ -/* int imod; */ -/* int ret=ethr; */ - -/* setSettings(GET_SETTINGS,-1);//-1 added by dhanya */ -/* if (thisSettings>=0 || thisSettings<3){ */ -/* myg=g[thisSettings]; */ -/* myo=o[thisSettings]; */ -/* } */ -/* for (imod=0; imodgain>0) */ -/* myg=(detectorModules+imod)->gain; */ -/* else */ -/* if (thisSettings>=0 && thisSettings<3) */ -/* myg=g[thisSettings]; */ -/* else */ -/* myg=-1; */ -/* if ((detectorModules+imod)->offset>0) */ -/* myo=(detectorModules+imod)->offset; */ -/* else */ -/* if (thisSettings>=0 && thisSettings<3) */ -/* myo=o[thisSettings]; */ -/* else */ -/* myo=-1; */ -/* } else { */ -/* if (thisSettings>=0 && thisSettings<3) */ -/* myo=o[thisSettings]; */ -/* else */ -/* myo=-1; */ -/* if (thisSettings>=0 && thisSettings<3) */ -/* myg=g[thisSettings]; */ -/* else */ -/* myg=-1; */ -/* } */ -/* if (myg>0 && myo>0) { */ -/* dacu=myo-myg*((double)ethr)/1000.; */ -/* #ifdef VERBOSE */ -/* printf("module %d (%x): gain %f, off %f, energy %d eV, dac %d\n",imod,(unsigned int)((detectorModules+imod)),(detectorModules+imod)->gain,(detectorModules+imod)->offset, ethr,dacu); */ -/* #endif */ -/* } else { */ -/* dacu=ethr; */ -/* #ifdef VERBOSE */ -/* printf("could not set threshold energy for module %d, settings %d (offset is %f; gain is %f)\n",imod,thisSettings,myo,myg); */ -/* #endif */ -/* } */ -/* initDACbyIndexDACU(VDAC0, dacu, imod); ///needs to be fixed dhanya */ -/* } */ -/* return ret; */ -/* } */ - - - -/* int getDACbyIndexDACU(int ind, int imod) { */ -/* /\* */ -/* if (detectorDacs) { */ -/* if (imodndac) */ -/* return (detectorDacs[ind+imod*N_DAC]); */ -/* } */ -/* return FAIL; */ -/* *\/ */ -/* return setDACRegister(ind, -1, imod); */ -/* } */ - - -/* int initDAC(int dac_addr, int value, int imod) { */ -/* // int i; */ -/* #ifdef VERBOSE */ -/* printf("Programming dac %d with value %d\n", dac_addr, value); */ -/* #endif */ -/* clearDACSregister(imod); */ -/* program_one_dac(dac_addr,value,imod); */ -/* nextDAC(imod); */ -/* clearDACSregister(imod); */ - -/* return 0; */ -/* } */ - -int getTemperatureByModule(int tempSensor, int imod) -{ - int im; - //for the particular module - if (imod>=0 && imod=0 && imod=0 && imod=0) { */ -/* #ifdef VERBOSE */ -/* fprintf(stdout, "voltage %d\n", *(v+iaddr)); */ -/* #endif */ -/* program_one_dac(iaddr, *(v+iaddr),imod); */ -/* } */ -/* nextDAC(imod); */ -/* } */ - - -/* clearDACSregister(imod); */ - -/* return 0; */ - -/* } */ - - - - -int setSettings(int i, int imod) { -/* #ifdef VERBOSE */ -/* if(i==-1) */ -/* printf("\nReading settings of detector...\n"); */ -/* else */ -/* printf("\ninside set settings wit settings=%d...\n",i); */ -/* #endif */ -/* int isett=-1,val=-1,retval=-1; */ -/* enum conf_gain { */ -/* dynamic = 0x0f00, //dynamic */ -/* dynamichighgain0 = 0x0f01, //dynamichighgain0 */ -/* fixgain1 = 0x0f02, //fixgain1 */ -/* fixgain2 = 0x0f06, //fixgain2 */ -/* forceswitchgain1 = 0x1f00, //forceswitchgain1 */ -/* forceswitchgain2 = 0x3f00 //forceswitchgain2 */ -/* }; */ - -/* //determine conf value to write */ -/* if(i!=GET_SETTINGS){ */ -/* switch(i){ */ -/* case DYNAMICGAIN: val = dynamic;break; */ -/* case DYNAMICHG0: val = dynamichighgain0;break; */ -/* case FIXGAIN1: val = fixgain1;break; */ -/* case FIXGAIN2: val = fixgain2;break; */ -/* case FORCESWITCHG1: val = forceswitchgain1;break; */ -/* case FORCESWITCHG2: val = forceswitchgain2;break; */ -/* default: */ -/* printf("Error: This settings is not defined for this detector %d\n",i); */ -/* return GET_SETTINGS; */ -/* } */ -/* } */ - -/* retval=initConfGainByModule(i,val,imod); */ - -/* switch(retval){ */ -/* case dynamic: isett=DYNAMICGAIN; break; */ -/* case dynamichighgain0: isett=DYNAMICHG0; break; */ -/* case fixgain1: isett=FIXGAIN1; break; */ -/* case fixgain2: isett=FIXGAIN2; break; */ -/* case forceswitchgain1: isett=FORCESWITCHG1; break; */ -/* case forceswitchgain2: isett=FORCESWITCHG2; break; */ -/* default: */ -/* isett=UNDEFINED; */ -/* printf("Error:Wrong settings read out from Gain Reg 0x%x\n",retval); */ -/* break; */ -/* } */ - -/* thisSettings=isett; */ -/* //#ifdef VERBOSE */ -/* printf("detector settings are %d\n",thisSettings); */ -/* //#endif */ - return thisSettings; -} - - - - -/* Initialization*/ - -int initChannelbyNumber(sls_detector_channel myChan) {printf("in init channel by number\n"); -/* int reg=myChan.reg; */ -/* int ft=reg & TRIM_DR; */ -/* int cae=(reg>>(NTRIMBITS))&1; */ -/* int ae=(reg>>(NTRIMBITS+1))&1; */ -/* int coe=(reg>>(NTRIMBITS+2))&1; */ -/* int ocoe=(reg>>(NTRIMBITS+3))&1; */ -/* int counts=(reg>>(NTRIMBITS+4)); */ -/* #ifdef VERBOSE */ -/* printf("Initializing channel %d chip %d module %d reg %x\n",myChan.chan,myChan.chip,myChan.module, reg); */ -/* printf("trim %d, cae %d, ae %d, coe %d, ocoe %d, counts %d\n",ft, cae, ae, coe, ocoe, counts); */ -/* #endif */ - -/* if (myChan.chip<0) */ -/* setCSregister(myChan.module); */ -/* else */ -/* selChip(myChan.chip,myChan.module); */ - -/* if (myChan.chan<0) */ -/* setSSregister(myChan.module); */ -/* else */ -/* selChannel(myChan.chan,myChan.module); */ - -/* initChannel(ft,cae,ae, coe, ocoe, counts,myChan.module); */ - -/* setDynamicRange(dynamicRange); */ - -/* setCSregister(ALLMOD); */ -/* clearSSregister(ALLMOD); */ -/* putout("0000000000000000",ALLMOD); */ - - return myChan.reg; - -} - -int getChannelbyNumber(sls_detector_channel* myChan) { - /* int imod, ichip, ichan; */ - /* imod=myChan->module; */ - /* ichip=myChan->chip; */ - /* ichan=myChan->chan; */ - - /* if (detectorChans) { */ - /* if (imod=0) { */ - /* if (ichip<(detectorModules+imod)->nchip && ichan<(detectorModules+imod)->nchan/(detectorModules+imod)->nchip) */ - /* myChan->reg=detectorChans[imod*N_CHAN*N_CHIP+ichip*N_CHAN+ichan]; */ - /* return OK; */ - /* } */ - /* } */ - return FAIL; - -} - -int getTrimbit(int imod, int ichip, int ichan) { - /* if (detectorChans) { */ - /* if (imod=0) */ - /* if (ichip<(detectorModules+imod)->nchip && ichan<(detectorModules+imod)->nchan/(detectorModules+imod)->nchip) */ - /* return (detectorChans[imod*N_CHAN*N_CHIP+ichip*N_CHAN+ichan] & TRIM_DR); */ - /* } */ - - return -1; -} - -int initChannel(int ft,int cae, int ae, int coe, int ocoe, int counts, int imod){ - -/* int ibit, bit, i, im, ichip, ichan; */ -/* int chanmi, chanma, chipmi, chipma, modmi, modma; */ - - - -/* sMod=imod; */ -/* // printf("initializing module %d\n",sMod); */ -/* if (imod==ALLMOD) { */ -/* sMod=allSelected; */ - -/* // printf("initializing all modules\n"); */ -/* } */ - -/* if (sChan==allSelected) { */ -/* // printf("initializing all channels ft=%d coe=%d\n",ft,coe); */ -/* chanmi=0; */ -/* chanma=N_CHAN; */ -/* } else if (sChan==noneSelected || sChan>N_CHAN || sChan<0) { */ -/* // printf("initializing no channels ft=%d coe=%d\n",ft,coe); */ -/* chanmi=0; */ -/* chanma=-1; */ -/* } else { */ -/* // printf("initializing channel %d ft=%d coe=%d\n",sChan, ft,coe); */ -/* chanmi=sChan; */ -/* chanma=sChan+1; */ -/* } */ - -/* if (sChip==allSelected) { */ -/* // printf("initializing all chips\n"); */ -/* chipmi=0; */ -/* chipma=N_CHIP; */ -/* } else if (sChip==noneSelected || sChip>N_CHIP || sChip<0) { */ -/* // printf("initializing no chips\n"); */ -/* chipmi=0; */ -/* chipma=-1; */ -/* } else { */ -/* // printf("initializing chip %d\n",sChip); */ -/* chipmi=sChip; */ -/* chipma=sChip+1; */ -/* } */ - - -/* if (sMod==allSelected) { */ -/* modmi=0; */ -/* modma=nModX;//getNModBoard(); */ -/* } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { */ -/* modmi=0; */ -/* modma=-1; */ -/* return 1; */ -/* } else { */ -/* modmi=sMod; */ -/* modma=sMod+1; */ -/* } */ - -/* if (detectorChans) { */ -/* for (im=modmi; im63 || ft<0) { */ -/* fprintf(stdout,"Fine Threshold is %d while should be between 0 and 63!",ft); */ -/* return 1; */ -/* } */ -/* /\*cal_enable*\/ */ -/* if (cae) { */ -/* putout("0100000000000000",imod); */ -/* putout("0110000000000000",imod); */ -/* } else { */ -/* putout("0000000000000000",imod); */ -/* putout("0010000000000000",imod); */ -/* } */ -/* /\*n_an_enable*\/ */ -/* if (ae) { */ -/* putout("0000000000000000",imod); */ -/* putout("0010000000000000",imod); */ -/* putout("0000000000000000",imod); */ -/* } else { */ -/* putout("0100000000000000",imod); */ -/* putout("0110000000000000",imod); */ -/* putout("0100000000000000",imod); */ -/* } */ -/* /\*trb5*\/ */ -/* ibit=5; */ -/* bit=ft & (1<>1; */ - /* int nchan, ichan; */ - /* int ft, cae, ae, coe, ocoe, counts, chanreg; */ - - - - /* nchan=myChip.nchan; */ - /* if (ichip<0) */ - /* setCSregister(imod); */ - /* else */ - /* selChip(ichip,imod); */ - - /* clearSSregister(imod); */ - /* for (ichan=0; ichan>(NTRIMBITS+1))&1; */ - /* ae=(chanreg>>(NTRIMBITS+2))&1; */ - /* coe=((chanreg)>>(NTRIMBITS+3))&1; */ - /* ocoe=((chanreg)>>(NTRIMBITS+4))&1; */ - /* counts=((chanreg)>>(NTRIMBITS+5)); */ - /* nextStrip(imod); */ - /* initChannel(ft,cae,ae, coe, ocoe, counts,imod); */ - /* } */ - /* initChip(obe,ow,imod); */ - return myChip.reg; - -} - -int getChipbyNumber(sls_detector_chip* myChip){ - /* int imod, ichip; */ - /* imod=myChip->module; */ - /* ichip=myChip->chip; */ - - /* if (detectorChips) { */ - /* if (imodnchip) { */ - /* myChip->reg=detectorChips[ichip+imod*N_CHIP]; */ - /* myChip->nchan=N_CHAN; */ - /* myChip->chanregs=detectorChans+imod*N_CHAN*N_CHIP+ichip*N_CHIP; */ - /* return OK; */ - /* } */ - /* } */ - return FAIL; - -} - - - -int initChip(int obe, int ow,int imod){ - /* int i; */ - /* int im, ichip; */ - /* int chipmi, chipma, modmi, modma; */ - /* switch (ow) { - case 0:; - case 1: - setDynamicRange(32); - break; - case 2: - setDynamicRange(16); - break; - case 3: - setDynamicRange(8); - break; - case 4: - setDynamicRange(4); - break; - case 5: - setDynamicRange(1); - break; - default: - setDynamicRange(32); - break; - } - */ - -/* #ifdef DEBUGOUT */ -/* printf("Initializing chip\n"); */ -/* #endif */ -/* putout("0000000000000000",imod); */ -/* #ifdef DEBUGOUT */ -/* printf("Output mode= %d\n", ow); */ -/* #endif */ - -/* /\* clearing shift in register *\/ */ -/* for (i=0; i<10; i++) */ -/* putout("0000100000000000",imod); */ -/* putout("0000000000000000",imod); */ - -/* if (ow>0) { */ -/* putout("0100000000000000",imod); */ -/* putout("0110000000000000",imod); */ -/* putout("0100000000000000",imod); */ -/* for (i=0; i<(OUTMUX_OFFSET-1); i++) { */ -/* putout("0000000000000000",imod); */ -/* putout("0010000000000000",imod); */ -/* putout("0000000000000000",imod); */ -/* } */ -/* if (ow>1) { */ -/* putout("0000000000000000",imod); */ -/* putout("0010000000000000",imod); */ -/* putout("0000000000000000",imod); */ -/* } */ -/* if (ow>2) { */ -/* putout("0000000000000000",imod); */ -/* putout("0010000000000000",imod); */ -/* putout("0000000000000000",imod); */ -/* } */ -/* if (ow>3) { */ -/* putout("0000000000000000",imod); */ -/* putout("0010000000000000",imod); */ -/* putout("0000000000000000",imod); */ -/* } */ -/* if (ow>4) { */ -/* putout("0000000000000000",imod); */ -/* putout("0010000000000000",imod); */ -/* putout("0000000000000000",imod); */ -/* } */ -/* } */ -/* #ifdef DEBUGOUT */ -/* printf("Output buffer enable= %d\n", obe); */ -/* #endif */ -/* if (obe) { */ -/* putout("0100000000000000",imod); */ -/* putout("0110000000000000",imod); */ -/* putout("0100000000000000",imod); */ -/* } else { */ -/* putout("0000000000000000",imod); */ -/* putout("0010000000000000",imod); */ -/* putout("0000000000000000",imod); */ -/* } */ -/* /\*}*\/ */ -/* putout("0000000000000000",imod); */ - - - - - -/* sMod=imod; */ -/* if (imod==ALLMOD) */ -/* sMod=allSelected; */ - - -/* if (sChip==allSelected) { */ -/* chipmi=0; */ -/* chipma=N_CHIP; */ -/* } else if (sChip==noneSelected || sChip>N_CHIP || sChip<0) { */ -/* chipmi=0; */ -/* chipma=-1; */ -/* } else { */ -/* chipmi=sChip; */ -/* chipma=sChip+1; */ -/* } */ - - -/* if (sMod==allSelected) { */ -/* modmi=0; */ -/* modma=nModX;//getNModBoard(); */ -/* } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { */ -/* modmi=0; */ -/* modma=-1; */ -/* } else { */ -/* modmi=sMod; */ -/* modma=sMod+1; */ -/* } */ - -/* if (detectorChips) { */ -/* for (im=modmi; imN_CHIP || sChip<0) { */ -/* chipmi=0; */ -/* chipma=-1; */ -/* } else { */ -/* chipmi=sChip; */ -/* chipma=sChip+1; */ -/* } */ - - -/* if (sMod==allSelected) { */ -/* modmi=0; */ -/* modma=nModX;//getNModBoard(); */ -/* } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { */ -/* modmi=0; */ -/* modma=-1; */ -/* } else { */ -/* modmi=sMod; */ -/* modma=sMod+1; */ -/* } */ - -/* if (detectorChips) { */ -/* for (im=modmi; imnModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorModules) { - for (im=modmi; imreg)=cm; -#ifdef VERBOSE - printf("imod=%d reg=%d (%x)\n",im,(detectorModules+im)->reg,(unsigned int)((detectorModules+im))); -#endif - } - } - return 0; -} - -int initModulebyNumber(sls_detector_module myMod) { - - printf("\ninside initmoduleynumberrrr..\n"); - printf("000\n"); - int nchip,nchan;//int ichip, nchip, ichan, nchan; - int im, modmi,modma; - // int ft, cae, ae, coe, ocoe, counts, chanreg; - int imod; - // int obe; - // int ow; - /* int v[N_DAC];*/ - int retval =-1, idac; - - - nchip=myMod.nchip; - nchan=(myMod.nchan)/nchip; - - imod=myMod.module; - sMod=imod; - - if (sMod==ALLMOD) - sMod=allSelected; - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {// (sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - printf("222\n"); - /* - for (idac=0; idacmodule; -#ifdef VERBOSE - printf("Getting module %d\n",imod); -#endif - if (detectorModules) { - copyModule(myMod,detectorModules+imod); - ; - } else - return FAIL; - - return OK; -} - -/* To chips */ -int clearCounter(int imod){ - int i; -#ifdef DEBUG - printf("Clearing counter with contclear\n"); -#endif - putout("0000000000000000",imod); - for (i=0; i<10; i++) - putout("0000000000010000",imod); - putout("0000000000000000",imod); - - return 0; -} - -int clearOutReg(int imod){ - int i; -#ifdef DEBUG - printf("Clearing output register\n"); -#endif - putout("0000010000000000",imod); - for (i=0; i<10; i++) - putout("0000110000000000",imod); - putout("0000010000000000",imod); - return 0; -} -int setOutReg(int imod){ - int i; -#ifdef DEBUG - printf("Setting output register\n"); -#endif - putout("0000010000000000",imod); - for (i=0; i<10; i++) - putout("0001010000000000",imod); - putout("0000010000000000",imod); - return 0; -} - - -int extPulse(int ncal, int imod) { - int ical; -#ifdef DEBUG - printf("Giving a clock pulse to the counter\n"); -#endif - for (ical=0; ical0 && i%2==0) { - printf("Shift in: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, i%2); - result++; - } - if (i%2>0 && (val & 1<0 && (dum & (1<0) { - printf("Shift out: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, (dum &1<0 && i%2==0) { - printf("Shift stsel: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, i%2); - result++; - } - if (i%2>0 && (val & 1<> 1; - - - putout("0000000000000000",ALLMOD); - putout("0010000000000000",ALLMOD); //change mux setting - putout("0000000000000000",ALLMOD); - } - - printf("Test FpgaMux module %d : %d errors\n", imod,result); - if (result) - return 1; - else - return 0; -} - - - - - - - - - -int calibration_sensor(int num, int *v, int *dacs) { - int ich, ichip, imod; - int val[10]; - - - printf("calibrating sensor..."); - for (imod=0; imod=0){ */ - -/* //clear rois */ -/* for(i=0;i=0) && (adc<=4)); */ -/* else { */ -/* printf("warning:adc value greater than 5. deleting roi\n"); */ -/* adc=-1; */ -/* } */ -/* } */ -/* } */ - - -/* //set rois for just 1 adc - take only 1st roi */ -/* if(adc!=-1){ */ -/* rois[0].xmin=adc*(GOTTHARDNCHAN*NCHIPS_PER_ADC); */ -/* rois[0].xmax=(adc+1)*(GOTTHARDNCHAN*NCHIPS_PER_ADC)-1; */ -/* rois[0].ymin=-1; */ -/* rois[0].ymax=-1; */ -/* nROI = 1; */ -/* }else */ -/* nROI = 0; */ - -/* if((arg[0].xmin!=rois[0].xmin)||(arg[0].xmax!=rois[0].xmax)||(arg[0].ymin!=rois[0].ymin)||(arg[0].ymax!=rois[0].ymax)) */ -/* *ret=FAIL; */ -/* if(n!=nROI) */ -/* *ret=FAIL; */ - -/* //set adc of interest */ -/* setADC(adc); */ -/* } */ - -/* //#ifdef VERBOSE */ -/* printf("Rois:\n"); */ -/* for( i=0;i /sys/class/gpio/export -echo 9 > /sys/class/gpio/export -echo in > /sys/class/gpio/gpio7/direction -echo out > /sys/class/gpio/gpio9/direction - - -echo 0 > /sys/class/gpio/gpio9/value - - -flash_eraseall /dev/mtd3 -cat /mnt/$f > /dev/mtd3 - -echo 1 > /sys/class/gpio/gpio9/value -cat /sys/class/gpio/gpio7/value - diff --git a/slsDetectorSoftware/jctbDetectorServer/registers_m.h b/slsDetectorSoftware/jctbDetectorServer/registers_m.h deleted file mode 100644 index 996d50cbc..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/registers_m.h +++ /dev/null @@ -1,551 +0,0 @@ -#ifndef REGISTERS_G_H -#define REGISTERS_G_H - - -#include "sls_detector_defs.h" - - -/* Definitions for FPGA*/ -#define CSP0 0x20200000 -#define MEM_SIZE 0x100000 - - - -/* values defined for FPGA */ -#define MCSNUM 0x0 -#define FIXED_PATT_VAL 0xacdc1980 - - -#define FPGA_INIT_PAT 0x60008 -#define FPGA_INIT_ADDR 0xb0000000 - -//#ifdef JUNGFRAU_DHANYA -#define POWER_ON_REG 0x5e << MEM_MAP_SHIFT -// Pwr_I2C_SDA <= PowerReg_s(1) when PowerReg_s(3)='1' else 'Z'; -// Pwr_I2C_SCL <= PowerReg_s(0) when PowerReg_s(2)='1' else 'Z'; - -#define PWR_I2C_SCL_BIT 0 -#define PWR_I2C_SDA_BIT 1 -#define PWR_I2C_SCL_EN_BIT 2 -#define PWR_I2C_SDA_EN_BIT 3 - -#define POWER_STATUS_REG 41 << MEM_MAP_SHIFT - -#define ADCREG1 0x08 -#define ADCREG2 0x14//20 -#define ADCREG3 0x4 -#define ADCREG4 0x5 -#define ADCREG_VREFS 24 -#define DBIT_PIPELINE_REG 89 << MEM_MAP_SHIFT //0x59 same PATTERN_N_LOOP2_REG -#define MEM_MACHINE_FIFOS_REG 79 << MEM_MAP_SHIFT //from gotthard -#define CONFGAIN_REG 93 << MEM_MAP_SHIFT //from gotthard -#define ADC_PIPELINE_REG 66 << MEM_MAP_SHIFT //0x42 same as ADC_OFFSET_REG -//#endif - -//#define ADC_OFFSET_REG 93 << MEM_MAP_SHIFT //same as DAQ_REG -#define ADC_INVERSION_REG 67 << MEM_MAP_SHIFT - -#define DAC_REG 64 << MEM_MAP_SHIFT//0x17 << MEM_MAP_SHIFT// control the dacs -//ADC -#define ADC_WRITE_REG 65 << MEM_MAP_SHIFT//0x18 << MEM_MAP_SHIFT -//#define ADC_SYNC_REG 66 << MEM_MAP_SHIFT//0x19 << MEM_MAP_SHIFT -//#define HV_REG 67 << MEM_MAP_SHIFT//0x20 << MEM_MAP_SHIFT - - - - -//#define MUTIME_REG 0x1a << MEM_MAP_SHIFT -//temperature -#define TEMP_IN_REG 0x1b << MEM_MAP_SHIFT -#define TEMP_OUT_REG 0x1c << MEM_MAP_SHIFT -//configure MAC -#define TSE_CONF_REG 0x1d << MEM_MAP_SHIFT -#define ENET_CONF_REG 0x1e << MEM_MAP_SHIFT -//#define WRTSE_SHAD_REG 0x1f << MEM_MAP_SHIFT -//HV - - -#define DUMMY_REG 68 << MEM_MAP_SHIFT//0x21 << MEM_MAP_SHIFT -#define FPGA_VERSION_REG 0 << MEM_MAP_SHIFT //0x22 << MEM_MAP_SHIFT -#define PCB_REV_REG 0 << MEM_MAP_SHIFT -#define FIX_PATT_REG 1 << MEM_MAP_SHIFT //0x23 << MEM_MAP_SHIFT -#define CONTROL_REG 79 << MEM_MAP_SHIFT//0x24 << MEM_MAP_SHIFT -#define STATUS_REG 2 << MEM_MAP_SHIFT //0x25 << MEM_MAP_SHIFT -#define CONFIG_REG 77 << MEM_MAP_SHIFT//0x26 << MEM_MAP_SHIFT -#define EXT_SIGNAL_REG 78 << MEM_MAP_SHIFT// 0x27 << MEM_MAP_SHIFT -//#define FPGA_SVN_REG 0x29 << MEM_MAP_SHIFT - - -#define CHIP_OF_INTRST_REG 0x2A << MEM_MAP_SHIFT - -//FIFO -#define LOOK_AT_ME_REG 3 << MEM_MAP_SHIFT //0x28 << MEM_MAP_SHIFT -#define SYSTEM_STATUS_REG 4 << MEM_MAP_SHIFT - -#define FIFO_DATA_REG 6 << MEM_MAP_SHIFT -#define FIFO_STATUS_REG 7 << MEM_MAP_SHIFT - -// constant FifoDigitalInReg_c : integer := 60; -#define FIFO_DIGITAL_DATA_LSB_REG 60 << MEM_MAP_SHIFT -#define FIFO_DIGITAL_DATA_MSB_REG 61 << MEM_MAP_SHIFT - -#define FIFO_DATA_REG_OFF 0x50 << MEM_MAP_SHIFT /////// -//to read back dac registers -//#define MOD_DACS1_REG 0x65 << MEM_MAP_SHIFT -//#define MOD_DACS2_REG 0x66 << MEM_MAP_SHIFT -//#define MOD_DACS3_REG 0x67 << MEM_MAP_SHIFT - -//user entered - - - - - - -#define GET_ACTUAL_TIME_LSB_REG 16 << MEM_MAP_SHIFT -#define GET_ACTUAL_TIME_MSB_REG 17 << MEM_MAP_SHIFT - -#define GET_MEASUREMENT_TIME_LSB_REG 38 << MEM_MAP_SHIFT -#define GET_MEASUREMENT_TIME_MSB_REG 39 << MEM_MAP_SHIFT - - -#define SET_DELAY_LSB_REG 96 << MEM_MAP_SHIFT //0x68 << MEM_MAP_SHIFT -#define SET_DELAY_MSB_REG 97 << MEM_MAP_SHIFT //0x69 << MEM_MAP_SHIFT -#define GET_DELAY_LSB_REG 18 << MEM_MAP_SHIFT//0x6a << MEM_MAP_SHIFT -#define GET_DELAY_MSB_REG 19 << MEM_MAP_SHIFT//0x6b << MEM_MAP_SHIFT - -#define SET_CYCLES_LSB_REG 98 << MEM_MAP_SHIFT//0x6c << MEM_MAP_SHIFT -#define SET_CYCLES_MSB_REG 99 << MEM_MAP_SHIFT//0x6d << MEM_MAP_SHIFT -#define GET_CYCLES_LSB_REG 20 << MEM_MAP_SHIFT//0x6e << MEM_MAP_SHIFT -#define GET_CYCLES_MSB_REG 21 << MEM_MAP_SHIFT//0x6f << MEM_MAP_SHIFT - -#define SET_FRAMES_LSB_REG 100 << MEM_MAP_SHIFT//0x70 << MEM_MAP_SHIFT -#define SET_FRAMES_MSB_REG 101 << MEM_MAP_SHIFT//0x71 << MEM_MAP_SHIFT -#define GET_FRAMES_LSB_REG 22 << MEM_MAP_SHIFT//0x72 << MEM_MAP_SHIFT -#define GET_FRAMES_MSB_REG 23 << MEM_MAP_SHIFT//0x73 << MEM_MAP_SHIFT - -#define SET_PERIOD_LSB_REG 102 << MEM_MAP_SHIFT//0x74 << MEM_MAP_SHIFT -#define SET_PERIOD_MSB_REG 103 << MEM_MAP_SHIFT//0x75 << MEM_MAP_SHIFT -#define GET_PERIOD_LSB_REG 24 << MEM_MAP_SHIFT//0x76 << MEM_MAP_SHIFT -#define GET_PERIOD_MSB_REG 25 << MEM_MAP_SHIFT//0x77 << MEM_MAP_SHIFT - -//#define PATTERN_WAIT0_TIME_REG_LSB 114 << MEM_MAP_SHIFT -//#define PATTERN_WAIT0_TIME_REG_MSB 115 << MEM_MAP_SHIFT -#define SET_EXPTIME_LSB_REG 114 << MEM_MAP_SHIFT//0x78 << MEM_MAP_SHIFT -#define SET_EXPTIME_MSB_REG 115 << MEM_MAP_SHIFT//0x79 << MEM_MAP_SHIFT -#define GET_EXPTIME_LSB_REG 26 << MEM_MAP_SHIFT//0x7a << MEM_MAP_SHIFT -#define GET_EXPTIME_MSB_REG 27 << MEM_MAP_SHIFT//0x7b << MEM_MAP_SHIFT - -#define SET_GATES_LSB_REG 106 << MEM_MAP_SHIFT//0x7c << MEM_MAP_SHIFT -#define SET_GATES_MSB_REG 107 << MEM_MAP_SHIFT//0x7d << MEM_MAP_SHIFT -#define GET_GATES_LSB_REG 28 << MEM_MAP_SHIFT//0x7e << MEM_MAP_SHIFT -#define GET_GATES_MSB_REG 29 << MEM_MAP_SHIFT//0x7f << MEM_MAP_SHIFT - -#define DATA_IN_LSB_REG 30 << MEM_MAP_SHIFT -#define DATA_IN_MSB_REG 31 << MEM_MAP_SHIFT - -#define PATTERN_OUT_LSB_REG 32 << MEM_MAP_SHIFT -#define PATTERN_OUT_MSB_REG 33 << MEM_MAP_SHIFT - -#define FRAMES_FROM_START_LSB_REG 34 << MEM_MAP_SHIFT -#define FRAMES_FROM_START_MSB_REG 35 << MEM_MAP_SHIFT - -#define FRAMES_FROM_START_PG_LSB_REG 36 << MEM_MAP_SHIFT -#define FRAMES_FROM_START_PG_MSB_REG 37 << MEM_MAP_SHIFT - -#define SLOW_ADC_REG 43 << MEM_MAP_SHIFT - - - -#define PLL_PARAM_REG 80 << MEM_MAP_SHIFT//0x37 << MEM_MAP_SHIFT -#define PLL_PARAM_OUT_REG 5 << MEM_MAP_SHIFT //0x38 << MEM_MAP_SHIFT -#define PLL_CNTRL_REG 81 << MEM_MAP_SHIFT//0x34 << MEM_MAP_SHIFT - - -#ifdef NEW_GBE_INTERFACE -#define GBE_PARAM_OUT_REG 40 << MEM_MAP_SHIFT -#define GBE_PARAM_REG 69 << MEM_MAP_SHIFT -#define GBE_CNTRL_REG 70 << MEM_MAP_SHIFT -#else -#define RX_UDP_AREG 69 << MEM_MAP_SHIFT //rx_udpip_AReg_c : integer:= 69; *\/ -#define UDPPORTS_AREG 70 << MEM_MAP_SHIFT// udpports_AReg_c : integer:= 70; *\/ -#define RX_UDPMACL_AREG 71 << MEM_MAP_SHIFT//rx_udpmacL_AReg_c : integer:= 71; *\/ -#define RX_UDPMACH_AREG 72 << MEM_MAP_SHIFT//rx_udpmacH_AReg_c : integer:= 72; *\/ -#define DETECTORMACL_AREG 73 << MEM_MAP_SHIFT//detectormacL_AReg_c : integer:= 73; *\/ -#define DETECTORMACH_AREG 74 << MEM_MAP_SHIFT//detectormacH_AReg_c : integer:= 74; *\/ -#define DETECTORIP_AREG 75 << MEM_MAP_SHIFT//detectorip_AReg_c : integer:= 75; *\/ -#define IPCHKSUM_AREG 76 << MEM_MAP_SHIFT//ipchksum_AReg_c : integer:= 76; *\/ */ -#endif - - -#define PATTERN_CNTRL_REG 82 << MEM_MAP_SHIFT -#define PATTERN_LIMITS_AREG 83 << MEM_MAP_SHIFT - -#define PATTERN_LOOP0_AREG 84 << MEM_MAP_SHIFT -#define PATTERN_N_LOOP0_REG 85 << MEM_MAP_SHIFT - -#define PATTERN_LOOP1_AREG 86 << MEM_MAP_SHIFT -#define PATTERN_N_LOOP1_REG 87 << MEM_MAP_SHIFT - -#define PATTERN_LOOP2_AREG 88 << MEM_MAP_SHIFT -#define PATTERN_N_LOOP2_REG 89 << MEM_MAP_SHIFT - -#define PATTERN_WAIT0_AREG 90 << MEM_MAP_SHIFT -#define PATTERN_WAIT1_AREG 91 << MEM_MAP_SHIFT -#define PATTERN_WAIT2_AREG 92 << MEM_MAP_SHIFT - - - -//#define DAQ_REG 93 << MEM_MAP_SHIFT //unused -#define NSAMPLES_REG 93 << MEM_MAP_SHIFT - - -#define HV_REG 95 << MEM_MAP_SHIFT - - - -#define PATTERN_IOCTRL_REG_LSB 108 << MEM_MAP_SHIFT -#define PATTERN_IOCTRL_REG_MSB 109 << MEM_MAP_SHIFT - -#define PATTERN_IOCLKCTRL_REG_LSB 110 << MEM_MAP_SHIFT -#define PATTERN_IOCLKCTRL_REG_MSB 111 << MEM_MAP_SHIFT -#define PATTERN_IN_REG_LSB 112 << MEM_MAP_SHIFT -#define PATTERN_IN_REG_MSB 113 << MEM_MAP_SHIFT -#define PATTERN_WAIT0_TIME_REG_LSB 114 << MEM_MAP_SHIFT -#define PATTERN_WAIT0_TIME_REG_MSB 115 << MEM_MAP_SHIFT -#define PATTERN_WAIT1_TIME_REG_LSB 116 << MEM_MAP_SHIFT -#define PATTERN_WAIT1_TIME_REG_MSB 117 << MEM_MAP_SHIFT -#define PATTERN_WAIT2_TIME_REG_LSB 118 << MEM_MAP_SHIFT -#define PATTERN_WAIT2_TIME_REG_MSB 119 << MEM_MAP_SHIFT - -//#define DAC_REG_OFF 120 -//#define DAC_0_1_VAL_REG 120 << MEM_MAP_SHIFT -//#define DAC_2_3_VAL_REG 121 << MEM_MAP_SHIFT -//#define DAC_4_5_VAL_REG 122 << MEM_MAP_SHIFT -//#define DAC_6_7_VAL_REG 123 << MEM_MAP_SHIFT -//#define DAC_8_9_VAL_REG 124 << MEM_MAP_SHIFT -//#define DAC_10_11_VAL_REG 125 << MEM_MAP_SHIFT -//#define DAC_12_13_VAL_REG 126 << MEM_MAP_SHIFT -//#define DAC_14_15_VAL_REG 127 << MEM_MAP_SHIFT -#define DAC_VAL_REG 121 << MEM_MAP_SHIFT -#define DAC_NUM_REG 122 << MEM_MAP_SHIFT -#define DAC_VAL_OUT_REG 42 << MEM_MAP_SHIFT -#define ADC_LATCH_DISABLE_REG 120 << MEM_MAP_SHIFT - - - - - - - - -/* registers defined in FPGA */ -#define GAIN_REG 0 -//#define FLOW_CONTROL_REG 0x11 << MEM_MAP_SHIFT -//#define FLOW_STATUS_REG 0x12 << MEM_MAP_SHIFT -//#define FRAME_REG 0x13 << MEM_MAP_SHIFT -#define MULTI_PURPOSE_REG 0 -//#define TIME_FROM_START_REG 0x16 << MEM_MAP_SHIFT - - -#define ROI_REG 0 // 0x35 << MEM_MAP_SHIFT -#define OVERSAMPLING_REG 0 // 0x36 << MEM_MAP_SHIFT -#define MOENCH_CNTR_REG 0 // 0x31 << MEM_MAP_SHIFT -#define MOENCH_CNTR_OUT_REG 0 // 0x33 << MEM_MAP_SHIFT -#define MOENCH_CNTR_CONF_REG 0 // 0x32 << MEM_MAP_SHIFT - - - -//image -#define DARK_IMAGE_REG 0 // 0x81 << MEM_MAP_SHIFT -#define GAIN_IMAGE_REG 0 // 0x82 << MEM_MAP_SHIFT - -//counter block memory -#define COUNTER_MEMORY_REG 0 // 0x85 << MEM_MAP_SHIFT - - -//not used -//#define MCB_DOUT_REG_OFF 0 // 0x200000 -//#define FIFO_CNTRL_REG_OFF 0 // 0x300000 -//#define FIFO_COUNTR_REG_OFF 0 // 0x400000 -//not used so far -//#define SPEED_REG 0 // 0x006000 -//#define SET_NBITS_REG 0 // 0x008000 -//not used -//#define GET_SHIFT_IN_REG 0 // 0x022000 - - - -#define SHIFTMOD 2 -#define SHIFTFIFO 9 - -/** for PCB_REV_REG */ -#define DETECTOR_TYPE_MASK 0xFF000000 -#define DETECTOR_TYPE_OFFSET 24 -#define BOARD_REVISION_MASK 0xFFFFFF -#define MOENCH03_MODULE_ID 2 -#define JUNGFRAU_MODULE_ID 1 -#define JUNGFRAU_CTB_ID 3 - - - - -/* for control register (16bit only)*/ -#define START_ACQ_BIT 0x0001 -#define STOP_ACQ_BIT 0x0002 -#define START_FIFOTEST_BIT 0x0004 // ????? -#define STOP_FIFOTEST_BIT 0x0008 // ?????? -#define START_READOUT_BIT 0x0010 -#define STOP_READOUT_BIT 0x0020 -#define START_EXPOSURE_BIT 0x0040 -#define STOP_EXPOSURE_BIT 0x0080 -#define START_TRAIN_BIT 0x0100 -#define STOP_TRAIN_BIT 0x0200 -#define FIFO_RESET_BIT 0x8000 -#define SYNC_RESET 0x0400 -#define GB10_RESET_BIT 0x0800 -#define MEM_RESET_BIT 0x1000 - -/* for status register */ -#define RUN_BUSY_BIT 0x00000001 -#define READOUT_BUSY_BIT 0x00000002 -#define FIFOTEST_BUSY_BIT 0x00000004 //???? -#define WAITING_FOR_TRIGGER_BIT 0x00000008 -#define DELAYBEFORE_BIT 0x00000010 -#define DELAYAFTER_BIT 0x00000020 -#define EXPOSING_BIT 0x00000040 -#define COUNT_ENABLE_BIT 0x00000080 -#define READSTATE_0_BIT 0x00000100 -#define READSTATE_1_BIT 0x00000200 -#define READSTATE_2_BIT 0x00000400 -#define LAM_BIT 0x00000400 // error! -#define SOME_FIFO_FULL_BIT 0x00000800 // error! - - - -#define RUNSTATE_0_BIT 0x00001000 -#define RUNSTATE_1_BIT 0x00002000 -#define RUNSTATE_2_BIT 0x00004000 -#define STOPPED_BIT 0x00008000 // stopped! -#define ALL_FIFO_EMPTY_BIT 0x00010000 // data ready -#define RUNMACHINE_BUSY_BIT 0x00020000 -#define READMACHINE_BUSY_BIT 0x00040000 -#define PLL_RECONFIG_BUSY 0x00100000 - - - -/* for fifo status register */ -#define FIFO_ENABLED_BIT 0x80000000 -#define FIFO_DISABLED_BIT 0x01000000 -#define FIFO_ERROR_BIT 0x08000000 -#define FIFO_EMPTY_BIT 0x04000000 -#define FIFO_DATA_READY_BIT 0x02000000 -#define FIFO_COUNTER_MASK 0x000001ff -#define FIFO_NM_MASK 0x00e00000 -#define FIFO_NM_OFF 21 -#define FIFO_NC_MASK 0x001ffe00 -#define FIFO_NC_OFF 9 - -/* for config register *///not really used yet -#define TOT_ENABLE_BIT 0x00000002 -#define TIMED_GATE_BIT 0x00000004 -#define CONT_RO_ENABLE_BIT 0x00080000 -#define GB10_NOT_CPU_BIT 0x00001000 -#define ADC_OUTPUT_DISABLE_BIT 0x00100 -#define DIGITAL_OUTPUT_ENABLE_BIT 0x00200 - - -/* for speed register */ -#define CLK_DIVIDER_MASK 0x000000ff -#define CLK_DIVIDER_OFFSET 0 -#define SET_LENGTH_MASK 0x00000f00 -#define SET_LENGTH_OFFSET 8 -#define WAIT_STATES_MASK 0x0000f000 -#define WAIT_STATES_OFFSET 12 -#define TOTCLK_DIVIDER_MASK 0xff000000 -#define TOTCLK_DIVIDER_OFFSET 24 -#define TOTCLK_DUTYCYCLE_MASK 0x00ff0000 -#define TOTCLK_DUTYCYCLE_OFFSET 16 - -/* for external signal register */ -#define SIGNAL_OFFSET 4 -#define SIGNAL_MASK 0xF -#define EXT_SIG_OFF 0x0 -#define EXT_GATE_IN_ACTIVEHIGH 0x1 -#define EXT_GATE_IN_ACTIVELOW 0x2 -#define EXT_TRIG_IN_RISING 0x3 -#define EXT_TRIG_IN_FALLING 0x4 -#define EXT_RO_TRIG_IN_RISING 0x5 -#define EXT_RO_TRIG_IN_FALLING 0x6 -#define EXT_GATE_OUT_ACTIVEHIGH 0x7 -#define EXT_GATE_OUT_ACTIVELOW 0x8 -#define EXT_TRIG_OUT_RISING 0x9 -#define EXT_TRIG_OUT_FALLING 0xA -#define EXT_RO_TRIG_OUT_RISING 0xB -#define EXT_RO_TRIG_OUT_FALLING 0xC - - - -/* for temperature register */ -#define T1_CLK_BIT 0x00000001 -#define T1_CS_BIT 0x00000002 -#define T2_CLK_BIT 0x00000004 -#define T2_CS_BIT 0x00000008 - - - -/* fifo control register */ -//#define FIFO_RESET_BIT 0x00000001 -//#define FIFO_DISABLE_TOGGLE_BIT 0x00000002 - - -//chip shiftin register meaning -#define OUTMUX_OFF 20 -#define OUTMUX_MASK 0x1f -#define PROBES_OFF 4 -#define PROBES_MASK 0x7f -#define OUTBUF_OFF 0 -#define OUTBUF_MASK 1 - - -/* multi purpose register */ -#define PHASE_STEP_BIT 0x00000001 -#define PHASE_STEP_OFFSET 0 -// #define xxx_BIT 0x00000002 -#define RESET_COUNTER_BIT 0x00000004 -#define RESET_COUNTER_OFFSET 2 -//#define xxx_BIT 0x00000008 -//#define xxx_BIT 0x00000010 -#define SW1_BIT 0x00000020 -#define SW1_OFFSET 5 -#define WRITE_BACK_BIT 0x00000040 -#define WRITE_BACK_OFFSET 6 -#define RESET_BIT 0x00000080 -#define RESET_OFFSET 7 -#define ENET_RESETN_BIT 0x00000800 -#define ENET_RESETN_OFFSET 11 -#define INT_RSTN_BIT 0x00002000 -#define INT_RSTN_OFFSET 13 -#define DIGITAL_TEST_BIT 0x00004000 -#define DIGITAL_TEST_OFFSET 14 -//#define CHANGE_AT_POWER_ON_BIT 0x00008000 -//#define CHANGE_AT_POWER_ON_OFFSET 15 - - -/* settings/conf gain register */ -#define GAIN_MASK 0x0000000f -#define GAIN_OFFSET 0 -#define SETTINGS_MASK 0x000000f0 -#define SETTINGS_OFFSET 4 - - -/* CHIP_OF_INTRST_REG */ -#define CHANNEL_MASK 0xffff0000 -#define CHANNEL_OFFSET 16 -#define ACTIVE_ADC_MASK 0x0000001f - - - -/**ADC SYNC CLEAN FIFO*/ -#define ADCSYNC_CLEAN_FIFO_BITS 0x300000 -#define CLEAN_FIFO_MASK 0x0fffff - - - - -enum {run_clk_c, adc_clk_c, sync_clk_c, dbit_clk_c}; - - - - -#define PLL_CNTR_ADDR_OFF 16 //PLL_CNTR_REG bits 21 downto 16 represent the counter address - -#define PLL_CNTR_RECONFIG_RESET_BIT 0 -#define PLL_CNTR_READ_BIT 1 -#define PLL_CNTR_WRITE_BIT 2 -#define PLL_CNTR_PLL_RESET_BIT 3 - - -#define PLL_CNTR_PHASE_EN_BIT 8 -#define PLL_CNTR_UPDN_BIT 9 -#define PLL_CNTR_CNTSEL_OFF 10 - - - - - -#define PLL_MODE_REG 0x0 -#define PLL_STATUS_REG 0x1 -#define PLL_START_REG 0x2 -#define PLL_N_COUNTER_REG 0x3 -#define PLL_M_COUNTER_REG 0x4 -#define PLL_C_COUNTER_REG 0x5 //which ccounter stands in param 22:18; 7:0 lowcount 15:8 highcount; 16 bypassenable; 17 oddivision -#define PLL_PHASE_SHIFT_REG 0x6 // which ccounter stands in param 16:20; 21 updown (1 up, 0 down) -#define PLL_K_COUNTER_REG 0x7 -#define PLL_BANDWIDTH_REG 0x8 -#define PLL_CHARGEPUMP_REG 0x9 -#define PLL_VCO_DIV_REG 0x1c -#define PLL_MIF_REG 0x1f - -#define PPL_M_CNT_PARAM_DEFAULT 0x4040 -#define PPL_N_CNT_PARAM_DEFAULT 0x20D0C -#define PPL_C0_CNT_PARAM_DEFAULT 0x20D0C -#define PPL_C1_CNT_PARAM_DEFAULT 0xA0A0 -#define PPL_C2_CNT_PARAM_DEFAULT 0x20D0C -#define PPL_C3_CNT_PARAM_DEFAULT 0x0808 -#define PPL_BW_PARAM_DEFAULT 0x2EE0 -#define PPL_VCO_PARAM_DEFAULT 0x1 - -#define NEW_PLL_RECONFIG - -#ifdef NEW_PLL_RECONFIG -#define PLL_VCO_FREQ_MHZ 400//480//800 -#else -#define PLL_VCO_FREQ_MHZ 480//800 -#endif - - - - - -/* - GBE parameter and control registers definitions -*/ - -#define GBE_CTRL_WSTROBE 0 -#define GBE_CTRL_VAR_OFFSET 16 -#define GBE_CTRL_VAR_MASK 0XF -#define GBE_CTRL_RAMADDR_OFFSET 24 -#define GBE_CTRL_RAMADDR_MASK 0X3F -#define GBE_CTRL_INTERFACE 23 - -#define RX_UDP_IP_ADDR 0 -#define RX_UDP_PORTS_ADDR 1 -#define RX_UDP_MAC_L_ADDR 2 -#define RX_UDP_MAC_H_ADDR 3 -#define IPCHECKSUM_ADDR 4 -#define GBE_DELAY_ADDR 5 -#define GBE_RESERVED1_ADDR 6 -#define GBE_RESERVED2_ADDR 7 -#define DETECTOR_MAC_L_ADDR 8 -#define DETECTOR_MAC_H_ADDR 9 -#define DETECTOR_IP_ADDR 10 - - - -/**------------------ --- pattern registers definitions ---------------------------------------------- */ -#define IOSIGNALS_MASK 0xfffffffffffff -#define ADC_ENABLE_BIT 63 -#define APATTERN_MASK 0xffff -#define ASTART_OFFSET 0 -#define ASTOP_OFFSET 16 -#define PATTERN_CTRL_WRITE_BIT 0 -#define PATTERN_CTRL_READ_BIT 1 -#define PATTERN_CTRL_ADDR_OFFSET 16 -#define MAX_PATTERN_LENGTH 1024 - - -#endif - diff --git a/slsDetectorSoftware/jctbDetectorServer/server.c b/slsDetectorSoftware/jctbDetectorServer/server.c deleted file mode 100755 index e3c8e4334..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/server.c +++ /dev/null @@ -1,139 +0,0 @@ -/* A simple server in the internet domain using TCP - The port number is passed as an argument */ - -#include "sls_detector_defs.h" - -#include -#include "communication_funcs.h" -#include "server_funcs.h" -#include - - - -extern int sockfd; -extern int phase_shift; - - - -void error(char *msg) -{ - perror(msg); -} - -int main(int argc, char *argv[]) -{ - int portno, b; - char cmd[500]; - int retval=OK; - int sd, fd; - int iarg; - int checkType = 1; - - - for(iarg=1; iarg 2) && (!strcasecmp(argv[2],"stopserver"))){ - portno = DEFAULT_PORTNO+1; - if ( sscanf(argv[1],"%d",&portno) ==0) { - printf("could not open stop server: unknown port\n"); - return 1; - } - b=0; - printf("\n\nStop Server\nOpening stop server on port %d\n",portno); - checkType=0; - - } - - //control server - else { - portno = DEFAULT_PORTNO; - if(checkType) - sprintf(cmd,"%s %d stopserver &",argv[0],DEFAULT_PORTNO+1); - else - sprintf(cmd,"%s %d stopserver -test with_gotthard &",argv[0],DEFAULT_PORTNO+1); - printf("\n\nControl Server\nOpening control server on port %d\n",portno ); - - //printf("\n\ncmd:%s\n",cmd); - system(cmd); - b=1; - checkType=1; - - } - - - - - - init_detector(b, checkType); - - - sd=bindSocket(portno); - sockfd=sd; - if (getServerError(sd)) { - printf("server error!\n"); - return -1; - } - - /* assign function table */ - function_table(); -#ifdef VERBOSE - printf("function table assigned \n"); -#endif - - - /* waits for connection */ - while(retval!=GOODBYE) { -#ifdef VERBOSE - printf("\n"); -#endif -#ifdef VERY_VERBOSE - printf("Waiting for client call\n"); -#endif - fd=acceptConnection(sockfd); -#ifdef VERY_VERBOSE - printf("Conenction accepted\n"); -#endif - retval=decode_function(fd); -#ifdef VERY_VERBOSE - printf("function executed\n"); -#endif - closeConnection(fd); -#ifdef VERY_VERBOSE - printf("connection closed\n"); -#endif - } - - exitServer(sockfd); - printf("Goodbye!\n"); - - return 0; -} - diff --git a/slsDetectorSoftware/jctbDetectorServer/server_defs.h b/slsDetectorSoftware/jctbDetectorServer/server_defs.h deleted file mode 100755 index 07144546f..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/server_defs.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef SERVER_DEFS_H -#define SERVER_DEFS_H - -#include "sls_detector_defs.h" - -#include - - -// Hardware definitions - -#define NCHAN 36 -#define NCHIP 1 -#define NADC 9 // - -/* #ifdef CTB */ -/* #define NDAC 24 */ -/* #define NPWR 5 */ -/* #else */ -/* #define NDAC 16 */ -/* #define NPWR 0 */ -/* #endif */ -#define DAC_CMD_OFF 20 - -#define NMAXMODX 1 -#define NMAXMODY 1 -#define NMAXMOD (NMAXMODX*NMAXMODY) - -#define NCHANS (NCHAN*NCHIP*NMAXMOD) -#define NDACS (NDAC*NMAXMOD) - - -/**when moench readout tested with gotthard module*/ - -#define TRIM_DR (((int)pow(2,NTRIMBITS))-1) -#define COUNT_DR (((int)pow(2,NCOUNTBITS))-1) - - -#define ALLMOD 0xffff -#define ALLFIFO 0xffff - -#define GOTTHARD_ADCSYNC_VAL 0x32214 -#define ADCSYNC_VAL 0x02111 -#define TOKEN_RESTART_DELAY 0x88000000 -#define TOKEN_RESTART_DELAY_ROI 0x1b000000 -#define TOKEN_TIMING_REV1 0x1f16 -#define TOKEN_TIMING_REV2 0x1f0f - -#define DEFAULT_PHASE_SHIFT 0 // 120 -#define DEFAULT_IP_PACKETSIZE 0x0522 -#define DEFAULT_UDP_PACKETSIZE 0x050E -#define ADC1_IP_PACKETSIZE 256*2+14+20 -#define ADC1_UDP_PACKETSIZE 256*2+4+8+2 - -#ifdef VIRTUAL -#define DEBUGOUT -#endif - -#define CLK_FREQ 156.25E+6 -#define ADC_CLK_FREQ 32E+6 - - -#endif diff --git a/slsDetectorSoftware/jctbDetectorServer/server_funcs.c b/slsDetectorSoftware/jctbDetectorServer/server_funcs.c deleted file mode 100644 index e54c3c562..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/server_funcs.c +++ /dev/null @@ -1,3738 +0,0 @@ -#include "sls_detector_defs.h" -#include "sls_receiver_defs.h" -#include "server_funcs.h" -#include "server_defs.h" -#include "firmware_funcs.h" -#include "mcb_funcs.h" -#include "slow_adc.h" -#include "registers_m.h" -#include "gitInfoMoench.h" -#include "blackfin.h" - -#define FIFO_DATA_REG_OFF 0x50 << MEM_MAP_SHIFT -// Global variables - - -int (*flist[256])(int); - - - -//defined in the detector specific file -/* #ifdef MYTHEND */ -/* const enum detectorType myDetectorType=MYTHEN; */ -/* #elif GOTTHARDD */ -/* const enum detectorType myDetectorType=GOTTHARD; */ -/* #elif EIGERD */ -/* const enum detectorType myDetectorType=EIGER; */ -/* #elif PICASSOD */ -/* const enum detectorType myDetectorType=PICASSO; */ -/* #elif MOENCHD */ -/* const enum detectorType myDetectorType=MOENCH; */ -/* #else */ -enum detectorType myDetectorType=GENERIC; -/* #endif */ - - -extern int nModX; -extern int nModY; -extern int dataBytes; -extern int nSamples; -extern int dynamicRange; -extern int storeInRAM; - -extern int lockStatus; -extern char lastClientIP[INET_ADDRSTRLEN]; -extern char thisClientIP[INET_ADDRSTRLEN]; -extern int differentClients; - -/* global variables for optimized readout */ -extern unsigned int *ram_values; -char *dataretval=NULL; -int nframes, iframes, dataret; -char mess[1000]; - -int digitalTestBit = 0; - -extern int withGotthard; - - -int adcvpp=0x4; - -/** for jungfrau reinitializing macro later */ -int N_CHAN=NCHAN; -int N_CHIP=NCHIP; -int N_DAC=24; -int N_ADC=NADC; -int N_PWR=5; -int N_CHANS=NCHANS; - - -int init_detector(int b, int checkType) { - - int i; - int ret; - int ii; - if (mapCSP0()==FAIL) { printf("Could not map memory\n"); - exit(1); - } - - // defineGPIOpins(); - //checktype - if (checkType) { - printf("Bus test... (checktype is %d; b is %d)",checkType,b ); - for (i=0; i<1000000; i++) { - bus_w(SET_DELAY_LSB_REG, i*100); - bus_r(FPGA_VERSION_REG); - //usleep(100); - ii=0; - // usleep(100); - //usleep(100); - - // ret=bus_r(SET_DELAY_LSB_REG); - ret=bus_r(SET_DELAY_LSB_REG); - while (ret!=i*100 && ii<100) { - //if (i*100!=ret) - printf("ERROR %d: wrote 0x%x, read 0x%x\n",i, i*100,ret); - ret=bus_r(SET_DELAY_LSB_REG); - } - } - printf("Finished\n"); - }else - printf("(checktype is %d; b is %d)",checkType,b ); - - - //confirm the detector type - switch ((bus_r(PCB_REV_REG) & DETECTOR_TYPE_MASK)>>DETECTOR_TYPE_OFFSET) { - case MOENCH03_MODULE_ID: - myDetectorType=MOENCH; - printf("This is a MOENCH03 module %d\n",MOENCH); - N_DAC=8; - N_PWR=0; - break; - - case JUNGFRAU_MODULE_ID: - myDetectorType=JUNGFRAU; - printf("This is a Jungfrau module %d\n Not supported: exiting!", JUNGFRAU); - N_DAC=8; - N_PWR=0; - exit(1); - break; - - case JUNGFRAU_CTB_ID: - myDetectorType=JUNGFRAUCTB; - printf("This is a CTB %d\n", JUNGFRAUCTB); - N_DAC=24; - N_PWR=5; - break; - - default: - myDetectorType=GENERIC; - printf("Unknown detector type %02x\n",(bus_r(PCB_REV_REG) & DETECTOR_TYPE_MASK)>>DETECTOR_TYPE_OFFSET); - N_DAC=8; - N_PWR=0; - break; - - } - printf("Detector type is %d\n", myDetectorType); - if (b) - initDetector(); - - //common for both control and stop server - strcpy(mess,"dummy message"); - strcpy(lastClientIP,"none"); - strcpy(thisClientIP,"none1"); - lockStatus=0; - // getDynamicRange(); - - /* both these functions setROI and allocateRAM should go into the control server part. */ - - return OK; -} - - -int decode_function(int file_des) { - int fnum,n; - int retval=FAIL; -#ifdef VERBOSE - printf( "receive data\n"); -#endif - n = receiveDataOnly(file_des,&fnum,sizeof(fnum)); - if (n <= 0) { -#ifdef VERBOSE - printf("ERROR reading from socket %d, %d %d\n", n, fnum, file_des); -#endif - return FAIL; - } -#ifdef VERBOSE - else - printf("size of data received %d\n",n); -#endif - printf("calling function=%d (%s)\n", fnum, getFunctionName((enum detFuncs)fnum)); -#ifdef VERBOSE - printf( "calling function fnum = %d %x %x %x\n",fnum,(unsigned int)(flist[fnum]), (unsigned int)(flist[F_READ_REGISTER]),(unsigned int)(&read_register)); -#endif - if (fnum<0 || fnum>255) - fnum=255; - retval=(*flist[fnum])(file_des); - printf(" function=%d (%s) returned: %d\n", fnum, getFunctionName((enum detFuncs)fnum), retval); - if (retval==FAIL) - printf( "Error executing the function = %d \n",fnum); - return retval; -} - - -const char* getFunctionName(enum detFuncs func) { - switch (func) { - case F_EXEC_COMMAND: return "F_EXEC_COMMAND"; - case F_GET_ERROR: return "F_GET_ERROR"; - case F_GET_DETECTOR_TYPE: return "F_GET_DETECTOR_TYPE"; - case F_SET_NUMBER_OF_MODULES: return "F_SET_NUMBER_OF_MODULES"; - case F_GET_MAX_NUMBER_OF_MODULES: return "F_GET_MAX_NUMBER_OF_MODULES"; - case F_SET_EXTERNAL_SIGNAL_FLAG: return "F_SET_EXTERNAL_SIGNAL_FLAG"; - case F_SET_EXTERNAL_COMMUNICATION_MODE: return "F_SET_EXTERNAL_COMMUNICATION_MODE"; - case F_GET_ID: return "F_GET_ID"; - case F_DIGITAL_TEST: return "F_DIGITAL_TEST"; - case F_ANALOG_TEST: return "F_ANALOG_TEST"; - case F_ENABLE_ANALOG_OUT: return "F_ENABLE_ANALOG_OUT"; - case F_CALIBRATION_PULSE: return "F_CALIBRATION_PULSE"; - case F_SET_DAC: return "F_SET_DAC"; - case F_GET_ADC: return "F_GET_ADC"; - case F_WRITE_REGISTER: return "F_WRITE_REGISTER"; - case F_READ_REGISTER: return "F_READ_REGISTER"; - case F_WRITE_MEMORY: return "F_WRITE_MEMORY"; - case F_READ_MEMORY: return "F_READ_MEMORY"; - case F_SET_CHANNEL: return "F_SET_CHANNEL"; - case F_GET_CHANNEL: return "F_GET_CHANNEL"; - case F_SET_ALL_CHANNELS: return "F_SET_ALL_CHANNELS"; - case F_SET_CHIP: return "F_SET_CHIP"; - case F_GET_CHIP: return "F_GET_CHIP"; - case F_SET_ALL_CHIPS: return "F_SET_ALL_CHIPS"; - case F_SET_MODULE: return "F_SET_MODULE"; - case F_GET_MODULE: return "F_GET_MODULE"; - case F_SET_ALL_MODULES: return "F_SET_ALL_MODULES"; - case F_SET_SETTINGS: return "F_SET_SETTINGS"; - case F_GET_THRESHOLD_ENERGY: return "F_GET_THRESHOLD_ENERGY"; - case F_SET_THRESHOLD_ENERGY: return "F_SET_THRESHOLD_ENERGY"; - case F_START_ACQUISITION: return "F_START_ACQUISITION"; - case F_STOP_ACQUISITION: return "F_STOP_ACQUISITION"; - case F_START_READOUT: return "F_START_READOUT"; - case F_GET_RUN_STATUS: return "F_GET_RUN_STATUS"; - case F_START_AND_READ_ALL: return "F_START_AND_READ_ALL"; - case F_READ_FRAME: return "F_READ_FRAME"; - case F_READ_ALL: return "F_READ_ALL"; - case F_SET_TIMER: return "F_SET_TIMER"; - case F_GET_TIME_LEFT: return "F_GET_TIME_LEFT"; - case F_SET_DYNAMIC_RANGE: return "F_SET_DYNAMIC_RANGE"; - case F_SET_READOUT_FLAGS: return "F_SET_READOUT_FLAGS"; - case F_SET_ROI: return "F_SET_ROI"; - case F_SET_SPEED: return "F_SET_SPEED"; - case F_EXECUTE_TRIMMING: return "F_EXECUTE_TRIMMING"; - case F_EXIT_SERVER: return "F_EXIT_SERVER"; - case F_LOCK_SERVER: return "F_LOCK_SERVER"; - case F_GET_LAST_CLIENT_IP: return "F_GET_LAST_CLIENT_IP"; - case F_SET_PORT: return "F_SET_PORT"; - case F_UPDATE_CLIENT: return "F_UPDATE_CLIENT"; - case F_CONFIGURE_MAC: return "F_CONFIGURE_MAC"; - case F_LOAD_IMAGE: return "F_LOAD_IMAGE"; - case F_SET_MASTER: return "F_SET_MASTER"; - case F_SET_SYNCHRONIZATION_MODE: return "F_SET_SYNCHRONIZATION_MODE"; - case F_READ_COUNTER_BLOCK: return "F_READ_COUNTER_BLOCK"; - case F_RESET_COUNTER_BLOCK: return "F_RESET_COUNTER_BLOCK"; - case F_CALIBRATE_PEDESTAL: return "F_CALIBRATE_PEDESTAL"; - case F_ENABLE_TEN_GIGA: return "F_ENABLE_TEN_GIGA"; - case F_SET_ALL_TRIMBITS: return "F_SET_ALL_TRIMBITS"; - case F_SET_CTB_PATTERN: return "F_SET_CTB_PATTERN"; - case F_WRITE_ADC_REG: return "F_WRITE_ADC_REG"; - case F_SET_COUNTER_BIT: return "F_SET_COUNTER_BIT"; - case F_PULSE_PIXEL: return "F_PULSE_PIXEL"; - case F_PULSE_PIXEL_AND_MOVE: return "F_PULSE_PIXEL_AND_MOVE"; - case F_PULSE_CHIP: return "F_PULSE_CHIP"; - case F_SET_RATE_CORRECT: return "F_SET_RATE_CORRECT"; - case F_GET_RATE_CORRECT: return "F_GET_RATE_CORRECT"; - case F_SET_NETWORK_PARAMETER: return "F_SET_NETWORK_PARAMETER"; - case F_PROGRAM_FPGA: return "F_PROGRAM_FPGA"; - case F_RESET_FPGA: return "F_RESET_FPGA"; - case F_POWER_CHIP: return "F_POWER_CHIP"; - case F_ACTIVATE: return "F_ACTIVATE"; - case F_PREPARE_ACQUISITION: return "F_PREPARE_ACQUISITION"; - case F_CLEANUP_ACQUISITION: return "F_CLEANUP_ACQUISITION"; - default: return "Unknown Function"; - } -} - - -int function_table() { - int i; - for (i=0;i<256;i++){ - flist[i]=&M_nofunc; - } - flist[F_EXIT_SERVER]=&exit_server; - flist[F_EXEC_COMMAND]=&exec_command; - flist[F_GET_DETECTOR_TYPE]=&get_detector_type; - flist[F_SET_NUMBER_OF_MODULES]=&set_number_of_modules; - flist[F_GET_MAX_NUMBER_OF_MODULES]=&get_max_number_of_modules; - flist[F_SET_EXTERNAL_SIGNAL_FLAG]=&set_external_signal_flag; - flist[F_SET_EXTERNAL_COMMUNICATION_MODE]=&set_external_communication_mode; - flist[F_GET_ID]=&get_id; - flist[F_DIGITAL_TEST]=&digital_test; - flist[F_WRITE_REGISTER]=&write_register; - flist[F_READ_REGISTER]=&read_register; - flist[F_SET_DAC]=&set_dac; - flist[F_GET_ADC]=&get_adc; - flist[F_SET_CHANNEL]=&set_channel; - flist[F_SET_CHIP]=&set_chip; - flist[F_SET_MODULE]=&set_module; - flist[F_GET_CHANNEL]=&get_channel; - flist[F_GET_CHIP]=&get_chip; - flist[F_GET_MODULE]=&get_module; - flist[F_GET_THRESHOLD_ENERGY]=&get_threshold_energy; - flist[F_SET_THRESHOLD_ENERGY]=&set_threshold_energy; - flist[F_SET_SETTINGS]=&set_settings; - flist[F_START_ACQUISITION]=&start_acquisition; - flist[F_STOP_ACQUISITION]=&stop_acquisition; - flist[F_START_READOUT]=&start_readout; - flist[F_GET_RUN_STATUS]=&get_run_status; - flist[F_READ_FRAME]=&read_frame; - flist[F_READ_ALL]=&read_all; - flist[F_START_AND_READ_ALL]=&start_and_read_all; - flist[F_SET_TIMER]=&set_timer; - flist[F_GET_TIME_LEFT]=&get_time_left; - flist[F_SET_DYNAMIC_RANGE]=&set_dynamic_range; - flist[F_SET_ROI]=&set_roi; - flist[F_SET_SPEED]=&set_speed; - flist[F_SET_READOUT_FLAGS]=&set_readout_flags; - flist[F_EXECUTE_TRIMMING]=&execute_trimming; - flist[F_LOCK_SERVER]=&lock_server; - flist[F_SET_PORT]=&set_port; - flist[F_GET_LAST_CLIENT_IP]=&get_last_client_ip; - flist[F_UPDATE_CLIENT]=&update_client; - flist[F_CONFIGURE_MAC]=&configure_mac; - flist[F_LOAD_IMAGE]=&load_image; - flist[F_SET_MASTER]=&set_master; - flist[F_SET_SYNCHRONIZATION_MODE]=&set_synchronization; - flist[F_READ_COUNTER_BLOCK]=&read_counter_block; - flist[F_RESET_COUNTER_BLOCK]=&reset_counter_block; - flist[F_CALIBRATE_PEDESTAL]=&calibrate_pedestal; - flist[F_SET_CTB_PATTERN]=&set_ctb_pattern; - flist[F_WRITE_ADC_REG]=&write_adc_register; - flist[F_PROGRAM_FPGA]=&program_fpga; - flist[F_POWER_CHIP]=&power_chip; - flist[F_RESET_FPGA]=&reset_fpga; - flist[F_ACTIVATE]=&activate; - flist[F_PREPARE_ACQUISITION]=&prepare_acquisition; - flist[F_CLEANUP_ACQUISITION]=&cleanup_acquisition; - return OK; -} - - -int M_nofunc(int file_des){ - - int ret=FAIL; - sprintf(mess,"Unrecognized Function\n"); - printf(mess); - - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); - return FAIL; -} - - -int exit_server(int file_des) { - int retval=FAIL; - sendDataOnly(file_des,&retval,sizeof(retval)); - printf("closing server."); - sprintf(mess,"closing server"); - sendDataOnly(file_des,mess,sizeof(mess)); - return GOODBYE; -} - -int exec_command(int file_des) { - char cmd[MAX_STR_LENGTH]; - char answer[MAX_STR_LENGTH]; - int retval=OK; - int sysret=0; - int n=0; - - /* receive arguments */ - n = receiveDataOnly(file_des,cmd,MAX_STR_LENGTH); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - - /* execute action if the arguments correctly arrived*/ - if (retval==OK) { -#ifdef VERBOSE - printf("executing command %s\n", cmd); -#endif - if (lockStatus==0 || differentClients==0) - sysret=system(cmd); - - //should be replaced by popen - if (sysret==0) { - sprintf(answer,"Succeeded\n"); - if (lockStatus==1 && differentClients==1) - sprintf(answer,"Detector locked by %s\n", lastClientIP); - } else { - sprintf(answer,"Failed\n"); - retval=FAIL; - } - } else { - sprintf(answer,"Could not receive the command\n"); - } - - /* send answer */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - n = sendDataOnly(file_des,answer,MAX_STR_LENGTH); - if (n < 0) { - sprintf(mess,"Error writing to socket"); - retval=FAIL; - } - - - /*return ok/fail*/ - return retval; - -} - - - -int get_detector_type(int file_des) { - int n=0; - enum detectorType ret; - int retval=OK; - - sprintf(mess,"Can't return detector type\n"); - - - /* receive arguments */ - /* execute action */ - ret=JUNGFRAUCTB;//myDetectorType; - -#ifdef VERBOSE - printf("Returning detector type %d\n",ret); -#endif - - /* send answer */ - /* send OK/failed */ - if (differentClients==1) - retval=FORCE_UPDATE; - - n += sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - /*return ok/fail*/ - return retval; - - -} - - -int set_number_of_modules(int file_des) { - int n; - int arg[2], ret=0; - int retval=OK; - int dim, nm; - - sprintf(mess,"Can't set number of modules\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket %d", n); - retval=GOODBYE; - } - if (retval==OK) { - dim=arg[0]; - nm=arg[1]; - - /* execute action */ -#ifdef VERBOSE - printf("Setting the number of modules in dimension %d to %d\n",dim,nm ); -#endif - - //if (nm!=GET_FLAG) { - if (dim!=X && nm!=GET_FLAG) { - retval=FAIL; - sprintf(mess,"Can't change module number in dimension %d\n",dim); - } else { - if (lockStatus==1 && differentClients==1 && nm!=GET_FLAG) { - sprintf(mess,"Detector locked by %s\n", lastClientIP); - retval=FAIL; - } else { - ret=setNMod(nm); - if (nModX==nm || nm==GET_FLAG) { - retval=OK; - if (differentClients==1) - retval=FORCE_UPDATE; - } else - retval=FAIL; - } - } - } - /*} else { - if (dim==Y) { - ret=nModY; - } else if (dim==X) { - ret=setNMod(-1); - } - } - */ - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - /*return ok/fail*/ - return retval; - -} - - -int get_max_number_of_modules(int file_des) { - int n; - int ret; - int retval=OK; - enum dimension arg; - - sprintf(mess,"Can't get max number of modules\n"); - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - /* execute action */ -#ifdef VERBOSE - printf("Getting the max number of modules in dimension %d \n",arg); -#endif - - - switch (arg) { - case X: - ret=getNModBoard(); - break; - case Y: - ret=NMAXMODY; - break; - default: - ret=FAIL; - retval=FAIL; - break; - } -#ifdef VERBOSE - printf("Max number of module in dimension %d is %d\n",arg,ret ); -#endif - - - - if (differentClients==1 && retval==OK) { - retval=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - - /*return ok/fail*/ - return retval; -} - - -//index 0 is in gate -//index 1 is in trigger -//index 2 is out gate -//index 3 is out trigger - -int set_external_signal_flag(int file_des) { - int n; - int arg[2]; - int ret=OK; - int signalindex; - enum externalSignalFlag flag, retval; - - sprintf(mess,"Can't set external signal flag\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - retval=SIGNAL_OFF; - if (ret==OK) { - signalindex=arg[0]; - flag=arg[1]; - /* execute action */ - switch (flag) { - case GET_EXTERNAL_SIGNAL_FLAG: - retval=getExtSignal(signalindex); - break; - - default: - if (differentClients==0 || lockStatus==0) { - retval=setExtSignal(signalindex,flag); - } else { - if (lockStatus!=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n", lastClientIP); - } - } - - } - -#ifdef VERBOSE - printf("Setting external signal %d to flag %d\n",signalindex,flag ); - printf("Set to flag %d\n",retval); -#endif - - } else { - ret=FAIL; - } - - if (ret==OK && differentClients!=0) - ret=FORCE_UPDATE; - - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - /*return ok/fail*/ - return ret; - -} - - -int set_external_communication_mode(int file_des) { - int n; - enum externalCommunicationMode arg, ret=GET_EXTERNAL_COMMUNICATION_MODE; - int retval=OK; - - sprintf(mess,"Can't set external communication mode\n"); - - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - /* - enum externalCommunicationMode{ - GET_EXTERNAL_COMMUNICATION_MODE, - AUTO, - TRIGGER_EXPOSURE_SERIES, - TRIGGER_EXPOSURE_BURST, - TRIGGER_READOUT, - TRIGGER_COINCIDENCE_WITH_INTERNAL_ENABLE, - GATE_FIX_NUMBER, - GATE_FIX_DURATION, - GATE_WITH_START_TRIGGER, - GATE_COINCIDENCE_WITH_INTERNAL_ENABLE - }; - */ - if (retval==OK) { - /* execute action */ - - ret=setTiming(arg); - - /* switch(arg) { */ - /* default: */ - /* sprintf(mess,"The meaning of single signals should be set\n"); */ - /* retval=FAIL; */ - /* } */ - - -#ifdef VERBOSE - printf("Setting external communication mode to %d\n", arg); -#endif - } else - ret=FAIL; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return retval; -} - - - -int get_id(int file_des) { - // sends back 64 bits! - int64_t retval=-1; - int ret=OK; - int n=0; - enum idMode arg; - - sprintf(mess,"Can't return id\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - -#ifdef VERBOSE - printf("Getting id %d\n", arg); -#endif - - switch (arg) { - case DETECTOR_SERIAL_NUMBER: - retval=getDetectorNumber(); - break; - case DETECTOR_FIRMWARE_VERSION: - retval=getFirmwareSVNVersion(); - retval=(retval <<32) | getFirmwareVersion(); - break; - case DETECTOR_SOFTWARE_VERSION: - retval= GITREV; - retval= (retval <<32) | GITDATE; - break; - default: - printf("Required unknown id %d \n", arg); - ret=FAIL; - retval=FAIL; - break; - } - -#ifdef VERBOSE - printf("Id is %llx\n", retval); -#endif - - if (differentClients==1) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - -int digital_test(int file_des) { - - int retval; - int ret=OK; - int imod=-1; - int n=0; - int ibit=0; - int ow; - int ival; - enum digitalTestMode arg; - - sprintf(mess,"Can't send digital test\n"); - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - -#ifdef VERBOSE - printf("Digital test mode %d\n",arg ); -#endif - - switch (arg) { - case CHIP_TEST: - n = receiveDataOnly(file_des,&imod,sizeof(imod)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } -#ifdef VERBOSE - printf("of module %d\n", imod); -#endif - retval=0; - - break; - case MODULE_FIRMWARE_TEST: - retval=0x2; - break; - case DETECTOR_FIRMWARE_TEST: - retval=testFpga(); - break; - case DETECTOR_MEMORY_TEST: - ret=testRAM(); - break; - case DETECTOR_BUS_TEST: - retval=testBus(); - break; - case DETECTOR_SOFTWARE_TEST: - retval=testFpga(); - break; - case DIGITAL_BIT_TEST: - n = receiveDataOnly(file_des,&ival,sizeof(ival)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } -#ifdef VERBOSE - printf("with value %d\n", ival); -#endif - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - break; - } - digitalTestBit = ival; - retval=digitalTestBit; - break; - default: - printf("Unknown digital test required %d\n",arg); - ret=FAIL; - retval=FAIL; - break; - } - -#ifdef VERBOSE - printf("digital test result is 0x%x\n", retval); -#endif - //Always returns force update such that the dynamic range is always updated on the client - - // if (differentClients==1 && ret==OK) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - -int write_register(int file_des) { - - int retval; - int ret=OK; - int arg[2]; - int addr, val; - int n; - u_int32_t address; - - sprintf(mess,"Can't write to register\n"); - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - addr=arg[0]; - val=arg[1]; - -#ifdef VERBOSE - printf("writing to register 0x%x data 0x%x\n", addr, val); -#endif - - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } - - - if(ret!=FAIL){ - address=(addr << MEM_MAP_SHIFT); - if((address==FIFO_DATA_REG_OFF)||(address==CONTROL_REG)) - ret = bus_w16(address,val); - else - ret=bus_w(address,val); - if(ret==OK){ - if((address==FIFO_DATA_REG_OFF)||(address==CONTROL_REG)) - retval=bus_r16(address); - else - retval=bus_r(address); - } - } - - -#ifdef VERBOSE - printf("Data set to 0x%x\n", retval); -#endif - if (retval==val) { - ret=OK; - if (differentClients) - ret=FORCE_UPDATE; - } else { - ret=FAIL; - sprintf(mess,"Writing to register 0x%x failed: wrote 0x%x but read 0x%x\n", addr, val, retval); - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - -int read_register(int file_des) { - - int retval; - int ret=OK; - int arg; - int addr; - int n; - u_int32_t address; - - sprintf(mess,"Can't read register\n"); - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - addr=arg; - - - - //#ifdef VERBOSE - printf("reading register 0x%x\n", addr); - //#endif - - if(ret!=FAIL){ - address=(addr << MEM_MAP_SHIFT); - if((address==FIFO_DATA_REG_OFF)||(address==CONTROL_REG)) - retval=bus_r16(address); - else - retval=bus_r(address); - } - - - -#ifdef VERBOSE - printf("Returned value 0x%x\n", retval); -#endif - if (ret==FAIL) { - ret=FAIL; - printf("Reading register 0x%x failed\n", addr); - } else if (differentClients) - ret=FORCE_UPDATE; - - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - -int set_dac(int file_des) { - //default:all mods - int retval, retval1; - int ret=OK; - int arg[3]; - enum dacIndex ind; - int imod; - int n; - int val; - int mV=0; - int v; - sprintf(mess,"Can't set DAC\n"); - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ind=arg[0]; - - imod=arg[1]; - - mV=arg[2]; - - if (mV) - printf("DAC will be set in mV %d!\n",mV); - else - printf("DAC will be set in DACu! %d\n", mV); - - n = receiveDataOnly(file_des,&val,sizeof(val)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - //#ifdef VERBOSE - printf("Setting DAC %d of module %d to %d , mode %d\n", ind, imod, val, mV); - //#endif - - if (imod>=getNModBoard()) - ret=FAIL; - if (imod<0) - imod=ALLMOD; - - - - - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else{ - if (ind2500) - val=-1; - printf("%d mV is ",val); - if (val>0) - val=val/2500*4095; - printf("%d DACu\n", val); - } else { - v=val*2500/4095; - if (val>4095) { - val=-1; - } - } - - if (vLimitCompliant(v)) - retval=setDac(ind,val); // in DACu - - - } else { - switch (ind) { - case ADC_VPP: - - printf("Setting ADC VPP to %d\n",val); - if (val>4 || val<0) - printf("Cannot set ADC VPP to %d\n",val); - else { - writeADC(0x18,val); - adcvpp=val; - } - retval=adcvpp;; - break; - - case HV_NEW: - retval=initHighVoltage(val,imod);//ByModule - break; - - case V_POWER_A: - case V_POWER_B: - case V_POWER_C: - case V_POWER_D: - case V_POWER_IO: - case V_POWER_CHIP: - if (mV) { - if (vLimitCompliant(val)) - retval=setPower(ind,val); - else - printf("********power %d exceeds voltage limits", ind); - - } else - printf("********power %d should be set in mV instead od DACu", ind); - break; - - case V_LIMIT: - if (mV) { - retval=setPower(ind,val); - } else - printf("********power %d should be set in mV instead od DACu", ind); - break; - - default: - printf("**********No dac with index %d\n",ind); - printf("**********%d %d\n",N_DAC,N_PWR); - ret=FAIL; - } - - } - } - } - - - if(ret==OK){ - if (ind=getNModBoard() || imod<0) - ret=FAIL; - - //#ifdef MCB_FUNCS - switch (ind) { - case TEMPERATURE_FPGA: - idac=TEMP_FPGA; - break; - case TEMPERATURE_ADC: - idac=TEMP_ADC; - break; - - case V_POWER_D: - idac++; - case V_POWER_C: - idac++; - case V_POWER_B: - idac++; - case V_POWER_A: - idac++; - case V_POWER_IO: - idac+=100; - break; - - case I_POWER_D: - idac++; - case I_POWER_C: - idac++; - case I_POWER_B: - idac++; - case I_POWER_A: - idac++; - case I_POWER_IO: - idac+=200; - break; - - default: - // printf("Unknown DAC index %d\n",ind); - sprintf(mess,"Unknown DAC index %d\n",ind); - ret=FAIL; - break; - } - printf("DAC index %d (%d)\n",idac,ind); - - if (ret==OK) { - - - if (idac>=200) - retval=getCurrent(idac-200); - else if (idac>=100) - retval=getVoltage(idac-100); - else - retval=getTemperature(idac); - - - }else if (ind>=1000) { - retval=readSlowADC(ind-1000); - if (retval>=0) { - ret=OK; - } - - } - - - //#endif - -#ifdef VERBOSE - printf("ADC is %d V\n", retval); -#endif - if (ret==FAIL) { - printf("Getting adc %d of module %d failed\n", ind, imod); - } - - if (differentClients) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - -int set_channel(int file_des) { - int ret=OK; - sls_detector_channel myChan; - int retval; - int n; - - - sprintf(mess,"Can't set channel\n"); - -#ifdef VERBOSE - printf("Setting channel\n"); -#endif - ret=receiveChannel(file_des, &myChan); - if (ret>=0) - ret=OK; - else - ret=FAIL; -#ifdef VERBOSE - printf("channel number is %d, chip number is %d, module number is %d, register is %lld\n", myChan.chan,myChan.chip, myChan.module, myChan.reg); -#endif - - if (ret==OK) { - if (myChan.module>=getNModBoard()) - ret=FAIL; - if (myChan.chip>=N_CHIP) - ret=FAIL; - if (myChan.chan>=N_CHAN) - ret=FAIL; - if (myChan.module<0) - myChan.module=ALLMOD; - } - - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - - } - } - /* Maybe this is done inside the initialization funcs */ - //copyChannel(detectorChans[myChan.module][myChan.chip]+(myChan.chan), &myChan); - - - - if (differentClients==1 && ret==OK) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - /*return ok/fail*/ - return ret; - -} - - - - -int get_channel(int file_des) { - - int ret=OK; - sls_detector_channel retval; - - int arg[3]; - int ichan, ichip, imod; - int n; - - sprintf(mess,"Can't get channel\n"); - - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ichan=arg[0]; - ichip=arg[1]; - imod=arg[2]; - - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod=0 && ichip=0 && ichan=0) - ret=OK; - else - ret=FAIL; -#ifdef VERBOSE - printf("chip number is %d, module number is %d, register is %d, nchan %d\n",myChip.chip, myChip.module, myChip.reg, myChip.nchan); -#endif - - if (ret==OK) { - if (myChip.module>=getNModBoard()) - ret=FAIL; - if (myChip.module<0) - myChip.module=ALLMOD; - if (myChip.chip>=N_CHIP) - ret=FAIL; - } - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - ; - } - /* Maybe this is done inside the initialization funcs */ - //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); - - if (differentClients && ret==OK) - ret=FORCE_UPDATE; - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - return ret; -} - -int get_chip(int file_des) { - - - int ret=OK; - sls_detector_chip retval; - int arg[2]; - int ichip, imod; - int n; - - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ichip=arg[0]; - imod=arg[1]; - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod=0 && ichip=0) - ret=OK; - else - ret=FAIL; - - -#ifdef VERBOSE - printf("module number is %d,register is %d, nchan %d, nchip %d, ndac %d, nadc %d, gain %f, offset %f\n",myModule.module, myModule.reg, myModule.nchan, myModule.nchip, myModule.ndac, myModule.nadc, myModule.gain,myModule.offset); -#endif - - if (ret==OK) { - if (myModule.module>=getNModBoard()) { - ret=FAIL; - printf("Module number is too large %d\n",myModule.module); - } - if (myModule.module<0) - myModule.module=ALLMOD; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - } - } - - if (differentClients==1 && ret==OK) - ret=FORCE_UPDATE; - - /* Maybe this is done inside the initialization funcs */ - //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - free(myDac); - if(myAdc != NULL) free(myAdc); - if(myChip != NULL) free(myChip); - if(myChan != NULL) free(myChan); - - - //setDynamicRange(dr); always 16 commented out - - return ret; -} - - - - -int get_module(int file_des) { - - int ret=OK; - int arg; - int imod; - int n; - sls_detector_module myModule; - int *myDac=malloc(N_DAC*sizeof(int)); - int *myChip=NULL; - int *myChan=NULL; - int *myAdc=NULL; - - /*not required for jungfrau. so save memory*/ - if(myDetectorType != JUNGFRAU){ - myChip=malloc(N_CHIP*sizeof(int)); - myChan=malloc(N_CHIP*N_CHAN*sizeof(int)); - myAdc=malloc(N_ADC*sizeof(int)); - } - - - if (myDac) - myModule.dacs=myDac; - else { - sprintf(mess,"could not allocate dacs\n"); - ret=FAIL; - } - - - myModule.adcs=NULL; - myModule.chipregs=NULL; - myModule.chanregs=NULL; - /*not required for jungfrau. so save memory*/ - if(myDetectorType != JUNGFRAU){ - if (myAdc) - myModule.adcs=myAdc; - else { - sprintf(mess,"could not allocate adcs\n"); - ret=FAIL; - } - if (myChip) - myModule.chipregs=myChip; - else { - sprintf(mess,"could not allocate chips\n"); - ret=FAIL; - } - if (myChan) - myModule.chanregs=myChan; - else { - sprintf(mess,"could not allocate chans\n"); - ret=FAIL; - } - } - - myModule.ndac=N_DAC; - myModule.nchip=N_CHIP; - myModule.nchan=N_CHAN*N_CHIP; - myModule.nadc=N_ADC; - - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - imod=arg; - - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod-1) { - dataret=FAIL; - sprintf(mess,"no data and run stopped: %d frames left\n",(int)(getFrames()+2)); - printf("%s\n",mess); - } else { - dataret=FINISHED; - sprintf(mess,"acquisition successfully finished\n"); - printf("%s\n",mess); - if (differentClients) - dataret=FORCE_UPDATE; - } -#ifdef VERBOSE - printf("Frames left %d\n",(int)(getFrames())); -#endif - sendDataOnly(file_des,&dataret,sizeof(dataret)); - sendDataOnly(file_des,mess,sizeof(mess)); - } - - - - - return dataret; - -} - - - - - - - - -int read_all(int file_des) { - -while(read_frame(file_des)==OK) { - -#ifdef VERBOSE - printf("frame read\n"); -#endif - ; - } -#ifdef VERBOSE - printf("Frames finished\n"); -#endif - return OK; - - -} - -int start_and_read_all(int file_des) { - //int dataret=OK; -#ifdef VERBOSE - printf("Starting and reading all frames\n"); -#endif - - if (differentClients==1 && lockStatus==1) { - dataret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - sendDataOnly(file_des,&dataret,sizeof(dataret)); - sendDataOnly(file_des,mess,sizeof(mess)); - return dataret; - - } - nframes = 0; - startStateMachine(); - - /* ret=startStateMachine(); - if (ret!=OK) { - sprintf(mess,"could not start state machine\n"); - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); - - #ifdef VERBOSE - printf("could not start state machine\n"); -#endif -} else {*/ - read_all(file_des); -#ifdef VERBOSE - printf("Frames finished\n"); -#endif - //} - - - return OK; - - -} - -int set_timer(int file_des) { - enum timerIndex ind; - int64_t tns; - int n; - int64_t retval; - int ret=OK; - - - sprintf(mess,"can't set timer\n"); - - n = receiveDataOnly(file_des,&ind,sizeof(ind)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,&tns,sizeof(tns)); // total received data - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret!=OK) { - printf(mess); - } - -#ifdef VERBOSE - printf("setting timer %d to %lld ns\n",ind,tns); -#endif - if (ret==OK) { - - if (differentClients==1 && lockStatus==1 && tns!=-1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - switch(ind) { - case FRAME_NUMBER: - retval=setFrames(tns); - break; - case ACQUISITION_TIME: - retval=setExposureTime(tns); - break; - case FRAME_PERIOD: - retval=setPeriod(tns); - break; - case DELAY_AFTER_TRIGGER: - retval=setDelay(tns); - break; - case GATES_NUMBER: - retval=setGates(tns); - break; - case PROBES_NUMBER: - sprintf(mess,"can't set timer for moench\n"); - ret=FAIL; - break; - case CYCLES_NUMBER: - retval=setTrains(tns); - break; - case SAMPLES_JCTB: - retval=setSamples(tns); - break; - default: - ret=FAIL; - sprintf(mess,"timer index unknown %d\n",ind); - break; - } - } - } - if (ret!=OK) { - printf(mess); - if (differentClients) - ret=FORCE_UPDATE; - } - - if (ret!=OK) { - printf(mess); - printf("set timer failed\n"); - } else if (ind==FRAME_NUMBER) { - // ret=allocateRAM(); - // if (ret!=OK) - // sprintf(mess, "could not allocate RAM for %lld frames\n", tns); - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { -#ifdef VERBOSE - printf("returning ok %d\n",(int)(sizeof(retval))); -#endif - - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - - return ret; - -} - - - - - - - - -int get_time_left(int file_des) { - - enum timerIndex ind; - int n; - int64_t retval; - int ret=OK; - - sprintf(mess,"can't get timer\n"); - n = receiveDataOnly(file_des,&ind,sizeof(ind)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - - //#ifdef VERBOSE - - printf("getting time left on timer %d \n",ind); - //#endif - - if (ret==OK) { - switch(ind) { - case FRAME_NUMBER: - printf("getting frames \n"); - retval=getFrames(); - break; - case ACQUISITION_TIME: - retval=getExposureTime(); - break; - case FRAME_PERIOD: - retval=getPeriod(); - break; - case DELAY_AFTER_TRIGGER: - retval=getDelay(); - break; - case GATES_NUMBER: - retval=getGates(); - break; - case PROBES_NUMBER: - retval=getProbes(); - break; - case CYCLES_NUMBER: - retval=getTrains(); - break; - case PROGRESS: - retval=getProgress(); - break; - case ACTUAL_TIME: - retval=getActualTime(); - break; - case MEASUREMENT_TIME: - retval=getMeasurementTime(); - break; - case FRAMES_FROM_START: - case FRAMES_FROM_START_PG: - retval=getFramesFromStart(); - break; - case SAMPLES_JCTB: - retval=setSamples(-1); - break; - default: - ret=FAIL; - sprintf(mess,"timer index unknown %d\n",ind); - break; - } - } - - - if (ret!=OK) { - printf("get time left failed\n"); - } else if (differentClients) - ret=FORCE_UPDATE; - - //#ifdef VERBOSE - - printf("time left on timer %d is %lld\n",ind, retval); - //#endif - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } else - n = sendDataOnly(file_des,&retval,sizeof(retval)); - -#ifdef VERBOSE - - printf("data sent\n"); -#endif - - return ret; - - -} - -int set_dynamic_range(int file_des) { - - - - int dr; - int n; - int retval; - int ret=OK; - - printf("Set dynamic range?\n"); - sprintf(mess,"can't set dynamic range\n"); - - - n = receiveDataOnly(file_des,&dr,sizeof(dr)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - - if (differentClients==1 && lockStatus==1 && dr>=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=setDynamicRange(dr); - } - - //if (dr>=0 && retval!=dr) ret=FAIL; - if (ret!=OK) { - sprintf(mess,"set dynamic range failed\n"); - } else { - /* ret=allocateRAM(); */ -/* if (ret!=OK) */ -/* sprintf(mess,"Could not allocate RAM for the dynamic range selected\n"); */ -// else - if (differentClients) - ret=FORCE_UPDATE; - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - -int set_roi(int file_des) { - - int i; - int ret=OK; - int nroi=-1; - int n=0; - int retvalsize=0; - ROI arg[MAX_ROIS]; - int retval; - strcpy(mess,"Could not set/get roi\n"); - // u_int32_t disable_reg=0; - - n = receiveDataOnly(file_des,&nroi,sizeof(nroi)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - - if(nroi>=0){ - n = receiveDataOnly(file_des,arg,nroi*sizeof(ROI)); - if (n != (nroi*sizeof(ROI))) { - sprintf(mess,"Received wrong number of bytes for ROI\n"); - ret=FAIL; - } - - printf("Setting ROI to:"); - for( i=0;i=0){//necessary??? - sprintf(mess,"Detector locked by %s\n", lastClientIP); - ret=FAIL; - } else{ - retval=setROI(nroi,arg,&retvalsize,&ret); - if (ret==FAIL){ - printf("mess:%s\n",mess); - sprintf(mess,"Could not set all roi, should have set %d rois, but only set %d rois\n",nroi,retvalsize); - } - } - - if(ret==OK && differentClients){ - printf("Force update\n"); - ret=FORCE_UPDATE; - } - - /* send answer */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if(ret==FAIL) - n = sendDataOnly(file_des,mess,sizeof(mess)); - else{ - sendDataOnly(file_des,&retvalsize,sizeof(retvalsize)); - sendDataOnly(file_des,arg,retvalsize*sizeof(ROI)); - } - /*return ok/fail*/ - return ret; -} - -int get_roi(int file_des) { - - - return FAIL; -} - -int set_speed(int file_des) { - - enum speedVariable arg; - int val,n; - int ret=OK; - int retval; - - n=receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - n=receiveDataOnly(file_des,&val,sizeof(val)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - - - if (ret==OK) { - - /* if (arg==PHASE_SHIFT || arg==ADC_PHASE) { */ - - - /* retval=phaseStep(val); */ - - /* } else if ( arg==DBIT_PHASE) { */ - /* retval=dbitPhaseStep(val); */ - /* } else { */ - - - /* if (val!=-1) { */ - - - if (differentClients==1 && lockStatus==1 && val>=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - switch (arg) { - case PHASE_SHIFT: - case ADC_PHASE: - if (val==-1) - retval=getPhase(run_clk_c); - else - retval=configurePhase(val,run_clk_c); - break; - - case DBIT_PHASE: - if (val==-1) - retval=getPhase(dbit_clk_c); - else - retval=configurePhase(val,dbit_clk_c); - break; - - case CLOCK_DIVIDER: - retval=configureFrequency(val,run_clk_c);//setClockDivider(val,0); - if (configureFrequency(-1,sync_clk_c)>retval) { - configureFrequency(retval,sync_clk_c); - printf("--Configuring sync clk to %d MHz\n",val); - } else if (configureFrequency(-1,dbit_clk_c)>val && configureFrequency(-1,adc_clk_c)>retval) { - printf("++Configuring sync clk to %d MHz\n",val); - configureFrequency(retval,sync_clk_c); - } - break; - -/* case PHASE_SHIFT: */ -/* retval=phaseStep(val,0); */ -/* break; */ - - case OVERSAMPLING: - retval=setOversampling(val); - break; - - case ADC_CLOCK: - retval=configureFrequency(val,adc_clk_c);//setClockDivider(val,1); - if (configureFrequency(-1,sync_clk_c)>val) { - configureFrequency(retval,sync_clk_c); - printf("--Configuring sync clk to %d MHz\n",val); - } else if (configureFrequency(-1,dbit_clk_c)>val && configureFrequency(-1,run_clk_c)>retval) { - printf("++Configuring sync clk to %d MHz\n",val); - configureFrequency(retval,sync_clk_c); - } - break; - - case DBIT_CLOCK: - retval=configureFrequency(val,dbit_clk_c);//setClockDivider(val,2); - if (configureFrequency(-1,sync_clk_c)>retval){ - configureFrequency(retval,sync_clk_c); - printf("--Configuring sync clk to %d MHz\n",val); - } else if (configureFrequency(-1,adc_clk_c)>retval && configureFrequency(-1,run_clk_c)>retval) { - printf("++Configuring sync clk to %d MHz\n",val); - configureFrequency(retval,sync_clk_c); - } - - break; - - - - case ADC_PIPELINE: - retval=adcPipeline(val); - break; - - - case DBIT_PIPELINE: - retval=dbitPipeline(val); - break; - - default: - ret=FAIL; - sprintf(mess,"Unknown speed parameter %d",arg); - } - } - // } - - - } - - - - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - - - -int set_readout_flags(int file_des) { - - enum readOutFlags arg; - int ret=OK; - enum readOutFlags v=-1; - - receiveDataOnly(file_des,&arg,sizeof(arg)); - - switch (arg) { - case NORMAL_READOUT: - case DIGITAL_ONLY: - case ANALOG_AND_DIGITAL: - case GET_READOUT_FLAGS: - break; - default: - sprintf(mess,"unknown readout flags for jctb\n"); - ret=FAIL; - } - if (ret==OK) - v=setReadOutMode(arg); - - if (v<0) { - ret=FAIL; - sprintf(mess,"found non valid readout mode (neither analog nor digital)\n"); - } - sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==OK) - sendDataOnly(file_des,&v,sizeof(v)); - else - sendDataOnly(file_des,mess,sizeof(mess)); - // sendDataOnly(file_des,mess,sizeof(mess)); - - return ret; -} - - - - - -int execute_trimming(int file_des) { - - int arg[3]; - int ret=FAIL; - enum trimMode mode; - - sprintf(mess,"can't set execute trimming for moench\n"); - - receiveDataOnly(file_des,&mode,sizeof(mode)); - receiveDataOnly(file_des,arg,sizeof(arg)); - - - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); - - return ret; -} - - -int lock_server(int file_des) { - - - int n; - int ret=OK; - - int lock; - n = receiveDataOnly(file_des,&lock,sizeof(lock)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (lock)\n"); - ret=FAIL; - } - if (lock>=0) { - if (lockStatus==0 || strcmp(lastClientIP,thisClientIP)==0 || strcmp(lastClientIP,"none")==0) - lockStatus=lock; - else { - ret=FAIL; - sprintf(mess,"Server already locked by %s\n", lastClientIP); - } - } - if (differentClients && ret==OK) - ret=FORCE_UPDATE; - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else - n = sendDataOnly(file_des,&lockStatus,sizeof(lockStatus)); - - return ret; - -} - -int set_port(int file_des) { - int n; - int ret=OK; - int sd=-1; - - enum portType p_type; /** data? control? stop? Unused! */ - int p_number; /** new port number */ - - n = receiveDataOnly(file_des,&p_type,sizeof(p_type)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (ptype)\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,&p_number,sizeof(p_number)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (pnum)\n"); - ret=FAIL; - } - if (differentClients==1 && lockStatus==1 ) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - if (p_number<1024) { - sprintf(mess,"Too low port number %d\n", p_number); - printf("\n"); - ret=FAIL; - } - - printf("set port %d to %d\n",p_type, p_number); - - sd=bindSocket(p_number); - } - if (sd>=0) { - ret=OK; - if (differentClients ) - ret=FORCE_UPDATE; - } else { - ret=FAIL; - sprintf(mess,"Could not bind port %d\n", p_number); - printf("Could not bind port %d\n", p_number); - if (sd==-10) { - sprintf(mess,"Port %d already set\n", p_number); - printf("Port %d already set\n", p_number); - - } - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&p_number,sizeof(p_number)); - closeConnection(file_des); - exitServer(sockfd); - sockfd=sd; - - } - - return ret; - -} - -int get_last_client_ip(int file_des) { - int ret=OK; - int n; - if (differentClients ) - ret=FORCE_UPDATE; - n = sendDataOnly(file_des,&ret,sizeof(ret)); - n = sendDataOnly(file_des,lastClientIP,sizeof(lastClientIP)); - - return ret; - -} - - -int send_update(int file_des) { - - int ret=OK; - enum detectorSettings t; - int n;//int thr, n; - //int it; - int64_t retval, tns=-1; - enum readOutFlags v=-1; - n = sendDataOnly(file_des,lastClientIP,sizeof(lastClientIP)); - n = sendDataOnly(file_des,&nModX,sizeof(nModX)); - n = sendDataOnly(file_des,&nModY,sizeof(nModY)); - n = sendDataOnly(file_des,&dynamicRange,sizeof(dynamicRange)); - n = sendDataOnly(file_des,&dataBytes,sizeof(dataBytes)); - t=GET_SETTINGS;//setSettings(GET_SETTINGS,-1); - n = sendDataOnly(file_des,&t,sizeof(t)); -/* thr=getThresholdEnergy(); - n = sendDataOnly(file_des,&thr,sizeof(thr));*/ - retval=setFrames(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setExposureTime(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setPeriod(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setDelay(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setGates(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); -/* retval=setProbes(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t));*/ - retval=setTrains(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setSamples(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - - v=setReadOutMode(-1); - sendDataOnly(file_des,&v,sizeof(v)); - - if (lockStatus==0) { - strcpy(lastClientIP,thisClientIP); - } - - return ret; - - -} -int update_client(int file_des) { - - int ret=OK; - - sendDataOnly(file_des,&ret,sizeof(ret)); - return send_update(file_des); - - - -} - - -int configure_mac(int file_des) { - - int ret=OK; - char arg[5][50]; - int n; - - int imod=0;//should be in future sent from client as -1, arg[2] - int ipad; - long long int imacadd; - long long int idetectormacadd; - int udpport; - int detipad; - int retval=-100; - - sprintf(mess,"Can't configure MAC\n"); - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - sscanf(arg[0], "%x", &ipad); - sscanf(arg[1], "%llx", &imacadd); - sscanf(arg[2], "%x", &udpport); - sscanf(arg[3], "%llx", &idetectormacadd); - sscanf(arg[4], "%x", &detipad); - - //#ifdef VERBOSE - int i; - printf("\ndigital_test_bit in server %d\t",digitalTestBit); - printf("\nipadd %x\t",ipad); - printf("destination ip is %d.%d.%d.%d = 0x%x \n",(ipad>>24)&0xff,(ipad>>16)&0xff,(ipad>>8)&0xff,(ipad)&0xff,ipad); - printf("macad:%llx\n",imacadd); - for (i=0;i<6;i++) - printf("mac adress %d is 0x%x \n",6-i,(unsigned int)(((imacadd>>(8*i))&0xFF))); - printf("udp port:0x%x\n",udpport); - printf("detector macad:%llx\n",idetectormacadd); - for (i=0;i<6;i++) - printf("detector mac adress %d is 0x%x \n",6-i,(unsigned int)(((idetectormacadd>>(8*i))&0xFF))); - printf("detipad %x\n",detipad); - printf("\n"); - //#endif - - - - if (imod>=getNModBoard()) - ret=FAIL; - if (imod<0) - imod=ALLMOD; - - //#ifdef VERBOSE - printf("Configuring MAC of module %d at port %x\n", imod, udpport); - //#endif - //#ifdef MCB_FUNCS - if (ret==OK){ - if(runBusy()){ - ret=stopStateMachine(); - if(ret==FAIL) - strcpy(mess,"could not stop detector acquisition to configure mac"); - } - - if(ret==OK) - configureMAC(ipad,imacadd,idetectormacadd,detipad,digitalTestBit,udpport); - retval=getAdcConfigured(); - } - //#endif - if (ret==FAIL) - printf("configuring MAC of mod %d failed\n", imod); - else - printf("Configuremac successful of mod %d and adc %d\n",imod,retval); - - if (differentClients) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval,sizeof(retval)); - /*return ok/fail*/ - return ret; - -} - - - -int load_image(int file_des) { - int retval; - int ret=OK; - int n; - enum imageType index; - short int ImageVals[N_CHAN*N_CHIP]; - - sprintf(mess,"Loading image failed\n"); - - n = receiveDataOnly(file_des,&index,sizeof(index)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,ImageVals,dataBytes); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - switch (index) { - case DARK_IMAGE : -#ifdef VERBOSE - printf("Loading Dark image\n"); -#endif - break; - case GAIN_IMAGE : -#ifdef VERBOSE - printf("Loading Gain image\n"); -#endif - break; - default: - printf("Unknown index %d\n",index); - sprintf(mess,"Unknown index %d\n",index); - ret=FAIL; - break; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else{ - retval=loadImage(index,ImageVals); - if (retval==-1) - ret = FAIL; - } - } - - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; -} - - - -int set_master(int file_des) { - - enum masterFlags retval=GET_MASTER; - enum masterFlags arg; - int n; - int ret=OK; - // int regret=OK; - - - sprintf(mess,"can't set master flags\n"); - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - -#ifdef VERBOSE - printf("setting master flags to %d\n",arg); -#endif - - if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=setMaster(arg); - - } - if (retval==GET_MASTER) { - ret=FAIL; - } - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - - - - - - -int set_synchronization(int file_des) { - - enum synchronizationMode retval=GET_MASTER; - enum synchronizationMode arg; - int n; - int ret=OK; - //int regret=OK; - - - sprintf(mess,"can't set synchronization mode\n"); - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } -#ifdef VERBOSE - printf("setting master flags to %d\n",arg); -#endif - - if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - //ret=setStoreInRAM(0); - // initChipWithProbes(0,0,0, ALLMOD); - retval=setSynchronization(arg); - } - if (retval==GET_SYNCHRONIZATION_MODE) { - ret=FAIL; - } - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - - - - - - -int read_counter_block(int file_des) { - - int ret=OK; - int n; - int startACQ; - //char *retval=NULL; - short int CounterVals[N_CHAN*N_CHIP]; - - sprintf(mess,"Read counter block failed\n"); - - n = receiveDataOnly(file_des,&startACQ,sizeof(startACQ)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else{ - ret=readCounterBlock(startACQ,CounterVals); -#ifdef VERBOSE - int i; - for(i=0;i<6;i++) - printf("%d:%d\t",i,CounterVals[i]); -#endif - } - } - - if(ret!=FAIL){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,CounterVals,dataBytes);//1280*2 - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; -} - - - - - -int reset_counter_block(int file_des) { - - int ret=OK; - int n; - int startACQ; - - sprintf(mess,"Reset counter block failed\n"); - - n = receiveDataOnly(file_des,&startACQ,sizeof(startACQ)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else - ret=resetCounterBlock(startACQ); - } - - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - - /*return ok/fail*/ - return ret; -} - - - -int calibrate_pedestal(int file_des){ - - int ret=OK; - int retval=-1; - int n; - int frames; - - sprintf(mess,"Could not calibrate pedestal\n"); - - n = receiveDataOnly(file_des,&frames,sizeof(frames)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else - ret=calibratePedestal(frames); - } - - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval,sizeof(retval)); - - /*return ok/fail*/ - return ret; -} - - -int set_ctb_pattern(int file_des){ - - int ret=OK;//FAIL; - int retval=-1; - int n; - int mode; - uint64_t word, retval64, t; - int addr; - int level, start, stop, nl; - uint64_t pat[1024]; - - sprintf(mess,"Could not set pattern\n"); - - n = receiveDataOnly(file_des,&mode,sizeof(mode)); - printf("pattern mode is %d\n",mode); - switch (mode) { - - case 0: //sets word - n = receiveDataOnly(file_des,&addr,sizeof(addr)); - n = receiveDataOnly(file_des,&word,sizeof(word)); - ret=OK; - - printf("pattern addr is %d %x\n",addr, word); - switch (addr) { - case -1: - retval64=writePatternIOControl(word); - break; - case -2: - retval64=writePatternClkControl(word); - break; - default: - retval64=writePatternWord(addr,word); - }; - - - //write word; - //@param addr address of the word, -1 is I/O control register, -2 is clk control register - //@param word 64bit word to be written, -1 gets - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval64,sizeof(retval64)); - break; - - case 1: //pattern loop - // printf("loop\n"); - n = receiveDataOnly(file_des,&level,sizeof(level)); - n = receiveDataOnly(file_des,&start,sizeof(start)); - n = receiveDataOnly(file_des,&stop,sizeof(stop)); - n = receiveDataOnly(file_des,&nl,sizeof(nl)); - - - - // printf("level %d start %x stop %x nl %d\n",level, start, stop, nl); - /** Sets the pattern or loop limits in the CTB - @param level -1 complete pattern, 0,1,2, loop level - @param start start address if >=0 - @param stop stop address if >=0 - @param n number of loops (if level >=0) - @returns OK/FAIL - */ - ret=setPatternLoop(level, &start, &stop, &nl); - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else { - n += sendDataOnly(file_des,&start,sizeof(start)); - n += sendDataOnly(file_des,&stop,sizeof(stop)); - n += sendDataOnly(file_des,&nl,sizeof(nl)); - } - break; - - - - case 2: //wait address - printf("wait\n"); - n = receiveDataOnly(file_des,&level,sizeof(level)); - n = receiveDataOnly(file_des,&addr,sizeof(addr)); - - - - /** Sets the wait address in the CTB - @param level 0,1,2, wait level - @param addr wait address, -1 gets - @returns actual value - */ - printf("wait addr %d %x\n",level, addr); - retval=setPatternWaitAddress(level,addr); - printf("ret: wait addr %d %x\n",level, retval); - ret=OK; - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else { - n += sendDataOnly(file_des,&retval,sizeof(retval)); - - } - - - break; - - - case 3: //wait time - printf("wait time\n"); - n = receiveDataOnly(file_des,&level,sizeof(level)); - n = receiveDataOnly(file_des,&t,sizeof(t)); - - - /** Sets the wait time in the CTB - @param level 0,1,2, wait level - @param t wait time, -1 gets - @returns actual value - */ - - ret=OK; - - retval64=setPatternWaitTime(level,t); - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval64,sizeof(retval64)); - - break; - - - - case 4: - n = receiveDataOnly(file_des,pat,sizeof(pat)); - for (addr=0; addr<1024; addr++) - writePatternWord(addr,word); - ret=OK; - retval=0; - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval64,sizeof(retval64)); - - break; - - - - - - default: - ret=FAIL; - printf(mess); - sprintf(mess,"%s - wrong mode %d\n",mess, mode); - n = sendDataOnly(file_des,&ret,sizeof(ret)); - n += sendDataOnly(file_des,mess,sizeof(mess)); - - - - } - - - /*return ok/fail*/ - return ret; -} - - -int write_adc_register(int file_des) { - - int retval; - int ret=OK; - int arg[2]; - int addr, val; - int n; - - sprintf(mess,"Can't write to register\n"); - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - addr=arg[0]; - val=arg[1]; - -#ifdef VERBOSE - printf("writing to register 0x%x data 0x%x\n", addr, val); -#endif - - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } - - - if(ret!=FAIL){ - ret=writeADC(addr,val); - if (ret==OK) - retval=val; - } - - -#ifdef VERBOSE - printf("Data set to 0x%x\n", retval); -#endif - if (retval==val) { - ret=OK; - if (differentClients) - ret=FORCE_UPDATE; - } else { - ret=FAIL; - sprintf(mess,"Writing to register 0x%x failed: wrote 0x%x but read 0x%x\n", addr, val, retval); - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - -int power_chip(int file_des) { - - int retval=-1; - int ret=OK; - int arg=-1; - int n; - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - -#ifdef VERBOSE - printf("Power chip to %d\n", arg); -#endif - - if (differentClients==1 && lockStatus==1 && arg!=-1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=powerChip(arg); -#ifdef VERBOSE - printf("Chip powered: %d\n",retval); -#endif - - if (retval==arg || arg<0) { - ret=OK; - } else { - ret=FAIL; - printf("Powering chip failed, wrote %d but read %d\n", arg, retval); - } - - } - if (ret==OK && differentClients==1) - ret=FORCE_UPDATE; - - /* send answer */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } else - n += sendDataOnly(file_des,&retval,sizeof(retval)); - - return ret; -} - - -int reset_fpga(int file_des) { - int ret=OK; - int n; - sprintf(mess,"Reset FPGA unsuccessful\n"); - - resetFPGA(); - initializeDetector(); - - ret = FORCE_UPDATE; - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - - /*return ok/fail*/ - return ret; -} - - -int program_fpga(int file_des) { - int ret=OK; - int n; - sprintf(mess,"Program FPGA unsuccessful\n"); - char* fpgasrc = NULL; - FILE* fp = NULL; - size_t filesize = 0; - size_t unitprogramsize = 0; - size_t totalsize = 0; - - - //filesize - n = receiveDataOnly(file_des,&filesize,sizeof(filesize)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - totalsize = filesize; -#ifdef VERY_VERBOSE - printf("\n\n Total size is:%d\n",totalsize); -#endif - - //lock - if (ret==OK && differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - filesize = 0; - } - - //opening file pointer to flash and telling FPGA to not touch flash - if(ret == OK && startWritingFPGAprogram(&fp) != OK){ - sprintf(mess,"Could not write to flash. Error at startup.\n"); - cprintf(RED,"%s",mess); - ret=FAIL; - filesize = 0; - } - - //---------------- first ret ---------------- - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - //---------------- first ret ---------------- - - - //erasing flash - if(ret != FAIL){ - eraseFlash(); - fpgasrc = (char*)malloc(MAX_FPGAPROGRAMSIZE); - } - - - - //writing to flash part by part - while(ret != FAIL && filesize){ - - unitprogramsize = MAX_FPGAPROGRAMSIZE; //2mb - if(unitprogramsize > filesize) //less than 2mb - unitprogramsize = filesize; -#ifdef VERY_VERBOSE - printf("unit size to receive is:%d\n",unitprogramsize); - printf("filesize:%d currentpointer:%d\n",filesize,currentPointer); -#endif - - - //receive - n = receiveDataOnly(file_des,fpgasrc,unitprogramsize); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - - if (ret==OK) { - if(!(unitprogramsize - filesize)){ - fpgasrc[unitprogramsize]='\0'; - filesize-=unitprogramsize; - unitprogramsize++; - }else - filesize-=unitprogramsize; - - ret = writeFPGAProgram(fpgasrc,unitprogramsize,fp); - } - - - //---------------- middle rets ---------------- - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - cprintf(RED,"Failure: Breaking out of program receiving\n"); - } - //---------------- middle rets ---------------- - - - if(ret != FAIL){ - //print progress - printf("Writing to Flash:%d%%\r",(int) (((double)(totalsize-filesize)/totalsize)*100) ); - fflush(stdout); - } - - } - - - - printf("\n"); - - //closing file pointer to flash and informing FPGA - if(stopWritingFPGAprogram(fp) == FAIL){ - sprintf(mess,"Could not write to flash. Error at end.\n"); - cprintf(RED,"%s",mess); - ret=FAIL; - } - - if(ret!=FAIL){ - ret=FORCE_UPDATE; - } - - - //---------------- last ret ---------------- - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - //---------------- last ret ---------------- - - - //free resources - if(fpgasrc != NULL) - free(fpgasrc); - if(fp!=NULL) - fclose(fp); -#ifdef VERY_VERBOSE - printf("Done with program receiving command\n"); -#endif - /*return ok/fail*/ - return ret; -} - - -int activate(int file_des) { - - int retval=-1; - int ret=OK; - int arg=-1; - int n; - - sprintf(mess,"Can't activate detector\n"); - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret==OK && differentClients==1) - ret=FORCE_UPDATE; - retval=arg; - /* send answer */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } else - n += sendDataOnly(file_des,&retval,sizeof(retval)); - - return ret; -} - -int prepare_acquisition(int file_des) { - int ret = OK; - int n=0; - strcpy(mess,"prepare acquisition failed\n"); - - - ret = FAIL; - strcpy(mess,"Not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); - /* - //lock - if (ret==OK && differentClients && lockStatus) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { - ret = startReceiver(1); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); - } -*/ - - if(ret==OK && differentClients) - ret=FORCE_UPDATE; - - /* send answer */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - return ret; -} - -int cleanup_acquisition(int file_des) { - int ret = OK; - int n=0; - - - //to receive any arguments - while (n > 0) - n = receiveDataOnly(file_des,mess,MAX_STR_LENGTH); - - ret = FAIL; - strcpy(mess,"Not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); - /* - if (lockStatus && differentClients){//necessary??? - sprintf(mess,"Detector locked by %s\n", lastClientIP); - cprintf(RED, "Warning: %s", mess); - ret=FAIL; - } - else { - ret=startReceiver(0); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); - } - */ - if(ret==OK && differentClients) - ret=FORCE_UPDATE; - - /* send answer */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - return ret; -} diff --git a/slsDetectorSoftware/jctbDetectorServer/server_funcs.h b/slsDetectorSoftware/jctbDetectorServer/server_funcs.h deleted file mode 100755 index 40da3b75a..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/server_funcs.h +++ /dev/null @@ -1,102 +0,0 @@ -#ifndef SERVER_FUNCS_H -#define SERVER_FUNCS_H - - -#include "sls_detector_defs.h" - - -#include -/* -#include -#include -#include -*/ -#include "communication_funcs.h" - - - - -#define GOODBYE -200 - -int sockfd; - -int function_table(); - -int decode_function(int); -const char* getFunctionName(enum detFuncs func); -int init_detector(int,int); - -int M_nofunc(int); -int exit_server(int); - - - - -// General purpose functions -int get_detector_type(int); -int set_number_of_modules(int); -int get_max_number_of_modules(int); - - -int exec_command(int); -int set_external_signal_flag(int); -int set_external_communication_mode(int); -int get_id(int); -int digital_test(int); -int write_register(int); -int read_register(int); -int set_dac(int); -int get_adc(int); -int set_channel(int); -int set_chip(int); -int set_module(int); -int get_channel(int); -int get_chip(int); -int get_module(int); - -int get_threshold_energy(int); -int set_threshold_energy(int); -int set_settings(int); -int start_acquisition(int); -int stop_acquisition(int); -int start_readout(int); -int get_run_status(int); -int read_frame(int); -int read_all(int); -int start_and_read_all(int); -int set_timer(int); -int get_time_left(int); -int set_dynamic_range(int); -int set_roi(int); -int get_roi(int); -int set_speed(int); -int set_readout_flags(int); -int execute_trimming(int); -int lock_server(int); -int set_port(int); -int get_last_client_ip(int); -int set_master(int); -int set_synchronization(int); - -int update_client(int); -int send_update(int); -int configure_mac(int); - -int load_image(int); -int read_counter_block(int); -int reset_counter_block(int); - -int calibrate_pedestal(int); - -int set_roi(int); -int set_ctb_pattern(int); - -int write_adc_register(int); -int power_chip(int); -int reset_fpga(int); -int program_fpga(int); - -int activate(int); -int prepare_acquisition(int); -int cleanup_acquisition(int); -#endif diff --git a/slsDetectorSoftware/jctbDetectorServer/sharedmemory.c b/slsDetectorSoftware/jctbDetectorServer/sharedmemory.c deleted file mode 100755 index 4504cfe05..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/sharedmemory.c +++ /dev/null @@ -1,39 +0,0 @@ -#include "sharedmemory.h" - -struct statusdata *stdata; - -int inism(int clsv) { - -static int scansmid; - - if (clsv==SMSV) { - if ( (scansmid=shmget(SMKEY,1024,IPC_CREAT | 0666 ))==-1 ) { - return -1; - } - if ( (stdata=shmat(scansmid,NULL,0))==(void*)-1) { - return -2; - } - } - - if (clsv==SMCL) { - if ( (scansmid=shmget(SMKEY,0,0) )==-1 ) { - return -3; - } - if ( (stdata=shmat(scansmid,NULL,0))==(void*)-1) { - return -4; - } - } - return 1; -} - -void write_status_sm(char *status) { - strcpy(stdata->status,status); -} - -void write_stop_sm(int v) { - stdata->stop=v; -} - -void write_runnumber_sm(int v) { - stdata->runnumber=v; -} diff --git a/slsDetectorSoftware/jctbDetectorServer/sharedmemory.h b/slsDetectorSoftware/jctbDetectorServer/sharedmemory.h deleted file mode 100755 index bdbddf719..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/sharedmemory.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef SM -#define SM - -#include "sls_detector_defs.h" - -#include -#include -#include -#include -#include -#include -#include -//#include -#include -#include -#include -#include -#include -#include - - -#include - -#include -#include - -/* key for shared memory */ -#define SMKEY 10001 - -#define SMSV 1 -#define SMCL 2 - - -struct statusdata { - int runnumber; - int stop; - char status[20]; -} ; - - -/* for shared memory */ - -int inism(int clsv); -void write_status_sm(char *status); -void write_stop_sm(int v); -void write_runnumber_sm(int v); - -#endif diff --git a/slsDetectorSoftware/jctbDetectorServer/slow_adc.c b/slsDetectorSoftware/jctbDetectorServer/slow_adc.c deleted file mode 100644 index 6f1b764b0..000000000 --- a/slsDetectorSoftware/jctbDetectorServer/slow_adc.c +++ /dev/null @@ -1,245 +0,0 @@ -#include "firmware_funcs.h" -#include "registers_m.h" -#include "server_defs.h" -#include "blackfin.h" - -int prepareSlowADCSeq() { - - // u_int16_t vv=0x3c40; - u_int16_t codata=( 1<<13) | (7<<10) | (7<<7) | (1<<6) | (0<<3) | (2<<1) | 1; - - u_int32_t valw; - int obit, ibit; - - // int cnv_bit=16, sdi_bit=17, sck_bit=18; - int cnv_bit=10, sdi_bit=8, sck_bit=9; - - // int oval=0; - - - printf("Codata is %04x\n",codata); - - /* //convert */ - valw=(1<> (13-ibit)) & 1); - // printf("%d",obit); - valw = obit << sdi_bit; - - bus_w(ADC_WRITE_REG,valw); - - usleep(20); - - bus_w(ADC_WRITE_REG,valw|(1<> (13-ibit)) & 1); - // printf("%d",obit); - valw = obit << sdi_bit; - - bus_w(ADC_WRITE_REG,valw); - - usleep(20); - - bus_w(ADC_WRITE_REG,valw|(1<7) - return -1; - - - prepareSlowADC(ichan); - - - /* printf("Codata is %04x\n",codata); */ - - /* /\* //convert *\/ */ - /* valw=(1<> (13-ibit)) & 1); */ - /* // printf("%d",obit); */ - /* valw = obit << sdi_bit; */ - - /* bus_w(ADC_WRITE_REG,valw); */ - - /* usleep(20); */ - - /* bus_w(ADC_WRITE_REG,valw|(1< gitInfo.txt - cd ../../ - ./genVersionHeader.sh $SPECDIR/gitInfo.txt $SPECDIR/$TMPFILE $SPECDIR/$INCLFILE - cd $WD -fi \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/ansi.h b/slsDetectorSoftware/jungfrauDetectorServer/ansi.h deleted file mode 120000 index a122db0ad..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/ansi.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/ansi.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/bin/jungfrauDetectorServer_developer b/slsDetectorSoftware/jungfrauDetectorServer/bin/jungfrauDetectorServer_developer deleted file mode 100755 index 8d37b975c..000000000 Binary files a/slsDetectorSoftware/jungfrauDetectorServer/bin/jungfrauDetectorServer_developer and /dev/null differ diff --git a/slsDetectorSoftware/jungfrauDetectorServer/bin/jungfrauDetectorServer_virtual b/slsDetectorSoftware/jungfrauDetectorServer/bin/jungfrauDetectorServer_virtual deleted file mode 100755 index 4635c35f2..000000000 Binary files a/slsDetectorSoftware/jungfrauDetectorServer/bin/jungfrauDetectorServer_virtual and /dev/null differ diff --git a/slsDetectorSoftware/jungfrauDetectorServer/communication_funcs.c b/slsDetectorSoftware/jungfrauDetectorServer/communication_funcs.c deleted file mode 120000 index 87a4f95d1..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/communication_funcs.c +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.c \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/communication_funcs.h b/slsDetectorSoftware/jungfrauDetectorServer/communication_funcs.h deleted file mode 120000 index f220903b2..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/communication_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/gitInfo.txt b/slsDetectorSoftware/jungfrauDetectorServer/gitInfo.txt deleted file mode 100644 index b7315b074..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/gitInfo.txt +++ /dev/null @@ -1,9 +0,0 @@ -Path: slsDetectorsPackage/slsDetectorSoftware/jungfrauDetectorServer -URL: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repository Root: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repsitory UUID: def79807f6f40ed1797b8154240adbc0e35c95e0 -Revision: 168 -Branch: developer -Last Changed Author: Dhanya_Thattil -Last Changed Rev: 4039 -Last Changed Date: 2019-02-11 11:53:14.000000002 +0100 ./RegisterDefs.h diff --git a/slsDetectorSoftware/jungfrauDetectorServer/gitInfoJungfrau.h b/slsDetectorSoftware/jungfrauDetectorServer/gitInfoJungfrau.h deleted file mode 100644 index 44a6315e3..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/gitInfoJungfrau.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "git@github.com:slsdetectorgroup/slsDetectorPackage.git" -#define GITREPUUID "def79807f6f40ed1797b8154240adbc0e35c95e0" -#define GITAUTH "Dhanya_Thattil" -#define GITREV 0x4039 -#define GITDATE 0x20190211 -#define GITBRANCH "developer" diff --git a/slsDetectorSoftware/jungfrauDetectorServer/gitInfoJungfrauTmp.h b/slsDetectorSoftware/jungfrauDetectorServer/gitInfoJungfrauTmp.h deleted file mode 100644 index dfd9bb246..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/gitInfoJungfrauTmp.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "" -#define GITREPUUID "" -#define GITAUTH "" -#define GITREV "" -#define GITDATE "" -#define GITBRANCH "" diff --git a/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorFunctionList.c b/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorFunctionList.c deleted file mode 100644 index 38d841538..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorFunctionList.c +++ /dev/null @@ -1,1762 +0,0 @@ -//#ifdef SLS_DETECTOR_FUNCTION_LIST - - -#include "slsDetectorFunctionList.h" -#include "gitInfoJungfrau.h" -#include "AD9257.h" // include "commonServerFunctions.h", which in turn includes "blackfin.h" -#include "programfpga.h" -#include "versionAPI.h" - -#ifdef VIRTUAL -#include -#include -#endif -/* global variables */ -//jungfrau doesnt require chips and chans (save memory) -sls_detector_module *detectorModules=NULL; -dacs_t *detectorDacs=NULL; -dacs_t *detectorAdcs=NULL; - -enum detectorSettings thisSettings; -enum masterFlags masterMode = NO_MASTER; - -int highvoltage = 0; -int dacValues[NDAC]; -int32_t clkPhase[2] = {0, 0}; - -#ifdef VIRTUAL -pthread_t pthread_virtual_tid; -int virtual_status = 0; -int virtual_stop = 0; -#endif - - -/* basic tests */ - -int firmware_compatibility = OK; -int firmware_check_done = 0; -char firmware_message[MAX_STR_LENGTH]; - -int isFirmwareCheckDone() { - return firmware_check_done; -} - -int getFirmwareCheckResult(char** mess) { - *mess = firmware_message; - return firmware_compatibility; -} - -void checkFirmwareCompatibility(int flag) { -#ifdef VIRTUAL - cprintf(BLUE,"\n\n" - "********************************************************\n" - "************** Jungfrau Virtual Server *****************\n" - "********************************************************\n\n"); - if (mapCSP0() == FAIL) { - strcpy(firmware_message, - "FATAL ERROR: Could not map to memory. Dangerous to continue.\n"); - cprintf(RED,"%s\n\n", firmware_message); - firmware_compatibility = FAIL; - firmware_check_done = 1; - return; - } - firmware_check_done = 1; - return; -#endif - - defineGPIOpins(); - resetFPGA(); - if (mapCSP0() == FAIL) { - strcpy(firmware_message, - "FATAL ERROR: Could not map to memory. Dangerous to continue.\n"); - cprintf(RED,"%s\n\n", firmware_message); - firmware_compatibility = FAIL; - firmware_check_done = 1; - return; - } - - // does check only if flag is 0 (by default), set by command line - if ((!flag) && ((checkType() == FAIL) || (testFpga() == FAIL) || (testBus() == FAIL))) { - strcpy(firmware_message, - "FATAL ERROR: Could not pass basic tests of FPGA and bus. Dangerous to continue.\n"); - cprintf(RED,"%s\n\n", firmware_message); - firmware_compatibility = FAIL; - firmware_check_done = 1; - return; - } - - uint16_t hversion = getHardwareVersionNumber(); - uint16_t hsnumber = getHardwareSerialNumber(); - uint32_t ipadd = getDetectorIP(); - uint64_t macadd = getDetectorMAC(); - int64_t fwversion = getDetectorId(DETECTOR_FIRMWARE_VERSION); - int64_t swversion = getDetectorId(DETECTOR_SOFTWARE_VERSION); - int64_t sw_fw_apiversion = 0; - int64_t client_sw_apiversion = getDetectorId(CLIENT_SOFTWARE_API_VERSION); - - - if (fwversion >= MIN_REQRD_VRSN_T_RD_API) - sw_fw_apiversion = getDetectorId(SOFTWARE_FIRMWARE_API_VERSION); - cprintf(BLUE,"\n\n" - "********************************************************\n" - "****************** Jungfrau Server *********************\n" - "********************************************************\n\n" - "Hardware Version:\t\t 0x%x\n" - "Hardware Serial Nr:\t\t 0x%x\n" - - "Detector IP Addr:\t\t 0x%x\n" - "Detector MAC Addr:\t\t 0x%llx\n\n" - - "Firmware Version:\t\t 0x%llx\n" - "Software Version:\t\t 0x%llx\n" - "F/w-S/w API Version:\t\t 0x%llx\n" - "Required Firmware Version:\t 0x%x\n" - "Client-Software API Version:\t 0x%llx\n" - "\n" - "********************************************************\n", - hversion, hsnumber, - ipadd, - (long long unsigned int)macadd, - (long long int)fwversion, - (long long int)swversion, - (long long int)sw_fw_apiversion, - REQRD_FRMWR_VRSN, - (long long int)client_sw_apiversion - ); - - // return if flag is not zero, debug mode - if (flag) { - firmware_check_done = 1; - return; - } - - - //cant read versions - printf("Testing Firmware-software compatibility ...\n"); - if(!fwversion || !sw_fw_apiversion){ - strcpy(firmware_message, - "FATAL ERROR: Cant read versions from FPGA. Please update firmware.\n"); - cprintf(RED,"%s\n\n", firmware_message); - firmware_compatibility = FAIL; - firmware_check_done = 1; - return; - } - - //check for API compatibility - old server - if(sw_fw_apiversion > REQRD_FRMWR_VRSN){ - sprintf(firmware_message, - "FATAL ERROR: This detector software software version (0x%llx) is incompatible.\n" - "Please update detector software (min. 0x%llx) to be compatible with this firmware.\n", - (long long int)sw_fw_apiversion, - (long long int)REQRD_FRMWR_VRSN); - cprintf(RED,"%s\n\n", firmware_message); - firmware_compatibility = FAIL; - firmware_check_done = 1; - return; - } - - //check for firmware compatibility - old firmware - if( REQRD_FRMWR_VRSN > fwversion){ - sprintf(firmware_message, - "FATAL ERROR: This firmware version (0x%llx) is incompatible.\n" - "Please update firmware (min. 0x%llx) to be compatible with this server.\n", - (long long int)fwversion, - (long long int)REQRD_FRMWR_VRSN); - cprintf(RED,"%s\n\n", firmware_message); - firmware_compatibility = FAIL; - firmware_check_done = 1; - return; - } - printf("Compatibility - success\n"); - firmware_check_done = 1; -} - - -int checkType() { -#ifdef VIRTUAL - return OK; -#endif - volatile u_int32_t type = ((bus_r(FPGA_VERSION_REG) & DETECTOR_TYPE_MSK) >> DETECTOR_TYPE_OFST); - if (type != JUNGFRAU){ - cprintf(BG_RED,"This is not a Jungfrau Server (read %d, expected %d)\n",type, JUNGFRAU); - return FAIL; - } - - return OK; -} - - - -u_int32_t testFpga(void) { -#ifdef VIRTUAL - return OK; -#endif - printf("\nTesting FPGA...\n"); - - //fixed pattern - int ret = OK; - volatile u_int32_t val = bus_r(FIX_PATT_REG); - if (val == FIX_PATT_VAL) { - printf("Fixed pattern: successful match 0x%08x\n",val); - } else { - cprintf(RED,"Fixed pattern does not match! Read 0x%08x, expected 0x%08x\n", val, FIX_PATT_VAL); - ret = FAIL; - } - return ret; -} - - -int testBus() { -#ifdef VIRTUAL - return OK; -#endif - printf("\nTesting Bus...\n"); - - int ret = OK; - u_int32_t addr = SET_TRIGGER_DELAY_LSB_REG; - int times = 1000 * 1000; - int i = 0; - - for (i = 0; i < times; ++i) { - bus_w(addr, i * 100); - if (i * 100 != bus_r(addr)) { - cprintf(RED,"ERROR: Mismatch! Wrote 0x%x, read 0x%x\n", - i * 100, bus_r(addr)); - ret = FAIL; - } - } - - bus_w(addr, 0); - - if (ret == OK) - printf("Successfully tested bus %d times\n", times); - return ret; -} - - -int moduleTest( enum digitalTestMode arg, int imod){ - return OK; -} - -int detectorTest( enum digitalTestMode arg){ -#ifdef VIRTUAL - return OK; -#endif - switch(arg){ - case DETECTOR_FIRMWARE_TEST: return testFpga(); - case DETECTOR_BUS_TEST: return testBus(); - //DETECTOR_MEMORY_TEST:testRAM - //DETECTOR_SOFTWARE_TEST: - default: - cprintf(RED,"Warning: Test not implemented for this detector %d\n", (int)arg); - break; - } - return OK; -} - - - - - -/* Ids */ - -int64_t getDetectorId(enum idMode arg){ - int64_t retval = -1; - - switch(arg){ - case DETECTOR_SERIAL_NUMBER: - return getDetectorNumber();// or getDetectorMAC() - case DETECTOR_FIRMWARE_VERSION: - return getFirmwareVersion(); - case SOFTWARE_FIRMWARE_API_VERSION: - return getFirmwareAPIVersion(); - case DETECTOR_SOFTWARE_VERSION: - return (GITDATE & 0xFFFFFF); - case CLIENT_SOFTWARE_API_VERSION: - return APIJUNGFRAU; - default: - return retval; - } -} - -u_int64_t getFirmwareVersion() { -#ifdef VIRTUAL - return 0; -#endif - return ((bus_r(FPGA_VERSION_REG) & BOARD_REVISION_MSK) >> BOARD_REVISION_OFST); -} - -u_int64_t getFirmwareAPIVersion() { -#ifdef VIRTUAL - return 0; -#endif - return ((bus_r(API_VERSION_REG) & API_VERSION_MSK) >> API_VERSION_OFST); -} - -u_int16_t getHardwareVersionNumber() { -#ifdef VIRTUAL - return 0; -#endif - return ((bus_r(MOD_SERIAL_NUM_REG) & HARDWARE_VERSION_NUM_MSK) >> HARDWARE_VERSION_NUM_OFST); -} - -u_int16_t getHardwareSerialNumber() { -#ifdef VIRTUAL - return 0; -#endif - return ((bus_r(MOD_SERIAL_NUM_REG) & HARDWARE_SERIAL_NUM_MSK) >> HARDWARE_SERIAL_NUM_OFST); -} - -u_int32_t getDetectorNumber(){ -#ifdef VIRTUAL - return 0; -#endif - return bus_r(MOD_SERIAL_NUM_REG); -} - -u_int64_t getDetectorMAC() { -#ifdef VIRTUAL - return 0; -#else - char output[255],mac[255]=""; - u_int64_t res=0; - FILE* sysFile = popen("ifconfig eth0 | grep HWaddr | cut -d \" \" -f 11", "r"); - fgets(output, sizeof(output), sysFile); - pclose(sysFile); - //getting rid of ":" - char * pch; - pch = strtok (output,":"); - while (pch != NULL){ - strcat(mac,pch); - pch = strtok (NULL, ":"); - } - sscanf(mac,"%llx",&res); - return res; -#endif -} - -u_int32_t getDetectorIP(){ -#ifdef VIRTUAL - return 0; -#endif - char temp[50]=""; - u_int32_t res=0; - //execute and get address - char output[255]; - FILE* sysFile = popen("ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2", "r"); - fgets(output, sizeof(output), sysFile); - pclose(sysFile); - - //converting IPaddress to hex. - char* pcword = strtok (output,"."); - while (pcword != NULL) { - sprintf(output,"%02x",atoi(pcword)); - strcat(temp,output); - pcword = strtok (NULL, "."); - } - strcpy(output,temp); - sscanf(output, "%x", &res); - //printf("ip:%x\n",res); - - return res; -} - - - - - - - - -/* initialization */ - -void initControlServer(){ - clkPhase[0] = 0; clkPhase[1] = 0; - setupDetector(); - printf("\n"); -} - - - -void initStopServer() { - - usleep(CTRL_SRVR_INIT_TIME_US); - if (mapCSP0() == FAIL) { - cprintf(BG_RED, "Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"); - exit(EXIT_FAILURE); - } -} - - - - - - -/* set up detector */ - -void allocateDetectorStructureMemory(){ - printf("This Server is for 1 Jungfrau module (500k)\n"); - - //Allocation of memory - if (detectorModules!=NULL) free(detectorModules); - if (detectorDacs!=NULL) free(detectorDacs); - if (detectorAdcs!=NULL) free(detectorAdcs); - detectorModules=malloc(sizeof(sls_detector_module)); - detectorDacs=malloc(NDAC*sizeof(dacs_t)); - detectorAdcs=malloc(NADC*sizeof(dacs_t)); -#ifdef VERBOSE - printf("modules from 0x%x to 0x%x\n",detectorModules, detectorModules+n); - printf("dacs from 0x%x to 0x%x\n",detectorDacs, detectorDacs+n*NDAC); - printf("adcs from 0x%x to 0x%x\n",detectorAdcs, detectorAdcs+n*NADC); -#endif - (detectorModules)->dacs=detectorDacs; - (detectorModules)->adcs=detectorAdcs; - (detectorModules)->ndac=NDAC; - (detectorModules)->nadc=NADC; - (detectorModules)->nchip=NCHIP; - (detectorModules)->nchan=NCHIP*NCHAN; - (detectorModules)->module=0; - (detectorModules)->gain=0; - (detectorModules)->offset=0; - (detectorModules)->reg=0; - thisSettings = UNINITIALIZED; - - { // initialize to -1 - int i = 0; - for (i = 0; i < NDAC; ++i) { - dacValues[i] = -1; - } - } -} - - - -void setupDetector() { - - allocateDetectorStructureMemory(); - - printf("Resetting PLL\n"); - resetPLL(); - resetCore(); - resetPeripheral(); - cleanFifos(); -#ifndef VIRTUAL - prepareADC(); -#endif - // initialize dac series - initDac(0); /* todo might work without */ - initDac(8); //only for old board compatibility - - //set dacs - setDefaultDacs(); - - bus_w(DAQ_REG, 0x0); /* Only once at server startup */ - - setSpeed(CLOCK_DIVIDER, HALF_SPEED); - cleanFifos(); - resetCore(); - - configureASICTimer(); - bus_w(ADC_PORT_INVERT_REG, ADC_PORT_INVERT_VAL); - - //Initialization of acquistion parameters - setSettings(DEFAULT_SETTINGS,-1); - - setTimer(FRAME_NUMBER, DEFAULT_NUM_FRAMES); - setTimer(CYCLES_NUMBER, DEFAULT_NUM_CYCLES); - setTimer(ACQUISITION_TIME, DEFAULT_EXPTIME); - setTimer(FRAME_PERIOD, DEFAULT_PERIOD); - setTimer(DELAY_AFTER_TRIGGER, DEFAULT_DELAY); - setTimer(STORAGE_CELL_NUMBER, DEFAULT_NUM_STRG_CLLS); - selectStoragecellStart(DEFAULT_STRG_CLL_STRT); - /*setSpeed(CLOCK_DIVIDER, HALF_SPEED); depends if all the previous stuff works*/ - setTiming(DEFAULT_TIMING_MODE); - setHighVoltage(DEFAULT_HIGH_VOLTAGE); - - /* temporary set up until new firmware fixes bug */ - // set temperature threshold - setThresholdTemperature(DEFAULT_TMP_THRSHLD); - // reset temp event - setTemperatureEvent(0); - - -} - - -int setDefaultDacs() { - int ret = OK; - printf("Setting Default Dac values\n"); - { - int i = 0; - int retval[2]={-1,-1}; - const int defaultvals[NDAC] = DEFAULT_DAC_VALS; - for(i = 0; i < NDAC; ++i) { - // if not already default, set it to default - if (dacValues[i] != defaultvals[i]) { - setDAC((enum DACINDEX)i,defaultvals[i],0,0,retval); - if (retval[0] != defaultvals[i]) { - cprintf(RED, "Warning: Setting dac %d failed, wrote %d, read %d\n",i ,defaultvals[i], retval[0]); - ret = FAIL; - } - } - } - } - return ret; -} - - - - -/* firmware functions (resets) */ - -int powerChip (int on){ - if(on != -1){ - if(on){ - cprintf(BLUE, "\n*** Powering on the chip ***\n"); - bus_w(CHIP_POWER_REG, bus_r(CHIP_POWER_REG) | CHIP_POWER_ENABLE_MSK); - } - else{ - cprintf(BLUE, "\n*** Powering off the chip*** \n"); - bus_w(CHIP_POWER_REG, bus_r(CHIP_POWER_REG) & ~CHIP_POWER_ENABLE_MSK); - } - } - - //return ((bus_r(CHIP_POWER_REG) & CHIP_POWER_ENABLE_MSK) >> CHIP_POWER_ENABLE_OFST); - /**temporary fix until power reg status can be read */ - return ((bus_r(CHIP_POWER_REG) & CHIP_POWER_STATUS_MSK) >> CHIP_POWER_STATUS_OFST); -} - - - -int autoCompDisable(int on) { - if(on != -1){ - if(on){ - cprintf(BLUE, "\n*** Auto comp disable mode: enabling ***\n"); - bus_w(VREF_COMP_MOD_REG, bus_r(VREF_COMP_MOD_REG) | VREF_COMP_MOD_ENABLE_MSK); - } - else{ - cprintf(BLUE, "\n*** Auto comp disable mode: disabling *** \n"); - bus_w(VREF_COMP_MOD_REG, bus_r(VREF_COMP_MOD_REG) & ~VREF_COMP_MOD_ENABLE_MSK); - } - } - - return (bus_r(VREF_COMP_MOD_REG) & VREF_COMP_MOD_ENABLE_MSK); -} - - -void cleanFifos() { -#ifdef VIRTUAL - return; -#endif - printf("\nClearing Acquisition Fifos\n"); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_ACQ_FIFO_CLR_MSK); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_ACQ_FIFO_CLR_MSK); -} - -void resetCore() { -#ifdef VIRTUAL - return; -#endif - printf("\nResetting Core\n"); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_CORE_RST_MSK); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_CORE_RST_MSK); -} - -void resetPeripheral() { -#ifdef VIRTUAL - return; -#endif - printf("\nResetting Peripheral\n"); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_PERIPHERAL_RST_MSK); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_PERIPHERAL_RST_MSK); -} - -int adcPhase(int st){ /**carlos needed clkphase 1 and 2? cehck with Aldo */ - printf("Setting ADC Phase to %d\n",st); - if (st > 65535 || st < -65535) - return clkPhase[0]; - - clkPhase[1] = st - clkPhase[0]; - if (clkPhase[1] == 0) - return clkPhase[0]; - - configurePll(); - clkPhase[0] = st; - return clkPhase[0]; -} - -int getPhase() { - return clkPhase[0]; -} - -void configureASICTimer() { - printf("\nConfiguring ASIC Timer\n"); - bus_w(ASIC_CTRL_REG, (bus_r(ASIC_CTRL_REG) & ~ASIC_CTRL_PRCHRG_TMR_MSK) | ASIC_CTRL_PRCHRG_TMR_VAL); - bus_w(ASIC_CTRL_REG, (bus_r(ASIC_CTRL_REG) & ~ASIC_CTRL_DS_TMR_MSK) | ASIC_CTRL_DS_TMR_VAL); -} - - - - - - - - -/* set parameters - nmod, dr, roi */ - -int setNMod(int nm, enum dimension dim){ - return NMOD; -} - - -int getNModBoard(enum dimension arg){ - return NMAXMOD; -} - - -int setDynamicRange(int dr){ - return DYNAMIC_RANGE; -} - - - - -/* parameters - readout */ - -int setSpeed(enum speedVariable arg, int val) { - - if (arg != CLOCK_DIVIDER) - return -1; - - // setting - if(val >= 0) { - - // stop state machine if running - if(runBusy()) - stopStateMachine(); - - uint32_t txndelay_msk = 0; - - switch(val){ - - // todo in firmware, for now setting half speed - case FULL_SPEED://40 - printf("\nSetting Half Speed (20 MHz):\n"); - - printf("Setting Sample Reg to 0x%x\n", SAMPLE_ADC_HALF_SPEED); - bus_w(SAMPLE_REG, SAMPLE_ADC_HALF_SPEED); - - txndelay_msk = (bus_r(CONFIG_REG) & CONFIG_TDMA_TIMESLOT_MSK); // read config tdma timeslot value - printf("Setting Config Reg to 0x%x\n", CONFIG_HALF_SPEED | txndelay_msk); - bus_w(CONFIG_REG, CONFIG_HALF_SPEED | txndelay_msk); - - printf("Setting ADC Ofst Reg to 0x%x\n", ADC_OFST_HALF_SPEED_VAL); - bus_w(ADC_OFST_REG, ADC_OFST_HALF_SPEED_VAL); - - printf("Setting ADC Phase Reg to 0x%x\n", ADC_PHASE_HALF_SPEED); - adcPhase(ADC_PHASE_HALF_SPEED); - - break; - case HALF_SPEED: - printf("\nSetting Half Speed (20 MHz):\n"); - - printf("Setting Sample Reg to 0x%x\n", SAMPLE_ADC_HALF_SPEED); - bus_w(SAMPLE_REG, SAMPLE_ADC_HALF_SPEED); - - txndelay_msk = (bus_r(CONFIG_REG) & CONFIG_TDMA_TIMESLOT_MSK); // read config tdma timeslot value - printf("Setting Config Reg to 0x%x\n", CONFIG_HALF_SPEED | txndelay_msk); - bus_w(CONFIG_REG, CONFIG_HALF_SPEED | txndelay_msk); - - printf("Setting ADC Ofst Reg to 0x%x\n", ADC_OFST_HALF_SPEED_VAL); - bus_w(ADC_OFST_REG, ADC_OFST_HALF_SPEED_VAL); - - printf("Setting ADC Phase Reg to 0x%x\n", ADC_PHASE_HALF_SPEED); - adcPhase(ADC_PHASE_HALF_SPEED); - - break; - case QUARTER_SPEED: - printf("\nSetting Half Speed (10 MHz):\n"); - - printf("Setting Sample Reg to 0x%x\n", SAMPLE_ADC_QUARTER_SPEED); - bus_w(SAMPLE_REG, SAMPLE_ADC_QUARTER_SPEED); - - txndelay_msk = (bus_r(CONFIG_REG) & CONFIG_TDMA_TIMESLOT_MSK); // read config tdma timeslot value - printf("Setting Config Reg to 0x%x\n", CONFIG_QUARTER_SPEED | txndelay_msk); - bus_w(CONFIG_REG, CONFIG_QUARTER_SPEED | txndelay_msk); - - printf("Setting ADC Ofst Reg to 0x%x\n", ADC_OFST_QUARTER_SPEED_VAL); - bus_w(ADC_OFST_REG, ADC_OFST_QUARTER_SPEED_VAL); - - printf("Setting ADC Phase Reg to 0x%x\n", ADC_PHASE_QUARTER_SPEED); - adcPhase(ADC_PHASE_QUARTER_SPEED); - - break; - } - printf("\n"); - } - - //getting - u_int32_t speed = bus_r(CONFIG_REG) & CONFIG_READOUT_SPEED_MSK; - switch(speed){ - case CONFIG_FULL_SPEED_40MHZ_VAL: - return FULL_SPEED; - case CONFIG_HALF_SPEED_20MHZ_VAL: - return HALF_SPEED; - case CONFIG_QUARTER_SPEED_10MHZ_VAL: - return QUARTER_SPEED; - default: - return -1; - } -} - - - - - - -/* parameters - timer */ -int selectStoragecellStart(int pos) { - if (pos >= 0) { - bus_w(DAQ_REG, bus_r(DAQ_REG) & ~DAQ_STRG_CELL_SLCT_MSK); - bus_w(DAQ_REG, bus_r(DAQ_REG) | ((pos << DAQ_STRG_CELL_SLCT_OFST) & DAQ_STRG_CELL_SLCT_MSK)); - } - return ((bus_r(DAQ_REG) & DAQ_STRG_CELL_SLCT_MSK) >> DAQ_STRG_CELL_SLCT_OFST); -} - - - -int64_t setTimer(enum timerIndex ind, int64_t val) { - - int64_t retval = -1; - switch(ind){ - - case FRAME_NUMBER: - if(val >= 0) - printf("\nSetting #frames: %lld\n",(long long int)val); - retval = set64BitReg(val, SET_FRAMES_LSB_REG, SET_FRAMES_MSB_REG); - printf("Getting #frames: %lld\n",(long long int)retval); - break; - - case ACQUISITION_TIME: - if(val >= 0){ - printf("\nSetting exptime: %lldns\n", (long long int)val); - val *= (1E-3 * CLK_RUN); - val -= ACQ_TIME_MIN_CLOCK; - if(val < 0) val = 0; - } - retval = (set64BitReg(val, SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG) + ACQ_TIME_MIN_CLOCK) / (1E-3 * CLK_RUN); - printf("Getting exptime: %lldns\n", (long long int)retval); - break; - - case FRAME_PERIOD: - if(val >= 0){ - printf("\nSetting period to %lldns\n",(long long int)val); - val *= (1E-3 * CLK_SYNC); - } - retval = set64BitReg(val, SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG )/ (1E-3 * CLK_SYNC); - printf("Getting period: %lldns\n", (long long int)retval); - break; - - case DELAY_AFTER_TRIGGER: - if(val >= 0){ - printf("\nSetting delay to %lldns\n", (long long int)val); - val *= (1E-3 * CLK_SYNC); - } - retval = set64BitReg(val, SET_TRIGGER_DELAY_LSB_REG, SET_TRIGGER_DELAY_MSB_REG) / (1E-3 * CLK_SYNC); - printf("Getting delay: %lldns\n", (long long int)retval); - break; - - case CYCLES_NUMBER: - if(val >= 0) - printf("\nSetting #cycles to %lld\n", (long long int)val); - retval = set64BitReg(val, SET_CYCLES_LSB_REG, SET_CYCLES_MSB_REG); - printf("Getting #cycles: %lld\n", (long long int)retval); - break; - - case STORAGE_CELL_NUMBER: - if(val >= 0) { - printf("\nSetting #storage cells to %lld\n", (long long int)val); - bus_w(CONTROL_REG, (bus_r(CONTROL_REG) & ~CONTROL_STORAGE_CELL_NUM_MSK) | - ((val << CONTROL_STORAGE_CELL_NUM_OFST) & CONTROL_STORAGE_CELL_NUM_MSK)); - } - retval = ((bus_r(CONTROL_REG) & CONTROL_STORAGE_CELL_NUM_MSK) >> CONTROL_STORAGE_CELL_NUM_OFST); - printf("Getting #storage cells: %lld\n", (long long int)retval); - break; - - default: - cprintf(RED,"Warning: Timer Index not implemented for this detector: %d\n", ind); - break; - } - - return retval; - -} - - - -int64_t getTimeLeft(enum timerIndex ind){ -#ifdef VIRTUAL - return 0; -#endif - int64_t retval = -1; - switch(ind){ - - case FRAME_NUMBER: - retval = get64BitReg(GET_FRAMES_LSB_REG, GET_FRAMES_MSB_REG); - printf("Getting number of frames left: %lld\n",(long long int)retval); - break; - - case FRAME_PERIOD: - retval = get64BitReg(GET_PERIOD_LSB_REG, GET_PERIOD_MSB_REG) / (1E-3 * CLK_SYNC); - printf("Getting period left: %lldns\n", (long long int)retval); - break; -/* - case DELAY_AFTER_TRIGGER: - retval = get64BitReg(xxx) / (1E-3 * CLK_SYNC); - printf("Getting delay left: %lldns\n", (long long int)retval); - break; -*/ - case CYCLES_NUMBER: - retval = get64BitReg(GET_CYCLES_LSB_REG, GET_CYCLES_MSB_REG); - printf("Getting number of cycles left: %lld\n", (long long int)retval); - break; - - case ACTUAL_TIME: - retval = get64BitReg(TIME_FROM_START_LSB_REG, TIME_FROM_START_MSB_REG) / (1E-9 * CLK_SYNC); - printf("Getting actual time (time from start): %lld\n", (long long int)retval); - break; - - case MEASUREMENT_TIME: - retval = get64BitReg(START_FRAME_TIME_LSB_REG, START_FRAME_TIME_MSB_REG) / (1E-9 * CLK_SYNC); - printf("Getting measurement time (timestamp/ start frame time): %lld\n", (long long int)retval); - break; - - case FRAMES_FROM_START: - case FRAMES_FROM_START_PG: - retval = get64BitReg(FRAMES_FROM_START_PG_LSB_REG, FRAMES_FROM_START_PG_MSB_REG); - printf("Getting frames from start run control %lld\n", (long long int)retval); - break; - - default: - cprintf(RED, "Warning: Remaining Timer index not implemented for this detector: %d\n", ind); - break; - } - - return retval; -} - - - - - - -/* parameters - channel, chip, module, settings */ - - -int setModule(sls_detector_module myMod){ - int retval[2]; - int i; - - //#ifdef VERBOSE - printf("Setting module with settings %d\n",myMod.reg); - //#endif - - setSettings( (enum detectorSettings)myMod.reg,-1); - - //copy module locally - if (detectorModules) - copyModule(detectorModules,&myMod); - - //set dac values - for(i=0;i vmax)) { - cprintf(RED,"Voltage value (to convert to dac value) is outside bounds: %d\n", value); - return -1; - } - return (int)(((value - vmin) / (vmax - vmin)) * (nsteps - 1) + 0.5); -} - -int dacToVoltage(unsigned int digital){ - int vmin = 0; - int vmax = 2500; - int nsteps = 4096; - int v = vmin + (vmax - vmin) * digital / (nsteps - 1); - if((v < 0) || (v > nsteps - 1)) { - cprintf(RED,"Voltage value (converted from dac value) is outside bounds: %d\n", v); - return -1; - } - return v; -} - - - -void setDAC(enum DACINDEX ind, int val, int imod, int mV, int retval[]){ - int dacval = val; - - //if set and mv, convert to dac - if (val > 0 && mV) { - val = voltageToDac(val); //gives -1 on error - } - - if ( (val >= 0) || (val == -100)) { -#ifdef VIRTUAL - dacValues[ind] = dacval; -#else - u_int32_t codata; - int csdx = ind / NDAC + DAC_SERIAL_CS_OUT_OFST; // old board (16 dacs),so can be DAC_SERIAL_CS_OUT_OFST or +1 - int dacchannel = ind % NDAC; // 0-8, dac channel number (also for dacnum 9-15 in old board) - - printf("\nSetting of DAC %d : %d dac units (%d mV)\n",ind, dacval, val); - // command - if (val >= 0) { - printf(" Write to Input Register and Update\n"); - codata = LTC2620_DAC_CMD_SET; - - } else if (val == -100) { - printf(" POWER DOWN\n"); - codata = LTC2620_DAC_CMD_POWER_DOWN; - } - // address - printf(" Chip select bit:%d\n" - " Dac Channel:0x%x\n" - " Dac Value:0x%x\n", - csdx, dacchannel, val); - codata += ((dacchannel << LTC2620_DAC_ADDR_OFST) & LTC2620_DAC_ADDR_MSK) + - ((val << LTC2620_DAC_DATA_OFST) & LTC2620_DAC_DATA_MSK); - // to spi - serializeToSPI(SPI_REG, codata, (0x1 << csdx), LTC2620_DAC_NUMBITS, - DAC_SERIAL_CLK_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_OFST); - - dacValues[ind] = dacval; - - if (ind == VREF_COMP) { - bus_w (VREF_COMP_MOD_REG, (bus_r(VREF_COMP_MOD_REG) &~ (VREF_COMP_MOD_MSK)) // reset - | ((val << VREF_COMP_MOD_OFST) & VREF_COMP_MOD_MSK)); // or it with value - } -#endif - } - - printf("Getting DAC %d : ",ind); - retval[0] = dacValues[ind]; printf("%d dac units ", retval[0]); - retval[1] = dacToVoltage(retval[0]);printf("(%d mV)\n", retval[1]); -} - - -int getADC(enum ADCINDEX ind, int imod){ -#ifdef VIRTUAL - return 0; -#endif - char tempnames[2][40]={"VRs/FPGAs Temperature", "ADCs/ASICs Temperature"}; - printf("Getting Temperature for %s\n",tempnames[ind]); - u_int32_t addr = GET_TEMPERATURE_TMP112_REG; - uint32_t regvalue = bus_r(addr); - uint32_t value = regvalue & TEMPERATURE_VALUE_MSK; - double retval = value; - - // negative - if (regvalue & TEMPERATURE_POLARITY_MSK) { - // 2s complement - int ret = (~value) + 1; - // attach negative sign - ret = 0 - value; - retval = ret; - } - - // conversion - retval *= 625.0/10.0; - printf("\nReal Temperature %s: %f °C\n",tempnames[ind],retval/1000.00); - return retval; -} - - - -int setHighVoltage(int val){ -#ifdef VIRTUAL - if (val >= 0) - highvoltage = val; - return highvoltage; -#endif - u_int32_t dacvalue; - float alpha = 0.55; - // setting hv - if (val >= 0) { - // limit values - if (val < 60) { - dacvalue = 0; - val = 0; - } else if (val >= 200) { - dacvalue = 0x1; - val = 200; - } else { - dacvalue = 1. + (200.-val) / alpha; - val=200.-(dacvalue-1)*alpha; - } - printf ("\nSetting High voltage to %d (dacval %d)\n",val, dacvalue); - dacvalue &= MAX1932_HV_DATA_MSK; - serializeToSPI(SPI_REG, dacvalue, HV_SERIAL_CS_OUT_MSK, MAX1932_HV_NUMBITS, - HV_SERIAL_CLK_OUT_MSK, HV_SERIAL_DIGITAL_OUT_MSK, HV_SERIAL_DIGITAL_OUT_OFST); - highvoltage = val; - } - return highvoltage; -} - - - - - - -/* parameters - timing, extsig */ - - -enum externalCommunicationMode setTiming( enum externalCommunicationMode arg){ - - if(arg != GET_EXTERNAL_COMMUNICATION_MODE){ - switch((int)arg){ - case AUTO_TIMING: bus_w(EXT_SIGNAL_REG, bus_r(EXT_SIGNAL_REG) & ~EXT_SIGNAL_MSK); break; - case TRIGGER_EXPOSURE: bus_w(EXT_SIGNAL_REG, bus_r(EXT_SIGNAL_REG) | EXT_SIGNAL_MSK); break; - default: - cprintf(RED,"Unknown timing mode %d\n", arg); - return GET_EXTERNAL_COMMUNICATION_MODE; - } - } - if (bus_r(EXT_SIGNAL_REG) == EXT_SIGNAL_MSK) - return TRIGGER_EXPOSURE; - return AUTO_TIMING; -} - - - - - -/* configure mac */ - - -long int calcChecksum(int sourceip, int destip) { - - ip_header ip; - int count; - unsigned short *addr; - long int sum = 0; - long int checksum; - ip.ip_ver = 0x4; - ip.ip_ihl = 0x5; - ip.ip_tos = 0x0; - ip.ip_len = IP_PACKETSIZE; - ip.ip_ident = 0x0000; - ip.ip_flag = 0x2; //not nibble aligned (flag& offset - ip.ip_offset = 0x000; - ip.ip_ttl = 0x40; - ip.ip_protocol = 0x11; - ip.ip_chksum = 0x0000 ; // pseudo - ip.ip_sourceip = sourceip; - ip.ip_destip = destip; - - count = sizeof(ip); - addr =& (ip); /* warning: assignment from incompatible pointer type */ - while( count > 1 ) { - sum += *addr++; - count -= 2; - } - if (count > 0) sum += *addr; // Add left-over byte, if any - while (sum>>16) sum = (sum & 0xffff) + (sum >> 16);// Fold 32-bit sum to 16 bits - checksum = (~sum) & 0xffff; - - printf("IP checksum is 0x%lx\n",checksum); - - return checksum; -} - - - -int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport, uint32_t udpport2, int ival){ -#ifdef VIRTUAL - return 0; -#endif - cprintf(BLUE, "\n*** Configuring MAC ***\n"); - uint32_t sourceport = DEFAULT_TX_UDP_PORT; - - printf("Source IP : %d.%d.%d.%d \t\t(0x%08x)\n",(sourceip>>24)&0xff,(sourceip>>16)&0xff,(sourceip>>8)&0xff,(sourceip)&0xff, sourceip); - printf("Source MAC : %02x:%02x:%02x:%02x:%02x:%02x \t(0x%010llx)\n", - (unsigned int)((sourcemac>>40)&0xFF), - (unsigned int)((sourcemac>>32)&0xFF), - (unsigned int)((sourcemac>>24)&0xFF), - (unsigned int)((sourcemac>>16)&0xFF), - (unsigned int)((sourcemac>>8)&0xFF), - (unsigned int)((sourcemac>>0)&0xFF), - (long long unsigned int)sourcemac); - printf("Source Port : %d \t\t\t(0x%08x)\n",sourceport, sourceport); - - printf("Dest. IP : %d.%d.%d.%d \t\t(0x%08x)\n",(destip>>24)&0xff,(destip>>16)&0xff,(destip>>8)&0xff,(destip)&0xff, destip); - printf("Dest. MAC : %02x:%02x:%02x:%02x:%02x:%02x \t(0x%010llx)\n", - (unsigned int)((destmac>>40)&0xFF), - (unsigned int)((destmac>>32)&0xFF), - (unsigned int)((destmac>>24)&0xFF), - (unsigned int)((destmac>>16)&0xFF), - (unsigned int)((destmac>>8)&0xFF), - (unsigned int)((destmac>>0)&0xFF), - (long long unsigned int)destmac); - printf("Dest. Port : %d \t\t\t(0x%08x)\n",udpport, udpport); - - long int checksum=calcChecksum(sourceip, destip); - bus_w(TX_IP_REG, sourceip); - bus_w(RX_IP_REG, destip); - -/* - bus_w(TX_MAC_LSB_REG,(destmac>>32)&0xFFFFFFFF);//rx_udpmacH_AReg_c - bus_w(TX_MAC_MSB_REG,(destmac)&0xFFFFFFFF);//rx_udpmacL_AReg_c - bus_w(RX_MAC_MSB_REG,(sourcemac>>32)&0xFFFFFFFF);//detectormacH_AReg_c - bus_w(RX_MAC_LSB_REG,(sourcemac)&0xFFFFFFFF);//detectormacL_AReg_c - bus_w(UDP_PORT_REG,((sourceport&0xFFFF)<<16)+(udpport&0xFFFF));//udpports_AReg_c -*/ - uint32_t val = 0; - - val = ((sourcemac >> LSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); - bus_w(TX_MAC_LSB_REG, val); -#ifdef VERBOSE - printf("Read from TX_MAC_LSB_REG: 0x%08x\n", bus_r(TX_MAC_LSB_REG)); -#endif - - val = ((sourcemac >> MSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); - bus_w(TX_MAC_MSB_REG,val); -#ifdef VERBOSE - printf("Read from TX_MAC_MSB_REG: 0x%08x\n", bus_r(TX_MAC_MSB_REG)); -#endif - - val = ((destmac >> LSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); - bus_w(RX_MAC_LSB_REG, val); -#ifdef VERBOSE - printf("Read from RX_MAC_LSB_REG: 0x%08x\n", bus_r(RX_MAC_LSB_REG)); -#endif - - val = ((destmac >> MSB_OF_64_BIT_REG_OFST) & BIT_32_MSK); - bus_w(RX_MAC_MSB_REG, val); -#ifdef VERBOSE - printf("Read from RX_MAC_MSB_REG: 0x%08x\n", bus_r(RX_MAC_MSB_REG)); -#endif - - val = (((sourceport << UDP_PORT_TX_OFST) & UDP_PORT_TX_MSK) | - ((udpport << UDP_PORT_RX_OFST) & UDP_PORT_RX_MSK)); - bus_w(UDP_PORT_REG, val); -#ifdef VERBOSE - printf("Read from UDP_PORT_REG: 0x%08x\n", bus_r(UDP_PORT_REG)); -#endif - - bus_w(TX_IP_CHECKSUM_REG,(checksum << TX_IP_CHECKSUM_OFST) & TX_IP_CHECKSUM_MSK); -#ifdef VERBOSE - printf("Read from TX_IP_CHECKSUM_REG: 0x%08x\n", bus_r(TX_IP_CHECKSUM_REG)); -#endif - cleanFifos(); - resetCore(); - - usleep(500 * 1000); /* todo maybe without */ - return 0; -} - - -int setDetectorPosition(int pos[]) { - int ret = OK; - - bus_w(COORD_0_REG, bus_r(COORD_0_REG) | ((pos[0] << COORD_0_X_OFST) & COORD_0_X_MSK)); - if ((bus_r(COORD_0_REG) & COORD_0_X_MSK) != ((pos[0] << COORD_0_X_OFST) & COORD_0_X_MSK)) - ret = FAIL; - - bus_w(COORD_0_REG, bus_r(COORD_0_REG) | ((pos[1] << COORD_0_Y_OFST) & COORD_0_Y_MSK)); - if ((bus_r(COORD_0_REG) & COORD_0_Y_MSK) != ((pos[1] << COORD_0_Y_OFST) & COORD_0_Y_MSK)) - ret = FAIL; - - bus_w(COORD_1_REG, bus_r(COORD_1_REG) | ((pos[2] << COORD_0_Z_OFST) & COORD_0_Z_MSK)); - if ((bus_r(COORD_1_REG) & COORD_0_Z_MSK) != ((pos[2] << COORD_0_Z_OFST) & COORD_0_Z_MSK)) - ret = FAIL; - - if (ret == OK) - printf("Position set to [%d, %d, %d]\n", pos[0], pos[1], pos[2]); - return ret; -} - - - -/* jungfrau specific - pll, flashing fpga */ - - - -void resetPLL() { -#ifdef VIRTUAL - return; -#endif - // reset PLL Reconfiguration and PLL - bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) | PLL_CTRL_RECONFIG_RST_MSK | PLL_CTRL_RST_MSK); - usleep(100); - bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) & ~PLL_CTRL_RECONFIG_RST_MSK & ~PLL_CTRL_RST_MSK); -} - - -u_int32_t setPllReconfigReg(u_int32_t reg, u_int32_t val) { -#ifdef VIRTUAL - return val; -#endif - // set parameter - bus_w(PLL_PARAM_REG, val); - - // set address - bus_w(PLL_CONTROL_REG, (reg << PLL_CTRL_ADDR_OFST) & PLL_CTRL_ADDR_MSK); - usleep(10*1000); - - //write parameter - bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) | PLL_CTRL_WR_PARAMETER_MSK); - bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) & ~PLL_CTRL_WR_PARAMETER_MSK); - usleep(10*1000); - - return val; -} - - - - -void configurePll() { -#ifdef VIRTUAL - return; -#endif - u_int32_t val; - int32_t phase=0, inv=0; - // ensuring PLL is never configured with same phase - if (clkPhase[1] == 0) { - return; - } - - printf("Configuring PLL with phase in %d\n", clkPhase[1]); - if (clkPhase[1]>0) { - inv=0; - phase=clkPhase[1]; - } else { - inv=1; - phase=-1*clkPhase[1]; - } - printf(" phase out %d (0x%08x)\n", phase, phase); - - if (inv) { - val = ((phase << PLL_SHIFT_NUM_SHIFTS_OFST) & PLL_SHIFT_NUM_SHIFTS_MSK) + PLL_SHIFT_CNT_SLCT_C1_VAL + PLL_SHIFT_UP_DOWN_NEG_VAL; - printf(" phase word 0x%08x\n", val); - setPllReconfigReg(PLL_PHASE_SHIFT_REG, val); - } else { - val = ((phase << PLL_SHIFT_NUM_SHIFTS_OFST) & PLL_SHIFT_NUM_SHIFTS_MSK) + PLL_SHIFT_CNT_SLCT_C0_VAL + PLL_SHIFT_UP_DOWN_NEG_VAL; - printf(" phase word 0x%08x\n", val); - setPllReconfigReg(PLL_PHASE_SHIFT_REG, val); - - printf(" phase word 0x%08x\n", val); - val = ((phase << PLL_SHIFT_NUM_SHIFTS_OFST) & PLL_SHIFT_NUM_SHIFTS_MSK) + PLL_SHIFT_CNT_SLCT_C2_VAL; - setPllReconfigReg(PLL_PHASE_SHIFT_REG, val); - } - usleep(10000); -} - - - -int setThresholdTemperature(int val) { - - if (val >= 0) { - printf("\nThreshold Temperature: %d\n", val); - - val *= (10.0/625.0); -#ifdef VERBOSE - printf("Converted Threshold Temperature: %d\n", val); -#endif - bus_w(TEMP_CTRL_REG, (bus_r(TEMP_CTRL_REG) &~(TEMP_CTRL_PROTCT_THRSHLD_MSK) &~(TEMP_CTRL_OVR_TMP_EVNT_MSK)) - | (((val << TEMP_CTRL_PROTCT_THRSHLD_OFST) & TEMP_CTRL_PROTCT_THRSHLD_MSK))); -#ifdef VERBOSE - printf("Converted Threshold Temperature set to %d\n", ((bus_r(TEMP_CTRL_REG) & TEMP_CTRL_PROTCT_THRSHLD_MSK) >> TEMP_CTRL_PROTCT_THRSHLD_OFST)); -#endif - } - uint32_t temp = ((bus_r(TEMP_CTRL_REG) & TEMP_CTRL_PROTCT_THRSHLD_MSK) >> TEMP_CTRL_PROTCT_THRSHLD_OFST); - - // conversion - temp *= (625.0/10.0); - printf("Threshold Temperature %f °C\n",(double)temp/1000.00); - - return temp; - -} - - -int setTemperatureControl(int val) { - if (val >= 0) { - // binary value - if (val > 0 ) val = 1; - printf("\nTemperature control: %d\n", val); - bus_w(TEMP_CTRL_REG, (bus_r(TEMP_CTRL_REG) &~(TEMP_CTRL_PROTCT_ENABLE_MSK) &~(TEMP_CTRL_OVR_TMP_EVNT_MSK)) - | (((val << TEMP_CTRL_PROTCT_ENABLE_OFST) & TEMP_CTRL_PROTCT_ENABLE_MSK))); -#ifdef VERBOSE - printf("Temperature control set to %d\n", ((bus_r(TEMP_CTRL_REG) & TEMP_CTRL_PROTCT_ENABLE_MSK) >> TEMP_CTRL_PROTCT_ENABLE_OFST)); -#endif - } - return ((bus_r(TEMP_CTRL_REG) & TEMP_CTRL_PROTCT_ENABLE_MSK) >> TEMP_CTRL_PROTCT_ENABLE_OFST); -} - - -int setTemperatureEvent(int val) { -#ifdef VIRTUAL - return 0; -#endif - if (val >= 0) { - // set bit to clear it - val = 1; - printf("\nTemperature Event: %d\n", val); - bus_w(TEMP_CTRL_REG, (bus_r(TEMP_CTRL_REG) &~TEMP_CTRL_OVR_TMP_EVNT_MSK) - | (((val << TEMP_CTRL_OVR_TMP_EVNT_OFST) & TEMP_CTRL_OVR_TMP_EVNT_MSK))); -#ifdef VERBOSE - printf("Temperature Event set to %d\n", ((bus_r(TEMP_CTRL_REG) & TEMP_CTRL_OVR_TMP_EVNT_MSK) >> TEMP_CTRL_OVR_TMP_EVNT_OFST)); -#endif - } - return ((bus_r(TEMP_CTRL_REG) & TEMP_CTRL_OVR_TMP_EVNT_MSK) >> TEMP_CTRL_OVR_TMP_EVNT_OFST); -} - - - -int setNetworkParameter(enum NETWORKINDEX mode, int value) { - if (mode != TXN_FRAME) - return -1; - - if (value >= 0) { - printf("\nSetting transmission delay: %d\n", value); - bus_w(CONFIG_REG, (bus_r(CONFIG_REG) &~CONFIG_TDMA_TIMESLOT_MSK) - | (((value << CONFIG_TDMA_TIMESLOT_OFST) & CONFIG_TDMA_TIMESLOT_MSK))); - if (value == 0) - bus_w(CONFIG_REG, bus_r(CONFIG_REG) &~ CONFIG_TDMA_MSK); - else - bus_w(CONFIG_REG, bus_r(CONFIG_REG) | CONFIG_TDMA_MSK); -#ifdef VERBOSE - printf("Transmission delay set to %d\n", ((bus_r(CONFIG_REG) & CONFIG_TDMA_TIMESLOT_MSK) >> CONFIG_TDMA_TIMESLOT_OFST)); -#endif - } - - return ((bus_r(CONFIG_REG) & CONFIG_TDMA_TIMESLOT_MSK) >> CONFIG_TDMA_TIMESLOT_OFST); -} - - - - - -/* aquisition */ - -int startStateMachine(){ -#ifdef VIRTUAL - virtual_status = 1; - virtual_stop = 0; - if(pthread_create(&pthread_virtual_tid, NULL, &start_timer, NULL)) { - virtual_status = 0; - cprintf(RED,"Could not start Virtual acquisition thread\n"); - return FAIL; - } - cprintf(GREEN,"***Virtual Acquisition started\n"); - return OK; -#endif - printf("*******Starting State Machine*******\n"); - - cleanFifos(); - - //start state machine - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_START_ACQ_MSK); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_START_ACQ_MSK); - - printf("Status Register: %08x\n",bus_r(STATUS_REG)); - return OK; -} - - -#ifdef VIRTUAL -void* start_timer(void* arg) { - int wait_in_s = (setTimer(FRAME_NUMBER, -1) * - setTimer(CYCLES_NUMBER, -1) * - (setTimer(STORAGE_CELL_NUMBER, -1) + 1) * - (setTimer(FRAME_PERIOD, -1)/(1E9))); - cprintf(GREEN,"going to wait for %d s\n", wait_in_s); - while(!virtual_stop && (wait_in_s >= 0)) { - usleep(1000 * 1000); - wait_in_s--; - } - cprintf(GREEN,"Virtual Timer Done***\n"); - - virtual_status = 0; - return NULL; -} -#endif - -int stopStateMachine(){ - cprintf(BG_RED,"*******Stopping State Machine*******\n"); -#ifdef VIRTUAL - virtual_stop = 0; - return OK; -#endif - //stop state machine - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_STOP_ACQ_MSK); - usleep(100); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_STOP_ACQ_MSK); - - printf("Status Register: %08x\n",bus_r(STATUS_REG)); - return OK; -} - - - - - -enum runStatus getRunStatus(){ -#ifdef VIRTUAL - if(virtual_status == 0){ - printf("Status: IDLE\n"); - return IDLE; - }else{ - printf("Status: RUNNING...\n"); - return RUNNING; - } -#endif -#ifdef VERBOSE - printf("Getting status\n"); -#endif - - enum runStatus s; - u_int32_t retval = bus_r(STATUS_REG); - printf("Status Register: %08x\n",retval); - - //running - if(((retval & RUN_BUSY_MSK) >> RUN_BUSY_OFST)) { - if ((retval & WAITING_FOR_TRIGGER_MSK) >> WAITING_FOR_TRIGGER_OFST) { - printf("-----------------------------------WAITING-----------------------------------\n"); - s=WAITING; - } - else{ - printf("-----------------------------------RUNNING-----------------------------------\n"); - s=RUNNING; - } - } - - //not running - else { - // stopped or error - if ((retval & STOPPED_MSK) >> STOPPED_OFST) { - printf("-----------------------------------STOPPED--------------------------\n"); - s=STOPPED; - } else if ((retval & RUNMACHINE_BUSY_MSK) >> RUNMACHINE_BUSY_OFST) { - printf("-----------------------------------READ MACHINE BUSY--------------------------\n"); - s=TRANSMITTING; - } else if (!retval) { - printf("-----------------------------------IDLE--------------------------------------\n"); - s=IDLE; - } else { - printf("-----------------------------------Unknown status %08x--------------------------------------\n", retval); - s=ERROR; - } - } - - return s; -} - - - -void readFrame(int *ret, char *mess){ -#ifdef VIRTUAL - while(virtual_status) { - //cprintf(RED,"Waiting for finished flag\n"); - usleep(5000); - } - *ret = (int)FINISHED; - strcpy(mess,"acquisition successfully finished\n"); - return; -#endif - // wait for status to be done - while(runBusy()){ - usleep(500); - } - - // frames left to give status - int64_t retval = getTimeLeft(FRAME_NUMBER) + 1; - if ( retval > 0) { - *ret = (int)FAIL; - sprintf(mess,"no data and run stopped: %lld frames left\n",(long long int)retval); - cprintf(RED,"%s\n",mess); - } else { - *ret = (int)FINISHED; - sprintf(mess,"acquisition successfully finished\n"); - printf("%s",mess); - } -} - - - -u_int32_t runBusy(void) { -#ifdef VIRTUAL - return virtual_status; -#endif - u_int32_t s = ((bus_r(STATUS_REG) & RUN_BUSY_MSK) >> RUN_BUSY_OFST); -#ifdef VERBOSE - printf("Status Register: %08x\n", s); -#endif - return s; -} - - - - - - - - -/* common */ - -//jungfrau doesnt require chips and chans (save memory) -int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod){ - - int idac, iadc; - int ret=OK; - -#ifdef VERBOSE - printf("Copying module %x to module %x\n",srcMod,destMod); -#endif - - if (srcMod->module>=0) { -#ifdef VERBOSE - printf("Copying module number %d to module number %d\n",srcMod->module,destMod->module); -#endif - destMod->module=srcMod->module; - } - if (srcMod->serialnumber>=0){ - - destMod->serialnumber=srcMod->serialnumber; - } - if ((srcMod->nchip)>(destMod->nchip)) { - printf("Number of chip of source is larger than number of chips of destination\n"); - return FAIL; - } - if ((srcMod->nchan)>(destMod->nchan)) { - printf("Number of channels of source is larger than number of channels of destination\n"); - return FAIL; - } - if ((srcMod->ndac)>(destMod->ndac)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - if ((srcMod->nadc)>(destMod->nadc)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - -#ifdef VERBOSE - printf("DACs: src %d, dest %d\n",srcMod->ndac,destMod->ndac); - printf("ADCs: src %d, dest %d\n",srcMod->nadc,destMod->nadc); - printf("Chips: src %d, dest %d\n",srcMod->nchip,destMod->nchip); - printf("Chans: src %d, dest %d\n",srcMod->nchan,destMod->nchan); - -#endif - destMod->ndac=srcMod->ndac; - destMod->nadc=srcMod->nadc; - destMod->nchip=srcMod->nchip; - destMod->nchan=srcMod->nchan; - if (srcMod->reg>=0) - destMod->reg=srcMod->reg; -#ifdef VERBOSE - printf("Copying register %x (%x)\n",destMod->reg,srcMod->reg ); -#endif - if (srcMod->gain>=0) - destMod->gain=srcMod->gain; - if (srcMod->offset>=0) - destMod->offset=srcMod->offset; - - for (idac=0; idac<(srcMod->ndac); idac++) { - if (*((srcMod->dacs)+idac)>=0) - *((destMod->dacs)+idac)=*((srcMod->dacs)+idac); - } - for (iadc=0; iadc<(srcMod->nadc); iadc++) { - if (*((srcMod->adcs)+iadc)>=0) - *((destMod->adcs)+iadc)=*((srcMod->adcs)+iadc); - } - return ret; -} - - -int calculateDataBytes(){ - return DATA_BYTES; -} - -int getTotalNumberOfChannels(){return ((int)getNumberOfChannelsPerModule() * (int)getTotalNumberOfModules());} -int getTotalNumberOfChips(){return ((int)getNumberOfChipsPerModule() * (int)getTotalNumberOfModules());} -int getTotalNumberOfModules(){return NMOD;} -int getNumberOfChannelsPerModule(){return ((int)getNumberOfChannelsPerChip() * (int)getTotalNumberOfChips());} -int getNumberOfChipsPerModule(){return NCHIP;} -int getNumberOfDACsPerModule(){return NDAC;} -int getNumberOfADCsPerModule(){return NADC;} -int getNumberOfChannelsPerChip(){return NCHAN;} - - - -/* sync */ - -enum masterFlags setMaster(enum masterFlags arg){ - return NO_MASTER; -} - -enum synchronizationMode setSynchronization(enum synchronizationMode arg){ - return NO_SYNCHRONIZATION; -} - - - - - - -//#endif diff --git a/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_defs.h b/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_defs.h deleted file mode 100644 index ee74bcd40..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/slsDetectorServer_defs.h +++ /dev/null @@ -1,176 +0,0 @@ -#ifndef SLSDETECTORSERVER_DEFS_H -#define SLSDETECTORSERVER_DEFS_H - -#include "sls_detector_defs.h" //default dynamicgain in settings -#include "RegisterDefs.h" -#include - - - -#define GOODBYE (-200) -#define PROGRAMMING_MODE (-200) -#define MIN_REQRD_VRSN_T_RD_API 0x171220 -#define REQRD_FRMWR_VRSN 0x181206 // temp bug fix from last version, timing mode is backwards compatible - - -/* Struct Definitions */ -typedef struct ip_header_struct { - uint16_t ip_len; - uint8_t ip_tos; - uint8_t ip_ihl:4 ,ip_ver:4; - uint16_t ip_offset:13,ip_flag:3; - uint16_t ip_ident; - uint16_t ip_chksum; - uint8_t ip_protocol; - uint8_t ip_ttl; - uint32_t ip_sourceip; - uint32_t ip_destip; -} ip_header; - -/* Enums */ -enum CLK_SPEED_INDEX {FULL_SPEED, HALF_SPEED, QUARTER_SPEED}; -enum ADCINDEX {TEMP_FPGA, TEMP_ADC}; -enum DACINDEX {VB_COMP, VDD_PROT, VIN_COM, VREF_PRECH, VB_PIXBUF, VB_DS, VREF_DS, VREF_COMP }; -#define DEFAULT_DAC_VALS { 1220, /* VB_COMP */ \ - 3000, /* VDD_PROT */ \ - 1053, /* VIN_COM */ \ - 1450, /* VREF_PRECH */ \ - 750, /* VB_PIXBUF */ \ - 1000, /* VB_DS */ \ - 480, /* VREF_DS */ \ - 420 /* VREF_COMP */ \ - }; - -enum NETWORKINDEX { TXN_FRAME }; - - - -/* Hardware Definitions */ -#define NMAXMOD (1) -#define NMOD (1) -#define NCHAN (256 * 256) -#define NCHIP (8) -#define NADC (0) -#define NDAC (8) -#define NDAC_OLDBOARD (16) -#define DYNAMIC_RANGE (16) -#define NUM_BITS_PER_PIXEL (DYNAMIC_RANGE / 8) -#define DATA_BYTES (NCHIP * NCHAN * NUM_BITS_PER_PIXEL) -#define IP_PACKETSIZE (0x2052) -#define CLK_RUN (40) /* MHz */ -#define CLK_SYNC (20) /* MHz */ - - -/** Default Parameters */ -#define DEFAULT_NUM_FRAMES (100*1000*1000) -#define DEFAULT_NUM_CYCLES (1) -#define DEFAULT_EXPTIME (10*1000) //ns -#define DEFAULT_PERIOD (2*1000*1000) //ns -#define DEFAULT_DELAY (0) -#define DEFAULT_HIGH_VOLTAGE (0) -#define DEFAULT_TIMING_MODE (AUTO_TIMING) -#define DEFAULT_SETTINGS (DYNAMICGAIN) -#define DEFAULT_TX_UDP_PORT (0x7e9a) -#define DEFAULT_TMP_THRSHLD (65*1000) //milli degree Celsius -#define DEFAULT_NUM_STRG_CLLS (0) -#define DEFAULT_STRG_CLL_STRT (0xf) - -/* Defines in the Firmware */ -#define MAX_TIMESLOT_VAL (0x1F) -#define MAX_THRESHOLD_TEMP_VAL (127999) //millidegrees -#define MAX_STORAGE_CELL_VAL (15) //0xF -#define ACQ_TIME_MIN_CLOCK (2) - - -#define SAMPLE_ADC_HALF_SPEED (SAMPLE_DECMT_FACTOR_2_VAL + SAMPLE_DGTL_SAMPLE_0_VAL + SAMPLE_ADC_DECMT_FACTOR_0_VAL + SAMPLE_ADC_SAMPLE_0_VAL) /* 0x1000 */ -#define SAMPLE_ADC_QUARTER_SPEED (SAMPLE_DECMT_FACTOR_4_VAL + SAMPLE_DGTL_SAMPLE_8_VAL + SAMPLE_ADC_DECMT_FACTOR_1_VAL + SAMPLE_ADC_SAMPLE_0_VAL) /* 0x2810 */ -#define CONFIG_HALF_SPEED (CONFIG_TDMA_DISABLE_VAL + CONFIG_HALF_SPEED_20MHZ_VAL + CONFIG_OPRTN_MDE_1_X_10GBE_VAL) -#define CONFIG_QUARTER_SPEED (CONFIG_TDMA_DISABLE_VAL + CONFIG_QUARTER_SPEED_10MHZ_VAL + CONFIG_OPRTN_MDE_1_X_10GBE_VAL) -#define ADC_OFST_HALF_SPEED_VAL (0x1f) //(0x20) -#define ADC_OFST_QUARTER_SPEED_VAL (0x0f) //(0x0f) -#define ADC_PHASE_HALF_SPEED (0x2D) //45 -#define ADC_PHASE_QUARTER_SPEED (0x2D) //45 -#define ADC_PORT_INVERT_VAL (0x453b2a9c) - -/* Maybe not required for jungfrau */ -#define NTRIMBITS (6) -#define NCOUNTBITS (24) -#define NCHIPS_PER_ADC (2) -#define TRIM_DR (((int)pow(2,NTRIMBITS))-1) -#define COUNT_DR (((int)pow(2,NCOUNTBITS))-1) -#define ALLMOD (0xffff) -#define ALLFIFO (0xffff) - -/* MSB & LSB DEFINES */ -#define MSB_OF_64_BIT_REG_OFST (32) -#define LSB_OF_64_BIT_REG_OFST (0) -#define BIT_32_MSK (0xFFFFFFFF) - -/* LTC2620 DAC DEFINES */ -#define LTC2620_DAC_CMD_OFST (20) -#define LTC2620_DAC_CMD_MSK (0x0000000F << LTC2620_DAC_CMD_OFST) -#define LTC2620_DAC_ADDR_OFST (16) -#define LTC2620_DAC_ADDR_MSK (0x0000000F << LTC2620_DAC_ADDR_OFST) -#define LTC2620_DAC_DATA_OFST (4) -#define LTC2620_DAC_DATA_MSK (0x00000FFF << LTC2620_DAC_DATA_OFST) - -#define LTC2620_DAC_CMD_WRITE (0x00000000 << LTC2620_DAC_CMD_OFST) -#define LTC2620_DAC_CMD_SET (0x00000003 << LTC2620_DAC_CMD_OFST) -#define LTC2620_DAC_CMD_POWER_DOWN (0x00000004 << LTC2620_DAC_CMD_OFST) -#define LTC2620_DAC_NUMBITS (24) - - -/* MAX1932 HV DEFINES */ -#define MAX1932_HV_NUMBITS (8) -#define MAX1932_HV_DATA_OFST (0) -#define MAX1932_HV_DATA_MSK (0x000000FF << MAX1932_HV_DATA_OFST) - - - -/** PLL Reconfiguration Registers */ -//https://www.altera.com/documentation/mcn1424769382940.html -#define PLL_MODE_REG (0x00) -#define PLL_STATUS_REG (0x01) -#define PLL_START_REG (0x02) -#define PLL_N_COUNTER_REG (0x03) -#define PLL_M_COUNTER_REG (0x04) -#define PLL_C_COUNTER_REG (0x05) -#define PLL_PHASE_SHIFT_REG (0x06) - -#define PLL_SHIFT_NUM_SHIFTS_OFST (0) -#define PLL_SHIFT_NUM_SHIFTS_MSK (0x0000FFFF << PLL_SHIFT_NUM_SHIFTS_OFST) - -#define PLL_SHIFT_CNT_SELECT_OFST (16) -#define PLL_SHIFT_CNT_SELECT_MSK (0x0000001F << PLL_SHIFT_CNT_SELECT_OFST) -#define PLL_SHIFT_CNT_SLCT_C0_VAL ((0x0 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C1_VAL ((0x1 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C2_VAL ((0x2 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C3_VAL ((0x3 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C4_VAL ((0x4 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C5_VAL ((0x5 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C6_VAL ((0x6 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C7_VAL ((0x7 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C8_VAL ((0x8 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C9_VAL ((0x9 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C10_VAL ((0x10 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C11_VAL ((0x11 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C12_VAL ((0x12 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C13_VAL ((0x13 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C14_VAL ((0x14 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C15_VAL ((0x15 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C16_VAL ((0x16 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C17_VAL ((0x17 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) - -#define PLL_SHIFT_UP_DOWN_OFST (21) -#define PLL_SHIFT_UP_DOWN_MSK (0x00000001 << PLL_SHIFT_UP_DOWN_OFST) -#define PLL_SHIFT_UP_DOWN_NEG_VAL ((0x0 << PLL_SHIFT_UP_DOWN_OFST) & PLL_SHIFT_UP_DOWN_MSK) -#define PLL_SHIFT_UP_DOWN_POS_VAL ((0x1 << PLL_SHIFT_UP_DOWN_OFST) & PLL_SHIFT_UP_DOWN_MSK) - -#define PLL_K_COUNTER_REG (0x07) -#define PLL_BANDWIDTH_REG (0x08) -#define PLL_CHARGEPUMP_REG (0x09) -#define PLL_VCO_DIV_REG (0x1c) -#define PLL_MIF_REG (0x1f) - - -#endif /* SLSDETECTORSERVER_DEFS_H */ diff --git a/slsDetectorSoftware/jungfrauDetectorServer/sls_detector_defs.h b/slsDetectorSoftware/jungfrauDetectorServer/sls_detector_defs.h deleted file mode 120000 index c5062e03f..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/sls_detector_defs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/sls_detector_funcs.h b/slsDetectorSoftware/jungfrauDetectorServer/sls_detector_funcs.h deleted file mode 120000 index 844b67129..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/sls_detector_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/sls_receiver_defs.h b/slsDetectorSoftware/jungfrauDetectorServer/sls_receiver_defs.h deleted file mode 120000 index 1de31caf5..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/sls_receiver_defs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/sls_receiver_funcs.h b/slsDetectorSoftware/jungfrauDetectorServer/sls_receiver_funcs.h deleted file mode 120000 index c2ea4ded9..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/sls_receiver_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/updateAPIVersion.sh b/slsDetectorSoftware/jungfrauDetectorServer/updateAPIVersion.sh deleted file mode 100755 index ef65ec7e7..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/updateAPIVersion.sh +++ /dev/null @@ -1,7 +0,0 @@ -SRCFILE=gitInfoJungfrau.h -DSTFILE=versionAPI.h - -SRCPATTERN=GITDATE -DSTPATTERN=APIJUNGFRAU - -awk -v a="$SRCFILE" -v b="$DSTFILE" -v c="$SRCPATTERN" -v d="$DSTPATTERN" 'FNR==NR&&$2==c{x=$3} NR!=FNR{if($2==d){$3="0x"substr(x,5)}print > b}' $SRCFILE $DSTFILE \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/updateGitVersion.sh b/slsDetectorSoftware/jungfrauDetectorServer/updateGitVersion.sh deleted file mode 100755 index 0c25e7f1e..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/updateGitVersion.sh +++ /dev/null @@ -1,31 +0,0 @@ -SERVER=jungfrauDetectorServer -MAINDIR=slsDetectorsPackage -SPECDIR=slsDetectorSoftware/$SERVER -TMPFILE=gitInfoJungfrauTmp.h -INCLFILE=gitInfoJungfrau.h - - -#evaluate the variables -EVALFILE=../../evalVersionVariables.sh -source $EVALFILE - - -#get modified date -#RDATE1='git log --pretty=format:"%ci" -1' -RDATE1="find ../slsDetectorServer . -type f -exec stat --format '%Y :%y %n' '{}' \; | sort -nr | cut -d: -f2- | egrep -v 'gitInfo|bin|.git|updateGitVersion|.o' | head -n 1" -RDATE=`eval $RDATE1` -NEWDATE=$(sed "s/-//g" <<< $RDATE | awk '{print $1;}') -NEWDATE=${NEWDATE/#/0x} - - -#get old date from INCLFILE -OLDDATE=$(more $INCLFILE | grep '#define GITDATE' | awk '{print $3}') - - -#update INCLFILE if changes -if [ "$OLDDATE" != "$NEWDATE" ]; then - echo Path: ${MAINDIR}/${SPECDIR} $'\n'URL: ${GITREPO} $'\n'Repository Root: ${GITREPO} $'\n'Repsitory UUID: ${REPUID} $'\n'Revision: ${FOLDERREV} $'\n'Branch: ${BRANCH} $'\n'Last Changed Author: ${AUTH1}_${AUTH2} $'\n'Last Changed Rev: ${REV} $'\n'Last Changed Date: ${RDATE} > gitInfo.txt - cd ../../ - ./genVersionHeader.sh $SPECDIR/gitInfo.txt $SPECDIR/$TMPFILE $SPECDIR/$INCLFILE - cd $WD -fi \ No newline at end of file diff --git a/slsDetectorSoftware/jungfrauDetectorServer/versionAPI.h b/slsDetectorSoftware/jungfrauDetectorServer/versionAPI.h deleted file mode 120000 index d3bf8d6cf..000000000 --- a/slsDetectorSoftware/jungfrauDetectorServer/versionAPI.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/versionAPI.h \ No newline at end of file diff --git a/slsDetectorSoftware/moenchDetectorServer/.target-makefrag b/slsDetectorSoftware/moenchDetectorServer/.target-makefrag deleted file mode 100755 index ce093ecac..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/.target-makefrag +++ /dev/null @@ -1 +0,0 @@ -AXIS_BUILDTYPE ?= cris-axis-linux-gnu diff --git a/slsDetectorSoftware/moenchDetectorServer/Makefile b/slsDetectorSoftware/moenchDetectorServer/Makefile deleted file mode 100755 index 490d4761b..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/Makefile +++ /dev/null @@ -1,51 +0,0 @@ -# $Id: Makefile,v 1.1.1.1 2006/02/04 03:35:01 freza Exp $ -# first compile -# make cris-axis-linux-gnu - - -CROSS = bfin-uclinux- -CC = $(CROSS)gcc - -CFLAGS += -Wall -DMOENCHD -DMCB_FUNCS -DDACS_INT -DDEBUG #-DVERBOSE #-DVERYVERBOSE #-DVIRTUAL #-DDACS_INT_CSERVER - - -PROGS= moenchDetectorServer -INSTDIR= /tftpboot -INSTMODE= 0777 - - - -BINS = testlib_sharedlibc -SRCS = server.c server_funcs.c communication_funcs.c firmware_funcs.c mcb_funcs.c trimming_funcs.c sharedmemory.c -OBJS = $(SRCS:%.c=%.o) - - - -all: clean versioning $(PROGS) - -boot: $(OBJS) - -versioning: - @echo `tput setaf 6; ./updateGitVersion.sh; tput sgr0;` - -$(PROGS): $(OBJS) - echo $(OBJS) - $(CC) $(CFLAGS) -o $@ $^ $(LDLIBS_$@) $(LDFLAGS_$@) - - -install: $(PROGS) - $(INSTALL) -d $(INSTDIR) - $(INSTALL) -m $(INSTMODE) $(PROGS) $(INSTDIR) - - -romfs: - $(ROMFSINST) /bin/$(PROGS) - -clean: - rm -rf $(PROGS) *.o *.gdb - - - - - - diff --git a/slsDetectorSoftware/moenchDetectorServer/Makefile.virtual b/slsDetectorSoftware/moenchDetectorServer/Makefile.virtual deleted file mode 100755 index 38dd2537c..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/Makefile.virtual +++ /dev/null @@ -1,30 +0,0 @@ - -DESTDIR ?= ./ - -CC = gcc -CFLAGS += -Wall -DMOENCHD -DMCB_FUNCS -DDACS_INT -DDEBUG -DVIRTUAL - - -PROGS= $(DESTDIR)/moenchVirtualServer - - -SRCS = server.c server_funcs.c communication_funcs.c firmware_funcs.c mcb_funcs.c trimming_funcs.c sharedmemory.c -OBJS = $(SRCS:%.c=%.o) - -moenchVirtualServer = $(PROGS) - -all: clean $(PROGS) - - -$(PROGS): $(OBJS) - $(CC) $(CFLAGS) -o $@ $^ $(LDLIBS_$@) $(LDFLAGS_$@) - - -clean: - rm -rf $(PROGS) *.o *.gdb - - - - - - diff --git a/slsDetectorSoftware/moenchDetectorServer/ansi.h b/slsDetectorSoftware/moenchDetectorServer/ansi.h deleted file mode 120000 index a122db0ad..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/ansi.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/ansi.h \ No newline at end of file diff --git a/slsDetectorSoftware/moenchDetectorServer/communication_funcs.c b/slsDetectorSoftware/moenchDetectorServer/communication_funcs.c deleted file mode 120000 index 87a4f95d1..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/communication_funcs.c +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.c \ No newline at end of file diff --git a/slsDetectorSoftware/moenchDetectorServer/communication_funcs.h b/slsDetectorSoftware/moenchDetectorServer/communication_funcs.h deleted file mode 120000 index f220903b2..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/communication_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/moenchDetectorServer/firmware_funcs.c b/slsDetectorSoftware/moenchDetectorServer/firmware_funcs.c deleted file mode 100755 index 25b6e7598..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/firmware_funcs.c +++ /dev/null @@ -1,2613 +0,0 @@ - -#include "server_defs.h" -#include "firmware_funcs.h" -#include "mcb_funcs.h" -#include "registers_m.h" - -#ifdef SHAREDMEMORY -#include "sharedmemory.h" -#endif - -#include -#include -#include - -#include - -//for memory mapping -u_int64_t CSP0BASE; - -FILE *debugfp, *datafp; - -int fr; -int wait_time; -int *fifocntrl; - -//int *statusreg; commented out by dhanya -const int nModY=1; -int nModBoard; -int nModX=NMAXMOD; -int dynamicRange=16;//32; -int dataBytes=NMAXMOD*NCHIP*NCHAN*2; -int storeInRAM=0; -int ROI_flag=0; -int adcConfigured=-1; -u_int32_t *ram_values=NULL; -volatile char *now_ptr=NULL; -volatile u_int16_t *values; -int ram_size=0; - -int64_t totalTime=1; -u_int32_t progressMask=0; - -int phase_shift=0;//DEFAULT_PHASE_SHIFT; -int ipPacketSize=DEFAULT_IP_PACKETSIZE; -int udpPacketSize=DEFAULT_UDP_PACKETSIZE; - - -int ififostart, ififostop, ififostep, ififo; - -int masterMode=NO_MASTER, syncMode=NO_SYNCHRONIZATION, timingMode=AUTO_TIMING; - -enum externalSignalFlag signals[4]={EXT_SIG_OFF, EXT_SIG_OFF, EXT_SIG_OFF, EXT_SIG_OFF}; - - -#ifdef MCB_FUNCS -extern const int nChans; -extern const int nChips; -//extern const int nDacs; -//extern const int nAdcs; -#endif -#ifndef MCB_FUNCS - -const int nChans=NCHAN; -const int nChips=NCHIP; -const int nDacs=NDAC; -const int nAdcs=NADC; -#endif - - - - -/** - ENEt conf structs -*/ -typedef struct mac_header_struct{ - u_int8_t mac_dest_mac2; - u_int8_t mac_dest_mac1; - u_int8_t mac_dummy1; - u_int8_t mac_dummy2; - u_int8_t mac_dest_mac6; - u_int8_t mac_dest_mac5; - u_int8_t mac_dest_mac4; - u_int8_t mac_dest_mac3; - u_int8_t mac_src_mac4; - u_int8_t mac_src_mac3; - u_int8_t mac_src_mac2; - u_int8_t mac_src_mac1; - u_int16_t mac_ether_type; - u_int8_t mac_src_mac6; - u_int8_t mac_src_mac5; -} mac_header; - -typedef struct ip_header_struct { - u_int16_t ip_len; - u_int8_t ip_tos; - u_int8_t ip_ihl:4 ,ip_ver:4; - u_int16_t ip_offset:13,ip_flag:3; - u_int16_t ip_ident; - u_int16_t ip_chksum; - u_int8_t ip_protocol; - u_int8_t ip_ttl; - u_int32_t ip_sourceip; - u_int32_t ip_destip; -} ip_header; - -typedef struct udp_header_struct{ - u_int16_t udp_destport; - u_int16_t udp_srcport; - u_int16_t udp_chksum; - u_int16_t udp_len; -} udp_header; - -typedef struct mac_conf_struct{ - mac_header mac; - ip_header ip; - udp_header udp; - u_int32_t npack; - u_int32_t lpack; - u_int32_t npad; - u_int32_t cdone; -} mac_conf; - -typedef struct tse_conf_struct{ - u_int32_t rev; //0x0 - u_int32_t scratch; - u_int32_t command_config; - u_int32_t mac_0; //0x3 - u_int32_t mac_1; - u_int32_t frm_length; - u_int32_t pause_quant; - u_int32_t rx_section_empty; //0x7 - u_int32_t rx_section_full; - u_int32_t tx_section_empty; - u_int32_t tx_section_full; - u_int32_t rx_almost_empty; //0xB - u_int32_t rx_almost_full; - u_int32_t tx_almost_empty; - u_int32_t tx_almost_full; - u_int32_t mdio_addr0; //0xF - u_int32_t mdio_addr1; -}tse_conf; - - - -int mapCSP0(void) { - printf("Mapping memory\n"); -#ifndef VIRTUAL - int fd; - fd = open("/dev/mem", O_RDWR | O_SYNC, 0); - if (fd == -1) { - printf("\nCan't find /dev/mem!\n"); - return FAIL; - } - printf("/dev/mem opened\n"); - - CSP0BASE = (u_int32_t)mmap(0, MEM_SIZE, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, CSP0); - if (CSP0BASE == (u_int32_t)MAP_FAILED) { - printf("\nCan't map memmory area!!\n"); - return FAIL; - } - printf("CSP0 mapped\n"); - -#endif -#ifdef VIRTUAL - CSP0BASE = malloc(MEM_SIZE); - printf("memory allocated\n"); -#endif -#ifdef SHAREDMEMORY - if ( (res=inism(SMSV))<0) { - printf("error attaching shared memory! %i",res); - return FAIL; - } -#endif - printf("CSPObase is 0x%x \n",CSP0BASE); - printf("CSPOBASE=from %08x to %x\n",CSP0BASE,CSP0BASE+MEM_SIZE); - - u_int32_t address; - address = FIFO_DATA_REG_OFF; - values=(u_int16_t*)(CSP0BASE+address*2); - printf("statusreg=%08x\n",bus_r(STATUS_REG)); - printf("\n\n"); - return OK; -} - -u_int16_t bus_r16(u_int32_t offset){ - volatile u_int16_t *ptr1; - ptr1=(u_int16_t*)(CSP0BASE+offset*2); - return *ptr1; -} - -u_int16_t bus_w16(u_int32_t offset, u_int16_t data) { - volatile u_int16_t *ptr1; - ptr1=(u_int16_t*)(CSP0BASE+offset*2); - *ptr1=data; - return OK; -} - -/** ramType is DARK_IMAGE_REG or GAIN_IMAGE_REG */ -u_int16_t ram_w16(u_int32_t ramType, int adc, int adcCh, int Ch, u_int16_t data) { - unsigned int adr = (ramType | adc << 8 | adcCh << 5 | Ch ); - // printf("Writing to addr:%x\n",adr); - return bus_w16(adr,data); -} - -/** ramType is DARK_IMAGE_REG or GAIN_IMAGE_REG */ -u_int16_t ram_r16(u_int32_t ramType, int adc, int adcCh, int Ch){ - unsigned int adr = (ramType | adc << 8 | adcCh << 5 | Ch ); - // printf("Reading from addr:%x\n",adr); - return bus_r16(adr); -} - -u_int32_t bus_w(u_int32_t offset, u_int32_t data) { - volatile u_int32_t *ptr1; - - ptr1=(u_int32_t*)(CSP0BASE+offset*2); - *ptr1=data; - - return OK; -} - - -u_int32_t bus_r(u_int32_t offset) { - volatile u_int32_t *ptr1; - - ptr1=(u_int32_t*)(CSP0BASE+offset*2); - return *ptr1; -} - - -int setPhaseShiftOnce(){ - u_int32_t addr, reg; - int i; - addr=MULTI_PURPOSE_REG; - reg=bus_r(addr); -#ifdef VERBOSE - printf("Multipurpose reg:%x\n",reg); -#endif - - //Checking if it is power on(negative number) - // if(((reg&0xFFFF0000)>>16)>0){ - //bus_w(addr,0x0); //clear the reg - - if(reg==0){ - printf("\nImplementing phase shift of %d\n",phase_shift); - for (i=1;i0) { - bus_w(PLL_CNTRL_REG, 1);//reset PLL - bus_w(PLL_CNTRL_REG, 0); - phase_shift=0; - for (i=0;i1) nc=d;// nc=161/d; - else return -1; - - if (nc>255) - return -1; - - int addr, addr1, addr0; - u_int32_t pat,pat1,pat0; - - addr= PLL_PARAM_REG; - addr0= PLL_PARAM_OUT_REG; - addr1=PLL_CNTRL_REG; - pat1=0x10; - - - //write high count c0 -/* pat=(1<<12)|(7<<9)|nc; */ -/* bus_w(addr, pat); */ -/* bus_w(addr1, pat1); */ -/* bus_w(addr1, 0); */ -/* usleep (1000); */ -/* pat=bus_r(addr0); */ -/* bus_w(addr1, 0x4); */ -/* bus_w(addr1, 0); */ -/* pat=bus_r(addr0); */ -/* printf("M nominal count read %x (%d)\n",pat,(pat&0x1ff)); */ - - - - //write low count c0 - pat=(nc-1)|(4<<12)|(1<<9); - bus_w(addr, pat); - bus_w(addr1, pat1); - bus_w(addr1, 0); - pat0=bus_r(PLL_PARAM_OUT_REG); - usleep (1000); - printf("C0 low count status %x\n",pat0); - - //write high count c0 - pat=(nc)|(4<<12)|(0<<9); - bus_w(addr, pat); - bus_w(addr1, pat1); - bus_w(addr1, 0); - pat0=bus_r(PLL_PARAM_OUT_REG); - printf("C0 high count status %x\n",pat0); - usleep (1000); - - //write low count c1 - pat=(nc-1)|(5<<12)|(1<<9); - bus_w(addr, pat); - bus_w(addr1, pat1); - bus_w(addr1, 0); - pat0=bus_r(PLL_PARAM_OUT_REG); - printf("C1 high count status %x\n",pat0); - usleep (1000); - - //write high count c1 - pat=(nc)|(5<<12)|(0<<9); - bus_w(addr, pat); - bus_w(addr1, pat1); - bus_w(addr1, 0); - pat0=bus_r(PLL_PARAM_OUT_REG); - printf("C1 low count status %x\n",pat0); - usleep (1000); - - //reconfigure pll - pat1=0x8; - bus_w(addr1, pat1); - bus_w(addr1, 0); - pat0=bus_r(PLL_PARAM_OUT_REG); - printf("configure status %d\n",pat0); - sleep (1); - printf("finish status %x\n",pat0); - - - bus_w(PLL_CNTRL_REG, 1); //reset PLL - bus_w(PLL_CNTRL_REG, 0); - - return 0; -} - -u_int32_t getClockDivider() { - int addr, addr1, addr0; - u_int32_t pat,pat1; - - addr0= PLL_PARAM_REG; - addr= PLL_PARAM_OUT_REG; - addr1=PLL_CNTRL_REG; - pat1=0x4; - - - //write low count c0 - pat=(4<<12)|(1<<9); - bus_w(addr0, pat); - bus_w(addr1, pat1); - bus_w(addr1, 0); - usleep (1000); - pat=bus_r(addr); - printf("C0 low count read %x (%d)\n",pat,(pat&0xff)); - - //write high count c0 - pat=(4<<12)|(0<<9); - bus_w(addr0, pat); - bus_w(addr1, pat1); - bus_w(addr1, 0); - usleep (1000); - pat=bus_r(addr); - printf("C0 high count read %x (%d)\n",pat,(pat&0xff)); - - - //write low count c1 - pat=(5<<12)|(1<<9); - bus_w(addr0, pat); - bus_w(addr1, pat1); - bus_w(addr1, 0); - usleep (1000); - pat=bus_r(addr); - printf("C1 low count read %x (%d)\n",pat,(pat&0xff)); - - //write high count c1 - pat=(5<<12)|(0<<9); - bus_w(addr0, pat); - bus_w(addr1, pat1); - bus_w(addr1, 0); - usleep (1000); - pat=bus_r(addr); - printf("C1 high count read %x (%d)\n",pat,(pat&0xff)); - - - return (pat&0xff); - -/* //write low count c0 */ -/* pat=(0<<12)|(7<<9); */ -/* bus_w(addr0, pat); */ -/* bus_w(addr1, pat1); */ -/* bus_w(addr1, 0); */ -/* usleep (1000); */ -/* pat=bus_r(addr); */ -/* printf("N nominal count read %x (%d)\n",pat,pat&0x1ff); */ - -/* //write high count c0 */ -/* pat=(1<<12)|(7<<9); */ -/* bus_w(addr0, pat); */ -/* bus_w(addr1, pat1); */ -/* bus_w(addr1, 0); */ -/* usleep (1000); */ -/* pat=bus_r(addr); */ -/* printf("M nominal count read %x (%d)\n",pat,(pat&0x1ff)); */ - - - -/* if ((pat&0x1ff)!=0) */ -/* return 161/(pat&0x1ff); */ -/* else */ -/* return -1; */ -} - -u_int32_t setSetLength(int d) { - return 0; -} - -u_int32_t getSetLength() { - return 0; -} - -u_int32_t setOversampling(int d) { - - if (d>=0 && d<=255) - bus_w(OVERSAMPLING_REG, d); - - return bus_r(OVERSAMPLING_REG); -} - - -u_int32_t setWaitStates(int d1) { - return 0; -} - -u_int32_t getWaitStates() { - return 0; -} - - -u_int32_t setTotClockDivider(int d) { - return 0; -} - -u_int32_t getTotClockDivider() { - return 0; -} - - -u_int32_t setTotDutyCycle(int d) { - return 0; -} - -u_int32_t getTotDutyCycle() { - return 0; -} - - -u_int32_t setExtSignal(int d, enum externalSignalFlag mode) { - - //int modes[]={EXT_SIG_OFF, EXT_GATE_IN_ACTIVEHIGH, EXT_GATE_IN_ACTIVELOW,EXT_TRIG_IN_RISING,EXT_TRIG_IN_FALLING,EXT_RO_TRIG_IN_RISING, EXT_RO_TRIG_IN_FALLING,EXT_GATE_OUT_ACTIVEHIGH, EXT_GATE_OUT_ACTIVELOW, EXT_TRIG_OUT_RISING, EXT_TRIG_OUT_FALLING, EXT_RO_TRIG_OUT_RISING, EXT_RO_TRIG_OUT_FALLING}; - // int off=d*SIGNAL_OFFSET; - - u_int32_t c; - c=bus_r(EXT_SIGNAL_REG); - - if (d>=0 && d<4) { - signals[d]=mode; -#ifdef VERBOSE - printf("settings signal variable number %d to value %04x\n", d, signals[d]); -#endif - - // if output signal, set it! - - switch (mode) { - case GATE_IN_ACTIVE_HIGH: - case GATE_IN_ACTIVE_LOW: - if (timingMode==GATE_FIX_NUMBER || timingMode==GATE_WITH_START_TRIGGER) - setFPGASignal(d,mode); - else - setFPGASignal(d,SIGNAL_OFF); - break; - case TRIGGER_IN_RISING_EDGE: - case TRIGGER_IN_FALLING_EDGE: - if (timingMode==TRIGGER_EXPOSURE || timingMode==GATE_WITH_START_TRIGGER) - setFPGASignal(d,mode); - else - setFPGASignal(d,SIGNAL_OFF); - break; - case RO_TRIGGER_IN_RISING_EDGE: - case RO_TRIGGER_IN_FALLING_EDGE: - if (timingMode==TRIGGER_READOUT) - setFPGASignal(d,mode); - else - setFPGASignal(d,SIGNAL_OFF); - break; - case MASTER_SLAVE_SYNCHRONIZATION: - setSynchronization(syncMode); - break; - default: - setFPGASignal(d,mode); - break; - } - - setTiming(GET_EXTERNAL_COMMUNICATION_MODE); - } - - -// if (mode<=RO_TRIGGER_OUT_FALLING_EDGE && mode>=0) -// bus_w(EXT_SIGNAL_REG,((modes[mode])<=0) { -#ifdef VERBOSE - printf("writing signal register number %d mode %04x\n",d, modes[mode]); -#endif - bus_w(EXT_SIGNAL_REG,((modes[mode])<>off); - - if (mode=0 && d<4) { -#ifdef VERBOSE - printf("gettings signal variable number %d value %04x\n", d, signals[d]); -#endif - return signals[d]; - } else - return -1; - - -} - - -int getFPGASignal(int d) { - - int modes[]={SIGNAL_OFF, GATE_IN_ACTIVE_HIGH, GATE_IN_ACTIVE_LOW,TRIGGER_IN_RISING_EDGE, TRIGGER_IN_FALLING_EDGE,RO_TRIGGER_IN_RISING_EDGE, RO_TRIGGER_IN_FALLING_EDGE, GATE_OUT_ACTIVE_HIGH, GATE_OUT_ACTIVE_LOW, TRIGGER_OUT_RISING_EDGE, TRIGGER_OUT_FALLING_EDGE, RO_TRIGGER_OUT_RISING_EDGE,RO_TRIGGER_OUT_FALLING_EDGE}; - - int off=d*SIGNAL_OFFSET; - int mode=((bus_r(EXT_SIGNAL_REG)&(SIGNAL_MASK<>off); - - if (mode<=RO_TRIGGER_OUT_FALLING_EDGE) { - if (modes[mode]!=SIGNAL_OFF && signals[d]!=MASTER_SLAVE_SYNCHRONIZATION) - signals[d]=modes[mode]; -#ifdef VERYVERBOSE - printf("gettings signal register number %d value %04x\n", d, modes[mode]); -#endif - return modes[mode]; - } else - return -1; - -} - - - - - -/* -enum externalCommunicationMode{ - GET_EXTERNAL_COMMUNICATION_MODE, - AUTO, - TRIGGER_EXPOSURE_SERIES, - TRIGGER_EXPOSURE_BURST, - TRIGGER_READOUT, - TRIGGER_COINCIDENCE_WITH_INTERNAL_ENABLE, - GATE_FIX_NUMBER, - GATE_FIX_DURATION, - GATE_WITH_START_TRIGGER, - GATE_COINCIDENCE_WITH_INTERNAL_ENABLE -}; -*/ - - -int setTiming(int ti) { - - - int ret=GET_EXTERNAL_COMMUNICATION_MODE; - - int g=-1, t=-1, rot=-1; - - int i; - - switch (ti) { - case AUTO_TIMING: - timingMode=ti; - // disable all gates/triggers in except if used for master/slave synchronization - for (i=0; i<4; i++) { - if (getFPGASignal(i)>0 && getFPGASignal(i)=0 && t>=0 && rot<0) { - ret=GATE_WITH_START_TRIGGER; - } else if (g<0 && t>=0 && rot<0) { - ret=TRIGGER_EXPOSURE; - } else if (g>=0 && t<0 && rot<0) { - ret=GATE_FIX_NUMBER; - } else if (g<0 && t<0 && rot>0) { - ret=TRIGGER_READOUT; - } else if (g<0 && t<0 && rot<0) { - ret=AUTO_TIMING; - } - - // timingMode=ret; - - return ret; - -} - - - -int setConfigurationRegister(int d) { -#ifdef VERBOSE - printf("Setting configuration register to %x",d); -#endif - if (d>=0) { - bus_w(CONFIG_REG,d); - } -#ifdef VERBOSE - printf("configuration register is %x", bus_r(CONFIG_REG)); -#endif - return bus_r(CONFIG_REG); -} - -int setToT(int d) { - //int ret=0; - int reg; -#ifdef VERBOSE - printf("Setting ToT to %d\n",d); -#endif - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Before: ToT is %x\n", reg); -#endif - if (d>0) { - bus_w(CONFIG_REG,reg|TOT_ENABLE_BIT); - } else if (d==0) { - bus_w(CONFIG_REG,reg&(~TOT_ENABLE_BIT)); - } - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("ToT is %x\n", reg); -#endif - if (reg&TOT_ENABLE_BIT) - return 1; - else - return 0; -} - -int setContinousReadOut(int d) { - //int ret=0; - int reg; -#ifdef VERBOSE - printf("Setting Continous readout to %d\n",d); -#endif - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Before: Continous readout is %x\n", reg); -#endif - if (d>0) { - bus_w(CONFIG_REG,reg|CONT_RO_ENABLE_BIT); - } else if (d==0) { - bus_w(CONFIG_REG,reg&(~CONT_RO_ENABLE_BIT)); - } - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Continous readout is %x\n", reg); -#endif - if (reg&CONT_RO_ENABLE_BIT) - return 1; - else - return 0; -} - - -int startReceiver(int start) { - u_int32_t addr=CONFIG_REG; -#ifdef VERBOSE - if(start) - printf("Setting up detector to send to Receiver\n"); - else - printf("Setting up detector to send to CPU\n"); -#endif - int reg=bus_r(addr); - //for start recever, write 0 and for stop, write 1 - if (!start) - bus_w(CONFIG_REG,reg|CPU_OR_RECEIVER_BIT); - else - bus_w(CONFIG_REG,reg&(~CPU_OR_RECEIVER_BIT)); - - reg=bus_r(addr); -//#ifdef VERBOSE - printf("Config Reg %x\n", reg); -//#endif - int d =reg&CPU_OR_RECEIVER_BIT; - if(d!=0) d=1; - if(d!=start) - return OK; - else - return FAIL; -} - - -u_int64_t getDetectorNumber() { - char output[255],mac[255]=""; - u_int64_t res=0; - FILE* sysFile = popen("ifconfig eth0 | grep HWaddr | cut -d \" \" -f 11", "r"); - fgets(output, sizeof(output), sysFile); - pclose(sysFile); - //getting rid of ":" - char * pch; - pch = strtok (output,":"); - while (pch != NULL){ - strcat(mac,pch); - pch = strtok (NULL, ":"); - } - sscanf(mac,"%llx",&res); - return res; -} - -u_int32_t getFirmwareVersion() { - return bus_r(FPGA_VERSION_REG); -} - -u_int32_t getFirmwareSVNVersion(){ - return bus_r(FPGA_SVN_REG); -} - - -// for fpga test -u_int32_t testFpga(void) { - printf("Testing FPGA:\n"); - volatile u_int32_t val,addr,val2; - int result=OK,i; - //fixed pattern - val=bus_r(FIX_PATT_REG); - if (val==FIXED_PATT_VAL) { - printf("fixed pattern ok!! %08x\n",val); - } else { - printf("fixed pattern wrong!! %08x\n",val); - result=FAIL; - } - - //dummy register - addr = DUMMY_REG; - for(i=0;i<1000000;i++) - { - val=0x5A5A5A5A-i; - bus_w(addr, val); - val=bus_r(addr); - if (val!=0x5A5A5A5A-i) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of %x \n",i,val,0x5A5A5A5A-i); - result=FAIL; - } - val=(i+(i<<10)+(i<<20)); - bus_w(addr, val); - val2=bus_r(addr); - if (val2!=val) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! read %x instead of %x.\n",i,val2,val); - result=FAIL; - } - val=0x0F0F0F0F; - bus_w(addr, val); - val=bus_r(addr); - if (val!=0x0F0F0F0F) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of 0x0F0F0F0F \n",i,val); - result=FAIL; - } - val=0xF0F0F0F0; - bus_w(addr, val); - val=bus_r(addr); - if (val!=0xF0F0F0F0) { - printf("ATTEMPT:%d:\tFPGA dummy register wrong!! %x instead of 0xF0F0F0F0 \n\n",i,val); - result=FAIL; - } - } - if(result==OK) - { - printf("----------------------------------------------------------------------------------------------"); - printf("\nATTEMPT 1000000: FPGA DUMMY REGISTER OK!!!\n"); - printf("----------------------------------------------------------------------------------------------"); - } - printf("\n"); - return result; -} - - -// for fpga test -u_int32_t testRAM(void) { - int result=OK; - int i=0; - allocateRAM(); - // while(i<100000) { - memcpy(ram_values, values, dataBytes); - printf ("Testing RAM:\t%d: copied fifo %x to memory %x size %d\n",i++, (unsigned int)(values), (unsigned int)(ram_values), dataBytes); - // } - return result; -} - -int getNModBoard() { - return nModX; -} - -int setNMod(int n) { - return nModX; -} - - -// fifo test -int testFifos(void) { - printf("Fifo test not implemented!\n"); - bus_w16(CONTROL_REG, START_FIFOTEST_BIT); - bus_w16(CONTROL_REG, 0x0); - return OK; -} - - - -// program dacq settings - -int64_t set64BitReg(int64_t value, int aLSB, int aMSB){ - int64_t v64; - u_int32_t vLSB,vMSB; - if (value!=-1) { - vLSB=value&(0xffffffff); - bus_w(aLSB,vLSB); - v64=value>> 32; - vMSB=v64&(0xffffffff); - bus_w(aMSB,vMSB); - } - return get64BitReg(aLSB, aMSB); - -} - -int64_t get64BitReg(int aLSB, int aMSB){ - int64_t v64; - u_int32_t vLSB,vMSB; - vLSB=bus_r(aLSB); - vMSB=bus_r(aMSB); - v64=vMSB; - v64=(v64<<32) | vLSB; - - printf("reg64(%x,%x) %x %x %llx\n", aLSB, aMSB, vLSB, vMSB, v64); - - return v64; -} - -int64_t setFrames(int64_t value){ - return set64BitReg(value, SET_FRAMES_LSB_REG, SET_FRAMES_MSB_REG); -} - -int64_t getFrames(){ - printf("gf"); - return get64BitReg(GET_FRAMES_LSB_REG, GET_FRAMES_MSB_REG); -} - -int64_t setExposureTime(int64_t value){ - /* time is in ns */ - if (value!=-1) - value*=(1E-9*CLK_FREQ); - return set64BitReg(value,SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t getExposureTime(){ - return get64BitReg(GET_EXPTIME_LSB_REG, GET_EXPTIME_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t setGates(int64_t value){ - return set64BitReg(value, SET_GATES_LSB_REG, SET_GATES_MSB_REG); -} - -int64_t getGates(){ - return get64BitReg(GET_GATES_LSB_REG, GET_GATES_MSB_REG); -} - -int64_t setPeriod(int64_t value){ - /* time is in ns */ - if (value!=-1) { - value*=(1E-9*CLK_FREQ); - } - - - - return set64BitReg(value,SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t getPeriod(){ - return get64BitReg(GET_PERIOD_LSB_REG, GET_PERIOD_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t setDelay(int64_t value){ - /* time is in ns */ - if (value!=-1) { - value*=(1E-9*CLK_FREQ); - } - return set64BitReg(value,SET_DELAY_LSB_REG, SET_DELAY_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t getDelay(){ - return get64BitReg(GET_DELAY_LSB_REG, GET_DELAY_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t setTrains(int64_t value){ - return set64BitReg(value, SET_TRAINS_LSB_REG, SET_TRAINS_MSB_REG); -} - -int64_t getTrains(){ - return get64BitReg(GET_TRAINS_LSB_REG, GET_TRAINS_MSB_REG); -} - - -int64_t setProbes(int64_t value){ - return 0; -} - - -int64_t setProgress() { - - //????? eventually call after setting the registers - -return 0; - -} - - -int64_t getProgress() { - - - //should be done in firmware!!!! - - return 0; - -} - -int64_t getActualTime(){ - return get64BitReg(GET_ACTUAL_TIME_LSB_REG, GET_ACTUAL_TIME_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t getMeasurementTime(){ - int64_t v=get64BitReg(GET_MEASUREMENT_TIME_LSB_REG, GET_MEASUREMENT_TIME_MSB_REG); - int64_t mask=0x8000000000000000; - if (v & mask ) { -#ifdef VERBOSE - printf("no measurement time left\n"); -#endif - return -1E+9; - } else - return v/(1E-9*CLK_FREQ); -} - - - - -int loadImage(int index, short int ImageVals[]){ - u_int32_t address; - switch (index) { - case DARK_IMAGE : - address = DARK_IMAGE_REG; - break; - case GAIN_IMAGE : - address = GAIN_IMAGE_REG; - break; - } - volatile u_int16_t *ptr; - ptr=(u_int16_t*)(CSP0BASE+address*2); -#ifdef VERBOSE - int i; - for(i=0;i<6;i++) - printf("%d:%d\t",i,ImageVals[i]); -#endif - memcpy(ptr,ImageVals ,dataBytes); -#ifdef VERBOSE - printf("\nLoaded x%08x address with image of index %d\n",(unsigned int)(ptr),index); -#endif - return OK; -} - - - -int64_t getProbes(){ - return 0; -} - - -int setDACRegister(int idac, int val, int imod) { - u_int32_t addr, reg, mask; - int off; -#ifdef VERBOSE - if(val==-1) - printf("Getting dac register%d module %d\n",idac,imod); - else - printf("Setting dac register %d module %d to %d\n",idac,imod,val); -#endif - - switch(idac){ - case 0: - case 1: - case 2: - addr=MOD_DACS1_REG; - break; - case 3: - case 4: - case 5: - addr=MOD_DACS2_REG; - break; - case 6: - case 7: - addr=MOD_DACS3_REG; - break; - default: - printf("weird idac value %d\n",idac); - return -1; - break; - } - //saving only the msb - val=val>>2; - - off=(idac%3)*10; - mask=~((0x3ff)<=0 && val>off)&0x3ff; - //since we saved only the msb - val=val<<2; - - //val=(bus_r(addr)>>off)&0x3ff; - - -#ifdef VERBOSE - printf("Dac %d module %d register is %d\n\n",idac,imod,val); -#endif - return val; -} - - -int getTemperature(int tempSensor, int imod){ - int val; - imod=0;//ignoring more than 1 mod for now - int i,j,repeats=6; - u_int32_t tempVal=0; -#ifdef VERBOSE - char cTempSensor[2][100]={"ADCs/ASICs","VRs/FPGAs"}; - printf("Getting Temperature of module:%d for the %s for tempsensor:%d\n",imod,cTempSensor[tempSensor],tempSensor); -#endif - bus_w(TEMP_IN_REG,(T1_CLK_BIT)|(T1_CS_BIT)|(T2_CLK_BIT)|(T2_CS_BIT));//standby - bus_w(TEMP_IN_REG,((T1_CLK_BIT)&~(T1_CS_BIT))|(T2_CLK_BIT));//high clk low cs - - for(i=0;i<20;i++) { - //repeats is number of register writes for delay - for(j=0;j>1);//fpga - } - } - - bus_w(TEMP_IN_REG,(T1_CLK_BIT)|(T1_CS_BIT)|(T2_CLK_BIT)|(T2_CS_BIT));//standby - val=((int)tempVal)/4.0; - -#ifdef VERBOSE - printf("Temperature of module:%d for the %s is %.2fC\n",imod,cTempSensor[tempSensor],val); -#endif - return val; -} - - - -int initHighVoltage(int val, int imod){ -#ifdef VERBOSE - printf("Setting/Getting High Voltage of module:%d with val:%d\n",imod,val); -#endif - volatile u_int32_t addr=HV_REG; - int writeVal,writeVal2; - switch(val){ - case -1: break; - case 0: writeVal=0x0; writeVal2=0x0; break; - case 90: writeVal=0x0; writeVal2=0x1; break; - case 110:writeVal=0x2; writeVal2=0x3; break; - case 120:writeVal=0x4; writeVal2=0x5; break; - case 150:writeVal=0x6; writeVal2=0x7; break; - case 180:writeVal=0x8; writeVal2=0x9; break; - case 200:writeVal=0xA; writeVal2=0xB; break; - default :printf("Invalid voltage\n");return -2;break; - } - //to set value - if(val!=-1){ - //set value to converted value - bus_w(addr,writeVal); - bus_w(addr,writeVal2); -#ifdef VERBOSE - printf("Value sent is %d and then %d\n",writeVal,writeVal2); -#endif - } - //read value and return the converted value - val=bus_r(addr); -#ifdef VERBOSE - printf("Value read from reg is %d\n",val); -#endif - switch(val){ - case 0x0:val=0;break; - case 0x1:val=90;break; - case 0x3:val=110;break; - case 0x5:val=120;break; - case 0x7:val=150;break; - case 0x9:val=180;break; - case 0xB:val=200;break; - default:printf("Weird value read:%d\n",val);return -3;break; - } -#ifdef VERBOSE - printf("High voltage of module:%d is %d\n",imod,val); -#endif - return val; -} - - - -int initConfGain(int isettings,int val,int imod){ - int retval; - u_int32_t addr=GAIN_REG; - - if(val!=-1){ -#ifdef VERBOSE - printf("Setting Gain of module:%d with val:%d\n",imod,val); -#endif - bus_w(addr,((val<>SETTINGS_OFFSET); -#ifdef VERBOSE - printf("Settings read from reg is %d\n",retval); -#endif - if((isettings!=-1)&&(retval!=isettings)){ - printf("\n\nSettings r\n\n"); - return -1; - } - - return retval; -} - - - -int setADC(int adc){ - int reg,nchips,mask,nchans; - - if(adc==-1) ROI_flag=0; - else ROI_flag=1; - - setDAQRegister();//token timing - cleanFifo();//adc sync - -/* if(adc==-1){*/ - //set packet size - ipPacketSize= DEFAULT_IP_PACKETSIZE; - udpPacketSize=DEFAULT_UDP_PACKETSIZE; - //set channel mask - nchips = NCHIP; - nchans = NCHANS; - mask = ACTIVE_ADC_MASK; - /* - //with moench module 1 adc -- NOT IMPLEMENTED - else{ - ipPacketSize= ADC1_IP_PACKETSIZE; - udpPacketSize=ADC1_UDP_PACKETSIZE; - //set channel mask - nchips = NCHIPS_PER_ADC; - nchans = GOTTHARDNCHAN; - mask = 1<mac.mac_dest_mac1 =((macad>>(8*5))&0xFF);// 0x00; //pc7060 - mac_conf_regs->mac.mac_dest_mac2 =((macad>>(8*4))&0xFF);// 0x19; //pc7060 - mac_conf_regs->mac.mac_dest_mac3 =((macad>>(8*3))&0xFF);// 0x99; //pc7060 - mac_conf_regs->mac.mac_dest_mac4 =((macad>>(8*2))&0xFF);// 0x24; //pc7060 - mac_conf_regs->mac.mac_dest_mac5 =((macad>>(8*1))&0xFF);// 0xEB; //pc7060 - mac_conf_regs->mac.mac_dest_mac6 =((macad>>(8*0))&0xFF);// 0xEE; //pc7060 - - /* - mac_conf_regs->mac.mac_src_mac1 = 0x00; - mac_conf_regs->mac.mac_src_mac2 = 0xAA; - mac_conf_regs->mac.mac_src_mac3 = 0xBB; - mac_conf_regs->mac.mac_src_mac4 = 0xCC; - mac_conf_regs->mac.mac_src_mac5 = 0xDD; - mac_conf_regs->mac.mac_src_mac6 = 0xEE; - */ - mac_conf_regs->mac.mac_src_mac1 =((detectormacad>>(8*5))&0xFF); - mac_conf_regs->mac.mac_src_mac2 =((detectormacad>>(8*4))&0xFF); - mac_conf_regs->mac.mac_src_mac3 =((detectormacad>>(8*3))&0xFF); - mac_conf_regs->mac.mac_src_mac4 =((detectormacad>>(8*2))&0xFF); - mac_conf_regs->mac.mac_src_mac5 =((detectormacad>>(8*1))&0xFF); - mac_conf_regs->mac.mac_src_mac6 =((detectormacad>>(8*0))&0xFF); - mac_conf_regs->mac.mac_ether_type = 0x0800; //ipv4 - - - - mac_conf_regs->ip.ip_ver = 0x4; - mac_conf_regs->ip.ip_ihl = 0x5; - mac_conf_regs->ip.ip_tos = 0x0; - mac_conf_regs->ip.ip_len = ipPacketSize;//0x0522; // was 0x0526; - mac_conf_regs->ip.ip_ident = 0x0000; - mac_conf_regs->ip.ip_flag = 0x2; - mac_conf_regs->ip.ip_offset = 0x00; - mac_conf_regs->ip.ip_ttl = 0x70; - mac_conf_regs->ip.ip_protocol = 0x11; - mac_conf_regs->ip.ip_chksum = 0x0000 ; //6E42 now is automatically computed - mac_conf_regs->ip.ip_sourceip = detipad; //0x8181CA2E;129.129.202.46 - mac_conf_regs->ip.ip_destip = ipad; //CA57 - - //#ifdef VERBOSE - printf("mac_dest:%llx %x:%x:%x:%x:%x:%x\n", - macad, - mac_conf_regs->mac.mac_dest_mac1, - mac_conf_regs->mac.mac_dest_mac2, - mac_conf_regs->mac.mac_dest_mac3, - mac_conf_regs->mac.mac_dest_mac4, - mac_conf_regs->mac.mac_dest_mac5, - mac_conf_regs->mac.mac_dest_mac6); - printf("mac_src:%llx %x:%x:%x:%x:%x:%x\n", - detectormacad, - mac_conf_regs->mac.mac_src_mac1, - mac_conf_regs->mac.mac_src_mac2, - mac_conf_regs->mac.mac_src_mac3, - mac_conf_regs->mac.mac_src_mac4, - mac_conf_regs->mac.mac_src_mac5, - mac_conf_regs->mac.mac_src_mac6); - printf("ip_ttl:%x\n",mac_conf_regs->ip.ip_ttl); - printf("det_ip: %x %x\n",detipad, mac_conf_regs->ip.ip_sourceip); - printf("dest_ip: %x %x\n",ipad, mac_conf_regs->ip.ip_destip); - - //#endif - - //checksum - count=sizeof(mac_conf_regs->ip); - addr=&(mac_conf_regs->ip); - while( count > 1 ) { - sum += *addr++; - count -= 2; - } - if( count > 0 ) sum += *addr; // Add left-over byte, if any - while (sum>>16) sum = (sum & 0xffff) + (sum >> 16);// Fold 32-bit sum to 16 bits - checksum = (~sum)&0xffff; - mac_conf_regs->ip.ip_chksum = checksum; - //#ifdef VERBOSE - printf("IP header checksum is 0x%x s\n",(unsigned int)(checksum)); - //#endif - - mac_conf_regs->udp.udp_srcport = 0xE185; - mac_conf_regs->udp.udp_destport = udpport;//0xC351; - mac_conf_regs->udp.udp_len = udpPacketSize;//0x050E; //was 0x0512; - mac_conf_regs->udp.udp_chksum = 0x0000; - -#ifdef VERBOSE - printf("Configuring TSE\n"); -#endif - tse_conf_regs->rev = 0xA00; - tse_conf_regs->scratch = 0xCCCCCCCC; - tse_conf_regs->command_config = 0xB; - tse_conf_regs->mac_0 = 0x17231C00; - tse_conf_regs->mac_1 = 0xCB4A; - tse_conf_regs->frm_length = 0x5DC; //max frame length (1500 bytes) (was 0x41C) - tse_conf_regs->pause_quant = 0x0; - tse_conf_regs->rx_section_empty = 0x7F0; - tse_conf_regs->rx_section_full = 0x10; - tse_conf_regs->tx_section_empty = 0x3F8; //was 0x7F0; - tse_conf_regs->tx_section_full = 0x16; - tse_conf_regs->rx_almost_empty = 0x8; - tse_conf_regs->rx_almost_full = 0x8; - tse_conf_regs->tx_almost_empty = 0x8; - tse_conf_regs->tx_almost_full = 0x3; - tse_conf_regs->mdio_addr0 = 0x12; - tse_conf_regs->mdio_addr1 = 0x0; - - mac_conf_regs->cdone = 0xFFFFFFFF; - - - if(ival) - bus_w(addrr,(INT_RSTN_BIT|ENET_RESETN_BIT|WRITE_BACK_BIT|DIGITAL_TEST_BIT)); //0x2840,write shadow regs.. - else - bus_w(addrr,(INT_RSTN_BIT|ENET_RESETN_BIT|WRITE_BACK_BIT)); //0x2840,write shadow regs.. - - val=bus_r(addrr); -#ifdef VERBOSE - printf("Value read from Multi-purpose Reg:%x\n",val); -#endif - // if(val!=0x2840) return -1; - - usleep(100000); - - if(ival) - bus_w(addrr,(INT_RSTN_BIT|ENET_RESETN_BIT|SW1_BIT|DIGITAL_TEST_BIT)); //0x2820,write shadow regs.. - else - bus_w(addrr,(INT_RSTN_BIT|ENET_RESETN_BIT|SW1_BIT)); //0x2820,write shadow regs.. - - val=bus_r(addrr); -#ifdef VERBOSE - printf("Value read from Multi-purpose Reg:%x\n",val); -#endif - // if(val!=0x2820) return -1; - - - - - return adcConfigured; -} - - -int getAdcConfigured(){ - return adcConfigured; -} - -u_int32_t runBusy(void) { - u_int32_t s = bus_r(STATUS_REG) & 1; -#ifdef VERBOSE - printf("status %04x\n",s); -#endif - return s; -} - -u_int32_t dataPresent(void) { - return bus_r(LOOK_AT_ME_REG); -} - -u_int32_t runState(void) { - int s=bus_r(STATUS_REG); -#ifdef SHAREDMEMORY - if (s&RUN_BUSY_BIT) - write_status_sm("Running"); - else - write_status_sm("Stopped"); -#endif -#ifdef VERBOSE - printf("status %04x\n",s); -#endif - -/* if (s==0x62001) - exit(-1);*/ - return s; -} - - -// State Machine - -int startStateMachine(){ -int i; -//#ifdef VERBOSE - printf("*******Starting State Machine*******\n"); -//#endif - cleanFifo(); - // fifoReset(); - now_ptr=(char*)ram_values; -#ifdef SHAREDMEMORY - write_stop_sm(0); - write_status_sm("Started"); -#endif - - - for(i=0;i<100;i++){ - //start state machine - bus_w16(CONTROL_REG, START_ACQ_BIT | START_EXPOSURE_BIT); - bus_w16(CONTROL_REG, 0x0); - //verify - if(bus_r(STATUS_REG) & RUN_BUSY_BIT) - break; - else - usleep(5000); - } - if(i!=0) - printf("tried to start state machine %d times\n",i); - if(i==100){ - printf("\n***********COULD NOT START STATE MACHINE***************\n"); - return FAIL; - } - - printf("statusreg=%08x\n",bus_r(STATUS_REG)); - return OK; -} - - - - -int stopStateMachine(){ - int i; -//#ifdef VERBOSE - printf("*******Stopping State Machine*******\n"); -//#endif -#ifdef SHAREDMEMORY - write_stop_sm(1); - write_status_sm("Stopped"); -#endif - for(i=0;i<100;i++){ - //stop state machine - bus_w16(CONTROL_REG, STOP_ACQ_BIT); - bus_w16(CONTROL_REG, 0x0); - usleep(5000); - //verify - if(!(bus_r(STATUS_REG)&RUNMACHINE_BUSY_BIT)) - break; - } - if(i!=0) - printf("tried to stop state machine %d times\n",i); - if(i==100){ - printf("\n***********COULD NOT STOP STATE MACHINE***************\n"); - return FAIL; - } - -/* - usleep(5000); - // if (!runBusy()) - if(!(bus_r(STATUS_REG)&RUNMACHINE_BUSY_BIT)) - return OK; - else - return FAIL; - */ - printf("statusreg=%08x\n",bus_r(STATUS_REG)); - return OK; -} - - -int startReadOut(){ - u_int32_t status; -#ifdef VERBOSE - printf("Starting State Machine Readout\n"); -#endif - status=bus_r(STATUS_REG)&RUN_BUSY_BIT; -#ifdef DEBUG - printf("State machine status is %08x\n",bus_r(STATUS_REG)); -#endif - bus_w16(CONTROL_REG, START_ACQ_BIT |START_READOUT_BIT); // start readout - bus_w16(CONTROL_REG, 0x0); - return OK; -} - - -// fifo routines - -u_int32_t fifoReset(void) { - return -1; -} - - -u_int32_t setNBits(u_int32_t n) { - return -1; -} - -u_int32_t getNBits(){ - return -1; -} - - -u_int32_t fifoReadCounter(int fifonum){ - return -1; -} - -u_int32_t fifoReadStatus() -{ - // reads from the global status register - - return bus_r(STATUS_REG)&(SOME_FIFO_FULL_BIT | ALL_FIFO_EMPTY_BIT); -} - -u_int32_t fifo_full(void) -{ - // checks fifo empty flag returns 1 if fifo is empty - // otherwise 0 - return bus_r(STATUS_REG)&SOME_FIFO_FULL_BIT; -} - - -u_int32_t* fifo_read_event() -{ - - int i=0; - -#ifdef VIRTUAL - return NULL; -#endif - -#ifdef VERBOSE - printf("before looping\n"); -#endif - volatile u_int32_t t = bus_r(LOOK_AT_ME_REG); - -#ifdef VERBOSE - printf("lookatmereg=x%x\n",t); -#endif -/* - while ((t&0x1)==0) - { - t = bus_r(LOOK_AT_ME_REG); - if (!runBusy()){ - return NULL; - } - } -*/ - - while((t&0x1)==0) { -#ifdef VERYVERBOSE - printf("before readout %08x %08x\n", runState(), bus_r(LOOK_AT_ME_REG)); -#endif -#ifdef VERYVERBOSE - printf("look at me reg:%08x\n",bus_r(LOOK_AT_ME_REG)); -#endif - if (runBusy()==0) { - t = bus_r(LOOK_AT_ME_REG); -#ifdef VERYVERBOSE - printf("status should be idle!..look at me reg:%08x\n",bus_r(LOOK_AT_ME_REG)); -#endif - if ((t&0x1)==0) { -#ifdef VERBOSE - printf("no frame found - exiting\n"); - printf("%08x %08x\n", runState(), bus_r(LOOK_AT_ME_REG)); -#endif -#ifdef VERYVERBOSE - printf("returning null\n"); -#endif - printf("lookatmereg=x%x\n",t); - return NULL; - } else { -#ifdef VERBOSE - printf("no frame found %x status %x\n", bus_r(LOOK_AT_ME_REG),runState()); -#endif - break; - } - } - t = bus_r(LOOK_AT_ME_REG); -#ifdef VERYVERBOSE - printf("before starting while loop again: look at me reg:%08x\n\n",bus_r(LOOK_AT_ME_REG)); -#endif - if (i%1000==0) - printf("%08x %08x\n", runState(), bus_r(LOOK_AT_ME_REG)); - i++; - } -#ifdef VERYVERBOSE - printf(" out of while loop!\n"); -#endif -#ifdef VERYVERBOSE - printf("before readout %08x %08x\n", runState(), bus_r(LOOK_AT_ME_REG)); -#endif - - dma_memcpy(now_ptr,values ,dataBytes); - - -#ifdef VERYVERBOSE - int a; - for (a=0;a<8; a=a+2) - printf("\n%d %d: x%04x x%04x ",a+1,a,*(now_ptr+a+1),*(now_ptr+a) ); - for (a=2554;a<2560; a=a+2) - printf("\n%d %d: x%04x x%04x ",a+1,a,*(now_ptr+a+1),*(now_ptr+a) ); - printf("********\n"); - //memcpy(now_ptr, values, dataBytes); -#endif -#ifdef VERYVERBOSE - printf("Copying to ptr %08x %d\n",(unsigned int)(now_ptr), dataBytes); - printf("after readout %08x %08x\n", runState(), bus_r(LOOK_AT_ME_REG)); -#endif - - if (storeInRAM>0) { - now_ptr+=dataBytes; - } - printf("lookatmereg=x%x\n",t); - return ram_values; -} - - - -u_int32_t* decode_data(int *datain) -{ - u_int32_t *dataout; - // const char one=1; - const int bytesize=8; - char *ptr=(char*)datain; - //int nbits=dynamicRange; - int ipos=0, ichan=0;; - //int nch, boff=0; - int ibyte;//, ibit; - char iptr; - -#ifdef VERBOSE - printf("Decoding data for DR %d\n",dynamicRange); -#endif - dataout=malloc(nChans*nChips*nModX*4); - ichan=0; - switch (dynamicRange) { - case 1: - for (ibyte=0; ibyte>(ipos))&0x1; - ichan++; - } - } - break; - case 4: - for (ibyte=0; ibyte>(ipos*4))&0xf; - ichan++; - } - } - break; - case 8: - for (ichan=0; ichan0) - storeInRAM=1; - else - storeInRAM=0; - return allocateRAM(); -} - - -int allocateRAM() { - size_t size; - u_int32_t nt, nf; - nt=setTrains(-1); - nf=setFrames(-1); - if (nt==0) nt=1; - if (nf==0) nf=1; - // ret=clearRAM(); - if (storeInRAM) { - size=dataBytes*nf*nt; - if (size>(23-i))&0x1)<> 8); - // printf("%i: %i %i\n",a, frame[a],v); - avg[a] += ((double)frame[a])/(double)frames; - //if(frame[a] == 8191) - // printf("ch %i: %u\n",a,frame[a]); - } - // printf("********\n"); - numberFrames++; - } - - //no more data or no data - else { - if(getFrames()>-2) { - dataret=FAIL; - printf("no data and run stopped: %d frames left\n",(int)(getFrames()+2)); - - } else { - dataret=FINISHED; - printf("acquisition successfully finished\n"); - - } - printf("dataret %d\n",dataret); - } - } - - - - double nf = (double)numberFrames; - for(i =0; i < 1280; i++){ - adc = i / 256; - adcCh = (i - adc * 256) / 32; - Ch = i - adc * 256 - adcCh * 32; - adc--; - double v2 = avg[i]; - avg[i] = avg[i]/ ((double)numberFrames/(double)frames); - unsigned short v = (unsigned short)avg[i]; - printf("setting avg for channel %i(%i,%i,%i): %i (double= %f (%f))\t", i,adc,adcCh,Ch, v,avg[i],v2); - v=i*100; - ram_w16(DARK_IMAGE_REG,adc,adcCh,Ch,v-4096); - if(ram_r16(DARK_IMAGE_REG,adc,adcCh,Ch) != v-4096){ - printf("value is wrong (%i,%i,%i): %i \n",adc,adcCh,Ch, ram_r16(DARK_IMAGE_REG,adc,adcCh,Ch)); - } - } - - /*for(adc = 1; adc < 5; adc++){ - for(adcCh = 0; adcCh < 8; adcCh++){ - for(Ch=0 ; Ch < 32; Ch++){ - int channel = (adc+1) * 32 * 8 + adcCh * 32 + Ch; - double v2 = avg[channel]; - avg[channel] = avg[channel]/ ((double)numberFrames/(double)frames); - unsigned short v = (unsigned short)avg[channel]; - printf("setting avg for channel %i: %i (double= %f (%f))\t", channel, v,avg[channel],v2); - ram_w16(DARK_IMAGE_REG,adc,adcCh,Ch,v-4096); - if(ram_r16(DARK_IMAGE_REG,adc,adcCh,Ch) != v-4096){ - printf("value is wrong (%i,%i,%i): %i \n",adc,adcCh,Ch, ram_r16(DARK_IMAGE_REG,adc,adcCh,Ch)); - } - } - } - }*/ - - - - printf("frames: %i\n",numberFrames); - printf("corrected avg by: %f\n",(double)numberFrames/(double)frames); - - printf("restoring previous condition\n"); - setFrames(framesBefore); - setPeriod(periodBefore); - - printf("---------------------------\n"); - return 0; -} - diff --git a/slsDetectorSoftware/moenchDetectorServer/firmware_funcs.h b/slsDetectorSoftware/moenchDetectorServer/firmware_funcs.h deleted file mode 100755 index 48918e428..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/firmware_funcs.h +++ /dev/null @@ -1,179 +0,0 @@ -#ifndef FIRMWARE_FUNCS_H -#define FIRMWARE_FUNCS_H - - -#include "sls_detector_defs.h" - - -#include -#include -#include -#include -#include -#include -#include -//#include -#include -#include -#include -#include -#include -#include - - -int mapCSP0(void); - -u_int16_t bus_r16(u_int32_t offset); -u_int16_t bus_w16(u_int32_t offset, u_int16_t data);//aldos function -u_int32_t bus_w(u_int32_t offset, u_int32_t data); -u_int32_t bus_r(u_int32_t offset); - -int setPhaseShiftOnce(); -int phaseStep(int st); -int cleanFifo(); -int setDAQRegister(); - -u_int32_t putout(char *s, int modnum); -u_int32_t readin(int modnum); -u_int32_t setClockDivider(int d); -u_int32_t getClockDivider(); -u_int32_t setSetLength(int d); -u_int32_t getSetLength(); -u_int32_t setWaitStates(int d); -u_int32_t getWaitStates(); -u_int32_t setTotClockDivider(int d); -u_int32_t getTotClockDivider(); -u_int32_t setTotDutyCycle(int d); -u_int32_t getTotDutyCycle(); -u_int32_t setOversampling(int d); - -u_int32_t setExtSignal(int d, enum externalSignalFlag mode); -int getExtSignal(int d); - -u_int32_t setFPGASignal(int d, enum externalSignalFlag mode); -int getFPGASignal(int d); - -int setTiming(int t); - - -int setConfigurationRegister(int d); -int setToT(int d); -int setContinousReadOut(int d); -int startReceiver(int d); - -int setDACRegister(int idac, int val, int imod); - -int getTemperature(int tempSensor,int imod); -int initHighVoltage(int val,int imod); -int initConfGain(int isettings,int val,int imod); - -int setADC(int adc); -int configureMAC(int ipad, long long int macad, long long int detectormacadd, int detipad, int ival, int udpport); -int getAdcConfigured(); - - -u_int64_t getDetectorNumber(); -u_int32_t getFirmwareVersion(); -int testFifos(void); -u_int32_t testFpga(void); -u_int32_t testRAM(void); -int testBus(void); -int setDigitalTestBit(int ival); - -int64_t set64BitReg(int64_t value, int aLSB, int aMSB); -int64_t get64BitReg(int aLSB, int aMSB); - -int64_t setFrames(int64_t value); -int64_t getFrames(); - -int64_t setExposureTime(int64_t value); -int64_t getExposureTime(); - -int64_t setGates(int64_t value); -int64_t getGates(); - -int64_t setDelay(int64_t value); -int64_t getDelay(); - -int64_t setPeriod(int64_t value); -int64_t getPeriod(); - -int64_t setTrains(int64_t value); -int64_t getTrains(); - -int64_t setProbes(int64_t value); -int64_t getProbes(); - -int64_t getProgress(); -int64_t setProgress(); - -int64_t getActualTime(); -int64_t getMeasurementTime(); - - -u_int32_t runBusy(void); -u_int32_t runState(void); -u_int32_t dataPresent(void); - - -int startStateMachine(); -int stopStateMachine(); -int startReadOut(); -u_int32_t fifoReset(void); -u_int32_t fifoReadCounter(int fifonum); -u_int32_t fifoReadStatus(); - - -u_int32_t fifo_full(void); - - - -u_int32_t* fifo_read_event(); -u_int32_t* decode_data(int* datain); -//u_int32_t move_data(u_int64_t* datain, u_int64_t* dataout); -int setDynamicRange(int dr); -int getDynamicRange(); -int getNModBoard(); -int setNMod(int n); -int setStoreInRAM(int b); -int allocateRAM(); -int clearRAM(); - - -int setMaster(int f); -int setSynchronization(int s); - -int loadImage(int index, short int ImageVals[]); -int readCounterBlock(int startACQ, short int CounterVals[]); -int resetCounterBlock(int startACQ); - -int calibratePedestal(int frames); - - - -/* - -u_int32_t setNBits(u_int32_t); -u_int32_t getNBits(); -*/ - -/* -//move to mcb_funcs? - -int readOutChan(int *val); -u_int32_t getModuleNumber(int modnum); -int testShiftIn(int imod); -int testShiftOut(int imod); -int testShiftStSel(int imod); -int testDataInOut(int num, int imod); -int testExtPulse(int imod); -int testExtPulseMux(int imod, int ow); -int testDataInOutMux(int imod, int ow, int num); -int testOutMux(int imod); -int testFpgaMux(int imod); -int calibration_sensor(int num, int *values, int *dacs) ; -int calibration_chip(int num, int *values, int *dacs); -*/ - - -#endif diff --git a/slsDetectorSoftware/moenchDetectorServer/gitInfo.txt b/slsDetectorSoftware/moenchDetectorServer/gitInfo.txt deleted file mode 100644 index 4ff46c75b..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/gitInfo.txt +++ /dev/null @@ -1,9 +0,0 @@ -Path: slsDetectorsPackage/slsDetectorSoftware/moenchDetectorServer -URL: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repository Root: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repsitory UUID: e6bd874a88493557fc5127d4a1686832299aaf06 -Revision: 85 -Branch: 3.0.1 -Last Changed Author: Dhanya_Thattil -Last Changed Rev: 3346 -Last Changed Date: 2018-02-07 09:14:36.000000002 +0100 ./server_funcs.c diff --git a/slsDetectorSoftware/moenchDetectorServer/gitInfoMoench.h b/slsDetectorSoftware/moenchDetectorServer/gitInfoMoench.h deleted file mode 100644 index 96f110d39..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/gitInfoMoench.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "git@github.com:slsdetectorgroup/slsDetectorPackage.git" -#define GITREPUUID "e6bd874a88493557fc5127d4a1686832299aaf06" -#define GITAUTH "Dhanya_Thattil" -#define GITREV 0x3346 -#define GITDATE 0x20180207 -#define GITBRANCH "3.0.1" diff --git a/slsDetectorSoftware/moenchDetectorServer/gitInfoMoenchTmp.h b/slsDetectorSoftware/moenchDetectorServer/gitInfoMoenchTmp.h deleted file mode 100644 index dfd9bb246..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/gitInfoMoenchTmp.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "" -#define GITREPUUID "" -#define GITAUTH "" -#define GITREV "" -#define GITDATE "" -#define GITBRANCH "" diff --git a/slsDetectorSoftware/moenchDetectorServer/mcb_funcs.c b/slsDetectorSoftware/moenchDetectorServer/mcb_funcs.c deleted file mode 100755 index 1db487a31..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/mcb_funcs.c +++ /dev/null @@ -1,2528 +0,0 @@ -#ifdef MCB_FUNCS - -#include -#include -#include -#include -#include -#include "registers_m.h" - -#ifndef PICASSOD -#include "server_defs.h" -#else -#include "picasso_defs.h" -#endif -#include "firmware_funcs.h" -#include "mcb_funcs.h" - - -/* global variables */ -#undef DEBUG -#undef DEBUGOUT - -extern int nModX; -//extern int dataBytes; -extern int dynamicRange; -const int nChans=NCHAN; -const int nChips=NCHIP; -const int nDacs=NDAC; -const int nAdcs=NADC; -enum detectorSettings thisSettings; - -int sChan, sChip, sMod, sDac, sAdc; -const int allSelected=-2; -const int noneSelected=-1; - - -sls_detector_module *detectorModules=NULL; -int *detectorChips=NULL; -int *detectorChans=NULL; -int *detectorDacs=NULL; -int *detectorAdcs=NULL; -//int numberOfProbes; - -ROI rois[MAX_ROIS]; -int nROI=0; - - -int initDetector() { - - int imod; - // sls_detector_module *myModule; - int n=getNModBoard(); - nModX=n; - -#ifdef VERBOSE - printf("Board is for %d modules\n",n); -#endif - detectorModules=malloc(n*sizeof(sls_detector_module)); - detectorChips=malloc(n*NCHIP*sizeof(int)); - detectorChans=malloc(n*NCHIP*NCHAN*sizeof(int)); - detectorDacs=malloc(n*NDAC*sizeof(int)); - detectorAdcs=malloc(n*NADC*sizeof(int)); -#ifdef VERBOSE - printf("modules from 0x%x to 0x%x\n",(unsigned int)(detectorModules), (unsigned int)(detectorModules+n)); - printf("chips from 0x%x to 0x%x\n",(unsigned int)(detectorChips), (unsigned int)(detectorChips+n*NCHIP)); - printf("chans from 0x%x to 0x%x\n",(unsigned int)(detectorChans), (unsigned int)(detectorChans+n*NCHIP*NCHAN)); - printf("dacs from 0x%x to 0x%x\n",(unsigned int)(detectorDacs), (unsigned int)(detectorDacs+n*NDAC)); - printf("adcs from 0x%x to 0x%x\n",(unsigned int)(detectorAdcs), (unsigned int)(detectorAdcs+n*NADC)); -#endif - for (imod=0; imoddacs=detectorDacs+imod*NDAC; - (detectorModules+imod)->adcs=detectorAdcs+imod*NADC; - (detectorModules+imod)->chipregs=detectorChips+imod*NCHIP; - (detectorModules+imod)->chanregs=detectorChans+imod*NCHIP*NCHAN; - (detectorModules+imod)->ndac=NDAC; - (detectorModules+imod)->nadc=NADC; - (detectorModules+imod)->nchip=NCHIP; - (detectorModules+imod)->nchan=NCHIP*NCHAN; - (detectorModules+imod)->module=imod; - (detectorModules+imod)->gain=0; - (detectorModules+imod)->offset=0; - (detectorModules+imod)->reg=0; - /* initialize registers, dacs, retrieve sn, adc values etc */ - } - thisSettings=UNINITIALIZED; - sChan=noneSelected; - sChip=noneSelected; - sMod=noneSelected; - sDac=noneSelected; - sAdc=noneSelected; - - /* - setCSregister(ALLMOD); //commented out by dhanya - setSSregister(ALLMOD); - counterClear(ALLMOD); - clearSSregister(ALLMOD); - putout("0000000000000000",ALLMOD); - */ - - /* initialize dynamic range etc. */ - /* dynamicRange=getDynamicRange(); //always 16 not required commented out - nModX=setNMod(-1);*/ - - //dataBytes=nModX*NCHIP*NCHAN*4; - // dynamicRange=32; - // initChip(0, 0,ALLMOD); - //nModX=n; - // - allocateRAM(); - - - return OK; -} - - - - -int copyChannel(sls_detector_channel *destChan, sls_detector_channel *srcChan) { - destChan->chan=srcChan->chan; - destChan->chip=srcChan->chip; - destChan->module=srcChan->module; - destChan->reg=srcChan->reg; - return OK; -} - - -int copyChip(sls_detector_chip *destChip, sls_detector_chip *srcChip) { - - int ichan; - int ret=OK; - if ((srcChip->nchan)>(destChip->nchan)) { - printf("Number of channels of source is larger than number of channels of destination\n"); - return FAIL; - } - - destChip->nchan=srcChip->nchan; - destChip->reg=srcChip->reg; - destChip->chip=srcChip->chip; - destChip->module=srcChip->module; - for (ichan=0; ichan<(srcChip->nchan); ichan++) { - *((destChip->chanregs)+ichan)=*((srcChip->chanregs)+ichan); - } - return ret; -} - - -int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) { - - int ichip, idac, ichan, iadc; - - int ret=OK; - -#ifdef VERBOSE - printf("Copying module %x to module %x\n",(unsigned int)(srcMod),(unsigned int)(destMod)); -#endif - - if (srcMod->module>=0) { -#ifdef VERBOSE - printf("Copying module number %d to module number %d\n",srcMod->module,destMod->module); -#endif - destMod->module=srcMod->module; - } - if (srcMod->serialnumber>=0){ -/* #ifdef VERBOSE */ -/* printf("Copying module serial number %x to module serial number %x\n",srcMod->serialnumber,destMod->serialnumber); */ -/* #endif */ - destMod->serialnumber=srcMod->serialnumber; - } - if ((srcMod->nchip)>(destMod->nchip)) { - printf("Number of chip of source is larger than number of chips of destination\n"); - return FAIL; - } - if ((srcMod->nchan)>(destMod->nchan)) { - printf("Number of channels of source is larger than number of channels of destination\n"); - return FAIL; - } - if ((srcMod->ndac)>(destMod->ndac)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - if ((srcMod->nadc)>(destMod->nadc)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - -#ifdef VERBOSE - printf("DACs: src %d, dest %d\n",srcMod->ndac,destMod->ndac); - printf("ADCs: src %d, dest %d\n",srcMod->nadc,destMod->nadc); - printf("Chips: src %d, dest %d\n",srcMod->nchip,destMod->nchip); - printf("Chans: src %d, dest %d\n",srcMod->nchan,destMod->nchan); - -#endif - - - - destMod->ndac=srcMod->ndac; - destMod->nadc=srcMod->nadc; - destMod->nchip=srcMod->nchip; - destMod->nchan=srcMod->nchan; - if (srcMod->reg>=0) - destMod->reg=srcMod->reg; -#ifdef VERBOSE - printf("Copying register %x (%x)\n",destMod->reg,srcMod->reg ); -#endif - if (srcMod->gain>=0) - destMod->gain=srcMod->gain; - if (srcMod->offset>=0) - destMod->offset=srcMod->offset; - - // printf("copying gain and offset %f %f to %f %f\n",srcMod->gain,srcMod->offset,destMod->gain,destMod->offset); - - for (ichip=0; ichip<(srcMod->nchip); ichip++) { - if (*((srcMod->chipregs)+ichip)>=0) - *((destMod->chipregs)+ichip)=*((srcMod->chipregs)+ichip); - } - for (ichan=0; ichan<(srcMod->nchan); ichan++) { - if (*((srcMod->chanregs)+ichan)>=0) - *((destMod->chanregs)+ichan)=*((srcMod->chanregs)+ichan); - } - for (idac=0; idac<(srcMod->ndac); idac++) { - if (*((srcMod->dacs)+idac)>=0) - *((destMod->dacs)+idac)=*((srcMod->dacs)+idac); - } - for (iadc=0; iadc<(srcMod->nadc); iadc++) { - if (*((srcMod->adcs)+iadc)>=0) - *((destMod->adcs)+iadc)=*((srcMod->adcs)+iadc); - } - return ret; -} - - - -/* Register commands */ - - -int clearDACSregister(int imod) { - - putout("1111111111111111",imod);//reset - putout("1111111111111110",imod);//cs down - - /* commented out by dhanya - putout("0000000001000000",imod); - putout("0000000101000000",imod); - putout("0000000101000000",imod); - putout("0000000001000000",imod); - */ -#ifdef DEBUG - fprintf(stdout, "Clearing DAC shiftregister\n"); -#endif - // sDac=0; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return OK; -} - -int nextDAC(int imod) { - - putout("1111111111111011",imod);//cs up - putout("1111111111111001",imod);//clk down - putout("1111111111111111",imod);//reset - - /*commented out by dhanya - putout("0000000001000000",imod); - putout("0000000001001000",imod); - putout("0000000001000000",imod); - */ -#ifdef DEBUG - fprintf(stdout, "Next DAC\n"); -#endif - // sDac++; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return OK; -} - - -int clearCSregister(int imod) { - - putout("0000000001000000",imod); - putout("0000100001000000",imod); - putout("0000100001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Clearing CS shiftregister\n"); -#endif - /* - sChan=noneSelected; - sMod=noneSelected; - sDac=noneSelected; - sAdc=noneSelected; - */ - sChip=noneSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - //putout("0000000000000000",imod); - return 0; -} - -int setCSregister(int imod){ - - putout("0000000001000000",imod); - putout("0001000001000000",imod); - putout("0001000001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Setting CS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChip=allSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int nextChip(int imod){ - - putout("0000000001000000",imod); - putout("0010000001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Next Chip\n"); -#endif - sChip++; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int firstChip(int imod){ - - putout("0100000001000000",imod); - putout("0110000001000000",imod); - putout("0100000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "First Chip\n"); -#endif - sChip=0; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int clearSSregister(int imod){ - int i; - putout("0000011000000000",imod); - for (i=0; i<10; i++) - putout("0000111000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"Clearing SS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChan=noneSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int setSSregister(int imod){ - int i; - putout("0000011000000000",imod); - for (i=0; i<10; i++) - putout("0001011000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"Setting SS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChan=allSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int nextStrip(int imod){ - putout("0000011000000000",imod); - putout("0010011000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"|-"); -#endif - sChan++; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int selChannel(const int strip,int imod) { - int istrip; - clearSSregister(imod); - nextStrip(imod); - for (istrip=0; istrip=0 && imod=0) - initDAC(ind,val, imod); - - if (imod>=0 && imodndac) - return (detectorDacs[ind+imod*NDAC]); - } - return FAIL; - */ - return setDACRegister(ind, -1, imod); -} - - -int initDAC(int dac_addr, int value, int imod) { -// int i; -#ifdef VERBOSE - printf("Programming dac %d with value %d\n", dac_addr, value); -#endif - clearDACSregister(imod); - program_one_dac(dac_addr,value,imod); - nextDAC(imod); - clearDACSregister(imod); - - return 0; -} - -int getTemperatureByModule(int tempSensor, int imod) -{ - int im; - //for the particular module - if (imod>=0 && imod=0 && imod=0 && imod=0) { -#ifdef VERBOSE - fprintf(stdout, "voltage %d\n", *(v+iaddr)); -#endif - program_one_dac(iaddr, *(v+iaddr),imod); - } - nextDAC(imod); - } - - - clearDACSregister(imod); - - return 0; - -} - - - - -int setSettings(int i, int imod) { -#ifdef VERBOSE - if(i==-1) - printf("\nReading settings of detector...\n"); - else - printf("\ninside set settings wit settings=%d...\n",i); -#endif - int confgain[] = CONF_GAIN; - int isett=-2,retval; - - //reading settings - if(i==GET_SETTINGS){ - retval=initConfGainByModule(i,i,imod); - if(retval==i) - isett=UNDEFINED; - } - //writing settings - else{ - retval=initConfGainByModule(i,confgain[i],imod); - if(retval!=i) - isett=UNDEFINED; - } - //if error while read/writing - if(isett==UNDEFINED) - printf("Error:Weird Value read back from the Gain/Settings Reg\n"); - else{ - //validating the settings read back - if((retval>=HIGHGAIN)&&(retval<=VERYHIGHGAIN)) - isett=retval; - else{ - isett=UNDEFINED; - printf("Error:Wrong Settings Read out:%d\n",retval); - } - } - thisSettings=isett; -#ifdef VERBOSE - printf("detector settings are %d\n",thisSettings); -#endif - return thisSettings; -} - - - - -/* Initialization*/ - -int initChannelbyNumber(sls_detector_channel myChan) { - int reg=myChan.reg; - int ft=reg & TRIM_DR; - int cae=(reg>>(NTRIMBITS))&1; - int ae=(reg>>(NTRIMBITS+1))&1; - int coe=(reg>>(NTRIMBITS+2))&1; - int ocoe=(reg>>(NTRIMBITS+3))&1; - int counts=(reg>>(NTRIMBITS+4)); -#ifdef VERBOSE - printf("Initializing channel %d chip %d module %d reg %x\n",myChan.chan,myChan.chip,myChan.module, reg); - printf("trim %d, cae %d, ae %d, coe %d, ocoe %d, counts %d\n",ft, cae, ae, coe, ocoe, counts); -#endif - - if (myChan.chip<0) - setCSregister(myChan.module); - else - selChip(myChan.chip,myChan.module); - - if (myChan.chan<0) - setSSregister(myChan.module); - else - selChannel(myChan.chan,myChan.module); - - initChannel(ft,cae,ae, coe, ocoe, counts,myChan.module); - - setDynamicRange(dynamicRange); - - setCSregister(ALLMOD); - clearSSregister(ALLMOD); - putout("0000000000000000",ALLMOD); - - return myChan.reg; - -} - -int getChannelbyNumber(sls_detector_channel* myChan) { - int imod, ichip, ichan; - imod=myChan->module; - ichip=myChan->chip; - ichan=myChan->chan; - - if (detectorChans) { - if (imod=0) { - if (ichip<(detectorModules+imod)->nchip && ichan<(detectorModules+imod)->nchan/(detectorModules+imod)->nchip) - myChan->reg=detectorChans[imod*NCHAN*NCHIP+ichip*NCHAN+ichan]; - return OK; - } - } - return FAIL; - -} - -int getTrimbit(int imod, int ichip, int ichan) { - if (detectorChans) { - if (imod=0) - if (ichip<(detectorModules+imod)->nchip && ichan<(detectorModules+imod)->nchan/(detectorModules+imod)->nchip) - return (detectorChans[imod*NCHAN*NCHIP+ichip*NCHAN+ichan] & TRIM_DR); - } - - return -1; -} - -int initChannel(int ft,int cae, int ae, int coe, int ocoe, int counts, int imod){ - - int ibit, bit, i, im, ichip, ichan; - int chanmi, chanma, chipmi, chipma, modmi, modma; - - - - sMod=imod; - // printf("initializing module %d\n",sMod); - if (imod==ALLMOD) { - sMod=allSelected; - - // printf("initializing all modules\n"); - } - - if (sChan==allSelected) { - // printf("initializing all channels ft=%d coe=%d\n",ft,coe); - chanmi=0; - chanma=NCHAN; - } else if (sChan==noneSelected || sChan>NCHAN || sChan<0) { - // printf("initializing no channels ft=%d coe=%d\n",ft,coe); - chanmi=0; - chanma=-1; - } else { - // printf("initializing channel %d ft=%d coe=%d\n",sChan, ft,coe); - chanmi=sChan; - chanma=sChan+1; - } - - if (sChip==allSelected) { - // printf("initializing all chips\n"); - chipmi=0; - chipma=NCHIP; - } else if (sChip==noneSelected || sChip>NCHIP || sChip<0) { - // printf("initializing no chips\n"); - chipmi=0; - chipma=-1; - } else { - // printf("initializing chip %d\n",sChip); - chipmi=sChip; - chipma=sChip+1; - } - - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - return 1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorChans) { - for (im=modmi; im63 || ft<0) { - fprintf(stdout,"Fine Threshold is %d while should be between 0 and 63!",ft); - return 1; - } - /*cal_enable*/ - if (cae) { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - } else { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - } - /*n_an_enable*/ - if (ae) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } else { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - putout("0100000000000000",imod); - } - /*trb5*/ - ibit=5; - bit=ft & (1<>1; - int nchan, ichan; - int ft, cae, ae, coe, ocoe, counts, chanreg; - - - - nchan=myChip.nchan; - if (ichip<0) - setCSregister(imod); - else - selChip(ichip,imod); - - clearSSregister(imod); - for (ichan=0; ichan>(NTRIMBITS+1))&1; - ae=(chanreg>>(NTRIMBITS+2))&1; - coe=((chanreg)>>(NTRIMBITS+3))&1; - ocoe=((chanreg)>>(NTRIMBITS+4))&1; - counts=((chanreg)>>(NTRIMBITS+5)); - nextStrip(imod); - initChannel(ft,cae,ae, coe, ocoe, counts,imod); - } - initChip(obe,ow,imod); - return myChip.reg; - -} - -int getChipbyNumber(sls_detector_chip* myChip){ - int imod, ichip; - imod=myChip->module; - ichip=myChip->chip; - - if (detectorChips) { - if (imodnchip) { - myChip->reg=detectorChips[ichip+imod*NCHIP]; - myChip->nchan=NCHAN; - myChip->chanregs=detectorChans+imod*NCHAN*NCHIP+ichip*NCHIP; - return OK; - } - } - return FAIL; - -} - - - -int initChip(int obe, int ow,int imod){ - int i; - int im, ichip; - int chipmi, chipma, modmi, modma; - /* switch (ow) { - case 0:; - case 1: - setDynamicRange(32); - break; - case 2: - setDynamicRange(16); - break; - case 3: - setDynamicRange(8); - break; - case 4: - setDynamicRange(4); - break; - case 5: - setDynamicRange(1); - break; - default: - setDynamicRange(32); - break; - } - */ - -#ifdef DEBUGOUT - printf("Initializing chip\n"); -#endif - putout("0000000000000000",imod); -#ifdef DEBUGOUT - printf("Output mode= %d\n", ow); -#endif - - /* clearing shift in register */ - for (i=0; i<10; i++) - putout("0000100000000000",imod); - putout("0000000000000000",imod); - - if (ow>0) { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - putout("0100000000000000",imod); - for (i=0; i<(OUTMUX_OFFSET-1); i++) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>1) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>2) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>3) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>4) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - } -#ifdef DEBUGOUT - printf("Output buffer enable= %d\n", obe); -#endif - if (obe) { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - putout("0100000000000000",imod); - } else { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - /*}*/ - putout("0000000000000000",imod); - - - - - - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - - - if (sChip==allSelected) { - chipmi=0; - chipma=NCHIP; - } else if (sChip==noneSelected || sChip>NCHIP || sChip<0) { - chipmi=0; - chipma=-1; - } else { - chipmi=sChip; - chipma=sChip+1; - } - - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorChips) { - for (im=modmi; imNCHIP || sChip<0) { - chipmi=0; - chipma=-1; - } else { - chipmi=sChip; - chipma=sChip+1; - } - - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorChips) { - for (im=modmi; imnModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorModules) { - for (im=modmi; imreg)=cm; -#ifdef VERBOSE - printf("imod=%d reg=%d (%x)\n",im,(detectorModules+im)->reg,(unsigned int)((detectorModules+im))); -#endif - } - } - return 0; -} - -int initModulebyNumber(sls_detector_module myMod) { - - printf("\ninside initmoduleynumber..\n"); - - int nchip,nchan;//int ichip, nchip, ichan, nchan; - int im, modmi,modma; - // int ft, cae, ae, coe, ocoe, counts, chanreg; - int imod; - // int obe; - // int ow; - int v[NDAC]; - - - nchip=myMod.nchip; - nchan=(myMod.nchan)/nchip; - - imod=myMod.module; - sMod=imod; - - if (sMod==ALLMOD) - sMod=allSelected; - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {// (sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - - /* - for (idac=0; idacmodule; -#ifdef VERBOSE - printf("Getting module %d\n",imod); -#endif - if (detectorModules) { - copyModule(myMod,detectorModules+imod); - ; - } else - return FAIL; - - return OK; -} - -/* To chips */ -int clearCounter(int imod){ - int i; -#ifdef DEBUG - printf("Clearing counter with contclear\n"); -#endif - putout("0000000000000000",imod); - for (i=0; i<10; i++) - putout("0000000000010000",imod); - putout("0000000000000000",imod); - - return 0; -} - -int clearOutReg(int imod){ - int i; -#ifdef DEBUG - printf("Clearing output register\n"); -#endif - putout("0000010000000000",imod); - for (i=0; i<10; i++) - putout("0000110000000000",imod); - putout("0000010000000000",imod); - return 0; -} -int setOutReg(int imod){ - int i; -#ifdef DEBUG - printf("Setting output register\n"); -#endif - putout("0000010000000000",imod); - for (i=0; i<10; i++) - putout("0001010000000000",imod); - putout("0000010000000000",imod); - return 0; -} - - -int extPulse(int ncal, int imod) { - int ical; -#ifdef DEBUG - printf("Giving a clock pulse to the counter\n"); -#endif - for (ical=0; ical0 && i%2==0) { - printf("Shift in: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, i%2); - result++; - } - if (i%2>0 && (val & 1<0 && (dum & (1<0) { - printf("Shift out: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, (dum &1<0 && i%2==0) { - printf("Shift stsel: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, i%2); - result++; - } - if (i%2>0 && (val & 1<> 1; - - - putout("0000000000000000",ALLMOD); - putout("0010000000000000",ALLMOD); //change mux setting - putout("0000000000000000",ALLMOD); - } - - printf("Test FpgaMux module %d : %d errors\n", imod,result); - if (result) - return 1; - else - return 0; -} - - - - - - - - - -int calibration_sensor(int num, int *v, int *dacs) { - int ich, ichip, imod; - int val[10]; - - - printf("calibrating sensor..."); - for (imod=0; imod=0){ - - if(n==0) - adc=-1; - else{ - //if its for 1 adc or general - if ((arg[0].xmin==0) && (arg[0].xmax==GOTTHARDNCHIP*GOTTHARDNCHAN)) - adc=-1; - else{ - //adc = mid value/numchans also for only 1 roi - adc = ((((arg[0].xmax)+(arg[0].xmin))/2)/(GOTTHARDNCHAN*NCHIPS_PER_ADC)); - if((adc>=0) && (adc<=4)); - else { - printf("warning:adc value greater than 5. deleting roi\n"); - adc=-1; - } - } - } - - - //set rois for just 1 adc - take only 1st roi - if(adc!=-1){ - rois[0].xmin=adc*(GOTTHARDNCHAN*NCHIPS_PER_ADC); - rois[0].xmax=(adc+1)*(GOTTHARDNCHAN*NCHIPS_PER_ADC)-1; - rois[0].ymin=-1; - rois[0].ymax=-1; - nROI = 1; - }else - nROI = 0; - - if((arg[0].xmin!=rois[0].xmin)||(arg[0].xmax!=rois[0].xmax)||(arg[0].ymin!=rois[0].ymin)||(arg[0].ymax!=rois[0].ymax)) - *ret=FAIL; - if(n!=nROI) - *ret=FAIL; - - //set adc of interest - setADC(adc); - }*/ - -//#ifdef VERBOSE - printf("Rois:\n"); - for( i=0;i - - -extern int sockfd; -extern int phase_shift; - - - -void error(char *msg) -{ - perror(msg); -} - -int main(int argc, char *argv[]) -{ - int portno, b; - char cmd[500]; - int retval=OK; - int sd, fd; - int iarg; - - - for(iarg=1; iarg 2) && (!strcasecmp(argv[2],"stopserver"))){ - portno = DEFAULT_PORTNO+1; - if ( sscanf(argv[1],"%d",&portno) ==0) { - printf("could not open stop server: unknown port\n"); - return 1; - } - b=0; - printf("\n\nStop Server\nOpening stop server on port %d\n",portno); - } - - //control server - else { - portno = DEFAULT_PORTNO; - sprintf(cmd,"%s %d stopserver &",argv[0],DEFAULT_PORTNO+1); - printf("\n\nControl Server\nOpening control server on port %d\n",portno ); - - //printf("\n\ncmd:%s\n",cmd); - system(cmd); - b=1; - } - - - init_detector(b); - - - sd=bindSocket(portno); - sockfd=sd; - if (getServerError(sd)) { - printf("server error!\n"); - return -1; - } - - /* assign function table */ - function_table(); -#ifdef VERBOSE - printf("function table assigned \n"); -#endif - - - /* waits for connection */ - while(retval!=GOODBYE) { -#ifdef VERBOSE - printf("\n"); -#endif -#ifdef VERY_VERBOSE - printf("Waiting for client call\n"); -#endif - fd=acceptConnection(sockfd); -#ifdef VERY_VERBOSE - printf("Conenction accepted\n"); -#endif - retval=decode_function(fd); -#ifdef VERY_VERBOSE - printf("function executed\n"); -#endif - closeConnection(fd); -#ifdef VERY_VERBOSE - printf("connection closed\n"); -#endif - } - - exitServer(sockfd); - printf("Goodbye!\n"); - - return 0; -} - diff --git a/slsDetectorSoftware/moenchDetectorServer/server_defs.h b/slsDetectorSoftware/moenchDetectorServer/server_defs.h deleted file mode 100755 index e86b3107f..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/server_defs.h +++ /dev/null @@ -1,61 +0,0 @@ -#ifndef SERVER_DEFS_H -#define SERVER_DEFS_H - -#include "sls_detector_defs.h" - -#include - - -// Hardware definitions - -#define NCHAN (160*160) -#define NCHIP 1 -#define NMAXMODX 1 -#define NMAXMODY 1 -#define NMAXMOD (NMAXMODX*NMAXMODY) -#define NDAC 8 -#define NADC 1 - - - - - - -#define NCHANS (NCHAN*NCHIP*NMAXMOD) -#define NDACS (NDAC*NMAXMOD) - -#define NTRIMBITS 6 -#define NCOUNTBITS 24 - -#define NCHIPS_PER_ADC 2 - -//#define TRIM_DR ((2**NTRIMBITS)-1) -//#define COUNT_DR ((2**NCOUNTBITS)-1) -#define TRIM_DR (((int)pow(2,NTRIMBITS))-1) -#define COUNT_DR (((int)pow(2,NCOUNTBITS))-1) - - -#define ALLMOD 0xffff -#define ALLFIFO 0xffff - -#define GOTTHARD_ADCSYNC_VAL 0x32214 -#define ADCSYNC_VAL 0x02111 -#define TOKEN_RESTART_DELAY 0x88000000 -#define TOKEN_RESTART_DELAY_ROI 0x1b000000 -#define TOKEN_TIMING_REV1 0x1f16 -#define TOKEN_TIMING_REV2 0x1f0f - -#define DEFAULT_PHASE_SHIFT 0 // 120 -#define DEFAULT_IP_PACKETSIZE 0x0522 -#define DEFAULT_UDP_PACKETSIZE 0x050E -#define ADC1_IP_PACKETSIZE 256*2+14+20 -#define ADC1_UDP_PACKETSIZE 256*2+4+8+2 - -#ifdef VIRTUAL -#define DEBUGOUT -#endif - -#define CLK_FREQ 65.6E+6 - - -#endif diff --git a/slsDetectorSoftware/moenchDetectorServer/server_funcs.c b/slsDetectorSoftware/moenchDetectorServer/server_funcs.c deleted file mode 100755 index 33f776c33..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/server_funcs.c +++ /dev/null @@ -1,3083 +0,0 @@ -#include "sls_detector_defs.h" -#include "server_funcs.h" -#ifndef PICASSOD -#include "server_defs.h" -#else -#include "picasso_defs.h" -#endif -#include "firmware_funcs.h" -#include "mcb_funcs.h" -#include "trimming_funcs.h" -#include "registers_m.h" -#include "gitInfoMoench.h" - -#define FIFO_DATA_REG_OFF 0x50<<11 -#define CONTROL_REG 0x24<<11 -// Global variables - - -int (*flist[256])(int); - - -//defined in the detector specific file -#ifdef MYTHEND -const enum detectorType myDetectorType=MYTHEN; -#elif GOTTHARDD -const enum detectorType myDetectorType=GOTTHARD; -#elif EIGERD -const enum detectorType myDetectorType=EIGER; -#elif PICASSOD -const enum detectorType myDetectorType=PICASSO; -#elif MOENCHD -const enum detectorType myDetectorType=MOENCH; -#else -const enum detectorType myDetectorType=GENERIC; -#endif - - -extern int nModX; -extern int nModY; -extern int dataBytes; -extern int dynamicRange; -extern int storeInRAM; - -extern int lockStatus; -extern char lastClientIP[INET_ADDRSTRLEN]; -extern char thisClientIP[INET_ADDRSTRLEN]; -extern int differentClients; - -/* global variables for optimized readout */ -extern unsigned int *ram_values; -char *dataretval=NULL; -int nframes, iframes, dataret; -char mess[MAX_STR_LENGTH]; - -int digitalTestBit = 0; - - -int init_detector(int b) { - if (mapCSP0()==FAIL) { printf("Could not map memory\n"); - exit(1); - } - - // - - bus_w16(CONTROL_REG, SYNC_RESET); - bus_w16(CONTROL_REG, 0x0); - - //confirm if it is really moench - if(((bus_r(PCB_REV_REG) & DETECTOR_TYPE_MASK)>>DETECTOR_TYPE_OFFSET) != MOENCH_MODULE ){ - printf("This is a Gotthard detector. Exiting Moench Server.\n\n"); - exit(-1); - } - - if (b) { - printf("***This is a MOENCH detector with %d chips per module***\n",NCHIP); - -#ifdef MCB_FUNCS - printf("\nBoard Revision:0x%x\n",(bus_r(PCB_REV_REG)&BOARD_REVISION_MASK)); - initDetector(); - printf("Initializing Detector\n"); - bus_w16(CONTROL_REG, SYNC_RESET); // reset registers -#endif - - - testFpga(); - testRAM(); - printf("ADC_SYNC_REG:%x\n",bus_r(ADC_SYNC_REG)); - //moench specific - - // setPhaseShiftOnce(); //firmware.h - - - prepareADC(); // server_funcs - setADC(-1); //already does setdaqreg and clean fifo - setSettings(GET_SETTINGS,-1); - - //Initialization - setFrames(1); - setTrains(1); - setExposureTime(1e3); - setPeriod(1E6); - setDelay(0); - setGates(0); - - setTiming(GET_EXTERNAL_COMMUNICATION_MODE); - setMaster(GET_MASTER); - setSynchronization(GET_SYNCHRONIZATION_MODE); - startReceiver(0); //firmware - } - strcpy(mess,"dummy message"); - strcpy(lastClientIP,"none"); - strcpy(thisClientIP,"none1"); - lockStatus=0; - return OK; -} - - -int decode_function(int file_des) { - int fnum,n; - int retval=FAIL; -#ifdef VERBOSE - printf( "receive data\n"); -#endif - n = receiveDataOnly(file_des,&fnum,sizeof(fnum)); - if (n <= 0) { -#ifdef VERBOSE - printf("ERROR reading from socket %d, %d %d\n", n, fnum, file_des); -#endif - return FAIL; - } -#ifdef VERBOSE - else - printf("size of data received %d\n",n); -#endif - -#ifdef VERBOSE - printf( "calling function fnum = %d %x\n",fnum,(unsigned int)(flist[fnum])); -#endif - if (fnum<0 || fnum>255) - fnum=255; - retval=(*flist[fnum])(file_des); - if (retval==FAIL) - printf( "Error executing the function = %d \n",fnum); - return retval; -} - - -int function_table() { - int i; - for (i=0;i<256;i++){ - flist[i]=&M_nofunc; - } - flist[F_EXIT_SERVER]=&exit_server; - flist[F_EXEC_COMMAND]=&exec_command; - flist[F_GET_DETECTOR_TYPE]=&get_detector_type; - flist[F_SET_NUMBER_OF_MODULES]=&set_number_of_modules; - flist[F_GET_MAX_NUMBER_OF_MODULES]=&get_max_number_of_modules; - flist[F_SET_EXTERNAL_SIGNAL_FLAG]=&set_external_signal_flag; - flist[F_SET_EXTERNAL_COMMUNICATION_MODE]=&set_external_communication_mode; - flist[F_GET_ID]=&get_id; - flist[F_DIGITAL_TEST]=&digital_test; - flist[F_WRITE_REGISTER]=&write_register; - flist[F_READ_REGISTER]=&read_register; - flist[F_SET_DAC]=&set_dac; - flist[F_GET_ADC]=&get_adc; - flist[F_SET_CHANNEL]=&set_channel; - flist[F_SET_CHIP]=&set_chip; - flist[F_SET_MODULE]=&set_module; - flist[F_GET_CHANNEL]=&get_channel; - flist[F_GET_CHIP]=&get_chip; - flist[F_GET_MODULE]=&get_module; - flist[F_GET_THRESHOLD_ENERGY]=&get_threshold_energy; - flist[F_SET_THRESHOLD_ENERGY]=&set_threshold_energy; - flist[F_SET_SETTINGS]=&set_settings; - flist[F_START_ACQUISITION]=&start_acquisition; - flist[F_STOP_ACQUISITION]=&stop_acquisition; - flist[F_START_READOUT]=&start_readout; - flist[F_GET_RUN_STATUS]=&get_run_status; - flist[F_READ_FRAME]=&read_frame; - flist[F_READ_ALL]=&read_all; - flist[F_START_AND_READ_ALL]=&start_and_read_all; - flist[F_SET_TIMER]=&set_timer; - flist[F_GET_TIME_LEFT]=&get_time_left; - flist[F_SET_DYNAMIC_RANGE]=&set_dynamic_range; - flist[F_SET_ROI]=&set_roi; - flist[F_SET_SPEED]=&set_speed; - flist[F_SET_READOUT_FLAGS]=&set_readout_flags; - flist[F_EXECUTE_TRIMMING]=&execute_trimming; - flist[F_LOCK_SERVER]=&lock_server; - flist[F_SET_PORT]=&set_port; - flist[F_GET_LAST_CLIENT_IP]=&get_last_client_ip; - flist[F_UPDATE_CLIENT]=&update_client; - flist[F_CONFIGURE_MAC]=&configure_mac; - flist[F_LOAD_IMAGE]=&load_image; - flist[F_SET_MASTER]=&set_master; - flist[F_SET_SYNCHRONIZATION_MODE]=&set_synchronization; - flist[F_READ_COUNTER_BLOCK]=&read_counter_block; - flist[F_RESET_COUNTER_BLOCK]=&reset_counter_block; - flist[F_START_RECEIVER]=&start_receiver; - flist[F_STOP_RECEIVER]=&stop_receiver; - flist[F_CALIBRATE_PEDESTAL]=&calibrate_pedestal; - return OK; -} - - -int M_nofunc(int file_des){ - - int ret=FAIL; - sprintf(mess,"Unrecognized Function\n"); - printf(mess); - - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); - return GOODBYE; -} - - -int exit_server(int file_des) { - int retval=FAIL; - sendDataOnly(file_des,&retval,sizeof(retval)); - printf("closing server."); - sprintf(mess,"closing server"); - sendDataOnly(file_des,mess,sizeof(mess)); - return GOODBYE; -} - -int exec_command(int file_des) { - char cmd[MAX_STR_LENGTH]; - char answer[MAX_STR_LENGTH]; - int retval=OK; - int sysret=0; - int n=0; - - /* receive arguments */ - n = receiveDataOnly(file_des,cmd,MAX_STR_LENGTH); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - - /* execute action if the arguments correctly arrived*/ - if (retval==OK) { -#ifdef VERBOSE - printf("executing command %s\n", cmd); -#endif - if (lockStatus==0 || differentClients==0) - sysret=system(cmd); - - //should be replaced by popen - if (sysret==0) { - sprintf(answer,"Succeeded\n"); - if (lockStatus==1 && differentClients==1) - sprintf(answer,"Detector locked by %s\n", lastClientIP); - } else { - sprintf(answer,"Failed\n"); - retval=FAIL; - } - } else { - sprintf(answer,"Could not receive the command\n"); - } - - /* send answer */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - n = sendDataOnly(file_des,answer,MAX_STR_LENGTH); - if (n < 0) { - sprintf(mess,"Error writing to socket"); - retval=FAIL; - } - - - /*return ok/fail*/ - return retval; - -} - - - -int get_detector_type(int file_des) { - int n=0; - enum detectorType ret; - int retval=OK; - - sprintf(mess,"Can't return detector type\n"); - - - /* receive arguments */ - /* execute action */ - ret=myDetectorType; - -#ifdef VERBOSE - printf("Returning detector type %d\n",ret); -#endif - - /* send answer */ - /* send OK/failed */ - if (differentClients==1) - retval=FORCE_UPDATE; - - n += sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - /*return ok/fail*/ - return retval; - - -} - - -int set_number_of_modules(int file_des) { - int n; - int arg[2], ret=0; - int retval=OK; - int dim, nm; - - sprintf(mess,"Can't set number of modules\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket %d", n); - retval=GOODBYE; - } - if (retval==OK) { - dim=arg[0]; - nm=arg[1]; - - /* execute action */ -#ifdef VERBOSE - printf("Setting the number of modules in dimension %d to %d\n",dim,nm ); -#endif - - //if (nm!=GET_FLAG) { - if (dim!=X && nm!=GET_FLAG) { - retval=FAIL; - sprintf(mess,"Can't change module number in dimension %d\n",dim); - } else { - if (lockStatus==1 && differentClients==1 && nm!=GET_FLAG) { - sprintf(mess,"Detector locked by %s\n", lastClientIP); - retval=FAIL; - } else { - ret=setNMod(nm); - if (nModX==nm || nm==GET_FLAG) { - retval=OK; - if (differentClients==1) - retval=FORCE_UPDATE; - } else - retval=FAIL; - } - } - } - /*} else { - if (dim==Y) { - ret=nModY; - } else if (dim==X) { - ret=setNMod(-1); - } - } - */ - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - /*return ok/fail*/ - return retval; - -} - - -int get_max_number_of_modules(int file_des) { - int n; - int ret; - int retval=OK; - enum dimension arg; - - sprintf(mess,"Can't get max number of modules\n"); - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - /* execute action */ -#ifdef VERBOSE - printf("Getting the max number of modules in dimension %d \n",arg); -#endif - - - switch (arg) { - case X: - ret=getNModBoard(); - break; - case Y: - ret=NMAXMODY; - break; - default: - ret=FAIL; - retval=FAIL; - break; - } -#ifdef VERBOSE - printf("Max number of module in dimension %d is %d\n",arg,ret ); -#endif - - - - if (differentClients==1 && retval==OK) { - retval=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - - /*return ok/fail*/ - return retval; -} - - -//index 0 is in gate -//index 1 is in trigger -//index 2 is out gate -//index 3 is out trigger - -int set_external_signal_flag(int file_des) { - int n; - int arg[2]; - int ret=OK; - int signalindex; - enum externalSignalFlag flag, retval; - - sprintf(mess,"Can't set external signal flag\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - retval=SIGNAL_OFF; - if (ret==OK) { - signalindex=arg[0]; - flag=arg[1]; - /* execute action */ - switch (flag) { - case GET_EXTERNAL_SIGNAL_FLAG: - retval=getExtSignal(signalindex); - break; - - default: - if (differentClients==0 || lockStatus==0) { - retval=setExtSignal(signalindex,flag); - } else { - if (lockStatus!=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n", lastClientIP); - } - } - - } - -#ifdef VERBOSE - printf("Setting external signal %d to flag %d\n",signalindex,flag ); - printf("Set to flag %d\n",retval); -#endif - - } else { - ret=FAIL; - } - - if (ret==OK && differentClients!=0) - ret=FORCE_UPDATE; - - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - /*return ok/fail*/ - return ret; - -} - - -int set_external_communication_mode(int file_des) { - int n; - enum externalCommunicationMode arg, ret=GET_EXTERNAL_COMMUNICATION_MODE; - int retval=OK; - - sprintf(mess,"Can't set external communication mode\n"); - - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - /* - enum externalCommunicationMode{ - GET_EXTERNAL_COMMUNICATION_MODE, - AUTO, - TRIGGER_EXPOSURE_SERIES, - TRIGGER_EXPOSURE_BURST, - TRIGGER_READOUT, - TRIGGER_COINCIDENCE_WITH_INTERNAL_ENABLE, - GATE_FIX_NUMBER, - GATE_FIX_DURATION, - GATE_WITH_START_TRIGGER, - GATE_COINCIDENCE_WITH_INTERNAL_ENABLE - }; - */ - if (retval==OK) { - /* execute action */ - - ret=setTiming(arg); - - /* switch(arg) { */ - /* default: */ - /* sprintf(mess,"The meaning of single signals should be set\n"); */ - /* retval=FAIL; */ - /* } */ - - -#ifdef VERBOSE - printf("Setting external communication mode to %d\n", arg); -#endif - } else - ret=FAIL; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return retval; -} - - - -int get_id(int file_des) { - // sends back 64 bits! - int64_t retval=-1; - int ret=OK; - int n=0; - enum idMode arg; - - sprintf(mess,"Can't return id\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - -#ifdef VERBOSE - printf("Getting id %d\n", arg); -#endif - - switch (arg) { - case DETECTOR_SERIAL_NUMBER: - retval=getDetectorNumber(); - break; - case DETECTOR_FIRMWARE_VERSION: - retval = (getFirmwareVersion() & 0xFFFFFF); - break; - case DETECTOR_SOFTWARE_VERSION: - retval = (GITDATE & 0xFFFFFF); - break; - default: - printf("Required unknown id %d \n", arg); - ret=FAIL; - retval=FAIL; - break; - } - -#ifdef VERBOSE - printf("Id is %llx\n", retval); -#endif - - if (differentClients==1) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - -int digital_test(int file_des) { - - int retval; - int ret=OK; - int imod=-1; - int n=0; - int ibit=0; - int ow; - int ival; - enum digitalTestMode arg; - - sprintf(mess,"Can't send digital test\n"); - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - -#ifdef VERBOSE - printf("Digital test mode %d\n",arg ); -#endif - - switch (arg) { - case CHIP_TEST: - n = receiveDataOnly(file_des,&imod,sizeof(imod)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } -#ifdef VERBOSE - printf("of module %d\n", imod); -#endif - retval=0; -#ifdef MCB_FUNCS - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - break; - } - if (imod >= nModX) { - ret=FAIL; - sprintf(mess,"Module %d disabled\n",imod); - break; - } - if (testShiftIn(imod)) retval|=(1<<(ibit)); - ibit++; - if (testShiftOut(imod)) retval|=(1<<(ibit)); - ibit++; - if (testShiftStSel(imod)) retval|=(1<<(ibit)); - ibit++; - //if ( testDataInOut(0x123456, imod)) retval|=(1<<(ibit++)); - //if ( testExtPulse(imod)) retval|=(1<<(ibit++)); - // for (ow=0; ow<6; ow++) - // ow=1; - //#ifndef PICASSOD - for (ow=0; ow<5; ow++) { - //#endif - if (testDataInOutMux(imod, ow, 0x789abc)) retval|=(1<=getNModBoard()) - ret=FAIL; - if (imod<0) - imod=ALLMOD; - -#ifdef MCB_FUNCS - switch (ind) { - case V_DAC0 : - idac=VDAC0; - break; - case V_DAC1: - idac=VDAC1; - break; - case V_DAC2: - idac=VDAC2; - break; - case V_DAC3: - idac=VDAC3; - break; - case V_DAC4: - idac=VDAC4; - break; - case V_DAC5: - idac=VDAC5; - break; - case V_DAC6: - idac=VDAC6; - break; - case V_DAC7: - idac=VDAC7; - break; - case HV_POT: - idac=HIGH_VOLTAGE; - break; - - default: - printf("Unknown DAC index %d for Moench\n",ind); - sprintf(mess,"Unknown DAC index %d for Moench\n",ind); - ret=FAIL; - break; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else{ - if(idac==HIGH_VOLTAGE){ - retval[0]=initHighVoltageByModule(val,imod); - ret=FAIL; - if(retval[0]==-2) - strcpy(mess,"Invalid Voltage.Valid values are 0,90,110,120,150,180,200"); - else if(retval[0]==-3) - strcpy(mess,"Weird value read back or it has not been set yet\n"); - else - ret=OK; - }else{ - initDACbyIndexDACU(idac,val,imod,mV,retval); - ret=FAIL; - if(mV) - temp = retval[1]; - else - temp = retval[0]; - if ((abs(temp-val)<=3) || val==-1) { - ret=OK; -#ifdef VERBOSE - printf("DAC set to %d in dac units and %d mV\n", retval[0],retval[1]); -#endif - } - } - } - } - -#endif - - - if(ret==FAIL) - printf("Setting dac %d of module %d: wrote %d but read %d\n", ind, imod, val, temp); - else{ - if (differentClients) - ret=FORCE_UPDATE; - } - - - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - /*return ok/fail*/ - return ret; - -} - - - -int get_adc(int file_des) { - //default: mod 0 - int retval; - int ret=OK; - int arg[2]; - enum dacIndex ind; - int imod; - int n; - int idac=0; - - sprintf(mess,"Can't read ADC\n"); - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ind=arg[0]; - imod=arg[1]; - -#ifdef VERBOSE - printf("Getting ADC %d of module %d\n", ind, imod); -#endif - - if (imod>=getNModBoard() || imod<0) - ret=FAIL; - -#ifdef MCB_FUNCS - switch (ind) { - case TEMPERATURE_FPGA: - idac=TEMP_FPGA; - break; - case TEMPERATURE_ADC: - idac=TEMP_ADC; - break; - default: - printf("Unknown DAC index %d\n",ind); - sprintf(mess,"Unknown DAC index %d\n",ind); - ret=FAIL; - break; - } - - if (ret==OK) - retval=getTemperatureByModule(idac,imod); -#endif - -#ifdef VERBOSE - printf("ADC is %d V\n", retval); -#endif - if (ret==FAIL) { - printf("Getting adc %d of module %d failed\n", ind, imod); - } - - if (differentClients) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - -int set_channel(int file_des) { - int ret=OK; - sls_detector_channel myChan; - int retval; - int n; - - - sprintf(mess,"Can't set channel\n"); - -#ifdef VERBOSE - printf("Setting channel\n"); -#endif - ret=receiveChannel(file_des, &myChan); - if (ret>=0) - ret=OK; - else - ret=FAIL; -#ifdef VERBOSE - printf("channel number is %d, chip number is %d, module number is %d, register is %lld\n", myChan.chan,myChan.chip, myChan.module, myChan.reg); -#endif - - if (ret==OK) { - if (myChan.module>=getNModBoard()) - ret=FAIL; - if (myChan.chip>=NCHIP) - ret=FAIL; - if (myChan.chan>=NCHAN) - ret=FAIL; - if (myChan.module<0) - myChan.module=ALLMOD; - } - - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef MCB_FUNCS - retval=initChannelbyNumber(myChan); -#endif - } - } - /* Maybe this is done inside the initialization funcs */ - //copyChannel(detectorChans[myChan.module][myChan.chip]+(myChan.chan), &myChan); - - - - if (differentClients==1 && ret==OK) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - /*return ok/fail*/ - return ret; - -} - - - - -int get_channel(int file_des) { - - int ret=OK; - sls_detector_channel retval; - - int arg[3]; - int ichan, ichip, imod; - int n; - - sprintf(mess,"Can't get channel\n"); - - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ichan=arg[0]; - ichip=arg[1]; - imod=arg[2]; - - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod=0 && ichip=0 && ichan=0) - ret=OK; - else - ret=FAIL; -#ifdef VERBOSE - printf("chip number is %d, module number is %d, register is %d, nchan %d\n",myChip.chip, myChip.module, myChip.reg, myChip.nchan); -#endif - - if (ret==OK) { - if (myChip.module>=getNModBoard()) - ret=FAIL; - if (myChip.module<0) - myChip.module=ALLMOD; - if (myChip.chip>=NCHIP) - ret=FAIL; - } - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef MCB_FUNCS - retval=initChipbyNumber(myChip); -#endif - } - /* Maybe this is done inside the initialization funcs */ - //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); - - if (differentClients && ret==OK) - ret=FORCE_UPDATE; - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - return ret; -} - -int get_chip(int file_des) { - - - int ret=OK; - sls_detector_chip retval; - int arg[2]; - int ichip, imod; - int n; - - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ichip=arg[0]; - imod=arg[1]; - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod=0 && ichip=0) - ret=OK; - else - ret=FAIL; - - -#ifdef VERBOSE - printf("module number is %d,register is %d, nchan %d, nchip %d, ndac %d, nadc %d, gain %f, offset %f\n",myModule.module, myModule.reg, myModule.nchan, myModule.nchip, myModule.ndac, myModule.nadc, myModule.gain,myModule.offset); -#endif - - if (ret==OK) { - if (myModule.module>=getNModBoard()) { - ret=FAIL; - printf("Module number is too large %d\n",myModule.module); - } - if (myModule.module<0) - myModule.module=ALLMOD; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef MCB_FUNCS - retval=initModulebyNumber(myModule); -#endif - } - } - - if (differentClients==1 && ret==OK) - ret=FORCE_UPDATE; - - /* Maybe this is done inside the initialization funcs */ - //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - free(myChip); - free(myChan); - free(myDac); - free(myAdc); - - // setDynamicRange(dr); always 16 commented out - - - return ret; -} - - - - -int get_module(int file_des) { - - - int ret=OK; - - - int arg; - int imod; - int n; - - - - sls_detector_module myModule; - int *myChip=malloc(NCHIP*sizeof(int)); - int *myChan=malloc(NCHIP*NCHAN*sizeof(int)); - int *myDac=malloc(NDAC*sizeof(int));/**dhanya*/ - int *myAdc=malloc(NADC*sizeof(int));/**dhanya*/ - - - if (myDac) - myModule.dacs=myDac; - else { - sprintf(mess,"could not allocate dacs\n"); - ret=FAIL; - } - if (myAdc) - myModule.adcs=myAdc; - else { - sprintf(mess,"could not allocate adcs\n"); - ret=FAIL; - } - if (myChip) - myModule.chipregs=myChip; - else { - sprintf(mess,"could not allocate chips\n"); - ret=FAIL; - } - if (myChan) - myModule.chanregs=myChan; - else { - sprintf(mess,"could not allocate chans\n"); - ret=FAIL; - } - - myModule.ndac=NDAC; - myModule.nchip=NCHIP; - myModule.nchan=NCHAN*NCHIP; - myModule.nadc=NADC; - - - - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - imod=arg; - - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod-2) { - dataret=FAIL; - sprintf(mess,"no data and run stopped: %d frames left\n",(int)(getFrames()+2)); - printf("%s\n",mess); - } else { - dataret=FINISHED; - sprintf(mess,"acquisition successfully finished\n"); - printf("%s\n",mess); - } -#ifdef VERYVERBOSE - printf("%d %d %x %s\n",(int)(sizeof(mess)),(int)(strlen(mess)),(unsigned int)( mess),mess); -#endif - sendDataOnly(file_des,&dataret,sizeof(dataret)); - sendDataOnly(file_des,mess,sizeof(mess)); -#ifdef VERYVERBOSE - printf("message sent %s\n",mess); -#endif - printf("dataret %d\n",dataret); - return dataret; - } - } else { - nframes=0; - while(fifo_read_event()) { - nframes++; - } - dataretval=(char*)ram_values; - dataret=OK; -#ifdef VERBOSE - printf("sending data of %d frames\n",nframes); -#endif - for (iframes=0; iframes-2) { - dataret=FAIL; - sprintf(mess,"no data and run stopped: %d frames left\n",(int)(getFrames()+2)); - printf("%s\n",mess); - } else { - dataret=FINISHED; - sprintf(mess,"acquisition successfully finished\n"); - printf("%s\n",mess); - if (differentClients) - dataret=FORCE_UPDATE; - } -#ifdef VERBOSE - printf("Frames left %d\n",(int)(getFrames())); -#endif - sendDataOnly(file_des,&dataret,sizeof(dataret)); - sendDataOnly(file_des,mess,sizeof(mess)); - printf("dataret %d\n",dataret); - return dataret; - } - printf("dataret %d\n",dataret); - return dataret; -} - - - - - - - - -int read_all(int file_des) { - -while(read_frame(file_des)==OK) { - -#ifdef VERBOSE - printf("frame read\n"); -#endif - ; - } -#ifdef VERBOSE - printf("Frames finished\n"); -#endif - return OK; - - -} - -int start_and_read_all(int file_des) { - //int dataret=OK; -#ifdef VERBOSE - printf("Starting and reading all frames\n"); -#endif - - if (differentClients==1 && lockStatus==1) { - dataret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - sendDataOnly(file_des,&dataret,sizeof(dataret)); - sendDataOnly(file_des,mess,sizeof(mess)); - return dataret; - - } - - startStateMachine(); - - /* ret=startStateMachine(); - if (ret!=OK) { - sprintf(mess,"could not start state machine\n"); - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); - - #ifdef VERBOSE - printf("could not start state machine\n"); -#endif -} else {*/ - read_all(file_des); -#ifdef VERBOSE - printf("Frames finished\n"); -#endif - //} - - - return OK; - - -} - -int set_timer(int file_des) { - enum timerIndex ind; - int64_t tns; - int n; - int64_t retval; - int ret=OK; - - - sprintf(mess,"can't set timer\n"); - - n = receiveDataOnly(file_des,&ind,sizeof(ind)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,&tns,sizeof(tns)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret!=OK) { - printf(mess); - } - -#ifdef VERBOSE - printf("setting timer %d to %lld ns\n",ind,tns); -#endif - if (ret==OK) { - - if (differentClients==1 && lockStatus==1 && tns!=-1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - switch(ind) { - case FRAME_NUMBER: - retval=setFrames(tns); - break; - case ACQUISITION_TIME: - retval=setExposureTime(tns); - break; - case FRAME_PERIOD: - retval=setPeriod(tns); - break; - case DELAY_AFTER_TRIGGER: - retval=setDelay(tns); - break; - case GATES_NUMBER: - retval=setGates(tns); - break; - case PROBES_NUMBER: - sprintf(mess,"can't set timer for moench\n"); - ret=FAIL; - break; - case CYCLES_NUMBER: - retval=setTrains(tns); - break; - default: - ret=FAIL; - sprintf(mess,"timer index unknown %d\n",ind); - break; - } - } - } - if (ret!=OK) { - printf(mess); - if (differentClients) - ret=FORCE_UPDATE; - } - - if (ret!=OK) { - printf(mess); - printf("set timer failed\n"); - } else if (ind==FRAME_NUMBER) { - ret=allocateRAM(); - if (ret!=OK) - sprintf(mess, "could not allocate RAM for %lld frames\n", tns); - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { -#ifdef VERBOSE - printf("returning ok %d\n",(int)(sizeof(retval))); -#endif - - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - - return ret; - -} - - - - - - - - -int get_time_left(int file_des) { - - enum timerIndex ind; - int n; - int64_t retval; - int ret=OK; - - sprintf(mess,"can't get timer\n"); - n = receiveDataOnly(file_des,&ind,sizeof(ind)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - - //#ifdef VERBOSE - - printf("getting time left on timer %d \n",ind); - //#endif - - if (ret==OK) { - switch(ind) { - case FRAME_NUMBER: - printf("getting frames \n"); - retval=getFrames(); - break; - case ACQUISITION_TIME: - retval=getExposureTime(); - break; - case FRAME_PERIOD: - retval=getPeriod(); - break; - case DELAY_AFTER_TRIGGER: - retval=getDelay(); - break; - case GATES_NUMBER: - retval=getGates(); - break; - case PROBES_NUMBER: - retval=getProbes(); - break; - case CYCLES_NUMBER: - retval=getTrains(); - break; - case PROGRESS: - retval=getProgress(); - break; - case ACTUAL_TIME: - retval=getActualTime(); - break; - case MEASUREMENT_TIME: - retval=getMeasurementTime(); - break; - default: - ret=FAIL; - sprintf(mess,"timer index unknown %d\n",ind); - break; - } - } - - - if (ret!=OK) { - printf("get time left failed\n"); - } else if (differentClients) - ret=FORCE_UPDATE; - - //#ifdef VERBOSE - - printf("time left on timer %d is %lld\n",ind, retval); - //#endif - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=OK) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } -#ifdef VERBOSE - - printf("data sent\n"); -#endif - - return ret; - - -} - -int set_dynamic_range(int file_des) { - - - - int dr; - int n; - int retval; - int ret=OK; - - - sprintf(mess,"can't set dynamic range\n"); - - - n = receiveDataOnly(file_des,&dr,sizeof(dr)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - - if (differentClients==1 && lockStatus==1 && dr>=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=setDynamicRange(dr); - } - - //if (dr>=0 && retval!=dr) ret=FAIL; - if (ret!=OK) { - sprintf(mess,"set dynamic range failed\n"); - } else { - ret=allocateRAM(); - if (ret!=OK) - sprintf(mess,"Could not allocate RAM for the dynamic range selected\n"); - else if (differentClients) - ret=FORCE_UPDATE; - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - -int set_roi(int file_des) { - - int i; - int ret=OK; - int nroi=-1; - int n=0; - int retvalsize=0; - ROI arg[MAX_ROIS]; - ROI* retval=0; - - strcpy(mess,"Could not set/get roi\n"); - - - n = receiveDataOnly(file_des,&nroi,sizeof(nroi)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if(nroi!=-1){ - n = receiveDataOnly(file_des,arg,nroi*sizeof(ROI)); - if (n != (nroi*sizeof(ROI))) { - sprintf(mess,"Received wrong number of bytes for ROI\n"); - ret=FAIL; - } -//#ifdef VERBOSE - /* - printf("Setting ROI to:"); - for( i=0;i=0) { - if (differentClients==1 && lockStatus==1 && val>=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - switch (arg) { - case CLOCK_DIVIDER: - retval=setClockDivider(val); - break; - - case PHASE_SHIFT: - retval=phaseStep(val); - break; - - case OVERSAMPLING: - retval=setOversampling(val); - break; - - default: - ret=FAIL; - sprintf(mess,"Unknown speed parameter %d",arg); - } - } - } - - - switch (arg) { - case CLOCK_DIVIDER: - retval=getClockDivider(); - break; - - case PHASE_SHIFT: - retval=phaseStep(-1); - break; - - case OVERSAMPLING: - retval=setOversampling(-1); - break; - - default: - ret=FAIL; - sprintf(mess,"Unknown speed parameter %d",arg); - } - } - - - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - - - -int set_readout_flags(int file_des) { - - enum readOutFlags arg; - int n; - int ret=FAIL; - - - receiveDataOnly(file_des,&arg,sizeof(arg)); - - sprintf(mess,"can't set readout flags for moench\n"); - - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); - - return ret; -} - - - - - -int execute_trimming(int file_des) { - - int arg[3]; - int ret=FAIL; - enum trimMode mode; - - sprintf(mess,"can't set execute trimming for moench\n"); - - receiveDataOnly(file_des,&mode,sizeof(mode)); - receiveDataOnly(file_des,arg,sizeof(arg)); - - - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); - - return ret; -} - - -int lock_server(int file_des) { - - - int n; - int ret=OK; - - int lock; - n = receiveDataOnly(file_des,&lock,sizeof(lock)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (lock)\n"); - ret=FAIL; - } - if (lock>=0) { - if (lockStatus==0 || strcmp(lastClientIP,thisClientIP)==0 || strcmp(lastClientIP,"none")==0) - lockStatus=lock; - else { - ret=FAIL; - sprintf(mess,"Server already locked by %s\n", lastClientIP); - } - } - if (differentClients && ret==OK) - ret=FORCE_UPDATE; - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else - n = sendDataOnly(file_des,&lockStatus,sizeof(lockStatus)); - - return ret; - -} - -int set_port(int file_des) { - int n; - int ret=OK; - int sd=-1; - - enum portType p_type; /** data? control? stop? Unused! */ - int p_number; /** new port number */ - - n = receiveDataOnly(file_des,&p_type,sizeof(p_type)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (ptype)\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,&p_number,sizeof(p_number)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (pnum)\n"); - ret=FAIL; - } - if (differentClients==1 && lockStatus==1 ) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - if (p_number<1024) { - sprintf(mess,"Too low port number %d\n", p_number); - printf("\n"); - ret=FAIL; - } - - printf("set port %d to %d\n",p_type, p_number); - - sd=bindSocket(p_number); - } - if (sd>=0) { - ret=OK; - if (differentClients ) - ret=FORCE_UPDATE; - } else { - ret=FAIL; - sprintf(mess,"Could not bind port %d\n", p_number); - printf("Could not bind port %d\n", p_number); - if (sd==-10) { - sprintf(mess,"Port %d already set\n", p_number); - printf("Port %d already set\n", p_number); - - } - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&p_number,sizeof(p_number)); - closeConnection(file_des); - exitServer(sockfd); - sockfd=sd; - - } - - return ret; - -} - -int get_last_client_ip(int file_des) { - int ret=OK; - int n; - if (differentClients ) - ret=FORCE_UPDATE; - n = sendDataOnly(file_des,&ret,sizeof(ret)); - n = sendDataOnly(file_des,lastClientIP,sizeof(lastClientIP)); - - return ret; - -} - - -int send_update(int file_des) { - - int ret=OK; - enum detectorSettings t; - int n;//int thr, n; - //int it; - int64_t retval, tns=-1; - n = sendDataOnly(file_des,lastClientIP,sizeof(lastClientIP)); - n = sendDataOnly(file_des,&nModX,sizeof(nModX)); - n = sendDataOnly(file_des,&nModY,sizeof(nModY)); - n = sendDataOnly(file_des,&dynamicRange,sizeof(dynamicRange)); - n = sendDataOnly(file_des,&dataBytes,sizeof(dataBytes)); - t=setSettings(GET_SETTINGS,-1); - n = sendDataOnly(file_des,&t,sizeof(t)); -/* thr=getThresholdEnergy(); - n = sendDataOnly(file_des,&thr,sizeof(thr));*/ - retval=setFrames(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setExposureTime(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setPeriod(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setDelay(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setGates(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); -/* retval=setProbes(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t));*/ - retval=setTrains(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - - if (lockStatus==0) { - strcpy(lastClientIP,thisClientIP); - } - - return ret; - - -} -int update_client(int file_des) { - - int ret=OK; - - sendDataOnly(file_des,&ret,sizeof(ret)); - return send_update(file_des); - - - -} - - -int configure_mac(int file_des) { - - int ret=OK; - char arg[6][50]; - int n; - - int imod=0;//should be in future sent from client as -1, arg[2] - int ipad; - long long int imacadd; - long long int idetectormacadd; - int udpport; - int detipad; - int retval=-100; - - sprintf(mess,"Can't configure MAC\n"); - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - sscanf(arg[0], "%x", &ipad); - sscanf(arg[1], "%llx", &imacadd); - sscanf(arg[2], "%x", &udpport); - sscanf(arg[3], "%llx", &idetectormacadd); - sscanf(arg[4], "%x", &detipad); -//arg[5] is for eiger -#ifdef VERBOSE - int i; - printf("\ndigital_test_bit in server %d\t",digitalTestBit); - printf("\nipadd %x\t",ipad); - printf("destination ip is %d.%d.%d.%d = 0x%x \n",(ipad>>24)&0xff,(ipad>>16)&0xff,(ipad>>8)&0xff,(ipad)&0xff,ipad); - printf("macad:%llx\n",imacadd); - for (i=0;i<6;i++) - printf("mac adress %d is 0x%x \n",6-i,(unsigned int)(((imacadd>>(8*i))&0xFF))); - printf("udp port:0x%x\n",udpport); - printf("detector macad:%llx\n",idetectormacadd); - for (i=0;i<6;i++) - printf("detector mac adress %d is 0x%x \n",6-i,(unsigned int)(((idetectormacadd>>(8*i))&0xFF))); - printf("detipad %x\n",detipad); - printf("\n"); -#endif - - - - if (imod>=getNModBoard()) - ret=FAIL; - if (imod<0) - imod=ALLMOD; - - //#ifdef VERBOSE - printf("Configuring MAC of module %d at port %x\n", imod, udpport); - //#endif -#ifdef MCB_FUNCS - if (ret==OK){ - if(runBusy()){ - ret=stopStateMachine(); - if(ret==FAIL) - strcpy(mess,"could not stop detector acquisition to configure mac"); - } - - if(ret==OK) - configureMAC(ipad,imacadd,idetectormacadd,detipad,digitalTestBit,udpport); - retval=getAdcConfigured(); - } -#endif - if (ret==FAIL) - printf("configuring MAC of mod %d failed\n", imod); - else - printf("Configuremac successful of mod %d and adc %d\n",imod,retval); - - if (differentClients) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval,sizeof(retval)); - /*return ok/fail*/ - return ret; - -} - - - -int load_image(int file_des) { - int retval; - int ret=OK; - int n; - enum imageType index; - short int ImageVals[NCHAN*NCHIP]; - - sprintf(mess,"Loading image failed\n"); - - n = receiveDataOnly(file_des,&index,sizeof(index)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,ImageVals,dataBytes); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - switch (index) { - case DARK_IMAGE : -#ifdef VERBOSE - printf("Loading Dark image\n"); -#endif - break; - case GAIN_IMAGE : -#ifdef VERBOSE - printf("Loading Gain image\n"); -#endif - break; - default: - printf("Unknown index %d\n",index); - sprintf(mess,"Unknown index %d\n",index); - ret=FAIL; - break; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else{ - retval=loadImage(index,ImageVals); - if (retval==-1) - ret = FAIL; - } - } - - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; -} - - - -int set_master(int file_des) { - - enum masterFlags retval=GET_MASTER; - enum masterFlags arg; - int n; - int ret=OK; - // int regret=OK; - - - sprintf(mess,"can't set master flags\n"); - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - -#ifdef VERBOSE - printf("setting master flags to %d\n",arg); -#endif - - if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=setMaster(arg); - - } - if (retval==GET_MASTER) { - ret=FAIL; - } - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - - - - - - -int set_synchronization(int file_des) { - - enum synchronizationMode retval=GET_MASTER; - enum synchronizationMode arg; - int n; - int ret=OK; - //int regret=OK; - - - sprintf(mess,"can't set synchronization mode\n"); - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } -#ifdef VERBOSE - printf("setting master flags to %d\n",arg); -#endif - - if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - //ret=setStoreInRAM(0); - // initChipWithProbes(0,0,0, ALLMOD); - retval=setSynchronization(arg); - } - if (retval==GET_SYNCHRONIZATION_MODE) { - ret=FAIL; - } - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - - - - - - -int read_counter_block(int file_des) { - - int ret=OK; - int n; - int startACQ; - //char *retval=NULL; - short int CounterVals[NCHAN*NCHIP]; - - sprintf(mess,"Read counter block failed\n"); - - n = receiveDataOnly(file_des,&startACQ,sizeof(startACQ)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else{ - ret=readCounterBlock(startACQ,CounterVals); -#ifdef VERBOSE - int i; - for(i=0;i<6;i++) - printf("%d:%d\t",i,CounterVals[i]); -#endif - } - } - - if(ret!=FAIL){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,CounterVals,dataBytes);//1280*2 - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; -} - - - - - -int reset_counter_block(int file_des) { - - int ret=OK; - int n; - int startACQ; - - sprintf(mess,"Reset counter block failed\n"); - - n = receiveDataOnly(file_des,&startACQ,sizeof(startACQ)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else - ret=resetCounterBlock(startACQ); - } - - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - - /*return ok/fail*/ - return ret; -} - - - - - - -int start_receiver(int file_des) { - int ret=OK; - int n=0; - strcpy(mess,"Could not start receiver\n"); - - /* execute action if the arguments correctly arrived*/ -#ifdef MCB_FUNCS - if (lockStatus==1 && differentClients==1){//necessary??? - sprintf(mess,"Detector locked by %s\n", lastClientIP); - ret=FAIL; - } - else - ret = startReceiver(1); - -#endif - - - if(ret==OK && differentClients){ - printf("Force update\n"); - ret=FORCE_UPDATE; - } - - /* send answer */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if(ret==FAIL) - n = sendDataOnly(file_des,mess,sizeof(mess)); - /*return ok/fail*/ - return ret; -} - - - - - - -int stop_receiver(int file_des) { - int ret=OK; - int n=0; - - strcpy(mess,"Could not stop receiver\n"); - - /* execute action if the arguments correctly arrived*/ -#ifdef MCB_FUNCS - if (lockStatus==1 && differentClients==1){//necessary??? - sprintf(mess,"Detector locked by %s\n", lastClientIP); - ret=FAIL; - } - else - ret=startReceiver(0); - -#endif - - - if(ret==OK && differentClients){ - printf("Force update\n"); - ret=FORCE_UPDATE; - } - - /* send answer */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if(ret==FAIL) - n = sendDataOnly(file_des,mess,sizeof(mess)); - /*return ok/fail*/ - return ret; -} - - - - - -int calibrate_pedestal(int file_des){ - - int ret=OK; - int retval=-1; - int n; - int frames; - - sprintf(mess,"Could not calibrate pedestal\n"); - - n = receiveDataOnly(file_des,&frames,sizeof(frames)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else - ret=calibratePedestal(frames); - } - - if(ret==OK){ - if (differentClients) - ret=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval,sizeof(retval)); - - /*return ok/fail*/ - return ret; -} - - diff --git a/slsDetectorSoftware/moenchDetectorServer/server_funcs.h b/slsDetectorSoftware/moenchDetectorServer/server_funcs.h deleted file mode 100755 index 890c7452d..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/server_funcs.h +++ /dev/null @@ -1,97 +0,0 @@ -#ifndef SERVER_FUNCS_H -#define SERVER_FUNCS_H - - -#include "sls_detector_defs.h" - - -#include -/* -#include -#include -#include -*/ -#include "communication_funcs.h" - - - - -#define GOODBYE -200 - -int sockfd; - -int function_table(); - -int decode_function(int); -int init_detector(int); - -int M_nofunc(int); -int exit_server(int); - - - - -// General purpose functions -int get_detector_type(int); -int set_number_of_modules(int); -int get_max_number_of_modules(int); - - -int exec_command(int); -int set_external_signal_flag(int); -int set_external_communication_mode(int); -int get_id(int); -int digital_test(int); -int write_register(int); -int read_register(int); -int set_dac(int); -int get_adc(int); -int set_channel(int); -int set_chip(int); -int set_module(int); -int get_channel(int); -int get_chip(int); -int get_module(int); - -int get_threshold_energy(int); -int set_threshold_energy(int); -int set_settings(int); -int start_acquisition(int); -int stop_acquisition(int); -int start_readout(int); -int get_run_status(int); -int read_frame(int); -int read_all(int); -int start_and_read_all(int); -int set_timer(int); -int get_time_left(int); -int set_dynamic_range(int); -int set_roi(int); -int get_roi(int); -int set_speed(int); -void prepareADC(void); -int set_readout_flags(int); -int execute_trimming(int); -int lock_server(int); -int set_port(int); -int get_last_client_ip(int); -int set_master(int); -int set_synchronization(int); - -int update_client(int); -int send_update(int); -int configure_mac(int); - -int load_image(int); -int read_counter_block(int); -int reset_counter_block(int); - -int start_receiver(int); -int stop_receiver(int); - - -int calibrate_pedestal(int); - -int set_roi(int); - -#endif diff --git a/slsDetectorSoftware/moenchDetectorServer/sharedmemory.c b/slsDetectorSoftware/moenchDetectorServer/sharedmemory.c deleted file mode 100755 index 4504cfe05..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/sharedmemory.c +++ /dev/null @@ -1,39 +0,0 @@ -#include "sharedmemory.h" - -struct statusdata *stdata; - -int inism(int clsv) { - -static int scansmid; - - if (clsv==SMSV) { - if ( (scansmid=shmget(SMKEY,1024,IPC_CREAT | 0666 ))==-1 ) { - return -1; - } - if ( (stdata=shmat(scansmid,NULL,0))==(void*)-1) { - return -2; - } - } - - if (clsv==SMCL) { - if ( (scansmid=shmget(SMKEY,0,0) )==-1 ) { - return -3; - } - if ( (stdata=shmat(scansmid,NULL,0))==(void*)-1) { - return -4; - } - } - return 1; -} - -void write_status_sm(char *status) { - strcpy(stdata->status,status); -} - -void write_stop_sm(int v) { - stdata->stop=v; -} - -void write_runnumber_sm(int v) { - stdata->runnumber=v; -} diff --git a/slsDetectorSoftware/moenchDetectorServer/sharedmemory.h b/slsDetectorSoftware/moenchDetectorServer/sharedmemory.h deleted file mode 100755 index bdbddf719..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/sharedmemory.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef SM -#define SM - -#include "sls_detector_defs.h" - -#include -#include -#include -#include -#include -#include -#include -//#include -#include -#include -#include -#include -#include -#include - - -#include - -#include -#include - -/* key for shared memory */ -#define SMKEY 10001 - -#define SMSV 1 -#define SMCL 2 - - -struct statusdata { - int runnumber; - int stop; - char status[20]; -} ; - - -/* for shared memory */ - -int inism(int clsv); -void write_status_sm(char *status); -void write_stop_sm(int v); -void write_runnumber_sm(int v); - -#endif diff --git a/slsDetectorSoftware/moenchDetectorServer/sls_detector_defs.h b/slsDetectorSoftware/moenchDetectorServer/sls_detector_defs.h deleted file mode 120000 index c5062e03f..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/sls_detector_defs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/moenchDetectorServer/sls_detector_funcs.h b/slsDetectorSoftware/moenchDetectorServer/sls_detector_funcs.h deleted file mode 120000 index 844b67129..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/sls_detector_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/moenchDetectorServer/sls_receiver_defs.h b/slsDetectorSoftware/moenchDetectorServer/sls_receiver_defs.h deleted file mode 120000 index 1de31caf5..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/sls_receiver_defs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/moenchDetectorServer/sls_receiver_funcs.h b/slsDetectorSoftware/moenchDetectorServer/sls_receiver_funcs.h deleted file mode 120000 index c2ea4ded9..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/sls_receiver_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/moenchDetectorServer/stop_server.c b/slsDetectorSoftware/moenchDetectorServer/stop_server.c deleted file mode 100755 index e3c8ff7e1..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/stop_server.c +++ /dev/null @@ -1,46 +0,0 @@ -/* A simple server in the internet domain using TCP - The port number is passed as an argument */ - - -#include "sls_detector_defs.h" - - -#include "communication_funcs.h" -#include "firmware_funcs.h" - - -int sockfd; - -int main(int argc, char *argv[]) -{ - int portno; - int retval=0; - - portno = DEFAULT_PORTNO; - - - bindSocket(portno); - if (getServerError()) - return -1; - - - - /* waits for connection */ - while(retval!=GOODBYE) { -#ifdef VERBOSE - printf("\n"); -#endif -#ifdef VERY_VERBOSE - printf("Stop server: waiting for client call\n"); -#endif - acceptConnection(); - retval=stopStateMachine(); - closeConnection(); - } - - exitServer(); - printf("Goodbye!\n"); - - return 0; -} - diff --git a/slsDetectorSoftware/moenchDetectorServer/trimming_funcs.c b/slsDetectorSoftware/moenchDetectorServer/trimming_funcs.c deleted file mode 100755 index 9a28b9b4a..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/trimming_funcs.c +++ /dev/null @@ -1,749 +0,0 @@ -#ifndef PICASSOD -#include "server_defs.h" -#else -#include "picasso_defs.h" -#endif -#include "trimming_funcs.h" -#include "mcb_funcs.h" -#include "firmware_funcs.h" -#include - - - -extern int nModX; -//extern int *values; - -extern const int nChans; -extern const int nChips; -extern const int nDacs; -extern const int nAdcs; - - -int trim_fixed_settings(int countlim, int par2, int im) -{ - - int retval=OK; -#ifdef VERBOSE - printf("Trimming with fixed settings\n"); -#endif -#ifdef VIRTUAL - return OK; -#endif - - if (par2<=0) - retval=trim_with_level(countlim, im); - else - retval=trim_with_median(countlim,im); - - - return retval; -} - - -int trim_with_noise(int countlim, int nsigma, int im) -{ - - - int retval=OK, retval1=OK, retval2=OK; -#ifdef VERBOSE - printf("Trimming using noise\n"); -#endif -#ifdef VIRTUAL - return OK; -#endif - - /* threshold scan */ - -#ifdef VERBOSE - printf("chosing vthresh and vtrim....."); -#endif - retval1=choose_vthresh_and_vtrim(countlim,nsigma, im); - -#ifdef VERBOSE - printf("trimming with noise.....\n"); -#endif - retval2=trim_with_level(countlim, im); - -#ifdef DEBUGOUT - printf("done\n"); -#endif - if (retval1==OK && retval2==OK) - retval=OK; - else - retval=FAIL; - - return retval; - -} - -int trim_with_beam(int countlim, int nsigma, int im) //rpc -{ - - - int retval=OK, retval1=OK, retval2=OK; - - printf("Trimming using beam\n"); - //return OK; -#ifdef VIRTUAL - printf("Trimming using beam\n"); - return OK; -#endif - /* threshold scan */ -#ifdef DEBUGOUT - printf("chosing vthresh and vtrim....."); -#endif - - retval1=choose_vthresh_and_vtrim(countlim,nsigma,im); - retval2=trim_with_median(TRIM_DR, im); - -#ifdef DEBUGOUT - printf("done\n"); -#endif - - if (retval1==OK && retval2==OK) - retval=OK; - else - retval=FAIL; - - return retval; - -} - - -int trim_improve(int maxit, int par2, int im) //rpc -{ - - int retval=OK, retval1=OK, retval2=OK; - - -#ifdef VERBOSE - printf("Improve the trimming\n"); -#endif -#ifdef VIRTUAL - return OK; -#endif - - - if (par2!=0 && im==ALLMOD) - retval1=choose_vthresh(); - - retval2=trim_with_median(2*maxit+1, im); -#ifdef DEBUGOUT - printf("done\n"); -#endif - if (retval1==OK && retval2==OK) - retval=OK; - else - retval=FAIL; - - return retval; - -} - -int calcthr_from_vcal(int vcal) { - int thrmin; - //thrmin=140+3*vcal/5; - thrmin=180+3*vcal/5; - return thrmin; -} - -int calccal_from_vthr(int vthr) { - int vcal; - vcal=5*(vthr-140)/3; - return vcal; -} - -int choose_vthresh_and_vtrim(int countlim, int nsigma, int im) { - int retval=OK; -#ifdef MCB_FUNCS - int modma, modmi, nm; - int thr, thrstep=5, nthr=31; - - int *fifodata; - - double vthreshmean, vthreshSTDev; - int *thrmi, *thrma; - double c; - double b=BVTRIM; - double a=AVTRIM; - int *trim; - int ich, imod, ichan; - int nvalid=0; - u_int32_t *scan; - int ithr; - sls_detector_channel myChan; - - - - setFrames(1); - // setNMod(getNModBoard()); - - if (im==ALLMOD){ - modmi=0; - modma=nModX; - } else { - modmi=im; - modma=im+1; - } - nm=modma-modmi; - - trim=malloc(sizeof(int)*nChans*nChips*nModX); - thrmi=malloc(sizeof(int)*nModX); - thrma=malloc(sizeof(int)*nModX); - - - for (ich=0; ichcountlim && trim[ich]==-1) { -//commented out by dhanya trim[ich]=getDACbyIndexDACU(VTHRESH,imod); -#ifdef VERBOSE - // printf("yes: %d %d %d\n",ich,ithr,scan[ich]); -#endif - } -#ifdef VERBOSE - /* else { - printf("no: %d %d %d\n",ich,ithr,scan[ich]); - }*/ -#endif - } - } - free(scan); - } - - for (imod=modmi; imodthrmi[imod] && trim[ich]0) { - vthreshmean=vthreshmean/nvalid; - //commented out by dhanya vthreshSTDev=sqrt((vthreshSTDev/nvalid)-vthreshmean*vthreshmean); - } else { - vthreshmean=thrmi[imod]; - vthreshSTDev=nthr*thrstep; - printf("No valid channel for module %d\n",imod); - retval=FAIL; - } - -#ifdef DEBUGOUT - printf("module= %d nvalid = %d mean=%f RMS=%f\n",imod, nvalid, vthreshmean,vthreshSTDev); -#endif - // *vthresh=round(vthreshmean-nsigma*vthreshSTDev); - thr=(int)(vthreshmean-nsigma*vthreshSTDev); - if (thr<0 || thr>(DAC_DR-1)) { - thr=thrmi[imod]/2; - printf("Can't find correct threshold for module %d\n",imod); - retval=FAIL; - } -//commented out by dhanya initDACbyIndexDACU(VTHRESH,thr,imod); -#ifdef VERBOSE - printf("vthresh=%d \n",thr); -#endif - c=CVTRIM-2.*nsigma*vthreshSTDev/63.; - //commented out by dhanya thr=(int)((-b-sqrt(b*b-4*a*c))/(2*a)); - if (thr<500 || thr>(DAC_DR-1)) { - thr=750; - printf("Can't find correct trimbit size for module %d\n",imod); - retval=FAIL; - } - - //commented out by dhanya initDACbyIndexDACU(VTRIM,thr,imod); - -#ifdef VERBOSE - printf("vtrim=%d \n",thr); -#endif - - } - free(trim); - free(thrmi); - free(thrma); - -#endif - return retval; -} - - - - - -int trim_with_level(int countlim, int im) { - int ich, itrim, ichan, ichip, imod; - u_int32_t *scan; - int *inttrim; - int modma, modmi, nm; - int retval=OK; - int *fifodata; - sls_detector_channel myChan; - printf("trimming module number %d", im); - - -#ifdef MCB_FUNCS - setFrames(1); - // setNMod(getNModBoard()); - - if (im==ALLMOD){ - modmi=0; - modma=nModX; - } else { - modmi=im; - modma=im+1; - } - nm=modma-modmi; - - inttrim=malloc(sizeof(int)*nChips*nChans*nModX); - printf("countlim=%d\n",countlim); - for (ich=0; ichcountlim){ - inttrim[ich]=itrim; - if (scan[ich]>2*countlim && itrim>0) { - //if (scan[ich]>2*countlim || itrim==0) { - inttrim[ich]=itrim-1; - } -#ifdef VERBOSE - printf("Channel %d trimbit %d counted %d (%08x) countlim %d\n",ich,itrim,scan[ich],fifodata[ich],countlim); -#endif - } - } -#ifdef VERBOSE - /* else - printf("Channel %d trimbit %d counted %d countlim %d\n",ich,itrim,scan[ich],countlim);*/ -#endif - } - } - free(scan); - } - - for (imod=modmi; imod0) - direction[ichan]=1; - else - direction[ichan]=-1; - } - //commented out by dhanya vthresh=getDACbyIndexDACU(VTHRESH,imod); - if ( direction[ichan]!=-3) { - if (abs(diff)>abs(olddiff[ichan])) { - vthresh=vthresh-direction[ichan]; - if (vthresh>(DAC_DR-1)) { - vthresh=(DAC_DR-1); - printf("can't equalize threshold for module %d\n", ichan); - retval=FAIL; - } - if (vthresh<0) { - vthresh=0; - printf("can't equalize threshold for module %d\n", ichan); - retval=FAIL; - } - direction[ichan]=-3; - } else { - vthresh=vthresh+direction[ichan]; - olddiff[ichan]=diff; - change_flag=1; - } -//commented out by dhanya initDACbyIndex(VTHRESH,vthresh, ichan); - } - } - iteration++; - free(scan); - free(scan1); - } -#endif - return retval; -} - - - - - -int trim_with_median(int stop, int im) { - - - int retval=OK; - -#ifdef MCB_FUNCS - int ichan, imod, ichip, ich; - u_int32_t *scan, *scan1; - int *olddiff, *direction; - int med, diff; - int change_flag=1; - int iteration=0; - int me[nModX], me1[nModX]; - int modma, modmi, nm; - int trim; - int *fifodata; - - setFrames(1); - // setNMod(getNModBoard()); - - if (im==ALLMOD){ - modmi=0; - modma=nModX; - } else { - modmi=im; - modma=im+1; - } - nm=modma-modmi; - - olddiff=malloc(4*nModX*nChips*nChans); - direction=malloc(4*nModX*nChips*nChans); - for (imod=modmi; imod0) { - direction[ichan]=1; - } else { - direction[ichan]=-1; - } - } - if ( direction[ichan]!=-3) { - if (abs(diff)>abs(olddiff[ichan])) { - trim=getTrimbit(imod,ichip,ich)+direction[ichan]; - printf("%d old diff %d < new diff %d %d - trimbit %d\n",ichan, olddiff[ichan], diff, direction[ichan], trim); - direction[ichan]=-3; - } else { - trim=getTrimbit(imod,ichip,ich)-direction[ichan]; - olddiff[ichan]=diff; - change_flag=1; - } - if (trim>TRIM_DR) { - trim=63; - printf("can't trim channel %d chip %d module %d to trim %d\n",ich, ichip, imod, trim); - retval=FAIL; - } - if (trim<0) { - printf("can't trim channel %d chip %d module %d to trim %d\n",ich, ichip, imod, trim); - trim=0; - retval=FAIL; - } - initChannel(trim,0,0,1,0,0,imod); - } - } - } - } - iteration++; - free(scan); - free(scan1); - } - free(olddiff); - free(direction); -#endif - return retval; -} diff --git a/slsDetectorSoftware/moenchDetectorServer/trimming_funcs.h b/slsDetectorSoftware/moenchDetectorServer/trimming_funcs.h deleted file mode 100755 index 42ecea24a..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/trimming_funcs.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef TRIMMING_FUNCS_H -#define TRIMMING_FUNCS_H - -#include "sls_detector_defs.h" - -int trim_fixed_settings(int countlim, int par2, int imod); -int trim_with_noise(int countlim, int nsigma, int imod); -int trim_with_beam(int countlim, int nsigma, int imod); -int trim_improve(int maxit, int par2, int imod); -int calcthr_from_vcal(int vcal); -int calccal_from_vthr(int vthr); -int choose_vthresh_and_vtrim(int countlim, int nsigma, int imod); - -int choose_vthresh(); -int trim_with_level(int countlim, int imod); -int trim_with_median(int stop, int imod); -int calcthr_from_vcal(int vcal); -int calccal_from_vthr(int vthr); - -#endif diff --git a/slsDetectorSoftware/moenchDetectorServer/updateGitVersion.sh b/slsDetectorSoftware/moenchDetectorServer/updateGitVersion.sh deleted file mode 100755 index cea04b2de..000000000 --- a/slsDetectorSoftware/moenchDetectorServer/updateGitVersion.sh +++ /dev/null @@ -1,31 +0,0 @@ -SERVER=moenchDetectorServer -MAINDIR=slsDetectorsPackage -SPECDIR=slsDetectorSoftware/$SERVER -TMPFILE=gitInfoMoenchTmp.h -INCLFILE=gitInfoMoench.h - - -#evaluate the variables -EVALFILE=../../evalVersionVariables.sh -source $EVALFILE - - -#get modified date -#RDATE1='git log --pretty=format:"%ci" -1' -RDATE1="find . -type f -exec stat --format '%Y :%y %n' '{}' \; | sort -nr | cut -d: -f2- | egrep -v 'gitInfo|.git|updateGitVersion|.o' | head -n 1" -RDATE=`eval $RDATE1` -NEWDATE=$(sed "s/-//g" <<< $RDATE | awk '{print $1;}') -NEWDATE=${NEWDATE/#/0x} - - -#get old date from INCLFILE -OLDDATE=$(more $INCLFILE | grep '#define GITDATE' | awk '{print $3}') - - -#update INCLFILE if changes -if [ "$OLDDATE" != "$NEWDATE" ]; then - echo Path: ${MAINDIR}/${SPECDIR} $'\n'URL: ${GITREPO} $'\n'Repository Root: ${GITREPO} $'\n'Repsitory UUID: ${REPUID} $'\n'Revision: ${FOLDERREV} $'\n'Branch: ${BRANCH} $'\n'Last Changed Author: ${AUTH1}_${AUTH2} $'\n'Last Changed Rev: ${REV} $'\n'Last Changed Date: ${RDATE} > gitInfo.txt - cd ../../ - ./genVersionHeader.sh $SPECDIR/gitInfo.txt $SPECDIR/$TMPFILE $SPECDIR/$INCLFILE - cd $WD -fi \ No newline at end of file diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp deleted file mode 100644 index 3bc97a112..000000000 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.cpp +++ /dev/null @@ -1,5442 +0,0 @@ -/******************************************************************* - -Date: $Date$ -Revision: $Rev$ -Author: $Author$ -URL: $URL$ -ID: $Id$ - - ********************************************************************/ - -#include "multiSlsDetector.h" -#include "SharedMemory.h" -#include "slsDetector.h" -#include "sls_receiver_exceptions.h" -#include "ThreadPool.h" -#include "ZmqSocket.h" -#include "multiSlsDetectorClient.h" -#include "multiSlsDetectorCommand.h" -#include "postProcessingFuncs.h" -#include "usersFunctions.h" - -#include -#include -#include -#include -#include //json header in zmq stream -#include -#include - - - -multiSlsDetector::multiSlsDetector(int id, bool verify, bool update) -: slsDetectorUtils(), - detId(id), - sharedMemory(0), - thisMultiDetector(0), - client_downstream(false), - threadpool(0) { - setupMultiDetector(verify, update); -} - - - -multiSlsDetector::~multiSlsDetector() { - // delete zmq sockets first - for (std::vector::const_iterator it = zmqSocket.begin(); it != zmqSocket.end(); ++it) { - delete(*it); - } - zmqSocket.clear(); - - for (std::vector::const_iterator it = detectors.begin(); it != detectors.end(); ++it) { - delete(*it); - } - detectors.clear(); - - if (sharedMemory) { - sharedMemory->UnmapSharedMemory(thisMultiDetector); - delete sharedMemory; - } - - destroyThreadPool(); -} - - -bool multiSlsDetector::isMultiSlsDetectorClass() { - return true; -} - -void multiSlsDetector::setupMultiDetector(bool verify, bool update) { - if (initSharedMemory(verify)) - // shared memory just created, so initialize the structure - initializeDetectorStructure(); - initializeMembers(verify); - if (update) - updateUserdetails(); -} - -std::string multiSlsDetector::concatResultOrPos(std::string (slsDetector::*somefunc)(int), int pos) { - if (pos >= 0 && pos < (int)detectors.size()) { - return (detectors[pos]->*somefunc)(pos); - } else { - std::string s; - for (unsigned int i = 0; i < detectors.size(); ++i) { - s += (detectors[i]->*somefunc)(pos) + "+"; - } - return s; - } -} - -template -T multiSlsDetector::callDetectorMember(T (slsDetector::*somefunc)()) -{ - //(Erik) to handle enums, probably a bad idea but follow previous code - T defaultValue = static_cast(-1); - std::vector values(detectors.size(), defaultValue); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - values[idet] = (detectors[idet]->*somefunc)(); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - return minusOneIfDifferent(values); -} - -std::string multiSlsDetector::callDetectorMember(std::string (slsDetector::*somefunc)()) { - std::string concatenatedValue, firstValue; - bool valueNotSame = false; - - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - std::string thisValue = (detectors[idet]->*somefunc)(); - ; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - - if (firstValue.empty()) { - concatenatedValue = thisValue; - firstValue = thisValue; - } else { - concatenatedValue += "+" + thisValue; - } - if (firstValue != thisValue) - valueNotSame = true; - } - if (valueNotSame) - return concatenatedValue; - else - return firstValue; -} - -template -T multiSlsDetector::callDetectorMember(T (slsDetector::*somefunc)(V), V value) { - //(Erik) to handle enums, probably a bad idea but follow previous code - T defaultValue = static_cast(-1); - std::vector values(detectors.size(), defaultValue); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - values[idet] = (detectors[idet]->*somefunc)(value); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - return minusOneIfDifferent(values); -} - -template -T multiSlsDetector::callDetectorMember(T (slsDetector::*somefunc)(P1, P2), - P1 par1, P2 par2) { - //(Erik) to handle enums, probably a bad idea but follow previous code - T defaultValue = static_cast(-1); - std::vector values(detectors.size(), defaultValue); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - values[idet] = (detectors[idet]->*somefunc)(par1, par2); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - return minusOneIfDifferent(values); -} - -template -T multiSlsDetector::parallelCallDetectorMember(T (slsDetector::*somefunc)()) { - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } else { - std::vector return_values(detectors.size(), -1); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - Task* task = new Task(new func0_t(somefunc, - detectors[idet], &return_values[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - return minusOneIfDifferent(return_values); - } -} - -template -T multiSlsDetector::parallelCallDetectorMember(T (slsDetector::*somefunc)(P1), - P1 value) { - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } else { - std::vector return_values(detectors.size(), -1); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - Task* task = new Task(new func1_t(somefunc, - detectors[idet], value, &return_values[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - return minusOneIfDifferent(return_values); - } -} - -template -T multiSlsDetector::parallelCallDetectorMember(T (slsDetector::*somefunc)(P1, P2), - P1 par1, P2 par2) { - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } else { - std::vector return_values(detectors.size(), -1); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - Task* task = new Task(new func2_t(somefunc, - detectors[idet], par1, par2, &return_values[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - return minusOneIfDifferent(return_values); - } -} - -int multiSlsDetector::parallelCallDetectorMember(int (slsDetector::*somefunc)(int, int, int), - int v0, int v1, int v2) { - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } else { - std::vector return_values(detectors.size(), -1); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - Task* task = new Task(new func3_t(somefunc, - detectors[idet], v0, v1, v2, &return_values[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - return minusOneIfDifferent(return_values); - } -} - -template -T multiSlsDetector::minusOneIfDifferent(const std::vector& return_values) { - T ret = static_cast(-100); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (ret == static_cast(-100)) - ret = return_values[idet]; - else if (ret != return_values[idet]) - ret = static_cast(-1); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - return ret; -} - - -int multiSlsDetector::decodeNMod(int i, int& id, int& im) { -#ifdef VERBOSE - cout << " Module " << i << " belongs to detector " << id << endl; - ; - cout << getMaxMods(); -#endif - - if (i < 0 || i >= getMaxMods()) { - id = -1; - im = -1; -#ifdef VERBOSE - cout << " A---------" << id << " position " << im << endl; -#endif - - return -1; - } - int nm; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - nm = detectors[idet]->getNMods(); - if (nm > i) { - id = idet; - im = i; -#ifdef VERBOSE - cout << " B---------" << id << " position " << im << endl; -#endif - return im; - } else { - i -= nm; - } - } - id = -1; - im = -1; -#ifdef VERBOSE - cout << " C---------" << id << " position " << im << endl; -#endif - return -1; -} - - -int multiSlsDetector::decodeNChannel(int offsetX, int offsetY, int& channelX, int& channelY) { - channelX = -1; - channelY = -1; - //loop over - for (unsigned int i = 0; i < detectors.size(); ++i) { - int x = detectors[i]->getDetectorOffset(X); - int y = detectors[i]->getDetectorOffset(Y); - //check x offset range - if ((offsetX >= x) && - (offsetX < (x + detectors[i]->getMaxNumberOfChannelsInclGapPixels(X)))) { - if (offsetY == -1) { - channelX = offsetX - x; - return i; - } else { - //check y offset range - if ((offsetY >= y) && - (offsetY < (y + detectors[i]->getMaxNumberOfChannelsInclGapPixels(Y)))) { - channelX = offsetX - x; - channelY = offsetY - y; - return i; - } - } - } - } - return -1; -} - - -double* multiSlsDetector::decodeData(int* datain, int& nn, double* fdata) { - double* dataout; - - if (fdata) - dataout = fdata; - else { - if (detectors[0]->getDetectorsType() == JUNGFRAUCTB) { - nn = thisMultiDetector->dataBytes / 2; - dataout = new double[nn]; - } else { - nn = thisMultiDetector->numberOfChannels; - dataout = new double[nn]; - } - } - - int n; - double* detp = dataout; - int* datap = datain; - - for (unsigned int i = 0; i < detectors.size(); ++i) { - detectors[i]->decodeData(datap, n, detp); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); -#ifdef VERBOSE - cout << "increment pointers " << endl; -#endif - datap += detectors[i]->getDataBytes() / sizeof(int); - detp += n; -#ifdef VERBOSE - cout << "done " << endl; -#endif - } - - return dataout; -} - - - -int multiSlsDetector::writeDataFile(std::string fname, double* data, double* err, - double* ang, char dataformat, int nch) { -#ifdef VERBOSE - cout << "using overloaded multiSlsDetector function to write formatted data file " - << getTotalNumberOfChannels() << endl; -#endif - - std::ofstream outfile; - int choff = 0, off = 0; //idata, - double *pe = err, *pa = ang; - int nch_left = nch, n; //, nd; - - if (nch_left <= 0) - nch_left = getTotalNumberOfChannels(); - - if (data == NULL) - return FAIL; - - outfile.open(fname.c_str(), std::ios_base::out); - if (outfile.is_open()) { - - for (unsigned int i = 0; i < detectors.size(); ++i) { - n = detectors[i]->getTotalNumberOfChannels(); - if (nch_left < n) - n = nch_left; -#ifdef VERBOSE - cout << " write " << i << " position " << off << " offset " << choff << endl; -#endif - fileIOStatic::writeDataFile(outfile, n, data + off, pe, pa, dataformat, choff); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - - nch_left -= n; - - choff += detectors[i]->getMaxNumberOfChannels(); - - off += n; - - if (pe) - pe = err + off; - - if (pa) - pa = ang + off; - } - outfile.close(); - return OK; - } else { - std::cout << "Could not open file " << fname << "for writing" << std::endl; - return FAIL; - } -} - -int multiSlsDetector::writeDataFile(std::string fname, int* data) { - std::ofstream outfile; - int choff = 0, off = 0; -#ifdef VERBOSE - cout << "using overloaded multiSlsDetector function to write raw data file " << endl; -#endif - - if (data == NULL) - return FAIL; - - outfile.open(fname.c_str(), std::ios_base::out); - if (outfile.is_open()) { - for (unsigned int i = 0; i < detectors.size(); ++i) { -#ifdef VERBOSE - cout << " write " << i << " position " << off << " offset " << choff << endl; -#endif - detectors[i]->writeDataFile(outfile, - detectors[i]->getTotalNumberOfChannels(), data + off, choff); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - choff += detectors[i]->getMaxNumberOfChannels(); - off += detectors[i]->getTotalNumberOfChannels(); - } - outfile.close(); - return OK; - } else { - std::cout << "Could not open file " << fname << "for writing" << std::endl; - return FAIL; - } -} - -int multiSlsDetector::readDataFile(std::string fname, double* data, double* err, - double* ang, char dataformat) { -#ifdef VERBOSE - cout << "using overloaded multiSlsDetector function to read formatted data file " << endl; -#endif - - std::ifstream infile; - int iline = 0; - std::string str; - int choff = 0, off = 0; - double *pe = err, *pa = ang; - -#ifdef VERBOSE - std::cout << "Opening file " << fname << std::endl; -#endif - infile.open(fname.c_str(), std::ios_base::in); - if (infile.is_open()) { - - for (unsigned int i = 0; i < detectors.size(); ++i) { - iline += detectors[i]->readDataFile(detectors[i]->getTotalNumberOfChannels(), - infile, data + off, pe, pa, dataformat, choff); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - choff += detectors[i]->getMaxNumberOfChannels(); - off += detectors[i]->getTotalNumberOfChannels(); - if (pe) - pe = pe + off; - if (pa) - pa = pa + off; - } - - infile.close(); - } else { - std::cout << "Could not read file " << fname << std::endl; - return -1; - } - return iline; -} - -int multiSlsDetector::readDataFile(std::string fname, int* data) { -#ifdef VERBOSE - cout << "using overloaded multiSlsDetector function to read raw data file " << endl; -#endif - std::ifstream infile; - int iline = 0; - std::string str; - int choff = 0, off = 0; - -#ifdef VERBOSE - std::cout << "Opening file " << fname << std::endl; -#endif - infile.open(fname.c_str(), std::ios_base::in); - if (infile.is_open()) { - - for (unsigned int i = 0; i < detectors.size(); ++i) { - iline += detectors[i]->readDataFile(infile, data + off, - detectors[i]->getTotalNumberOfChannels(), choff); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - choff += detectors[i]->getMaxNumberOfChannels(); - off += detectors[i]->getTotalNumberOfChannels(); - } - infile.close(); - } else { - std::cout << "Could not read file " << fname << std::endl; - return -1; - } - return iline; -} - - -std::string multiSlsDetector::getErrorMessage(int& critical) { - int64_t multiMask, slsMask = 0; - std::string retval = ""; - char sNumber[100]; - critical = 0; - - multiMask = getErrorMask(); - if (multiMask) { - if (multiMask & MULTI_DETECTORS_NOT_ADDED) { - retval.append("Detectors not added:\n" + std::string(getNotAddedList()) + - std::string("\n")); - critical = 1; - } - if (multiMask & MULTI_HAVE_DIFFERENT_VALUES) { - retval.append("A previous multi detector command gave different values\n" - "Please check the console\n"); - critical = 0; - } - if (multiMask & MULTI_CONFIG_FILE_ERROR) { - retval.append("Could not load Config File\n"); - critical = 0; - } - - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - //if the detector has error - if (multiMask & (1 << idet)) { - //append detector id - sprintf(sNumber, "%d", idet); - retval.append("Detector " + std::string(sNumber) + std::string(":\n")); - //get sls det error mask - slsMask = detectors[idet]->getErrorMask(); -#ifdef VERYVERBOSE - //append sls det error mask - sprintf(sNumber, "0x%lx", slsMask); - retval.append("Error Mask " + std::string(sNumber) + std::string("\n")); -#endif - //get the error critical level - if ((slsMask > 0xFFFFFFFF) | critical) - critical = 1; - //append error message - retval.append(errorDefs::getErrorMessage(slsMask)); - } - } - } - return retval; -} - -int64_t multiSlsDetector::clearAllErrorMask() { - clearErrorMask(); - clearNotAddedList(); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) - detectors[idet]->clearErrorMask(); - - return getErrorMask(); -} - -void multiSlsDetector::setErrorMaskFromAllDetectors() { - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } -} - -void multiSlsDetector::setAcquiringFlag(bool b) { - thisMultiDetector->acquiringFlag = b; -} - -bool multiSlsDetector::getAcquiringFlag() { - return thisMultiDetector->acquiringFlag; -} - -bool multiSlsDetector::isAcquireReady() { - if (thisMultiDetector->acquiringFlag) { - std::cout << "Acquire has already started. " - "If previous acquisition terminated unexpectedly, " - "reset busy flag to restart.(sls_detector_put busy 0)" << std::endl; - return FAIL; - } - thisMultiDetector->acquiringFlag = true; - return OK; -} - -int multiSlsDetector::checkVersionCompatibility(portType t) { - return parallelCallDetectorMember(&slsDetector::checkVersionCompatibility, t); -} - -int64_t multiSlsDetector::getId(idMode mode, int imod) { - int id, im; - int64_t ret; - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return -1; - ret = detectors[id]->getId(mode, im); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - return ret; - } - - return callDetectorMember(&slsDetector::getId, mode, imod); -} - - -slsDetector* multiSlsDetector::getSlsDetector(unsigned int pos) { - if (pos < detectors.size()) { - return detectors[pos]; - } - return 0; -} - -slsDetector *multiSlsDetector::operator()(int pos) const { - if (pos >= 0 && pos < (int)detectors.size()) - return detectors[pos]; - return NULL; -} - - -void multiSlsDetector::freeSharedMemory(int multiId) { - // get number of detectors - int numDetectors = 0; - SharedMemory* shm = new SharedMemory(multiId, -1); - - // get number of detectors from multi shm - if (shm->IsExisting()) { - sharedMultiSlsDetector* mdet = (sharedMultiSlsDetector*)shm->OpenSharedMemory( - sizeof(sharedMultiSlsDetector)); - numDetectors = mdet->numberOfDetectors; - shm->UnmapSharedMemory(mdet); - shm->RemoveSharedMemory(); - } - delete shm; - - for (int i = 0; i < numDetectors; ++i) { - SharedMemory* shm = new SharedMemory(multiId, i); - shm->RemoveSharedMemory(); - delete shm; - } -} - - - -void multiSlsDetector::freeSharedMemory() { - // clear zmq vector - for (std::vector::const_iterator it = zmqSocket.begin(); it != zmqSocket.end(); ++it) { - delete(*it); - } - zmqSocket.clear(); - - // should be done before the detector list is deleted - clearAllErrorMask(); - - // clear sls detector vector shm - for (std::vector::const_iterator it = detectors.begin(); it != detectors.end(); ++it) { - (*it)->freeSharedMemory(); - delete (*it); - } - detectors.clear(); - - // clear multi detector shm - if (sharedMemory) { - if (thisMultiDetector) { - sharedMemory->UnmapSharedMemory(thisMultiDetector); - thisMultiDetector = 0; - } - sharedMemory->RemoveSharedMemory(); - delete sharedMemory; - sharedMemory = 0; - } - - // zmq - destroyThreadPool(); - client_downstream = false; -} - - -std::string multiSlsDetector::getUserDetails() { - std::ostringstream sstream; - - if (!detectors.size()) { - return std::string("none"); - } - - //hostname - sstream << "\nHostname: " << getHostname(); - //type - sstream<< "\nType: "; - - for (std::vector::const_iterator it = detectors.begin(); it != detectors.end(); ++it) - sstream<< (*it)->sgetDetectorsType() << "+"; - //PID - sstream << "\nPID: " << thisMultiDetector->lastPID - //user - << "\nUser: " << thisMultiDetector->lastUser - << "\nDate: " << thisMultiDetector->lastDate << endl; - - std::string s = sstream.str(); - return s; -} - -/* - * pre: sharedMemory=0, thisMultiDetector = 0, detectors.size() = 0 - * exceptions are caught in calling function, shm unmapped and deleted - */ -bool multiSlsDetector::initSharedMemory(bool verify) { - - size_t sz = sizeof(sharedMultiSlsDetector); - bool created = false; - - try { - // shared memory object with name - sharedMemory = new SharedMemory(detId, -1); - - //create - if (!sharedMemory->IsExisting()) { - thisMultiDetector = (sharedMultiSlsDetector*)sharedMemory->CreateSharedMemory(sz); - created = true; - } - // open and verify version - else { - thisMultiDetector = (sharedMultiSlsDetector*)sharedMemory->OpenSharedMemory(sz); - if (verify && thisMultiDetector->shmversion != MULTI_SHMVERSION) { - cprintf(RED, "Multi shared memory (%d) version mismatch " - "(expected 0x%x but got 0x%x)\n", detId, - MULTI_SHMVERSION, thisMultiDetector->shmversion); - throw SharedMemoryException(); - } - } - } catch (...) { - if (sharedMemory) { - // unmap - if (thisMultiDetector) { - sharedMemory->UnmapSharedMemory(thisMultiDetector); - thisMultiDetector = 0; - } - // delete - delete sharedMemory; - sharedMemory = 0; - } - throw; - } - - return created; -} - - -void multiSlsDetector::initializeDetectorStructure() { - thisMultiDetector->shmversion = MULTI_SHMVERSION; - thisMultiDetector->numberOfDetectors = 0; - thisMultiDetector->numberOfDetector[X] = 0; - thisMultiDetector->numberOfDetector[Y] = 0; - thisMultiDetector->onlineFlag = 1; - thisMultiDetector->stoppedFlag = 0; - thisMultiDetector->masterPosition = -1; - thisMultiDetector->syncMode = GET_SYNCHRONIZATION_MODE; - thisMultiDetector->dataBytes = 0; - thisMultiDetector->dataBytesInclGapPixels = 0; - thisMultiDetector->numberOfChannels = 0; - thisMultiDetector->numberOfChannel[X] = 0; - thisMultiDetector->numberOfChannel[Y] = 0; - thisMultiDetector->numberOfChannelInclGapPixels[X] = 0; - thisMultiDetector->numberOfChannelInclGapPixels[Y] = 0; - thisMultiDetector->maxNumberOfChannels = 0; - thisMultiDetector->maxNumberOfChannel[X] = 0; - thisMultiDetector->maxNumberOfChannel[Y] = 0; - thisMultiDetector->maxNumberOfChannelInclGapPixels[X] = 0; - thisMultiDetector->maxNumberOfChannelInclGapPixels[Y] = 0; - thisMultiDetector->maxNumberOfChannelsPerDetector[X] = 0; - thisMultiDetector->maxNumberOfChannelsPerDetector[Y] = 0; - for (int i = 0; i < MAX_TIMERS; ++i) { - thisMultiDetector->timerValue[i] = 0; - } - thisMultiDetector->currentSettings = GET_SETTINGS; - thisMultiDetector->currentThresholdEV = -1; - thisMultiDetector->progressIndex = 0; - thisMultiDetector->totalProgress = 1; - thisMultiDetector->fileIndex = 0; - strcpy(thisMultiDetector->fileName, "run"); - strcpy(thisMultiDetector->filePath, "/"); - thisMultiDetector->framesPerFile = 1; - thisMultiDetector->fileFormatType = ASCII; - thisMultiDetector->correctionMask = (1 << WRITE_FILE) | (1 << OVERWRITE_FILE); - thisMultiDetector->threadedProcessing = 1; - thisMultiDetector->tDead = 0; - strncpy(thisMultiDetector->flatFieldDir, getenv("HOME"), MAX_STR_LENGTH-1); - thisMultiDetector->flatFieldDir[MAX_STR_LENGTH-1] = 0; - strcpy(thisMultiDetector->flatFieldFile, "none"); - strcpy(thisMultiDetector->badChanFile, "none"); - strcpy(thisMultiDetector->angConvFile, "none"); - thisMultiDetector->angDirection = 1; - thisMultiDetector->fineOffset = 0; - thisMultiDetector->globalOffset = 0; - thisMultiDetector->binSize = 0.001; - for (int i = 0; i < 2; ++i) { - thisMultiDetector->sampleDisplacement[i] = 0.0; - } - thisMultiDetector->numberOfPositions = 0; - for (int i = 0; i < MAXPOS; ++i) { - thisMultiDetector->detPositions[i] = 0.0; - } - thisMultiDetector->actionMask = 0; - for (int i = 0; i < MAX_ACTIONS; ++i) { - strcpy(thisMultiDetector->actionScript[i], "none"); - strcpy(thisMultiDetector->actionParameter[i], "none"); - } - for (int i = 0; i < MAX_SCAN_LEVELS; ++i) { - thisMultiDetector->scanMode[i] = 0; - strcpy(thisMultiDetector->scanScript[i], "none"); - strcpy(thisMultiDetector-> scanParameter[i], "none"); - thisMultiDetector->nScanSteps[i] = 0; - { - double initValue = 0; - std::fill_n(thisMultiDetector->scanSteps[i], MAX_SCAN_STEPS, initValue); - } - thisMultiDetector->scanPrecision[i] = 0; - - } - thisMultiDetector->acquiringFlag = false; - thisMultiDetector->externalgui = false; - thisMultiDetector->receiverOnlineFlag = OFFLINE_FLAG; - thisMultiDetector->receiver_upstream = false; -} - -void multiSlsDetector::initializeMembers(bool verify) { - //slsDetectorUtils - stoppedFlag = &thisMultiDetector->stoppedFlag; - timerValue = thisMultiDetector->timerValue; - currentSettings = &thisMultiDetector->currentSettings; - currentThresholdEV = &thisMultiDetector->currentThresholdEV; - - //fileIO.h - filePath = thisMultiDetector->filePath; - fileName = thisMultiDetector->fileName; - fileIndex = &thisMultiDetector->fileIndex; - framesPerFile = &thisMultiDetector->framesPerFile; - fileFormatType = &thisMultiDetector->fileFormatType; - - //postprocessing - threadedProcessing = &thisMultiDetector->threadedProcessing; - correctionMask = &thisMultiDetector->correctionMask; - flatFieldDir = thisMultiDetector->flatFieldDir; - flatFieldFile = thisMultiDetector->flatFieldFile; - expTime = &timerValue[ACQUISITION_TIME]; - badChannelMask = NULL; - fdata = NULL; - thisData = NULL; - - //slsDetectorActions - actionMask = &thisMultiDetector->actionMask; - actionScript = thisMultiDetector->actionScript; - actionParameter = thisMultiDetector->actionParameter; - nScanSteps = thisMultiDetector->nScanSteps; - scanSteps = thisMultiDetector->scanSteps; - scanMode = thisMultiDetector->scanMode; - scanPrecision = thisMultiDetector->scanPrecision; - scanScript = thisMultiDetector->scanScript; - scanParameter = thisMultiDetector->scanParameter; - - //angularConversion.h - numberOfPositions = &thisMultiDetector->numberOfPositions; - detPositions = thisMultiDetector->detPositions; - angConvFile = thisMultiDetector->angConvFile; - binSize = &thisMultiDetector->binSize; - fineOffset = &thisMultiDetector->fineOffset; - globalOffset = &thisMultiDetector->globalOffset; - angDirection = &thisMultiDetector->angDirection; - moveFlag = NULL; - sampleDisplacement = thisMultiDetector->sampleDisplacement; - - //badChannelCorrections.h or postProcessing_Standalone.h - badChanFile = thisMultiDetector->badChanFile; - nBadChans = NULL; - badChansList = NULL; - nBadFF = NULL; - badFFList = NULL; - - //multiSlsDetector - for (std::vector::const_iterator it = zmqSocket.begin(); it != zmqSocket.end(); ++it) { - delete(*it); - } - zmqSocket.clear(); - - // get objects from single det shared memory (open) - for (int i = 0; i < thisMultiDetector->numberOfDetectors; i++) { - try { - slsDetector* sdet = new slsDetector(detId, i, verify, this); - detectors.push_back(sdet); - } catch (...) { - // clear detectors list - for (std::vector::const_iterator it = detectors.begin(); it != detectors.end(); ++it) { - delete(*it); - } - detectors.clear(); - throw; - } - } - - // depend on number of detectors - updateOffsets(); - createThreadPool(); -} - - -void multiSlsDetector::updateUserdetails() { - thisMultiDetector->lastPID = getpid(); - memset(thisMultiDetector->lastUser, 0, SHORT_STRING_LENGTH); - memset(thisMultiDetector->lastDate, 0, SHORT_STRING_LENGTH); - try { - strncpy(thisMultiDetector->lastUser, exec("whoami").c_str(), SHORT_STRING_LENGTH-1); - thisMultiDetector->lastUser[SHORT_STRING_LENGTH-1] = 0; - strncpy(thisMultiDetector->lastDate, exec("date").c_str(), DATE_LENGTH-1); - thisMultiDetector->lastDate[DATE_LENGTH-1] = 0; - } catch(...) { - strcpy(thisMultiDetector->lastUser, "errorreading"); - strcpy(thisMultiDetector->lastDate, "errorreading"); - } -} - - -std::string multiSlsDetector::exec(const char* cmd) { - int bufsize = 128; - char buffer[bufsize]; - std::string result = ""; - FILE* pipe = popen(cmd, "r"); - if (!pipe) throw std::exception(); - try { - while (!feof(pipe)) { - if (fgets(buffer, bufsize, pipe) != NULL) - result += buffer; - } - } catch (...) { - pclose(pipe); - throw; - } - pclose(pipe); - result.erase(result.find_last_not_of(" \t\n\r")+1); - return result; -} - - -void multiSlsDetector::setHostname(const char* name) { - // this check is there only to allow the previous detsizechan command - if (thisMultiDetector->numberOfDetectors) { - cprintf(RED, "Warning: There are already detector(s) in shared memory." - "Freeing Shared memory now.\n"); - freeSharedMemory(); - setupMultiDetector(); - } - addMultipleDetectors(name); -} - - -std::string multiSlsDetector::getHostname(int pos) { - return concatResultOrPos(&slsDetector::getHostname, pos); -} - -void multiSlsDetector::addMultipleDetectors(const char* name) { - size_t p1 = 0; - std::string temp = std::string(name); - size_t p2 = temp.find('+', p1); - //single - if (p2 == std::string::npos) { - addSlsDetector(temp); - } - // multi - else { - while(p2 != std::string::npos) { - addSlsDetector(temp.substr(p1, p2-p1)); - temp = temp.substr(p2 + 1); - p2 = temp.find('+'); - } - } - - // a get to update shared memory online flag - setOnline(); - updateOffsets(); - createThreadPool(); -} - -void multiSlsDetector::addSlsDetector (std::string s) { -#ifdef VERBOSE - cout << "Adding detector " << s << endl; -#endif - for (std::vector::const_iterator it = detectors.begin(); it != detectors.end(); ++it) { - if ((*it)->getHostname((it-detectors.begin())) == s) { - cout << "Detector " << s << "already part of the multiDetector!" << endl - << "Remove it before adding it back in a new position!" << endl; - return; - } - } - - //check entire shared memory if it doesnt exist?? needed? - //could be that detectors not loaded completely cuz of crash in new slsdetector in initsharedmemory - - // get type by connecting - detectorType type = slsDetector::getDetectorType(s.c_str(), DEFAULT_PORTNO); - if (type == GENERIC) { - cout << "Could not connect to Detector " << s << " to determine the type!" << endl; - setErrorMask(getErrorMask() | MULTI_DETECTORS_NOT_ADDED); - appendNotAddedList(s.c_str()); - return; - } - - - - int pos = (int)detectors.size(); - slsDetector* sdet = new slsDetector(type, detId, pos, false, this); - detectors.push_back(sdet); - thisMultiDetector->numberOfDetectors = detectors.size(); - - detectors[pos]->setHostname(s.c_str()); // also updates client - - thisMultiDetector->dataBytes += detectors[pos]->getDataBytes(); - thisMultiDetector->dataBytesInclGapPixels += detectors[pos]->getDataBytesInclGapPixels(); - thisMultiDetector->numberOfChannels += detectors[pos]->getTotalNumberOfChannels(); - thisMultiDetector->maxNumberOfChannels += detectors[pos]->getMaxNumberOfChannels(); -} - - -slsDetectorDefs::detectorType multiSlsDetector::getDetectorsType(int pos) { - detectorType dt = GENERIC; - if (pos >= 0 && pos < (int)detectors.size()) { - return detectors[pos]->getDetectorsType(); - } else - return detectors[0]->getDetectorsType();// needed?? - return dt; -} - - -std::string multiSlsDetector::sgetDetectorsType(int pos) { - return concatResultOrPos(&slsDetector::sgetDetectorsType, pos); -} - - -std::string multiSlsDetector::getDetectorType() { - return sgetDetectorsType(); -} - - -void multiSlsDetector::createThreadPool() { - if (threadpool) - destroyThreadPool(); - int numthreads = (int)detectors.size(); - if (numthreads < 1) { - numthreads = 1; //create threadpool anyway, threads initialized only when >1 detector added - } - threadpool = new ThreadPool(numthreads); - switch (threadpool->initialize_threadpool()) { - case 0: - std::cerr << "Failed to initialize thread pool!" << endl; - throw ThreadpoolException(); - case 1: -#ifdef VERBOSE - cout << "Not initializing threads, not multi detector" << endl; -#endif - break; - default: -#ifdef VERBOSE - cout << "Initialized Threadpool " << threadpool << endl; -#endif - break; - } -} - - -void multiSlsDetector::destroyThreadPool() { - if (threadpool) { - delete threadpool; - threadpool = 0; -#ifdef VERBOSE - cout << "Destroyed Threadpool " << threadpool << endl; -#endif - } -} - - -int multiSlsDetector::getNumberOfDetectors() { - return (int)detectors.size(); -} - -int multiSlsDetector::getNumberOfDetectors(dimension d) { - return thisMultiDetector->numberOfDetector[d]; -} - -void multiSlsDetector::getNumberOfDetectors(int& nx, int& ny) { - nx=thisMultiDetector->numberOfDetector[X];ny=thisMultiDetector->numberOfDetector[Y]; -} - -int multiSlsDetector::getNMods() { - int nm = 0; - for (std::vector::const_iterator it = detectors.begin(); it != detectors.end(); ++it) { - nm += (*it)->getNMods(); - } - return nm; -} - -int multiSlsDetector::getNMod(dimension d) { - int nm = 0; - for (std::vector::const_iterator it = detectors.begin(); it != detectors.end(); ++it) { - nm += (*it)->getNMod(d); - } - return nm; -} - -int multiSlsDetector::getMaxMods() { - int ret = 0; - for (std::vector::const_iterator it = detectors.begin(); it != detectors.end(); ++it) { - ret += (*it)->getMaxMods(); - } - return ret; -} - -int multiSlsDetector::getMaxMod(dimension d) { - int ret = 0, ret1; - for (std::vector::const_iterator it = detectors.begin(); it != detectors.end(); ++it) { - ret1 = (*it)->getNMaxMod(d); -#ifdef VERBOSE - cout << "detector " << (it-detectors.begin()) << " maxmods " << - ret1 << " in direction " << d << endl; -#endif - ret += ret1; - } -#ifdef VERBOSE - cout << "max mods in direction " << d << " is " << ret << endl; -#endif - - return ret; -} - -int multiSlsDetector::getMaxNumberOfModules(dimension d) { - int ret = 0; - for (std::vector::const_iterator it = detectors.begin(); it != detectors.end(); ++it) { - ret += (*it)->getMaxNumberOfModules(d); - } - return ret; -} - -int multiSlsDetector::setNumberOfModules(int p, dimension d) { - int ret = 0; - int nm = 0, mm = 0, nt = p; - - thisMultiDetector->dataBytes = 0; - thisMultiDetector->dataBytesInclGapPixels = 0; - thisMultiDetector->numberOfChannels = 0; - - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (p < 0) - nm = p; - else { - mm = detectors[idet]->getMaxNumberOfModules(); - if (nt > mm) { - nm = mm; - nt -= nm; - } else { - nm = nt; - nt -= nm; - } - } - ret += detectors[idet]->setNumberOfModules(nm); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - thisMultiDetector->dataBytes += detectors[idet]->getDataBytes(); - thisMultiDetector->dataBytesInclGapPixels += detectors[idet]->getDataBytesInclGapPixels(); - thisMultiDetector->numberOfChannels += detectors[idet]->getTotalNumberOfChannels(); - } - - if (p != -1) - updateOffsets(); - return ret; -} - -int multiSlsDetector::getChansPerMod(int imod) { - int id = -1, im = -1; - decodeNMod(imod, id, im); - if (id >= 0 && id < (int)detectors.size()) { - return detectors[id]->getChansPerMod(im); - } - return -1; -} - -int multiSlsDetector::getTotalNumberOfChannels() { - thisMultiDetector->numberOfChannels = 0; - for (std::vector::const_iterator it = detectors.begin(); it != detectors.end(); ++it) { - thisMultiDetector->numberOfChannels += (*it)->getTotalNumberOfChannels(); - } - return thisMultiDetector->numberOfChannels; -} - -int multiSlsDetector::getTotalNumberOfChannels(dimension d) { - return thisMultiDetector->numberOfChannel[d]; -} - -int multiSlsDetector::getTotalNumberOfChannelsInclGapPixels(dimension d) { - return thisMultiDetector->numberOfChannelInclGapPixels[d]; -} - -int multiSlsDetector::getMaxNumberOfChannels() { - thisMultiDetector->maxNumberOfChannels = 0; - for (std::vector::const_iterator it = detectors.begin(); it != detectors.end(); ++it) { - thisMultiDetector->maxNumberOfChannels += (*it)->getMaxNumberOfChannels(); - } - return thisMultiDetector->maxNumberOfChannels; -} - -int multiSlsDetector::getMaxNumberOfChannels(dimension d) { - return thisMultiDetector->maxNumberOfChannel[d]; -} - -int multiSlsDetector::getMaxNumberOfChannelsInclGapPixels(dimension d) { - return thisMultiDetector->maxNumberOfChannelInclGapPixels[d]; -} - -int multiSlsDetector::getMaxNumberOfChannelsPerDetector(dimension d) { - return thisMultiDetector->maxNumberOfChannelsPerDetector[d]; -} - -int multiSlsDetector::setMaxNumberOfChannelsPerDetector(dimension d,int i) { - thisMultiDetector->maxNumberOfChannelsPerDetector[d] = i; - return thisMultiDetector->maxNumberOfChannelsPerDetector[d]; -} - -int multiSlsDetector::getDetectorOffset(dimension d, int pos) { - if (pos < 0 || pos >= (int)detectors.size()) - return -1; - return detectors[pos]->getDetectorOffset(d); -} - - -void multiSlsDetector::setDetectorOffset(dimension d, int off, int pos) { - if (pos < 0 || pos >= (int)detectors.size()) - detectors[pos]->setDetectorOffset(d, off); -} - - -void multiSlsDetector::updateOffsets() { - //cannot paralllize due to slsdetector calling this via parentdet-> -#ifdef VERBOSE - cout << endl - << "Updating Multi-Detector Offsets" << endl; -#endif - int offsetX = 0, offsetY = 0, numX = 0, numY = 0, maxX = 0, maxY = 0; - int maxChanX = thisMultiDetector->maxNumberOfChannelsPerDetector[X]; - int maxChanY = thisMultiDetector->maxNumberOfChannelsPerDetector[Y]; - int prevChanX = 0; - int prevChanY = 0; - bool firstTime = true; - - thisMultiDetector->numberOfChannel[X] = 0; - thisMultiDetector->numberOfChannel[Y] = 0; - thisMultiDetector->maxNumberOfChannel[X] = 0; - thisMultiDetector->maxNumberOfChannel[Y] = 0; - thisMultiDetector->numberOfDetector[X] = 0; - thisMultiDetector->numberOfDetector[Y] = 0; - - // gap pixels - int offsetX_gp = 0, offsetY_gp = 0, numX_gp = 0, numY_gp = 0, maxX_gp = 0, maxY_gp = 0; - int prevChanX_gp = 0, prevChanY_gp = 0; - thisMultiDetector->numberOfChannelInclGapPixels[X] = 0; - thisMultiDetector->numberOfChannelInclGapPixels[Y] = 0; - thisMultiDetector->maxNumberOfChannelInclGapPixels[X] = 0; - thisMultiDetector->maxNumberOfChannelInclGapPixels[Y] = 0; - - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { -#ifdef VERBOSE - cout << "offsetX:" << offsetX << " prevChanX:" << prevChanX << " " - "offsetY:" << offsetY << " prevChanY:" << prevChanY << endl; - cout << "offsetX_gp:" << offsetX_gp << " " - "prevChanX_gp:" << prevChanX_gp << " " - "offsetY_gp:" << offsetY_gp << " " - "prevChanY_gp:" << prevChanY_gp << endl; -#endif - //cout<<" totalchan:"<< detectors[idet]->getTotalNumberOfChannels(Y) - //<<" maxChanY:"< 0) && ((offsetX + detectors[idet]->getTotalNumberOfChannels(X)) - > maxChanX)) - cout << "\nDetector[" << idet << "] exceeds maximum channels " - "allowed for complete detector set in X dimension!" << endl; - if ((maxChanY > 0) && ((offsetY + detectors[idet]->getTotalNumberOfChannels(Y)) - > maxChanY)) - cout << "\nDetector[" << idet << "] exceeds maximum channels " - "allowed for complete detector set in Y dimension!" << endl; - prevChanX = detectors[idet]->getTotalNumberOfChannels(X); - prevChanY = detectors[idet]->getTotalNumberOfChannels(Y); - prevChanX_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); - prevChanY_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); - numX += detectors[idet]->getTotalNumberOfChannels(X); - numY += detectors[idet]->getTotalNumberOfChannels(Y); - numX_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); - numY_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); - maxX += detectors[idet]->getMaxNumberOfChannels(X); - maxY += detectors[idet]->getMaxNumberOfChannels(Y); - maxX_gp += detectors[idet]->getMaxNumberOfChannelsInclGapPixels(X); - maxY_gp += detectors[idet]->getMaxNumberOfChannelsInclGapPixels(Y); - ++thisMultiDetector->numberOfDetector[X]; - ++thisMultiDetector->numberOfDetector[Y]; -#ifdef VERBOSE - cout << "incrementing in both direction" << endl; -#endif - } - - //incrementing in y direction - else if ((maxChanY == -1) || ((maxChanY > 0) && - ((offsetY + prevChanY + detectors[idet]->getTotalNumberOfChannels(Y)) - <= maxChanY))) { - offsetY += prevChanY; - offsetY_gp += prevChanY_gp; - prevChanY = detectors[idet]->getTotalNumberOfChannels(Y); - prevChanY_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); - numY += detectors[idet]->getTotalNumberOfChannels(Y); - numY_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); - maxY += detectors[idet]->getMaxNumberOfChannels(Y); - maxY_gp += detectors[idet]->getMaxNumberOfChannelsInclGapPixels(Y); - // increment in y again only in the first column (else you double increment) - if (thisMultiDetector->numberOfDetector[X] == 1) - ++thisMultiDetector->numberOfDetector[Y]; -#ifdef VERBOSE - cout << "incrementing in y direction" << endl; -#endif - } - - //incrementing in x direction - else { - if ((maxChanX > 0) && - ((offsetX + prevChanX + detectors[idet]->getTotalNumberOfChannels(X)) - > maxChanX)) - cout << "\nDetector[" << idet << "] exceeds maximum channels " - "allowed for complete detector set in X dimension!" << endl; - offsetY = 0; - offsetY_gp = 0; - prevChanY = detectors[idet]->getTotalNumberOfChannels(Y); - prevChanY_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); - numY = 0; //assuming symmetry with this statement. - //whats on 1st column should be on 2nd column - numY_gp = 0; - maxY = 0; - maxY_gp = 0; - offsetX += prevChanX; - offsetX_gp += prevChanX_gp; - prevChanX = detectors[idet]->getTotalNumberOfChannels(X); - prevChanX_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); - numX += detectors[idet]->getTotalNumberOfChannels(X); - numX_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); - maxX += detectors[idet]->getMaxNumberOfChannels(X); - maxX_gp += detectors[idet]->getMaxNumberOfChannelsInclGapPixels(X); - ++thisMultiDetector->numberOfDetector[X]; -#ifdef VERBOSE - cout << "incrementing in x direction" << endl; -#endif - } - - double bytesperchannel = (double)detectors[idet]->getDataBytes() / - (double)(detectors[idet]->getMaxNumberOfChannels(X) - * detectors[idet]->getMaxNumberOfChannels(Y)); - detectors[idet]->setDetectorOffset(X, (bytesperchannel >= 1.0) ? offsetX_gp : offsetX); - detectors[idet]->setDetectorOffset(Y, (bytesperchannel >= 1.0) ? offsetY_gp : offsetY); - -#ifdef VERBOSE - cout << "Detector[" << idet << "] has offsets (" << - detectors[idet]->getDetectorOffset(X) << ", " << - detectors[idet]->getDetectorOffset(Y) << ")" << endl; -#endif - //offsetY has been reset sometimes and offsetX the first time, - //but remember the highest values - if (numX > thisMultiDetector->numberOfChannel[X]) - thisMultiDetector->numberOfChannel[X] = numX; - if (numY > thisMultiDetector->numberOfChannel[Y]) - thisMultiDetector->numberOfChannel[Y] = numY; - if (numX_gp > thisMultiDetector->numberOfChannelInclGapPixels[X]) - thisMultiDetector->numberOfChannelInclGapPixels[X] = numX_gp; - if (numY_gp > thisMultiDetector->numberOfChannelInclGapPixels[Y]) - thisMultiDetector->numberOfChannelInclGapPixels[Y] = numY_gp; - if (maxX > thisMultiDetector->maxNumberOfChannel[X]) - thisMultiDetector->maxNumberOfChannel[X] = maxX; - if (maxY > thisMultiDetector->maxNumberOfChannel[Y]) - thisMultiDetector->maxNumberOfChannel[Y] = maxY; - if (maxX_gp > thisMultiDetector->maxNumberOfChannelInclGapPixels[X]) - thisMultiDetector->maxNumberOfChannelInclGapPixels[X] = maxX_gp; - if (maxY_gp > thisMultiDetector->maxNumberOfChannelInclGapPixels[Y]) - thisMultiDetector->maxNumberOfChannelInclGapPixels[Y] = maxY_gp; - } -#ifdef VERBOSE - cout << "Number of Channels in X direction:" << thisMultiDetector->numberOfChannel[X] << endl; - cout << "Number of Channels in Y direction:" << thisMultiDetector->numberOfChannel[Y] << endl - << endl; - cout << "Number of Channels in X direction with Gap Pixels:" << - thisMultiDetector->numberOfChannelInclGapPixels[X] << endl; - cout << "Number of Channels in Y direction with Gap Pixels:" << - thisMultiDetector->numberOfChannelInclGapPixels[Y] << endl - << endl; -#endif -} - - -int multiSlsDetector::setOnline(int off) { - if (off != GET_ONLINE_FLAG) - thisMultiDetector->onlineFlag = parallelCallDetectorMember(&slsDetector::setOnline, off); - return thisMultiDetector->onlineFlag; -} - - -std::string multiSlsDetector::checkOnline() { - std::string offlineDetectors = ""; - for (std::vector::const_iterator it = detectors.begin(); it != detectors.end(); ++it) { - std::string tmp = (*it)->checkOnline(); - if (!tmp.empty()) - offlineDetectors += tmp + "+"; - } - return offlineDetectors; -} - - -int multiSlsDetector::setPort(portType t, int p) { - return callDetectorMember(&slsDetector::setPort, t, p); -} - -int multiSlsDetector::lockServer(int p) { - return callDetectorMember(&slsDetector::lockServer, p); -} - -std::string multiSlsDetector::getLastClientIP() { - return callDetectorMember(&slsDetector::getLastClientIP); -} - -int multiSlsDetector::exitServer() { - int ival = FAIL, iv; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - iv = detectors[idet]->exitServer(); - if (iv == OK) - ival = iv; - } - return ival; -} - -int multiSlsDetector::readConfigurationFile(std::string const fname) { - - freeSharedMemory(); - setupMultiDetector(); - - - multiSlsDetectorClient* cmd; - std::string ans; - std::string str; - std::ifstream infile; - int iargval; - int interrupt = 0; - char* args[1000]; - - char myargs[1000][1000]; - - std::string sargname, sargval; - int iline = 0; - std::cout << "config file name " << fname << std::endl; - infile.open(fname.c_str(), std::ios_base::in); - if (infile.is_open()) { - - while (infile.good() and interrupt == 0) { - sargname = "none"; - sargval = "0"; - getline(infile, str); - ++iline; - - // remove comments that come after - if (str.find('#') != std::string::npos) - str.erase(str.find('#')); -#ifdef VERBOSE - std::cout << "string:" << str << std::endl; -#endif - if (str.length() < 2) { -#ifdef VERBOSE - std::cout << "Empty line or Comment " << std::endl; -#endif - continue; - } else { - std::istringstream ssstr(str); - iargval = 0; - while (ssstr.good()) { - ssstr >> sargname; -#ifdef VERBOSE - std::cout << iargval << " " << sargname << std::endl; -#endif - strcpy(myargs[iargval], sargname.c_str()); - args[iargval] = myargs[iargval]; -#ifdef VERBOSE - std::cout << "--" << iargval << " " << args[iargval] << std::endl; -#endif - ++iargval; - } -#ifdef VERBOSE - cout << endl; - for (int ia = 0; ia < iargval; ia++) - cout << args[ia] << " ??????? "; - cout << endl; -#endif - cmd = new multiSlsDetectorClient(iargval, args, PUT_ACTION, this); - delete cmd; - } - ++iline; - } - - infile.close(); - } else { - std::cout << "Error opening configuration file " << fname << " for reading" << std::endl; - setErrorMask(getErrorMask() | MULTI_CONFIG_FILE_ERROR); - return FAIL; - } -#ifdef VERBOSE - std::cout << "Read configuration file of " << iline << " lines" << std::endl; -#endif - - setNumberOfModules(-1); - getMaxNumberOfModules(); - - if (getErrorMask()) { - int c; - cprintf(RED, "\n----------------\n Error Messages\n----------------\n%s\n", - getErrorMessage(c).c_str()); - return FAIL; - } - - return OK; -} - - -int multiSlsDetector::writeConfigurationFile(std::string const fname) { - - std::string names[] = { - "detsizechan", - "hostname", - "master", - "sync", - "outdir", - "ffdir", - "headerbefore", - "headerafter", - "headerbeforepar", - "headerafterpar", - "badchannels", - "angconv", - "globaloff", - "binsize", - "threaded" - }; - - int nvar = 15; - char* args[100]; - for (int ia = 0; ia < 100; ++ia) { - args[ia] = new char[1000]; - } - int ret = OK, ret1 = OK; - - std::ofstream outfile; - int iline = 0; - - outfile.open(fname.c_str(), std::ios_base::out); - if (outfile.is_open()) { - - slsDetectorCommand* cmd = new slsDetectorCommand(this); - - // complete size of detector - cout << iline << " " << names[iline] << endl; - strcpy(args[0], names[iline].c_str()); - outfile << names[iline] << " " << cmd->executeLine(1, args, GET_ACTION) << std::endl; - ++iline; - - // hostname of the detectors - cout << iline << " " << names[iline] << endl; - strcpy(args[0], names[iline].c_str()); - outfile << names[iline] << " " << cmd->executeLine(1, args, GET_ACTION) << std::endl; - ++iline; - - // single detector configuration - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - outfile << endl; - ret1 = detectors[idet]->writeConfigurationFile(outfile, idet); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - if (ret1 == FAIL) - ret = FAIL; - } - - outfile << endl; - //other configurations - while (iline < nvar) { - cout << iline << " " << names[iline] << endl; - strcpy(args[0], names[iline].c_str()); - outfile << names[iline] << " " << cmd->executeLine(1, args, GET_ACTION) << std::endl; - ++iline; - } - - delete cmd; - outfile.close(); -#ifdef VERBOSE - std::cout << "wrote " << iline << " lines to configuration file " << std::endl; -#endif - } else { - std::cout << "Error opening configuration file " << fname << " for writing" << std::endl; - setErrorMask(getErrorMask() | MULTI_CONFIG_FILE_ERROR); - ret = FAIL; - } - - for (int ia = 0; ia < 100; ++ia) { - delete[] args[ia]; - } - - return ret; -} - - - -std::string multiSlsDetector::getSettingsFile() { - return callDetectorMember(&slsDetector::getSettingsFile); -} - - -slsDetectorDefs::detectorSettings multiSlsDetector::getSettings(int pos) { - int ret = -100; - int posmin = 0, posmax = (int)detectors.size(); - if (pos >= 0) { - posmin = pos; - posmax = pos + 1; - } - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return GET_SETTINGS; - } else { - //return storage values - detectorSettings* iret[posmax - posmin]; - for (int idet = posmin; idet < posmax; ++idet) { - iret[idet] = new detectorSettings(GET_SETTINGS); - Task* task = new Task(new func1_t(&slsDetector::getSettings, - detectors[idet], -1, iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (iret[idet] != NULL) { - if (ret == -100) - ret = *iret[idet]; - else if (ret != *iret[idet]) - ret = GET_SETTINGS; - delete iret[idet]; - } else - ret = GET_SETTINGS; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - - thisMultiDetector->currentSettings = (detectorSettings)ret; - return (detectorSettings)ret; -} - - - -int multiSlsDetector::getThresholdEnergy(int pos) { - int i, posmin, posmax; - int ret1 = -100, ret; - - if (pos < 0) { - posmin = 0; - posmax = (int)detectors.size(); - } else { - posmin = pos; - posmax = pos + 1; - } - - for (i = posmin; i < posmax; ++i) { - ret = detectors[i]->getThresholdEnergy(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret1 == -100) - ret1 = ret; - else if (ret < (ret1 - 200) || ret > (ret1 + 200)) - ret1 = -1; - } - thisMultiDetector->currentThresholdEV = ret1; - return ret1; -} - - -int multiSlsDetector::setThresholdEnergy(int e_eV, int pos, detectorSettings isettings, int tb) { - int posmin, posmax; - int ret = -100; - if (pos < 0) { - posmin = 0; - posmax = (int)detectors.size(); - } else { - posmin = pos; - posmax = pos + 1; - } - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } else { - //return storage values - int* iret[posmax - posmin]; - for (int idet = posmin; idet < posmax; ++idet) { - iret[idet] = new int(-1); - Task* task = new Task(new func4_t(&slsDetector::setThresholdEnergy, - detectors[idet], e_eV, -1, isettings, tb, iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (iret[idet] != NULL) { - if (ret == -100) - ret = *iret[idet]; - else if (*iret[idet] < (ret - 200) || *iret[idet] > (ret + 200)) - ret = -1; - delete iret[idet]; - } else - ret = -1; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - - thisMultiDetector->currentThresholdEV = ret; - return ret; -} - - -slsDetectorDefs::detectorSettings multiSlsDetector::setSettings(detectorSettings isettings, - int pos) { - int ret = -100; - int posmin = 0, posmax = (int)detectors.size(); - if (pos >= 0) { - posmin = pos; - posmax = pos + 1; - } - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return GET_SETTINGS; - } else { - //return storage values - detectorSettings* iret[posmax - posmin]; - for (int idet = posmin; idet < posmax; ++idet) { - if (detectors[idet]) { - iret[idet] = new detectorSettings(GET_SETTINGS); - Task* task = new Task(new func2_t - (&slsDetector::setSettings, detectors[idet], isettings, -1, iret[idet])); - threadpool->add_task(task); - } - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (detectors[idet]) { - if (iret[idet] != NULL) { - if (ret == -100) - ret = *iret[idet]; - else if (ret != *iret[idet]) - ret = GET_SETTINGS; - delete iret[idet]; - } else - ret = GET_SETTINGS; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - } - - thisMultiDetector->currentSettings = (detectorSettings)ret; - return (detectorSettings)ret; -} - - -std::string multiSlsDetector::getSettingsDir() { - return callDetectorMember(&slsDetector::getSettingsDir); -} - - -std::string multiSlsDetector::setSettingsDir(std::string s) { - - if (s.find('+') == std::string::npos) { - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - detectors[idet]->setSettingsDir(s); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } else { - size_t p1 = 0; - size_t p2 = s.find('+', p1); - int id = 0; - while (p2 != std::string::npos) { - detectors[id]->setSettingsDir(s.substr(p1, p2 - p1)); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - ++id; - s = s.substr(p2 + 1); - p2 = s.find('+'); - if (id >= (int)detectors.size()) - break; - } - } - return getSettingsDir(); -} - -std::string multiSlsDetector::getCalDir() { - return callDetectorMember(&slsDetector::getCalDir); -} - -std::string multiSlsDetector::setCalDir(std::string s) { - - if (s.find('+') == std::string::npos) { - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - detectors[idet]->setCalDir(s); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } else { - size_t p1 = 0; - size_t p2 = s.find('+', p1); - int id = 0; - while (p2 != std::string::npos) { - - if (detectors[id]) { - detectors[id]->setCalDir(s.substr(p1, p2 - p1)); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - } - ++id; - s = s.substr(p2 + 1); - p2 = s.find('+'); - if (id >= (int)detectors.size()) - break; - } - } - return getCalDir(); -} - - -int multiSlsDetector::loadSettingsFile(std::string fname, int imod) { - int ret = OK; - - // single - { - int id = -1, im = -1; - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return -1; - ret = detectors[id]->loadSettingsFile(fname, im); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - return ret; - } - } - - // multi - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } - - int* iret[detectors.size()]; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - iret[idet] = new int(OK); - Task* task = new Task(new func2_t(&slsDetector::loadSettingsFile, - detectors[idet], fname, imod, iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (iret[idet] != NULL) { - if (*iret[idet] != OK) - ret = FAIL; - delete iret[idet]; - } else - ret = FAIL; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - - return ret; -} - -int multiSlsDetector::saveSettingsFile(std::string fname, int imod) { - int id = -1, im = -1, ret; - - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return -1; - ret = detectors[id]->saveSettingsFile(fname, im); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - return ret; - - } - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - ret = detectors[idet]->saveSettingsFile(fname, imod); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - return ret; -} - - -int multiSlsDetector::loadCalibrationFile(std::string fname, int imod) { - int ret = OK; - - // single - { - int id = -1, im = -1; - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return -1; - ret = detectors[id]->loadCalibrationFile(fname, im); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - return ret; - } - } - - // multi - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } - - int* iret[detectors.size()]; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (detectors[idet]) { - iret[idet] = new int(OK); - Task* task = new Task(new func2_t(&slsDetector::loadCalibrationFile, - detectors[idet], fname, imod, iret[idet])); - threadpool->add_task(task); - } - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (detectors[idet]) { - if (iret[idet] != NULL) { - if (*iret[idet] != OK) - ret = FAIL; - delete iret[idet]; - } else - ret = FAIL; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - - return ret; -} - -int multiSlsDetector::saveCalibrationFile(std::string fname, int imod) { - int id = -1, im = -1, ret; - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return -1; - ret = detectors[id]->saveCalibrationFile(fname, im); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - return ret; - } - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - ret = detectors[idet]->saveCalibrationFile(fname, imod); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - return ret; -} - - - -int multiSlsDetector::setMaster(int i) { - int ret = -1, slave = 0; - masterFlags f; -#ifdef VERBOSE - cout << "settin master in position " << i << endl; -#endif - if (i >= 0 && i < (int)detectors.size()) { -#ifdef VERBOSE - cout << "detector position " << i << " "; -#endif - thisMultiDetector->masterPosition = i; - detectors[i]->setMaster(IS_MASTER); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (i != (int)idet) { -#ifdef VERBOSE - cout << "detector position " << idet << " "; -#endif - detectors[idet]->setMaster(IS_SLAVE); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - - } else if (i == -2) { - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { -#ifdef VERBOSE - cout << "detector position " << idet << " "; -#endif - detectors[idet]->setMaster(NO_MASTER); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - - // check return value - - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { -#ifdef VERBOSE - cout << "detector position " << idet << " "; -#endif - f = detectors[idet]->setMaster(GET_MASTER); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - - switch (f) { - case NO_MASTER: - if (ret != -1) - ret = -2; - break; - case IS_MASTER: - if (ret == -1) - ret = idet; - else - ret = -2; - break; - case IS_SLAVE: - slave = 1; - break; - default: - ret = -2; - } - - } - if (slave > 0 && ret < 0) - ret = -2; - - if (ret < 0) - ret = -1; - - thisMultiDetector->masterPosition = ret; - - return thisMultiDetector->masterPosition; -} - - -slsDetectorDefs::synchronizationMode multiSlsDetector::setSynchronization(synchronizationMode sync) { - synchronizationMode ret = GET_SYNCHRONIZATION_MODE, ret1 = GET_SYNCHRONIZATION_MODE; - - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - ret1 = detectors[idet]->setSynchronization(sync); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - if (idet == 0) - ret = ret1; - else if (ret != ret1) - ret = GET_SYNCHRONIZATION_MODE; - } - - thisMultiDetector->syncMode = ret; - - return thisMultiDetector->syncMode; -} - -slsDetectorDefs::runStatus multiSlsDetector::getRunStatus() { - runStatus s = IDLE, s1 = IDLE; - if (thisMultiDetector->masterPosition >= 0) { - s = detectors[thisMultiDetector->masterPosition]->getRunStatus(); - if (detectors[thisMultiDetector->masterPosition]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << thisMultiDetector->masterPosition)); - return s; - } - - for (unsigned int i = 0; i < detectors.size(); ++i) { - s1 = detectors[i]->getRunStatus(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (s1 == ERROR) { - return ERROR; - } - if (s1 != IDLE) - s = s1; - } - return s; -} - -int multiSlsDetector::prepareAcquisition() { - - int i = 0; - int ret = OK; - int posmin = 0, posmax = detectors.size(); - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return FAIL; - } else { - int* iret[posmax - posmin]; - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - iret[idet] = new int(OK); - Task* task = new Task(new func0_t(&slsDetector::prepareAcquisition, - detectors[idet], iret[idet])); - threadpool->add_task(task); - } - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - if (iret[idet] != NULL) { - if (*iret[idet] != OK) - ret = FAIL; - delete iret[idet]; - } else - ret = FAIL; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - } - - //master - int ret1 = OK; - i = thisMultiDetector->masterPosition; - if (thisMultiDetector->masterPosition >= 0) { - ret1 = detectors[i]->prepareAcquisition(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret1 != OK) - ret = FAIL; - } - - return ret; -} - -int multiSlsDetector::cleanupAcquisition() { - int i = 0; - int ret = OK, ret1 = OK; - int posmin = 0, posmax = detectors.size(); - - i = thisMultiDetector->masterPosition; - if (thisMultiDetector->masterPosition >= 0) { - ret1 = detectors[i]->cleanupAcquisition(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret1 != OK) - ret = FAIL; - } - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return FAIL; - } else { - int* iret[posmax - posmin]; - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - iret[idet] = new int(OK); - Task* task = new Task(new func0_t(&slsDetector::cleanupAcquisition, - detectors[idet], iret[idet])); - threadpool->add_task(task); - } - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - if (iret[idet] != NULL) { - if (*iret[idet] != OK) - ret = FAIL; - delete iret[idet]; - } else - ret = FAIL; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - } - return ret; -} - - -int multiSlsDetector::startAcquisition() { - if (getDetectorsType() == EIGER) { - if (prepareAcquisition() == FAIL) - return FAIL; - } - - int i = 0; - int ret = OK; - int posmin = 0, posmax = detectors.size(); - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return FAIL; - } else { - int* iret[posmax - posmin]; - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - iret[idet] = new int(OK); - Task* task = new Task(new func0_t(&slsDetector::startAcquisition, - detectors[idet], iret[idet])); - threadpool->add_task(task); - } - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - if (iret[idet] != NULL) { - if (*iret[idet] != OK) - ret = FAIL; - delete iret[idet]; - } else - ret = FAIL; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - } - - //master - int ret1 = OK; - i = thisMultiDetector->masterPosition; - if (thisMultiDetector->masterPosition >= 0) { - ret1 = detectors[i]->startAcquisition(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret1 != OK) - ret = FAIL; - } - return ret; -} - - -int multiSlsDetector::stopAcquisition() { - pthread_mutex_lock(&mg); // locks due to processing thread using threadpool when in use - int i = 0; - int ret = OK, ret1 = OK; - int posmin = 0, posmax = detectors.size(); - - i = thisMultiDetector->masterPosition; - if (thisMultiDetector->masterPosition >= 0) { - ret1 = detectors[i]->stopAcquisition(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret1 != OK) - ret = FAIL; - } - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return FAIL; - } else { - int* iret[posmax - posmin]; - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - iret[idet] = new int(OK); - Task* task = new Task(new func0_t(&slsDetector::stopAcquisition, - detectors[idet], iret[idet])); - threadpool->add_task(task); - } - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - if (iret[idet] != NULL) { - if (*iret[idet] != OK) - ret = FAIL; - delete iret[idet]; - } else - ret = FAIL; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - } - - *stoppedFlag = 1; - pthread_mutex_unlock(&mg); - return ret; -} - - - -int multiSlsDetector::sendSoftwareTrigger() { - int i = 0; - int ret = OK; - int posmin = 0, posmax = detectors.size(); - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return FAIL; - } else { - int* iret[posmax - posmin]; - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - iret[idet] = new int(OK); - Task* task = new Task(new func0_t(&slsDetector::sendSoftwareTrigger, - detectors[idet], iret[idet])); - threadpool->add_task(task); - } - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - if (iret[idet] != NULL) { - if (*iret[idet] != OK) - ret = FAIL; - delete iret[idet]; - } else - ret = FAIL; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - } - - //master - int ret1 = OK; - i = thisMultiDetector->masterPosition; - if (thisMultiDetector->masterPosition >= 0) { - ret1 = detectors[i]->sendSoftwareTrigger(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret1 != OK) - ret = FAIL; - } - return ret; -} - - - -int multiSlsDetector::startReadOut() { - int i = 0; - int ret = OK, ret1 = OK; - i = thisMultiDetector->masterPosition; - if (i >= 0) { - ret = detectors[i]->startReadOut(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret != OK) - ret1 = FAIL; - } - for (i = 0; i < (int)detectors.size(); ++i) { - ret = detectors[i]->startReadOut(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret != OK) - ret1 = FAIL; - } - - return ret1; -} - - -int* multiSlsDetector::startAndReadAll() { -#ifdef VERBOSE - cout << "Start and read all " << endl; -#endif - int* retval = NULL; - int i = 0; - if (thisMultiDetector->onlineFlag == ONLINE_FLAG) { - - if (getDetectorsType() == EIGER) { - if (prepareAcquisition() == FAIL) - return NULL; - } - startAndReadAllNoWait(); - - while ((retval = getDataFromDetector())) { - ++i; -#ifdef VERBOSE - std::cout << i << " " retval << std::endl; -#endif - dataQueue.push(retval); - } - - for (unsigned int id = 0; id < detectors.size(); ++id) { - if (detectors[id]) { - detectors[id]->disconnectControl(); - } - } - } -#ifdef VERBOSE - std::cout << "Recieved " << i << " frames" << std::endl; -#endif - return dataQueueFront(); -} - - -int multiSlsDetector::startAndReadAllNoWait() { - pthread_mutex_lock(&mg); // locks due to processing thread using threadpool when in use - int i = 0; - int ret = OK; - int posmin = 0, posmax = detectors.size(); - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return FAIL; - } else { - int* iret[posmax - posmin]; - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition){ - iret[idet] = new int(OK); - Task* task = new Task(new func0_t(&slsDetector::startAndReadAllNoWait, - detectors[idet], iret[idet])); - threadpool->add_task(task); - } - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - if (iret[idet] != NULL) { - if (*iret[idet] != OK) - ret = FAIL; - delete iret[idet]; - } else - ret = FAIL; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - } - - //master - int ret1 = OK; - i = thisMultiDetector->masterPosition; - if (thisMultiDetector->masterPosition >= 0) { - ret1 = detectors[i]->startAndReadAllNoWait(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret1 != OK) - ret = FAIL; - } - pthread_mutex_unlock(&mg); - return ret; -} - - - -int* multiSlsDetector::getDataFromDetector() { - - int nel = thisMultiDetector->dataBytes / sizeof(int); - int n = 0; - int* retval = NULL; - int *retdet, *p = retval; - int nodatadet = -1; - int nodatadetectortype = false; - detectorType types = getDetectorsType(); - if (types == EIGER || types == JUNGFRAU || types == GOTTHARD || types == PROPIX) { - nodatadetectortype = true; - } - - if (!nodatadetectortype) - retval = new int[nel]; - p = retval; - - for (unsigned int id = 0; id < detectors.size(); ++id) { - retdet = detectors[id]->getDataFromDetector(p); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - if (!nodatadetectortype) { - n = detectors[id]->getDataBytes(); - if (retdet) { - ; -#ifdef VERBOSE - cout << "Detector " << id << " returned " << n << " bytes " << endl; -#endif - } else { - nodatadet = id; -#ifdef VERBOSE - cout << "Detector " << id << " does not have data left " << endl; -#endif - } - p += n / sizeof(int); - } - } - - //eiger returns only null - if (nodatadetectortype) { - return NULL; - } - - if (nodatadet >= 0) { - for (unsigned int id = 0; id < detectors.size(); ++id) { - if ((int)id != nodatadet) { - if (detectors[id]) { - //#ifdef VERBOSE - cout << "Stopping detector " << id << endl; - //#endif - detectors[id]->stopAcquisition(); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - - while ((retdet = detectors[id]->getDataFromDetector())) { - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); -#ifdef VERBOSE - cout << "Detector " << id << " still sent data " << endl; -#endif - delete[] retdet; - } - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - } - } - } - delete[] retval; - return NULL; - } - - return retval; -} - - -int* multiSlsDetector::readFrame() { - int nel = thisMultiDetector->dataBytes / sizeof(int); - int n; - int* retval = new int[nel]; - int *retdet, *p = retval; - - for (unsigned int id = 0; id < detectors.size(); ++id) { - if (detectors[id]) { - retdet = detectors[id]->readFrame(); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - if (retdet) { - n = detectors[id]->getDataBytes(); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - memcpy(p, retdet, n); - delete[] retdet; - p += n / sizeof(int); - } else { -#ifdef VERBOSE - cout << "Detector " << id << " does not have data left " << endl; -#endif - delete[] retval; - return NULL; - } - } - } - dataQueue.push(retval); - return retval; -} - - -int* multiSlsDetector::readAll() { - int* retval = NULL; - int i = 0; -#ifdef VERBOSE - std::cout << "Reading all frames " << std::endl; -#endif - if (thisMultiDetector->onlineFlag == ONLINE_FLAG) { - - for (unsigned int id = 0; id < detectors.size(); ++id) { - detectors[id]->readAllNoWait(); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - } - while ((retval = getDataFromDetector())) { - ++i; -#ifdef VERBOSE - std::cout << i << std::endl; -#endif - dataQueue.push(retval); - } - for (unsigned int id = 0; id < detectors.size(); ++id) { - detectors[id]->disconnectControl(); - } - } - -#ifdef VERBOSE - std::cout << "received " << i << " frames" << std::endl; -#endif - return dataQueueFront(); -} - - -int* multiSlsDetector::popDataQueue() { - int* retval = NULL; - if (!dataQueue.empty()) { - retval = dataQueue.front(); - dataQueue.pop(); - } - return retval; -} - -detectorData* multiSlsDetector::popFinalDataQueue() { - detectorData* retval = NULL; - if (!finalDataQueue.empty()) { - retval = finalDataQueue.front(); - finalDataQueue.pop(); - } - return retval; -} - -void multiSlsDetector::resetDataQueue() { - int* retval = NULL; - while (!dataQueue.empty()) { - retval = dataQueue.front(); - dataQueue.pop(); - delete[] retval; - } -} - -void multiSlsDetector::resetFinalDataQueue() { - detectorData* retval = NULL; - while (!finalDataQueue.empty()) { - retval = finalDataQueue.front(); - finalDataQueue.pop(); - delete retval; - } -} - -int multiSlsDetector::configureMAC() { - return callDetectorMember(&slsDetector::configureMAC); -} - -int64_t multiSlsDetector::setTimer(timerIndex index, int64_t t, int imod) { - int64_t ret=-100; - - // single (for gotthard 25 um) - if (imod != -1) { - if (imod >= 0 && imod < (int)detectors.size()) { - ret = detectors[imod]->setTimer(index,t,imod); - if(detectors[imod]->getErrorMask()) - setErrorMask(getErrorMask()|(1<numberOfDetectors]; - for(int idet=0; idetnumberOfDetectors; ++idet){ - if(detectors[idet]){ - iret[idet]= new int64_t(-1); - Task* task = new Task(new func3_t(&slsDetector::setTimer, - detectors[idet],index,t,imod,iret[idet])); - threadpool->add_task(task); - } - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for(int idet=0; idetnumberOfDetectors; ++idet){ - if(detectors[idet]){ - if(iret[idet] != NULL){ - if (ret==-100) - ret=*iret[idet]; - else if (ret!=*iret[idet]) - ret=-1; - delete iret[idet]; - }else ret=-1; - if(detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask()|(1<timerValue[index] = ret; - return ret; -} - -int64_t multiSlsDetector::getTimeLeft(timerIndex index, int imod) { - int64_t ret = -100; - - { // single - int id = -1, im = -1; - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return -1; - ret = detectors[id]->getTimeLeft(index, im); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - return ret; - } - } - if (thisMultiDetector->masterPosition >= 0) - if (detectors[thisMultiDetector->masterPosition]) { - ret = detectors[thisMultiDetector->masterPosition]->getTimeLeft(index, imod); - if (detectors[thisMultiDetector->masterPosition]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << thisMultiDetector->masterPosition)); - return ret; - } - return callDetectorMember(&slsDetector::getTimeLeft, index, imod); -} - -int multiSlsDetector::setSpeed(speedVariable index, int value) { - int ret1 = -100, ret; - - for (unsigned i = 0; i < detectors.size(); ++i) { - ret = detectors[i]->setSpeed(index, value); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret1 == -100) - ret1 = ret; - else if (ret != ret1) - ret1 = FAIL; - } - - return ret1; -} - -int multiSlsDetector::setDynamicRange(int p) { - int ret = -100; - thisMultiDetector->dataBytes = 0; - thisMultiDetector->dataBytesInclGapPixels = 0; - thisMultiDetector->numberOfChannels = 0; - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } else { - //return storage values - int* iret[detectors.size()]; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - iret[idet] = new int(-1); - Task* task = new Task(new func1_t(&slsDetector::setDynamicRange, - detectors[idet], p, iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (iret[idet] != NULL) { - thisMultiDetector->dataBytes += detectors[idet]->getDataBytes(); - thisMultiDetector->dataBytesInclGapPixels += - detectors[idet]->getDataBytesInclGapPixels(); - thisMultiDetector->numberOfChannels += - detectors[idet]->getTotalNumberOfChannels(); - if (ret == -100) - ret = *iret[idet]; - else if (ret != *iret[idet]) - ret = -1; - delete iret[idet]; - } else - ret = -1; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - - //for usability for the user - if (getDetectorsType() == EIGER) { - if (p == 32) { - std::cout << "Setting Clock to Quarter Speed to cope with Dynamic Range of 32" << std::endl; - setSpeed(CLOCK_DIVIDER, 2); - } else if (p == 16) { - std::cout << "Setting Clock to Half Speed for Dynamic Range of 16" << std::endl; - setSpeed(CLOCK_DIVIDER, 1); - } - if (p != -1) - updateOffsets(); - } - return ret; -} - -int multiSlsDetector::getDataBytes() { - int n_bytes = 0; - for (unsigned int ip = 0; ip < detectors.size(); ++ip) { - n_bytes += detectors[ip]->getDataBytes(); - } - return n_bytes; -} - - -dacs_t multiSlsDetector::setDAC(dacs_t val, dacIndex idac, int mV, int imod) { - dacs_t ret = -100; - - // single - { - int id = -1, im = -1; - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 && id >= (int)detectors.size()) - return -1; - ret = detectors[id]->setDAC(val, idac, mV, im); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - return ret; - } - } - - // multi - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } - - int posmin = 0, posmax = detectors.size(); - dacs_t* iret[posmax - posmin]; - - for (int idet = posmin; idet < posmax; ++idet) { - iret[idet] = new dacs_t(-1); - Task* task = new Task(new func4_t - (&slsDetector::setDAC, detectors[idet], val, idac, mV, imod, iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (iret[idet] != NULL) { - - // highvoltage of slave, ignore value - if ((idac == HV_NEW) && (*iret[idet] == -999)) - ; - else { - if (ret == -100) - ret = *iret[idet]; - else if (ret != *iret[idet]) - ret = -1; - } - delete iret[idet]; - } else - ret = -1; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - if (ret == -100) - ret = -1; - - return ret; -} - -dacs_t multiSlsDetector::getADC(dacIndex idac, int imod) { - dacs_t ret = -100; - - // single - { - int id = -1, im = -1; - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 && id >= (int)detectors.size()) - return -1; - ret = detectors[id]->getADC(idac, im); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - return ret; - } - } - - // multi - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } - - int posmin = 0, posmax = detectors.size(); - dacs_t* iret[posmax - posmin]; - - for (int idet = posmin; idet < posmax; ++idet) { - iret[idet] = new dacs_t(-1); - Task* task = new Task(new func2_t(&slsDetector::getADC, - detectors[idet], idac, imod, iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (detectors[idet]) { - if (iret[idet] != NULL) { - if (ret == -100) - ret = *iret[idet]; - else if (ret != *iret[idet]) - ret = -1; - delete iret[idet]; - } else - ret = -1; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - - return ret; -} - - -slsDetectorDefs::externalCommunicationMode multiSlsDetector::setExternalCommunicationMode( - externalCommunicationMode pol) { - externalCommunicationMode ret, ret1; - //(Dhanya) FIXME: why first detector or is it the master one? - if (detectors.size()) - ret = detectors[0]->setExternalCommunicationMode(pol); - if (detectors[0]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << 0)); - - for (unsigned int idet = 1; idet < detectors.size(); ++idet) { - ret1 = detectors[idet]->setExternalCommunicationMode(pol); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - if (ret != ret1) - ret = GET_EXTERNAL_COMMUNICATION_MODE; - } - setMaster(); - setSynchronization(); - return ret; -} - -slsDetectorDefs::externalSignalFlag multiSlsDetector::setExternalSignalFlags( - externalSignalFlag pol, int signalindex) { - externalSignalFlag ret, ret1; - //(Dhanya) FIXME: why first detector or is it the master one? - if (detectors.size()) - ret = detectors[0]->setExternalSignalFlags(pol, signalindex); - if (detectors[0]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << 0)); - - for (unsigned int idet = 1; idet < detectors.size(); ++idet) { - ret1 = detectors[idet]->setExternalSignalFlags(pol, signalindex); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - if (ret != ret1) - ret = GET_EXTERNAL_SIGNAL_FLAG; - } - setMaster(); - setSynchronization(); - return ret; -} - -int multiSlsDetector::setReadOutFlags(readOutFlags flag) { - int ret = -100, ret1; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - ret1 = detectors[idet]->setReadOutFlags(flag); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - if (ret == -100) - ret = ret1; - else if (ret != ret1) - ret = -1; - } - - return ret; -} - - -uint32_t multiSlsDetector::writeRegister(uint32_t addr, uint32_t val) { - uint32_t ret, ret1; - for (unsigned int i = 0; i < detectors.size(); ++i) { - ret = detectors[i]->writeRegister(addr, val); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (i == 0) - ret1 = ret; - else if (ret != ret1) { - // not setting it to -1 as it is a possible value - std::cout << "Error: Different Values for function writeRegister [" - << ret << "," << ret1 << "]" << endl; - setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); - } - } - - return ret1; -} - - -uint32_t multiSlsDetector::readRegister(uint32_t addr) { - uint32_t ret, ret1; - for (unsigned int i = 0; i < detectors.size(); ++i) { - ret = detectors[i]->readRegister(addr); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (i == 0) - ret1 = ret; - else if (ret != ret1) { - // not setting it to -1 as it is a possible value - std::cout << "Error: Different Values for function readRegister [" - << ret << "," << ret1 << "]" << endl; - setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); - } - } - - return ret1; -} - - - - -uint32_t multiSlsDetector::setBit(uint32_t addr, int n) { - uint32_t ret, ret1; - for (unsigned int i = 0; i < detectors.size(); ++i) { - ret1 = detectors[i]->setBit(addr, n); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (i == 0) - ret = ret1; - else if (ret != ret1) { - // not setting it to -1 as it is a possible value - std::cout << "Error: Different Values for function setBit [" - << ret << "," << ret1 << "]" << endl; - setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); - } - } - - return ret; -} - -uint32_t multiSlsDetector::clearBit(uint32_t addr, int n) { - uint32_t ret, ret1; - for (unsigned int i = 0; i < detectors.size(); ++i) { - ret1 = detectors[i]->clearBit(addr, n); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (i == 0) - ret = ret1; - else if (ret != ret1) { - // not setting it to -1 as it is a possible value - std::cout << "Error: Different Values for function clearBit [" - << ret << "," << ret1 << "]" << endl; - setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); - } - } - - return ret; -} - -std::string multiSlsDetector::setNetworkParameter(networkParameter p, std::string s) { - - if (s.find('+') == std::string::npos) { - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return getNetworkParameter(p); - } else { - std::string* sret[detectors.size()]; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (p == RECEIVER_STREAMING_PORT || p == CLIENT_STREAMING_PORT) - s.append("multi\0"); - sret[idet] = new std::string("error"); - Task* task = new Task(new func2_t(&slsDetector::setNetworkParameter, - detectors[idet], p, s, sret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (sret[idet] != NULL) - delete sret[idet]; - //doing nothing with the return values - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - - } else { - size_t p1 = 0; - size_t p2 = s.find('+', p1); - int id = 0; - while (p2 != std::string::npos) { - detectors[id]->setNetworkParameter(p, s.substr(p1, p2 - p1)); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - ++id; - s = s.substr(p2 + 1); - p2 = s.find('+'); - if (id >= (int)detectors.size()) - break; - } - } - - return getNetworkParameter(p); -} - -std::string multiSlsDetector::getNetworkParameter(networkParameter p) { - std::string s0 = "", s1 = "", s; - std::string ans = ""; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - s = detectors[idet]->getNetworkParameter(p); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - - if (s0 == "") - s0 = s + std::string("+"); - else - s0 += s + std::string("+"); - - if (s1 == "") - s1 = s; - else if (s1 != s) - s1 = "bad"; - } - if (s1 == "bad") - ans = s0; - else - ans = s1; - return ans; -} - -int multiSlsDetector::digitalTest(digitalTestMode mode, int imod) { - - int id, im, ret; - - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return -1; - ret = detectors[id]->digitalTest(mode, im); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - return ret; - } - - return -1; -} - -int multiSlsDetector::executeTrimming(trimMode mode, int par1, int par2, int imod) { - int ret = 100; - - // single - { - int id = -1, im = -1; - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return -1; - ret = detectors[id]->executeTrimming(mode, par1, par2, im); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - return ret; - } - } - - // multi - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } - - int* iret[detectors.size()]; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - iret[idet] = new int(-1); - Task* task = new Task(new func4_t(&slsDetector::executeTrimming, - detectors[idet], mode, par1, par2, imod, iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (iret[idet] != NULL) { - if (ret == -100) - ret = *iret[idet]; - else if (ret != *iret[idet]) - ret = -1; - delete iret[idet]; - } else - ret = -1; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - - return ret; -} - - -int multiSlsDetector::loadImageToDetector(imageType index, std::string const fname) { - - int ret = -100, ret1; - short int imageVals[thisMultiDetector->numberOfChannels]; - - std::ifstream infile; - infile.open(fname.c_str(), std::ios_base::in); - if (infile.is_open()) { -#ifdef VERBOSE - std::cout << std::endl - << "Loading "; - if (!index) - std::cout << "Dark"; - else - std::cout << "Gain"; - std::cout << " image from file " << fname << std::endl; -#endif - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (detectors[idet]->readDataFile(infile, imageVals) >= 0) { - ret1 = detectors[idet]->sendImageToDetector(index, imageVals); - if (ret == -100) - ret = ret1; - else if (ret != ret1) - ret = -1; - } - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - infile.close(); - } else { - std::cout << "Could not open file " << fname << std::endl; - return -1; - } - return ret; -} - -int multiSlsDetector::writeCounterBlockFile(std::string const fname, int startACQ) { - int ret = OK, ret1 = OK; - short int arg[thisMultiDetector->numberOfChannels]; - std::ofstream outfile; - outfile.open(fname.c_str(), std::ios_base::out); - if (outfile.is_open()) { -#ifdef VERBOSE - std::cout << std::endl - << "Reading Counter to \"" << fname; - if (startACQ == 1) - std::cout << "\" and Restarting Acquisition"; - std::cout << std::endl; -#endif - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - ret1 = detectors[idet]->getCounterBlock(arg, startACQ); - if (ret1 != OK) - ret = FAIL; - else { - ret1 = detectors[idet]->writeDataFile(outfile, arg); - if (ret1 != OK) - ret = FAIL; - } - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - outfile.close(); - } else { - std::cout << "Could not open file " << fname << std::endl; - return -1; - } - return ret; -} - -int multiSlsDetector::resetCounterBlock(int startACQ) { - return callDetectorMember(&slsDetector::resetCounterBlock, startACQ); -} - -int multiSlsDetector::setCounterBit(int i) { - return callDetectorMember(&slsDetector::setCounterBit, i); -} - -void multiSlsDetector::verifyMinMaxROI(int n, ROI r[]) { - int temp; - for (int i = 0; i < n; ++i) { - if ((r[i].xmax) < (r[i].xmin)) { - temp = r[i].xmax; - r[i].xmax = r[i].xmin; - r[i].xmin = temp; - } - if ((r[i].ymax) < (r[i].ymin)) { - temp = r[i].ymax; - r[i].ymax = r[i].ymin; - r[i].ymin = temp; - } - } -} - -int multiSlsDetector::setROI(int n, ROI roiLimits[], int imod) { - if (imod > 0 && imod < (int)detectors.size()) { - return detectors[imod]->setROI(n, roiLimits, imod); - } - int ret1 = -100, ret; - int i, xmin, xmax, ymin, ymax, channelX, channelY, idet, lastChannelX, - lastChannelY, index, offsetX, offsetY; - bool invalidroi = false; - int ndet = detectors.size(); - ROI allroi[ndet][n]; - int nroi[ndet]; - for (i = 0; i < ndet; ++i) - nroi[i] = 0; - - if ((n < 0) || (roiLimits == NULL)) - return FAIL; - - // cout << "Setting ROI for " << n << "rois:" << endl; - //ensures min < max - verifyMinMaxROI(n, roiLimits); -#ifdef VERBOSE - cout << "Setting ROI for " << n << "rois:" << endl; - for (i = 0; i < n; ++i) - cout << i << ":" << roiLimits[i].xmin << "\t" << roiLimits[i].xmax - << "\t" << roiLimits[i].ymin << "\t" << roiLimits[i].ymax << endl; -#endif - //for each roi - for (i = 0; i < n; ++i) { - xmin = roiLimits[i].xmin; - xmax = roiLimits[i].xmax; - ymin = roiLimits[i].ymin; - ymax = roiLimits[i].ymax; - if (getDetectorsType() != JUNGFRAUCTB) { - //check roi max values - idet = decodeNChannel(xmax, ymax, channelX, channelY); -#ifdef VERBOSE - cout << "Decoded Channel max vals: " << endl; - cout << "det:" << idet << "\t" << xmax << "\t" << ymax << "\t" - << channelX << "\t" << channelY << endl; -#endif - //std::cout << getDetectorsType() << endl; - if (idet == -1 ) { - cout << "invalid roi" << endl; - continue; - } - - //split in x dir - while (xmin <= xmax) { - invalidroi = false; - ymin = roiLimits[i].ymin; - //split in y dir - while (ymin <= ymax) { - //get offset for each detector - idet = decodeNChannel(xmin, ymin, channelX, channelY); -#ifdef VERBOSE - cout << "Decoded Channel min vals: " << endl; - cout << "det:" << idet << "\t" << xmin << "\t" << ymin - << "\t" << channelX << "\t" << channelY << endl; -#endif - if (idet < 0 || idet >= (int)detectors.size()) { - cout << "invalid roi" << endl; - invalidroi = true; - break; - } - //get last channel for each det in x and y dir - lastChannelX = (detectors[idet]->getMaxNumberOfChannelsInclGapPixels(X)) - 1; - lastChannelY = (detectors[idet]->getMaxNumberOfChannelsInclGapPixels(Y)) - 1; - - offsetX = detectors[idet]->getDetectorOffset(X); - offsetY = detectors[idet]->getDetectorOffset(Y); - //at the end in x dir - if ((offsetX + lastChannelX) >= xmax) - lastChannelX = xmax - offsetX; - //at the end in y dir - if ((offsetY + lastChannelY) >= ymax) - lastChannelY = ymax - offsetY; - -#ifdef VERBOSE - cout << "lastChannelX:" << lastChannelX << "\t" - << "lastChannelY:" << lastChannelY << endl; -#endif - - //creating the list of roi for corresponding detector - index = nroi[idet]; - allroi[idet][index].xmin = channelX; - allroi[idet][index].xmax = lastChannelX; - allroi[idet][index].ymin = channelY; - allroi[idet][index].ymax = lastChannelY; - nroi[idet] = nroi[idet] + 1; - - ymin = lastChannelY + offsetY + 1; - if ((lastChannelY + offsetY) == ymax) - ymin = ymax + 1; - -#ifdef VERBOSE - cout << "nroi[idet]:" << nroi[idet] << "\tymin:" << ymin << endl; -#endif - - } - if (invalidroi) - break; - - xmin = lastChannelX + offsetX + 1; - if ((lastChannelX + offsetX) == xmax) - xmin = xmax + 1; - } - }else { - idet=0; - nroi[idet]=n; - index = 0; - allroi[idet][index].xmin = xmin; - allroi[idet][index].xmax = xmax; - allroi[idet][index].ymin = ymin; - allroi[idet][index].ymax = ymax; - // nroi[idet] = nroi[idet] + 1; - - } - } - -#ifdef VERBOSE - cout << "Setting ROI :" << endl; - for (i = 0; i < detectors.size(); ++i) { - cout << "detector " << i << endl; - for (int j = 0; j < nroi[i]; ++j) { - cout << allroi[i][j].xmin << "\t" << allroi[i][j].xmax << "\t" - << allroi[i][j].ymin << "\t" << allroi[i][j].ymax << endl; - } - } -#endif - - //settings the rois for each detector - for (unsigned i = 0; i < detectors.size(); ++i) { -#ifdef VERBOSE - cout << "detector " << i << ":" << endl; -#endif - ret = detectors[i]->setROI(nroi[i], allroi[i]); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret1 == -100) - ret1 = ret; - else - ret1 = FAIL; - } - - return ret1; -} - - -slsDetectorDefs::ROI* multiSlsDetector::getROI(int& n, int imod) { - if (imod > 0 && imod < (int)detectors.size()) { - return detectors[imod]->getROI(n, imod); - } - n = 0; - int num = 0, i, j; - int ndet = detectors.size(); - int maxroi = ndet * MAX_ROIS; - ROI temproi; - ROI roiLimits[maxroi]; - ROI* retval = new ROI[maxroi]; - ROI* temp = 0; - int index = 0; - - //get each detector's roi array - for (unsigned i = 0; i < detectors.size(); ++i) { - temp = detectors[i]->getROI(index); - // cout << index << endl; - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - - if (temp) { - //#ifdef VERBOSE - if (index) - cout << "detector " << i << ":" << endl; - //#endif - for (j = 0; j < index; ++j) { - //#ifdef VERBOSE - cout << temp[j].xmin << "\t" << temp[j].xmax << "\t" - << temp[j].ymin << "\t" << temp[j].ymax << endl; - //#endif - int x = detectors[i]->getDetectorOffset(X); - int y = detectors[i]->getDetectorOffset(Y); - roiLimits[n].xmin = temp[j].xmin + x; - roiLimits[n].xmax = temp[j].xmax + x; - roiLimits[n].ymin = temp[j].ymin + y; - roiLimits[n].ymax = temp[j].ymin + y; - ++n; - } - } - } - - //empty roi - if (!n) - return NULL; - -#ifdef VERBOSE - cout << "ROI :" << endl; - for (int j = 0; j < n; ++j) { - cout << roiLimits[j].xmin << "\t" << roiLimits[j].xmax << "\t" - << roiLimits[j].ymin << "\t" << roiLimits[j].ymax << endl; - } -#endif - - //combine all the adjacent rois in x direction - for (i = 0; i < n; ++i) { - //since the ones combined are replaced by -1 - if ((roiLimits[i].xmin) == -1) - continue; - for (j = i + 1; j < n; ++j) { - //since the ones combined are replaced by -1 - if ((roiLimits[j].xmin) == -1) - continue; - //if y values are same - if (((roiLimits[i].ymin) == (roiLimits[j].ymin)) && - ((roiLimits[i].ymax) == (roiLimits[j].ymax))) { - //if adjacent, increase [i] range and replace all [j] with -1 - if ((roiLimits[i].xmax) + 1 == roiLimits[j].xmin) { - roiLimits[i].xmax = roiLimits[j].xmax; - roiLimits[j].xmin = -1; - roiLimits[j].xmax = -1; - roiLimits[j].ymin = -1; - roiLimits[j].ymax = -1; - } - //if adjacent, increase [i] range and replace all [j] with -1 - else if ((roiLimits[i].xmin) - 1 == roiLimits[j].xmax) { - roiLimits[i].xmin = roiLimits[j].xmin; - roiLimits[j].xmin = -1; - roiLimits[j].xmax = -1; - roiLimits[j].ymin = -1; - roiLimits[j].ymax = -1; - } - } - } - } - -#ifdef VERBOSE - cout << "Combined along x axis Getting ROI :" << endl; - cout << "detector " << i << endl; - for (int j = 0; j < n; ++j) { - cout << roiLimits[j].xmin << "\t" << roiLimits[j].xmax << "\t" - << roiLimits[j].ymin << "\t" << roiLimits[j].ymax << endl; - } -#endif - - //combine all the adjacent rois in y direction - for (i = 0; i < n; ++i) { - //since the ones combined are replaced by -1 - if ((roiLimits[i].ymin) == -1) - continue; - for (j = i + 1; j < n; ++j) { - //since the ones combined are replaced by -1 - if ((roiLimits[j].ymin) == -1) - continue; - //if x values are same - if (((roiLimits[i].xmin) == (roiLimits[j].xmin)) && - ((roiLimits[i].xmax) == (roiLimits[j].xmax))) { - //if adjacent, increase [i] range and replace all [j] with -1 - if ((roiLimits[i].ymax) + 1 == roiLimits[j].ymin) { - roiLimits[i].ymax = roiLimits[j].ymax; - roiLimits[j].xmin = -1; - roiLimits[j].xmax = -1; - roiLimits[j].ymin = -1; - roiLimits[j].ymax = -1; - } - //if adjacent, increase [i] range and replace all [j] with -1 - else if ((roiLimits[i].ymin) - 1 == roiLimits[j].ymax) { - roiLimits[i].ymin = roiLimits[j].ymin; - roiLimits[j].xmin = -1; - roiLimits[j].xmax = -1; - roiLimits[j].ymin = -1; - roiLimits[j].ymax = -1; - } - } - } - } - - // get rid of -1s - for (i = 0; i < n; ++i) { - if ((roiLimits[i].xmin) != -1) { - retval[num] = roiLimits[i]; - ++num; - } - } - //sort final roi - for (i = 0; i < num; ++i) { - for (j = i + 1; j < num; ++j) { - if (retval[j].xmin < retval[i].xmin) { - temproi = retval[i]; - retval[i] = retval[j]; - retval[j] = temproi; - } - } - } - n = num; - - cout << "\nxmin\txmax\tymin\tymax" << endl; - for (i = 0; i < n; ++i) - cout << retval[i].xmin << "\t" << retval[i].xmax << "\t" - << retval[i].ymin << "\t" << retval[i].ymax << endl; - return retval; -} - -int multiSlsDetector::writeAdcRegister(int addr, int val) { - - int ret, ret1 = -100; - - for (unsigned int i = 0; i < detectors.size(); ++i) { - ret = detectors[i]->writeAdcRegister(addr, val); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret1 == -100) - ret1 = ret; - else if (ret != ret1) { - // not setting it to -1 as it is a possible value - std::cout << "Error: Different Values for function " - "writeAdcRegister [" << ret << "," << ret1 << "]" << endl; - setErrorMask(getErrorMask() | MULTI_HAVE_DIFFERENT_VALUES); - } - } - - return ret1; -} - -int multiSlsDetector::activate(int const enable) { - return callDetectorMember(&slsDetector::activate, enable); -} - -int multiSlsDetector::setDeactivatedRxrPaddingMode(int padding) { - return callDetectorMember(&slsDetector::setDeactivatedRxrPaddingMode, padding); -} - -int multiSlsDetector::getFlippedData(dimension d) { - return callDetectorMember(&slsDetector::getFlippedData, d); -} - -int multiSlsDetector::setFlippedData(dimension d, int value) { - return callDetectorMember(&slsDetector::setFlippedData, d, value); -} - -int multiSlsDetector::setAllTrimbits(int val, int imod) { - int ret = -100; - - // single - { - int id = -1, im = -1; - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return -1; - ret = detectors[id]->setAllTrimbits(val, im); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - return ret; - } - } - - // multi - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } - int* iret[detectors.size()]; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - iret[idet] = new int(-1); - Task* task = new Task(new func2_t(&slsDetector::setAllTrimbits, - detectors[idet], val, imod, iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (iret[idet] != NULL) { - if (ret == -100) - ret = *iret[idet]; - else if (ret != *iret[idet]) - ret = -1; - delete iret[idet]; - } else - ret = -1; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - return ret; -} - - -int multiSlsDetector::enableGapPixels(int val) { - if (val > 0 && getDetectorsType() != EIGER) { - std::cout << "Not implemented for this detector" << std::endl; - val = -1; - } - int ret = callDetectorMember(&slsDetector::enableGapPixels, val); - - if (val != -1) { - // update data bytes incl gap pixels - thisMultiDetector->dataBytesInclGapPixels = 0; - for (unsigned int i = 0; i < detectors.size(); ++i) { - thisMultiDetector->dataBytesInclGapPixels += - detectors[i]->getDataBytesInclGapPixels(); - } - // update offsets and number of channels incl gap pixels in multi level - updateOffsets(); - } - return ret; -} - -int multiSlsDetector::setTrimEn(int ne, int* ene) { - int ret = -100, ret1; - int* ene1 = 0; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - ret1 = detectors[idet]->setTrimEn(ne, ene); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - if (ret == -100) - ret = ret1; - else if (ret != ret1) - ret = -1; - - if (ene != NULL) { - if (ene1 == 0) { - ene1 = new int[ret1]; - for (int i = 0; i < ret1; ++i){ - ene1[i] = ene[i]; - } - }else if (ret != -1) { - // only check if it is not already a fail - for (int i = 0; i < ret; ++i){ - if (ene1[i] != ene[i]) - ret = -1; - } - } - } - } - return ret; -} - -int multiSlsDetector::getTrimEn(int* ene) { - int ret = -100, ret1; - int* ene1 = 0; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - ret1 = detectors[idet]->getTrimEn(ene); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - if (ret == -100) - ret = ret1; - else if (ret != ret1) - ret = -1; - - if (ene != NULL) { - if (ene1 == 0) { - ene1 = new int[ret1]; - for (int i = 0; i < ret1; ++i){ - ene1[i] = ene[i]; - } - }else if (ret != -1) { - // only check if it is not already a fail - for (int i = 0; i < ret; ++i){ - if (ene1[i] != ene[i]) - ret = -1; - } - } - } - } - - if (ene1) - delete [] ene1; - return ret; -} - -int multiSlsDetector::pulsePixel(int n, int x, int y) { - return parallelCallDetectorMember(&slsDetector::pulsePixel, n, x, y); -} - -int multiSlsDetector::pulsePixelNMove(int n, int x, int y) { - return parallelCallDetectorMember(&slsDetector::pulsePixelNMove, n, x, y); -} - -int multiSlsDetector::pulseChip(int n) { - return parallelCallDetectorMember(&slsDetector::pulseChip, n); -} - -int multiSlsDetector::setThresholdTemperature(int val, int imod) { - int ret = -100; - - // single - { - int id = -1, im = -1; - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return -1; - ret = detectors[id]->setThresholdTemperature(val, im); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - return ret; - } - } - - // multi - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } - - int posmin = 0, posmax = detectors.size(); - int* iret[posmax - posmin]; - - for (int idet = posmin; idet < posmax; ++idet) { - iret[idet] = new dacs_t(-1); - Task* task = new Task(new func2_t(&slsDetector::setThresholdTemperature, - detectors[idet], val, imod, iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (iret[idet] != NULL) { - if (ret == -100) - ret = *iret[idet]; - else if (ret != *iret[idet]) - ret = -1; - delete iret[idet]; - } else - ret = -1; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - - return ret; -} - -int multiSlsDetector::setTemperatureControl(int val, int imod) { - int ret = -100; - - // single - { - int id = -1, im = -1; - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return -1; - ret = detectors[id]->setTemperatureControl(val, im); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - return ret; - } - } - - // multi - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } - - int posmin = 0, posmax = detectors.size(); - int* iret[posmax - posmin]; - - for (int idet = posmin; idet < posmax; ++idet) { - iret[idet] = new dacs_t(-1); - Task* task = new Task(new func2_t(&slsDetector::setTemperatureControl, - detectors[idet], val, imod, iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (iret[idet] != NULL) { - if (ret == -100) - ret = *iret[idet]; - else if (ret != *iret[idet]) - ret = -1; - delete iret[idet]; - } else - ret = -1; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - - return ret; -} - -int multiSlsDetector::setTemperatureEvent(int val, int imod) { - int ret = -100; - - // single - { - int id = -1, im = -1; - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return -1; - ret = detectors[id]->setTemperatureEvent(val, im); - if (detectors[id]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << id)); - return ret; - } - } - - // multi - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } - - int posmin = 0, posmax = detectors.size(); - int* iret[posmax - posmin]; - - for (int idet = posmin; idet < posmax; ++idet) { - iret[idet] = new dacs_t(-1); - Task* task = new Task(new func2_t(&slsDetector::setTemperatureEvent, - detectors[idet], val, imod, iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (iret[idet] != NULL) { - if (ret == -100) - ret = *iret[idet]; - else if (ret != *iret[idet]) - ret = -1; - delete iret[idet]; - } else - ret = -1; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - - return ret; -} - -int multiSlsDetector::setStoragecellStart(int pos) { - return parallelCallDetectorMember(&slsDetector::setStoragecellStart, pos); -} - -int multiSlsDetector::programFPGA(std::string fname) { - int ret = OK, ret1 = OK; - - for (unsigned int i = 0; i < detectors.size(); ++i) { - ret = detectors[i]->programFPGA(fname); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret == FAIL) - ret1 = FAIL; - } - return ret1; -} - -int multiSlsDetector::resetFPGA() { - int ret = OK, ret1 = OK; - - for (unsigned int i = 0; i < detectors.size(); ++i) { - ret = detectors[i]->resetFPGA(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret == FAIL) - ret1 = FAIL; - } - return ret1; -} - -int multiSlsDetector::powerChip(int ival) { - int ret = OK, ret1 = OK; - - for (unsigned int i = 0; i < detectors.size(); ++i) { - ret = detectors[i]->powerChip(ival); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret == FAIL) - ret1 = FAIL; - } - return ret1; -} - -int multiSlsDetector::setAutoComparatorDisableMode(int ival) { - int ret = OK, ret1 = OK; - - for (unsigned int i = 0; i < detectors.size(); ++i) { - ret = detectors[i]->setAutoComparatorDisableMode(ival); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret == FAIL) - ret1 = FAIL; - } - return ret1; -} - -double multiSlsDetector::getScanStep(int index, int istep) { - return thisMultiDetector->scanSteps[index][istep]; -} - -int multiSlsDetector::getChanRegs(double* retval, bool fromDetector) { - //nChansDet and currentNumChans is because of varying channel size per detector - int n = thisMultiDetector->numberOfChannels, nChansDet, currentNumChans = 0; - double retval1[n]; - - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - nChansDet = detectors[idet]->getChanRegs(retval1, fromDetector); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - - memcpy(retval + (currentNumChans), retval1, nChansDet * sizeof(double)); - currentNumChans += nChansDet; - } - return n; -} - - - -int multiSlsDetector::setChannel(int64_t reg, int ichan, int ichip, int imod) { - int ret, ret1 = -100; - int id = -1, im = -1; - int dmi = 0, dma = detectors.size(); - - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return -1; - dmi = id; - dma = id + 1; - } - for (int idet = dmi; idet < dma; ++idet) { - ret = detectors[idet]->setChannel(reg, ichan, ichip, im); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - if (ret1 == -100) - ret1 = ret; - else if (ret != ret1) - ret1 = -1; - } - return ret1; -} - -int multiSlsDetector::getMoveFlag(int imod) { - int id = -1, im = -1; - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return -1; - return detectors[id]->getMoveFlag(im); - } - - //default!!! - return 1; -} - -int multiSlsDetector::fillModuleMask(int* mM) { - int imod = 0, off = 0; - if (mM) { - for (unsigned int i = 0; i < detectors.size(); ++i) { - for (int im = 0; im < detectors[i]->getNMods(); ++im) { - mM[imod] = im + off; - ++imod; - } - off += detectors[i]->getMaxMods(); - } - } - return getNMods(); -} - - -int multiSlsDetector::calibratePedestal(int frames) { - return callDetectorMember(&slsDetector::calibratePedestal, frames); -} - - -int multiSlsDetector::setRateCorrection(double t) { - -#ifdef VERBOSE - std::cout << "Setting rate correction with dead time " << - thisMultiDetector->tDead << std::endl; -#endif - int ret = OK; - int posmax = detectors.size(); - - // eiger return value is ok/fail - if (getDetectorsType() == EIGER) { - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return FAIL; - } else { - int* iret[posmax]; - for (int idet = 0; idet < posmax; ++idet) { - iret[idet] = new int(OK); - Task* task = new Task(new func1_t - (&slsDetector::setRateCorrection, - detectors[idet], t, iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = 0; idet < posmax; ++idet) { - if (iret[idet] != NULL) { - if (*iret[idet] != OK) - ret = FAIL; - delete iret[idet]; - } else - ret = FAIL; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - return ret; - } - - // mythen, others - if (t == 0) { - thisMultiDetector->correctionMask &= ~(1 << RATE_CORRECTION); - return thisMultiDetector->correctionMask & (1 << RATE_CORRECTION); - } else - thisMultiDetector->correctionMask |= (1 << RATE_CORRECTION); - - ret = -100; - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } else { - int* iret[posmax]; - for (int idet = 0; idet < posmax; ++idet) { - iret[idet] = new int(-1); - Task* task = new Task(new func1_t - (&slsDetector::setRateCorrection, - detectors[idet], t, iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = 0; idet < posmax; ++idet) { - if (iret[idet] != NULL) - delete iret[idet]; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - return thisMultiDetector->correctionMask & (1 << RATE_CORRECTION); -} - -int multiSlsDetector::getRateCorrection(double& t) { - if (getDetectorsType() == EIGER) { - t = getRateCorrectionTau(); - return t; - } - - if (thisMultiDetector->correctionMask & (1 << RATE_CORRECTION)) { -#ifdef VERBOSE - std::cout << "Rate correction is enabled with dead time " << - thisMultiDetector->tDead << std::endl; -#endif - return 1; - } else - t = 0; -#ifdef VERBOSE - std::cout << "Rate correction is disabled " << std::endl; -#endif - return 0; -} - -double multiSlsDetector::getRateCorrectionTau() { - - double ret = -100.0; - int posmax = detectors.size(); - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } else { - double* iret[posmax]; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - iret[idet] = new double(-1); - Task* task = new Task(new func0_t - (&slsDetector::getRateCorrectionTau, - detectors[idet], iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - - for (int idet = 0; idet < posmax; ++idet) { - if (iret[idet] != NULL) { - if (ret == -100.0) - ret = *iret[idet]; - else if ((ret - *iret[idet]) > 0.000000001) { - std::cout << "Rate correction is different for " - "different readouts " << std::endl; - ret = -1; - } - delete iret[idet]; - } else - ret = -1; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - - if (getDetectorsType() == EIGER) - return ret; - - //only mythen - if (thisMultiDetector->correctionMask & (1 << RATE_CORRECTION)) { -#ifdef VERBOSE - std::cout << "Rate correction is enabled with dead time " << - thisMultiDetector->tDead << std::endl; -#endif - } else { -#ifdef VERBOSE - std::cout << "Rate correction is disabled " << std::endl; -#endif - ret = 0; - } - return ret; -} - -int multiSlsDetector::getRateCorrection() { - if (getDetectorsType() == EIGER) { - return getRateCorrectionTau(); - } - if (thisMultiDetector->correctionMask & (1 << RATE_CORRECTION)) { - return 1; - } else - return 0; -}; - -int multiSlsDetector::rateCorrect(double* datain, double* errin, double* dataout, double* errout) { - int ichdet = 0; - double* perr = errin; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (errin) - perr += ichdet; - detectors[idet]->rateCorrect(datain + ichdet, perr, dataout + ichdet, - errout + ichdet); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - ichdet += detectors[idet]->getTotalNumberOfChannels(); - } - return 0; -} - - -int multiSlsDetector::setFlatFieldCorrection(std::string fname) { - double* data = new double[thisMultiDetector->numberOfChannels]; - double* ffcoefficients = new double[thisMultiDetector->numberOfChannels]; - double* fferrors = new double[thisMultiDetector->numberOfChannels]; - char ffffname[MAX_STR_LENGTH * 2]; - int nch; - if (fname == "default") { - fname = std::string(thisMultiDetector->flatFieldFile); - } - - thisMultiDetector->correctionMask &= ~(1 << FLAT_FIELD_CORRECTION); - - if (fname == "") { -#ifdef VERBOSE - std::cout << "disabling flat field correction" << std::endl; -#endif - thisMultiDetector->correctionMask &= ~(1 << FLAT_FIELD_CORRECTION); - for (unsigned int i = 0; i < detectors.size(); ++i) { - detectors[i]->setFlatFieldCorrection(NULL, NULL); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - } - } else { -#ifdef VERBOSE - std::cout << "Setting flat field correction from file " << fname << std::endl; -#endif - sprintf(ffffname, "%s/%s", thisMultiDetector->flatFieldDir, fname.c_str()); - nch = readDataFile(std::string(ffffname), data); - - if (nch > thisMultiDetector->numberOfChannels) - nch = thisMultiDetector->numberOfChannels; - - if (nch > 0) { - - int nm = getNMods(); - int chpm[nm]; - int mMask[nm]; - for (int i = 0; i < nm; ++i) { - chpm[i] = getChansPerMod(i); - mMask[i] = i; - } - fillModuleMask(mMask); - fillBadChannelMask(); - if ((postProcessingFuncs::calculateFlatField(&nm, chpm, mMask, - badChannelMask, data, ffcoefficients, fferrors)) >= 0) { - strcpy(thisMultiDetector->flatFieldFile, fname.c_str()); - - thisMultiDetector->correctionMask |= (1 << FLAT_FIELD_CORRECTION); - - setFlatFieldCorrection(ffcoefficients, fferrors); - - } else - std::cout << "Calculated flat field from file " << fname << - " is not valid " << nch << std::endl; - } else { - std::cout << "Flat field from file " << fname << " is not valid " - << nch << std::endl; - } - } - return thisMultiDetector->correctionMask & (1 << FLAT_FIELD_CORRECTION); -} - - -int multiSlsDetector::setFlatFieldCorrection(double* corr, double* ecorr) { - int ichdet = 0; - double *p, *ep; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (corr != NULL) - p = corr + ichdet; - else - p = NULL; - if (ecorr != NULL) - ep = ecorr + ichdet; - else - ep = NULL; - detectors[idet]->setFlatFieldCorrection(p, ep); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - ichdet += detectors[idet]->getTotalNumberOfChannels(); - } - return 0; -} - -int multiSlsDetector::getFlatFieldCorrection(double* corr, double* ecorr) { - int ichdet = 0; - double *p, *ep; - int ff = 1, dff; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - if (corr != NULL) - p = corr + ichdet; - else - p = NULL; - if (ecorr != NULL) - ep = ecorr + ichdet; - else - ep = NULL; - dff = detectors[idet]->getFlatFieldCorrection(p, ep); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - if (dff == 0) - ff = 0; - ichdet += detectors[idet]->getTotalNumberOfChannels(); - } - return ff; -} - -int multiSlsDetector::flatFieldCorrect(double* datain, double* errin, double* dataout, - double* errout) { - int ichdet = 0; - double* perr = errin; //*pdata, - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { -#ifdef VERBOSE - cout << " detector " << idet << " offset " << ichdet << endl; -#endif - if (errin) - perr += ichdet; - detectors[idet]->flatFieldCorrect(datain + ichdet, perr, - dataout + ichdet, errout + ichdet); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - ichdet += detectors[idet]->getTotalNumberOfChannels(); - } - return 0; -} - -int multiSlsDetector::setBadChannelCorrection(std::string fname) { - int badlist[MAX_BADCHANS]; - int nbad = 0; - int ret = 0; - - cout << thisMultiDetector->badChanFile << endl; - - if (fname == "default") - fname = std::string(thisMultiDetector->badChanFile); - - ret = setBadChannelCorrection(fname, nbad, badlist); - //#ifdef VERBOSE - cout << "multi: file contained " << ret << " badchans" << endl; - //#endif - if (ret == 0) { - thisMultiDetector->correctionMask &= ~(1 << DISCARD_BAD_CHANNELS); - nbad = 0; - } else { - thisMultiDetector->correctionMask |= (1 << DISCARD_BAD_CHANNELS); - strcpy(thisMultiDetector->badChanFile, fname.c_str()); - } - - return setBadChannelCorrection(nbad, badlist, 0); -} - -int multiSlsDetector::setBadChannelCorrection(int nbad, int* badlist, int ff) { - int badlistdet[MAX_BADCHANS]; - int nbaddet = 0, choff = 0, idet = 0; - if (nbad < 1) - badlistdet[0] = 0; - else - badlistdet[0] = badlist[0]; - - if (nbad > 0) { - thisMultiDetector->correctionMask |= (1 << DISCARD_BAD_CHANNELS); - - for (int ich = 0; ich < nbad; ++ich) { - if ((badlist[ich] - choff) >= detectors[idet]->getMaxNumberOfChannels()) { - //#ifdef VERBOSE - cout << "setting " << nbaddet << " badchans to detector " - << idet << endl; - //#endif - detectors[idet]->setBadChannelCorrection(nbaddet, badlistdet, 0); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - choff += detectors[idet]->getMaxNumberOfChannels(); - nbaddet = 0; - ++idet; - if (detectors[idet] == NULL) - break; - } - badlistdet[nbaddet] = (badlist[ich] - choff); - ++nbaddet; -#ifdef VERBOSE - cout << nbaddet << " " << badlist[ich] << " " - << badlistdet[nbaddet - 1] << endl; -#endif - } - if (nbaddet > 0) { -#ifdef VERBOSE - cout << "setting " << nbaddet << " badchans to detector " - << idet << endl; -#endif - detectors[idet]->setBadChannelCorrection(nbaddet, badlistdet, 0); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - choff += detectors[idet]->getMaxNumberOfChannels(); - nbaddet = 0; - ++idet; - } - nbaddet = 0; - for (unsigned int i = idet; i < detectors.size(); ++i) { -#ifdef VERBOSE - cout << "setting " << 0 << " badchans to detector " << i << endl; -#endif - detectors[i]->setBadChannelCorrection(nbaddet, badlistdet, 0); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - } - - } else { - nbaddet = 0; - for (unsigned int i = 0; i < detectors.size(); ++i) { -#ifdef VERBOSE - cout << "setting " << 0 << " badchans to detector " << idet << endl; -#endif - detectors[idet]->setBadChannelCorrection(nbaddet, badlistdet, 0); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - thisMultiDetector->correctionMask &= ~(1 << DISCARD_BAD_CHANNELS); - } -#ifdef VERBOSE - cout << (thisMultiDetector->correctionMask & (1 << DISCARD_BAD_CHANNELS)) << endl; -#endif - return thisMultiDetector->correctionMask & (1 << DISCARD_BAD_CHANNELS); -} - - -int multiSlsDetector::getBadChannelCorrection(int* bad) { - //int ichan; - int *bd, nd, ntot = 0, choff = 0; - ; - - if (((thisMultiDetector->correctionMask) & (1 << DISCARD_BAD_CHANNELS)) == 0) - return 0; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - nd = detectors[idet]->getBadChannelCorrection(); - if (nd > 0) { - bd = new int[nd]; - nd = detectors[idet]->getBadChannelCorrection(bd); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - - for (int id = 0; id < nd; ++id) { - if (bd[id] < detectors[idet]->getTotalNumberOfChannels()) { - if (bad) - bad[ntot] = choff + bd[id]; - ++ntot; - } - } - choff += detectors[idet]->getTotalNumberOfChannels(); - delete[] bd; - } else - ntot += nd; - } - return ntot; -} - - -int multiSlsDetector::readAngularConversionFile(std::string fname) { - - std::ifstream infile; - //int nm=0; - infile.open(fname.c_str(), std::ios_base::in); - if (infile.is_open()) { - - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { -#ifdef VERBOSE - cout << " detector " << idet << endl; -#endif - detectors[idet]->readAngularConversion(infile); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - infile.close(); - } else { - std::cout << "Could not open calibration file " << fname << std::endl; - return -1; - } - return 0; -} - -int multiSlsDetector::writeAngularConversion(std::string fname) { - - std::ofstream outfile; - // int nm=0; - outfile.open(fname.c_str(), std::ios_base::out); - if (outfile.is_open()) { - - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - detectors[idet]->writeAngularConversion(outfile); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - outfile.close(); - } else { - std::cout << "Could not open calibration file " << fname << std::endl; - return -1; - } - return 0; -} - -int multiSlsDetector::getAngularConversion(int& direction, angleConversionConstant* angconv) { - - int dir = -100, dir1; - angleConversionConstant* a1 = angconv; - - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - detectors[idet]->getAngularConversion(dir1, a1); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - if (dir == -100) - dir = dir1; - if (dir != dir1) - dir = 0; - if (angconv) { - a1 += detectors[idet]->getNMods(); - } - } - direction = dir; - - if (thisMultiDetector->correctionMask & (1 << ANGULAR_CONVERSION)) { - return 1; - } - return 0; -} - -double multiSlsDetector::setAngularConversionParameter(angleConversionParameter c, double v) { - double ret = slsDetectorUtils::setAngularConversionParameter(c, v); - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - detectors[idet]->setAngularConversionParameter(c, v); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - return ret; -} - -angleConversionConstant* multiSlsDetector::getAngularConversionPointer(int imod) { - int id = -1, im = -1; -#ifdef VERBOSE - cout << "get angular conversion pointer " << endl; -#endif - if (decodeNMod(imod, id, im) >= 0) { - if (id < 0 || id >= (int)detectors.size()) - return NULL; - return detectors[id]->getAngularConversionPointer(im); - } - return NULL; -} - - -int multiSlsDetector::printReceiverConfiguration() { - int ret, ret1 = -100; - std::cout << "Printing Receiver configurations for all detectors..." << std::endl; - for (unsigned int i = 0; i < detectors.size(); ++i) { - std::cout << std::endl - << "#Detector " << i << ":" << std::endl; - - ret = detectors[i]->printReceiverConfiguration(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret1 == -100) - ret1 = ret; - else if (ret != ret1) - ret1 = -1; - } - - return ret1; -} - - -int multiSlsDetector::setReceiverOnline(int off) { - if (off != GET_ONLINE_FLAG) { - thisMultiDetector->receiverOnlineFlag = parallelCallDetectorMember( - &slsDetector::setReceiverOnline, off); - } - return thisMultiDetector->receiverOnlineFlag; -} - -std::string multiSlsDetector::checkReceiverOnline() { - std::string retval1 = "", retval; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - retval = detectors[idet]->checkReceiverOnline(); - if (!retval.empty()) { - retval1.append(retval); - retval1.append("+"); - } - } - return retval1; -} - -int multiSlsDetector::lockReceiver(int lock) { - return callDetectorMember(&slsDetector::lockReceiver, lock); -} - -std::string multiSlsDetector::getReceiverLastClientIP() { - return callDetectorMember(&slsDetector::getReceiverLastClientIP); -} - -int multiSlsDetector::exitReceiver() { - //(Erik) logic is flawed should return fail if any fails? - int ival = FAIL, iv; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - iv = detectors[idet]->exitReceiver(); - if (iv == OK) - ival = iv; - } - return ival; -} - -std::string multiSlsDetector::getFilePath() { - return setFilePath(); -} - -std::string multiSlsDetector::setFilePath(std::string s) { - - std::string ret = "errorerror", ret1; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - ret1 = detectors[idet]->setFilePath(s); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - if (ret == "errorerror") - ret = ret1; - else if (ret != ret1) - ret = ""; - } - fileIO::setFilePath(ret); - return fileIO::getFilePath(); -} - -std::string multiSlsDetector::getFileName() { - return setFileName(); -} - -std::string multiSlsDetector::setFileName(std::string s) { - - std::string ret = "error"; - int posmax = detectors.size(); - - if (!s.empty()) { - fileIO::setFileName(s); - if (thisMultiDetector->receiverOnlineFlag == ONLINE_FLAG) - s = createReceiverFilePrefix(); - } - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return std::string(""); - } else { - std::string* sret[detectors.size()]; - for (int idet = 0; idet < posmax; ++idet) { - sret[idet] = new std::string("error"); - Task* task = new Task(new func1_t(&slsDetector::setFileName, - detectors[idet], s, sret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = 0; idet < posmax; ++idet) { - if (sret[idet] != NULL) { - if (ret == "error") - ret = *sret[idet]; - else if (ret != *sret[idet]) - ret = ""; - delete sret[idet]; - } else - ret = ""; - //doing nothing with the return values - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - - if ((thisMultiDetector->receiverOnlineFlag == ONLINE_FLAG) && - ((ret != "error") || (ret != ""))) { -#ifdef VERBOSE - std::cout << "Complete file prefix from receiver: " << ret << std::endl; -#endif - fileIO::setFileName(getNameFromReceiverFilePrefix(ret)); - } - - return ret; -} - -int multiSlsDetector::setReceiverFramesPerFile(int f) { - return parallelCallDetectorMember(&slsDetector::setReceiverFramesPerFile, f); -} - -slsReceiverDefs::frameDiscardPolicy multiSlsDetector::setReceiverFramesDiscardPolicy(frameDiscardPolicy f) { - return callDetectorMember(&slsDetector::setReceiverFramesDiscardPolicy, f); -} - -int multiSlsDetector::setReceiverPartialFramesPadding(int f) { - return callDetectorMember(&slsDetector::setReceiverPartialFramesPadding, f); -} - -slsReceiverDefs::fileFormat multiSlsDetector::getFileFormat() { - return setFileFormat(); -} - -slsReceiverDefs::fileFormat multiSlsDetector::setFileFormat(fileFormat f) { - return callDetectorMember(&slsDetector::setFileFormat, f); -} - -int multiSlsDetector::getFileIndex() { - return setFileIndex(); -} - -int multiSlsDetector::setFileIndex(int i) { - return parallelCallDetectorMember(&slsDetector::setFileIndex, i); -} - - -int multiSlsDetector::startReceiver() { - int i = 0; - int ret = OK; - int posmin = 0, posmax = detectors.size(); - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return FAIL; - } else { - int* iret[posmax - posmin]; - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition){ - iret[idet] = new int(OK); - Task* task = new Task(new func0_t(&slsDetector::startReceiver, - detectors[idet], iret[idet])); - threadpool->add_task(task); - } - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - if (iret[idet] != NULL) { - if (*iret[idet] != OK) - ret = FAIL; - delete iret[idet]; - } else - ret = FAIL; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - } - - //master - int ret1 = OK; - i = thisMultiDetector->masterPosition; - if (thisMultiDetector->masterPosition >= 0) { - ret1 = detectors[i]->startReceiver(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret1 != OK) - ret = FAIL; - } - return ret; -} - -int multiSlsDetector::stopReceiver() { - int i = 0; - int ret = OK, ret1 = OK; - int posmin = 0, posmax = detectors.size(); - - i = thisMultiDetector->masterPosition; - if (thisMultiDetector->masterPosition >= 0) { - ret1 = detectors[i]->stopReceiver(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (ret1 != OK) - ret = FAIL; - } - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return FAIL; - } else { - int* iret[posmax - posmin]; - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - iret[idet] = new int(OK); - Task* task = new Task(new func0_t(&slsDetector::stopReceiver, - detectors[idet], iret[idet])); - threadpool->add_task(task); - } - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - if (iret[idet] != NULL) { - if (*iret[idet] != OK) - ret = FAIL; - delete iret[idet]; - } else - ret = FAIL; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - } - - return ret; -} - -slsDetectorDefs::runStatus multiSlsDetector::startReceiverReadout() { - unsigned int i = 0; - runStatus s = IDLE, s1 = IDLE; - i = thisMultiDetector->masterPosition; - if (thisMultiDetector->masterPosition >= 0) { - s1 = detectors[i]->startReceiverReadout(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - } - for (i = 0; i < detectors.size(); ++i) { - s = detectors[i]->startReceiverReadout(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - if (s == ERROR) - s1 = ERROR; - if (s != IDLE) - s1 = s; - } - - return s1; -} - -slsDetectorDefs::runStatus multiSlsDetector::getReceiverStatus() { - int i = 0; - runStatus ret = IDLE; - int posmin = 0, posmax = detectors.size(); - - i = thisMultiDetector->masterPosition; - if (thisMultiDetector->masterPosition >= 0) { - ret = detectors[i]->getReceiverStatus(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - return ret; - } - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return ERROR; - } else { - runStatus* iret[posmax - posmin]; - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition) { - iret[idet] = new runStatus(ERROR); - Task* task = new Task(new func0_t(&slsDetector::getReceiverStatus, - detectors[idet], iret[idet])); - threadpool->add_task(task); - } - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - for (int idet = posmin; idet < posmax; ++idet) { - if (idet != thisMultiDetector->masterPosition){ - if (iret[idet] != NULL) { - if (*iret[idet] == (int)ERROR) - ret = ERROR; - if (*iret[idet] != IDLE) - ret = *iret[idet]; - delete iret[idet]; - } else - ret = ERROR; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - } - - return ret; -} - -int multiSlsDetector::getFramesCaughtByAnyReceiver() { - int ret = 0; - int i = thisMultiDetector->masterPosition; - if (i >= 0) { - ret = detectors[i]->getFramesCaughtByReceiver(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - // return master receivers frames caught - return ret; - } - - // return the first one that works - if (detectors.size()) { - ret = detectors[0]->getFramesCaughtByReceiver(); - if (detectors[0]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - return ret; - } - - return -1; -} - -int multiSlsDetector::getFramesCaughtByReceiver() { - - int ret = 0, ret1 = 0; - int posmax = detectors.size(); - - if (!threadpool) { - cout << "Error in creating threadpool. Exiting" << endl; - return -1; - } else { - int* iret[posmax]; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - iret[idet] = new int(0); - Task* task = new Task(new func0_t(&slsDetector::getFramesCaughtByReceiver, - detectors[idet], iret[idet])); - threadpool->add_task(task); - } - threadpool->startExecuting(); - threadpool->wait_for_tasks_to_complete(); - - for (int idet = 0; idet < posmax; ++idet) { - if (iret[idet] != NULL) { - if (*iret[idet] == -1) // could not connect - ret = -1; - else - ret1 += (*iret[idet]); - delete iret[idet]; - } else - ret = -1; - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - } - } - if ((!detectors.size()) || (ret == -1)) - return ret; - - ret = (int)(ret1 / detectors.size()); - return ret; -} - - -int multiSlsDetector::getReceiverCurrentFrameIndex() { - int ret = 0, ret1 = 0; - for (unsigned int i = 0; i < detectors.size(); ++i) { - ret1 += detectors[i]->getReceiverCurrentFrameIndex(); - if (detectors[i]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << i)); - } - if (!detectors.size()) - return ret; - ret = (int)(ret1 / detectors.size()); - - return ret; -} - -int multiSlsDetector::resetFramesCaught() { - return parallelCallDetectorMember(&slsDetector::resetFramesCaught); -} - -int multiSlsDetector::createReceivingDataSockets(const bool destroy) { - if (destroy) { - cprintf(MAGENTA, "Going to destroy data sockets\n"); - //close socket - for (std::vector::const_iterator it = zmqSocket.begin(); it != zmqSocket.end(); ++it) { - (*it)->Close(); - delete(*it); - } - zmqSocket.clear(); - - client_downstream = false; - cout << "Destroyed Receiving Data Socket(s)" << endl; - return OK; - } - - cprintf(MAGENTA, "Going to create data sockets\n"); - - int numSockets = detectors.size(); - int numSocketsPerDetector = 1; - if (getDetectorsType() == EIGER) { - numSocketsPerDetector = 2; - } - numSockets *= numSocketsPerDetector; - - for (int i = 0; i < numSockets; ++i) { - uint32_t portnum = 0; - sscanf(detectors[i / numSocketsPerDetector]->getClientStreamingPort().c_str(), - "%d", &portnum); - portnum += (i % numSocketsPerDetector); - //cout<<"ip to be set to :"<getClientStreamingIP().c_str()<getClientStreamingIP().c_str(), - portnum); - zmqSocket.push_back(z); - printf("Zmq Client[%d] at %s\n", i, z->GetZmqServerAddress()); - } catch (...) { - cprintf(RED, "Error: Could not create Zmq socket on port %d\n", portnum); - createReceivingDataSockets(true); - return FAIL; - } - } - - client_downstream = true; - cout << "Receiving Data Socket(s) created" << endl; - return OK; -} - -void multiSlsDetector::readFrameFromReceiver() { - - int nX = thisMultiDetector->numberOfDetector[X]; // to copy data in multi module - int nY = thisMultiDetector->numberOfDetector[Y]; // for eiger, to reverse the data - bool gappixelsenable = false; - bool eiger = false; - if (getDetectorsType() == EIGER) { - eiger = true; - nX *= 2; - gappixelsenable = detectors[0]->enableGapPixels(-1) >= 1 ? true : false; - } - - bool runningList[zmqSocket.size()], connectList[zmqSocket.size()]; - int numRunning = 0; - for (unsigned int i = 0; i < zmqSocket.size(); ++i) { - if (!zmqSocket[i]->Connect()) { - connectList[i] = true; - runningList[i] = true; - ++numRunning; - } else { - // to remember the list it connected to, to disconnect later - connectList[i] = false; - cprintf(RED, "Error: Could not connect to socket %s\n", - zmqSocket[i]->GetZmqServerAddress()); - runningList[i] = false; - } - } - int numConnected = numRunning; - bool data = false; - char* image = NULL; - char* multiframe = NULL; - char* multigappixels = NULL; - int multisize = 0; - // only first message header - uint32_t size = 0, nPixelsX = 0, nPixelsY = 0, dynamicRange = 0; - float bytesPerPixel = 0; - // header info every header - std::string currentFileName = ""; - uint64_t currentAcquisitionIndex = -1, currentFrameIndex = -1, currentFileIndex = -1; - uint32_t currentSubFrameIndex = -1, coordX = -1, coordY = -1, flippedDataX = -1; - - //wait for real time acquisition to start - bool running = true; - sem_wait(&sem_newRTAcquisition); - if (checkJoinThread()) - running = false; - - //exit when checkJoinThread() (all sockets done) - while (running) { - - // reset data - data = false; - if (multiframe != NULL) - memset(multiframe, 0xFF, multisize); - - //get each frame - for (unsigned int isocket = 0; isocket < zmqSocket.size(); ++isocket) { - - //if running - if (runningList[isocket]) { - - // HEADER - { - rapidjson::Document doc; - if (!zmqSocket[isocket]->ReceiveHeader(isocket, doc, - SLS_DETECTOR_JSON_HEADER_VERSION)) { - // parse error, version error or end of acquisition for socket - runningList[isocket] = false; - --numRunning; - continue; - } - - // if first message, allocate (all one time stuff) - if (image == NULL) { - // allocate - size = doc["size"].GetUint(); - multisize = size * zmqSocket.size(); - image = new char[size]; - multiframe = new char[multisize]; - memset(multiframe, 0xFF, multisize); - // dynamic range - dynamicRange = doc["bitmode"].GetUint(); - bytesPerPixel = (float)dynamicRange / 8; - // shape - nPixelsX = doc["shape"][0].GetUint(); - nPixelsY = doc["shape"][1].GetUint(); - -#ifdef VERBOSE - cprintf(BLUE, "(Debug) One Time Header Info:\n" - "size: %u\n" - "multisize: %u\n" - "dynamicRange: %u\n" - "bytesPerPixel: %f\n" - "nPixelsX: %u\n" - "nPixelsY: %u\n", - size, multisize, dynamicRange, bytesPerPixel, - nPixelsX, nPixelsY); -#endif - } - // each time, parse rest of header - currentFileName = doc["fname"].GetString(); - currentAcquisitionIndex = doc["acqIndex"].GetUint64(); - currentFrameIndex = doc["fIndex"].GetUint64(); - currentFileIndex = doc["fileIndex"].GetUint64(); - currentSubFrameIndex = doc["expLength"].GetUint(); - coordY = doc["row"].GetUint(); - coordX = doc["column"].GetUint(); - if (eiger) - coordY = (nY - 1) - coordY; - //cout << "X:" << doc["row"].GetUint() <<" Y:"<ReceiveData(isocket, image, size); - - // creating multi image - { - uint32_t xoffset = coordX * nPixelsX * bytesPerPixel; - uint32_t yoffset = coordY * nPixelsY; - uint32_t singledetrowoffset = nPixelsX * bytesPerPixel; - uint32_t rowoffset = nX * singledetrowoffset; -#ifdef VERBOSE - cprintf(BLUE, "(Debug) Multi Image Info:\n" - "xoffset: %u\n" - "yoffset: %u\n" - "singledetrowoffset: %u\n" - "rowoffset: %u\n", - xoffset, yoffset, singledetrowoffset, rowoffset); -#endif - if (eiger && flippedDataX) { - for (uint32_t i = 0; i < nPixelsY; ++i) { - memcpy(((char*)multiframe) + - ((yoffset + (nPixelsY - 1 - i)) * rowoffset) + xoffset, - (char*)image + (i * singledetrowoffset), - singledetrowoffset); - } - } else { - for (uint32_t i = 0; i < nPixelsY; ++i) { - memcpy(((char*)multiframe) + - ((yoffset + i) * rowoffset) + xoffset, - (char*)image + (i * singledetrowoffset), - singledetrowoffset); - } - } - } - } - } - - //send data to callback - if (data) { - // 4bit gap pixels - if (dynamicRange == 4 && gappixelsenable) { - int n = processImageWithGapPixels(multiframe, multigappixels); - nPixelsX = thisMultiDetector->numberOfChannelInclGapPixels[X]; - nPixelsY = thisMultiDetector->numberOfChannelInclGapPixels[Y]; - thisData = new detectorData(NULL, NULL, NULL, getCurrentProgress(), - currentFileName.c_str(), nPixelsX, nPixelsY, - multigappixels, n, dynamicRange, currentFileIndex); - } - // normal pixels - else { - thisData = new detectorData(NULL, NULL, NULL, getCurrentProgress(), - currentFileName.c_str(), nPixelsX, nPixelsY, - multiframe, multisize, dynamicRange, currentFileIndex); - } - dataReady(thisData, currentFrameIndex, - ((dynamicRange == 32) ? currentSubFrameIndex : -1), - pCallbackArg); - delete thisData; - setCurrentProgress(currentAcquisitionIndex + 1); - } - - //all done - if (!numRunning) { - // let main thread know that all dummy packets have been received - //(also from external process), - // main thread can now proceed to measurement finished call back - sem_post(&sem_endRTAcquisition); - // wait for next scan/measurement, else join thread - sem_wait(&sem_newRTAcquisition); - //done with complete acquisition - if (checkJoinThread()) - running = false; - else { - //starting a new scan/measurement (got dummy data) - for (unsigned int i = 0; i < zmqSocket.size(); ++i) - runningList[i] = connectList[i]; - numRunning = numConnected; - } - } - } - - // Disconnect resources - for (unsigned int i = 0; i < zmqSocket.size(); ++i) - if (connectList[i]) - zmqSocket[i]->Disconnect(); - - //free resources - if (image != NULL) - delete[] image; - if (multiframe != NULL) - delete[] multiframe; - if (multigappixels != NULL) - delete[] multigappixels; -} - -int multiSlsDetector::processImageWithGapPixels(char* image, char*& gpImage) { - // eiger 4 bit mode - int nxb = thisMultiDetector->numberOfDetector[X] * (512 + 3); - int nyb = thisMultiDetector->numberOfDetector[Y] * (256 + 1); - int gapdatabytes = nxb * nyb; - - int nxchip = thisMultiDetector->numberOfDetector[X] * 4; - int nychip = thisMultiDetector->numberOfDetector[Y] * 1; - - // allocate - if (gpImage == NULL) - gpImage = new char[gapdatabytes]; - // fill value - memset(gpImage, 0xFF, gapdatabytes); - - const int b1chipx = 128; - const int b1chipy = 256; - char* src = 0; - char* dst = 0; - - // copying line by line - src = image; - dst = gpImage; - for (int row = 0; row < nychip; ++row) { // for each chip in a row - for (int ichipy = 0; ichipy < b1chipy; ++ichipy) { //for each row in a chip - for (int col = 0; col < nxchip; ++col) { - memcpy(dst, src, b1chipx); - src += b1chipx; - dst += b1chipx; - if ((col + 1) % 4) - ++dst; - } - } - - dst += (2 * nxb); - } - - // vertical filling of values - { - uint8_t temp, g1, g2; - int mod; - dst = gpImage; - for (int row = 0; row < nychip; ++row) { // for each chip in a row - for (int ichipy = 0; ichipy < b1chipy; ++ichipy) { //for each row in a chip - for (int col = 0; col < nxchip; ++col) { - dst += b1chipx; - mod = (col + 1) % 4; - // copy gap pixel(chip 0, 1, 2) - if (mod) { - // neighbouring gap pixels to left - temp = (*((uint8_t*)(dst - 1))); - g1 = ((temp & 0xF) / 2); - (*((uint8_t*)(dst - 1))) = (temp & 0xF0) + g1; - - // neighbouring gap pixels to right - temp = (*((uint8_t*)(dst + 1))); - g2 = ((temp >> 4) / 2); - (*((uint8_t*)(dst + 1))) = (g2 << 4) + (temp & 0x0F); - - // gap pixels - (*((uint8_t*)dst)) = (g1 << 4) + g2; - - // increment to point to proper chip destination - ++dst; - } - } - } - - dst += (2 * nxb); - } - } - - //return gapdatabytes; - // horizontal filling - { - uint8_t temp, g1, g2; - char* dst_prevline = 0; - dst = gpImage; - for (int row = 0; row < nychip; ++row) { // for each chip in a row - dst += (b1chipy * nxb); - // horizontal copying of gap pixels from neighboring past line (bottom parts) - if (row < nychip - 1) { - dst_prevline = dst - nxb; - for (int gapline = 0; gapline < nxb; ++gapline) { - temp = (*((uint8_t*)dst_prevline)); - g1 = ((temp >> 4) / 2); - g2 = ((temp & 0xF) / 2); - (*((uint8_t*)dst_prevline)) = (g1 << 4) + g2; - (*((uint8_t*)dst)) = (*((uint8_t*)dst_prevline)); - ++dst; - ++dst_prevline; - } - } - - // horizontal copying of gap pixels from neihboring future line (top part) - if (row > 0) { - dst -= ((b1chipy + 1) * nxb); - dst_prevline = dst + nxb; - for (int gapline = 0; gapline < nxb; ++gapline) { - temp = (*((uint8_t*)dst_prevline)); - g1 = ((temp >> 4) / 2); - g2 = ((temp & 0xF) / 2); - temp = (g1 << 4) + g2; - (*((uint8_t*)dst_prevline)) = temp; - (*((uint8_t*)dst)) = temp; - ++dst; - ++dst_prevline; - } - dst += ((b1chipy + 1) * nxb); - } - - dst += nxb; - } - } - - return gapdatabytes; -} - - -int multiSlsDetector::enableWriteToFile(int enable) { - return callDetectorMember(&slsDetector::enableWriteToFile, enable); -} - -int multiSlsDetector::overwriteFile(int enable) { - return callDetectorMember(&slsDetector::overwriteFile, enable); -} - - -int multiSlsDetector::setReadReceiverFrequency(int freq) { - return callDetectorMember(&slsDetector::setReadReceiverFrequency, freq); -} - -int multiSlsDetector::setReceiverReadTimer(int time_in_ms) { - return callDetectorMember(&slsDetector::setReceiverReadTimer, time_in_ms); -} - -int multiSlsDetector::enableDataStreamingToClient(int enable) { - if (enable >= 0) { - //destroy data threads - if (!enable) - createReceivingDataSockets(true); - //create data threads - else { - if (createReceivingDataSockets() == FAIL) { - std::cout << "Could not create data threads in client." << std::endl; - //only for the first det as theres no general one - setErrorMask(getErrorMask() | (1 << 0)); - detectors[0]->setErrorMask((detectors[0]->getErrorMask()) | - (DATA_STREAMING)); - } - } - } - return client_downstream; -} - -int multiSlsDetector::enableDataStreamingFromReceiver(int enable) { - if (enable >= 0) { - thisMultiDetector->receiver_upstream = parallelCallDetectorMember( - &slsDetector::enableDataStreamingFromReceiver, enable); - } - return thisMultiDetector->receiver_upstream; -} - -int multiSlsDetector::enableReceiverCompression(int i) { - return callDetectorMember(&slsDetector::enableReceiverCompression, i); -} - -int multiSlsDetector::enableTenGigabitEthernet(int i) { - return callDetectorMember(&slsDetector::enableTenGigabitEthernet, i); -} - -int multiSlsDetector::setReceiverFifoDepth(int i) { - return callDetectorMember(&slsDetector::setReceiverFifoDepth, i); -} - -int multiSlsDetector::setReceiverSilentMode(int i) { - return callDetectorMember(&slsDetector::setReceiverSilentMode, i); -} - -int multiSlsDetector::setCTBPattern(std::string fname) { - uint64_t word; - int addr = 0; - FILE* fd = fopen(fname.c_str(), "r"); - if (fd) { - while (fread(&word, sizeof(word), 1, fd)) { - for (unsigned int idet = 0; idet < detectors.size(); ++idet) - detectors[idet]->setCTBWord(addr, word); - ++addr; - } - - fclose(fd); - } else - return -1; - - return addr; -} - - -uint64_t multiSlsDetector::setCTBWord(int addr, uint64_t word) { - return callDetectorMember(&slsDetector::setCTBWord, addr, word); -} - -int multiSlsDetector::setCTBPatLoops(int level, int& start, int& stop, int& n) { - int ret = -100, ret1; - for (unsigned int idet = 0; idet < detectors.size(); ++idet) { - ret1 = detectors[idet]->setCTBPatLoops(level, start, stop, n); - if (detectors[idet]->getErrorMask()) - setErrorMask(getErrorMask() | (1 << idet)); - if (ret == -100) - ret = ret1; - else if (ret != ret1) - ret = -1; - } - return ret; -} - -int multiSlsDetector::setCTBPatWaitAddr(int level, int addr) { - return callDetectorMember(&slsDetector::setCTBPatWaitAddr, level, addr); -} - -int multiSlsDetector::setCTBPatWaitTime(int level, uint64_t t) { - return callDetectorMember(&slsDetector::setCTBPatWaitTime, level, t); -} diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h deleted file mode 100644 index 6bc712ea9..000000000 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetector.h +++ /dev/null @@ -1,1944 +0,0 @@ -#ifndef MULTI_SLS_DETECTOR_H -#define MULTI_SLS_DETECTOR_H - -/** - @libdoc The multiSlsDetector class is used to operate several slsDetectors in parallel. - * @short This is the base class for multi detector system functionalities - * @author Anna Bergamaschi - */ - -#include "slsDetectorUtils.h" - -class slsDetector; -class SharedMemory; -class ThreadPool; -class ZmqSocket; - - -#include -#include - - -#define MULTI_SHMVERSION 0x180629 -#define SHORT_STRING_LENGTH 50 -#define DATE_LENGTH 30 - -class multiSlsDetector : public slsDetectorUtils { - -private: - - /** - * @short structure allocated in shared memory to store detector settings for IPC and cache - */ - typedef struct sharedMultiSlsDetector { - - - /* FIXED PATTERN FOR STATIC FUNCTIONS. DO NOT CHANGE, ONLY APPEND ------*/ - - /** shared memory version */ - int shmversion; - - /** last process id accessing the shared memory */ - pid_t lastPID; - - /** last user name accessing the shared memory */ - char lastUser[SHORT_STRING_LENGTH]; - - /** last time stamp when accessing the shared memory */ - char lastDate[SHORT_STRING_LENGTH]; - - /** number of sls detectors in shared memory */ - int numberOfDetectors; - - /** END OF FIXED PATTERN -----------------------------------------------*/ - - - - - /** Number of detectors operated at once */ - int numberOfDetector[2]; - - /** online flag - is set if the detector is connected, unset if socket - * connection is not possible */ - int onlineFlag; - - /** stopped flag - is set if an acquisition error occurs or the detector - * is stopped manually. Is reset to 0 at the start of the acquisition */ - int stoppedFlag; - - /** position of the master detector */ - int masterPosition; - - /** type of synchronization between detectors */ - synchronizationMode syncMode; - - /** size of the data that are transfered from all detectors */ - int dataBytes; - - /** data bytes including gap pixels transferred from all detectors */ - int dataBytesInclGapPixels; - - /** total number of channels for all detectors */ - int numberOfChannels; - - /** total number of channels for all detectors in one dimension*/ - int numberOfChannel[2]; - - /** total number of channels including gap pixels in one dimension */ - int numberOfChannelInclGapPixels[2]; - - /** total number of channels for all detectors */ - int maxNumberOfChannels; - - /** max number of channels for all detectors in one dimension*/ - int maxNumberOfChannel[2]; - - /** max number of channels including gap pixels for all detectors in - * one dimension*/ - int maxNumberOfChannelInclGapPixels[2]; - - /** max number of channels allowed for the complete set of detectors in - * one dimension */ - int maxNumberOfChannelsPerDetector[2]; - - /** timer values */ - int64_t timerValue[MAX_TIMERS]; - - /** detector settings (standard, fast, etc.) */ - detectorSettings currentSettings; - - /** detector threshold (eV) */ - int currentThresholdEV; - - /** indicator for the acquisition progress - set to 0 at the beginning - * of the acquisition and incremented every time that the data are written - * to file */ - int progressIndex; - - /** total number of frames to be acquired */ - int totalProgress; - - /** current index of the output file */ - int fileIndex; - - /** name root of the output files */ - char fileName[MAX_STR_LENGTH]; - - /** path of the output files */ - char filePath[MAX_STR_LENGTH]; - - /** max frames per file */ - int framesPerFile; - - /** file format*/ - fileFormat fileFormatType; - - /** corrections to be applied to the data \see ::correctionFlags */ - int correctionMask; - - /** threaded processing flag (i.e. if data are processed and written to - * file in a separate thread) */ - int threadedProcessing; - - /** dead time (in ns) for rate corrections */ - double tDead; - - /** directory where the flat field files are stored */ - char flatFieldDir[MAX_STR_LENGTH]; - - /** file used for flat field corrections */ - char flatFieldFile[MAX_STR_LENGTH]; - - /** file with the bad channels */ - char badChanFile[MAX_STR_LENGTH]; - - /** angular conversion file */ - char angConvFile[MAX_STR_LENGTH]; - - /** angular direction (1 if it corresponds to the encoder direction - * i.e. channel 0 is 0, maxchan is positive high angle, 0 otherwise */ - int angDirection; - - /** beamline fine offset (of the order of mdeg, might be adjusted for - * each measurements) */ - double fineOffset; - - /** beamline offset (might be a few degrees beacuse of encoder offset - - * normally it is kept fixed for a long period of time) */ - double globalOffset; - - /** bin size for data merging */ - double binSize; - - //X and Y displacement - double sampleDisplacement[2]; - - /** number of positions at which the detector should acquire */ - int numberOfPositions; - - /** list of encoder positions at which the detector should acquire */ - double detPositions[MAXPOS]; - - /** Scans and scripts */ - int actionMask; - - mystring actionScript[MAX_ACTIONS]; - mystring actionParameter[MAX_ACTIONS]; - int scanMode[MAX_SCAN_LEVELS]; - mystring scanScript[MAX_SCAN_LEVELS]; - mystring scanParameter[MAX_SCAN_LEVELS]; - int nScanSteps[MAX_SCAN_LEVELS]; - mysteps scanSteps[MAX_SCAN_LEVELS]; - int scanPrecision[MAX_SCAN_LEVELS]; - - /** flag for acquiring */ - bool acquiringFlag; - - /** external gui */ - bool externalgui; - - /** receiver online flag - is set if the receiver is connected, - * unset if socket connection is not possible */ - int receiverOnlineFlag; - - /** data streaming (up stream) enable in receiver */ - bool receiver_upstream; - - } sharedMultiSlsDetector; - - - - -public: - - - using slsDetectorUtils::flatFieldCorrect; - using slsDetectorUtils::rateCorrect; - using slsDetectorUtils::setBadChannelCorrection; - using slsDetectorUtils::readAngularConversion; - using slsDetectorUtils::writeAngularConversion; - - - /** - * Constructor - * @param id multi detector id - * @param verify true to verify if shared memory version matches existing one - * @param update true to update last user pid, date etc - */ - multiSlsDetector(int id = 0, bool verify = true, bool update = true); - - /** - * Destructor - */ - virtual ~multiSlsDetector(); - - /** - * returns true. Used when reference is slsDetectorUtils and to determine - * if command can be implemented as slsDetector/multiSlsDetector object/ - */ - bool isMultiSlsDetectorClass(); - - /** - * Creates/open shared memory, initializes detector structure and members - * Called by constructor/ set hostname / read config file - * @param verify true to verify if shared memory version matches existing one - * @param update true to update last user pid, date etc - */ - void setupMultiDetector(bool verify = true, bool update = true); - - /** - * If specific position, then provide result with that detector at position pos - * else concatenate the result of all detectors - * @param somefunc function pointer - * @param pos positin of detector in array (-1 is for all) - * @returns result for detector at that position or concatenated string of all detectors - */ - std::string concatResultOrPos(std::string (slsDetector::*somefunc)(int), int pos); - - /** - * Loop serially through all the detectors in calling a particular method - * @param somefunc function pointer - * @returns -1 if values are different, otherwise result in calling method - */ - template - T callDetectorMember(T (slsDetector::*somefunc)()); - - /** - * Loop serially through all the detectors in calling a particular method - * with string as return - * @param somefunc function pointer - * @returns concatenated string of results ifdifferent, otherwise result in - * calling method - */ - std::string callDetectorMember(std::string(slsDetector::*somefunc)()); - - /** - * Loop serially through all the detectors in calling a particular method - * with an extra argument - * @param somefunc function pointer - * @param value argument for calling method - * @returns -1 if values are different, otherwise result in calling method - */ - template - T callDetectorMember(T (slsDetector::*somefunc)(V), V value); - - /** - * Loop serially through all the detectors in calling a particular method - * with two extra arguments - * @param somefunc function pointer - * @param par1 argument for calling method - * @param par2 second argument for calling method - * @returns -1 if values are different, otherwise result in calling method - */ - template - T callDetectorMember(T (slsDetector::*somefunc)(P1, P2), P1 par1, P2 par2); - - - /** - * Parallel calls to all the detectors in calling a particular method - * @param somefunc function pointer - * @returns -1 if values are different, otherwise result in calling method - */ - template - T parallelCallDetectorMember(T (slsDetector::*somefunc)()); - - /** - * Loop serially through all the detectors in calling a particular method - * with an extra argument - * @param somefunc function pointer - * @param value argument for calling method - * @returns -1 if values are different, otherwise result in calling method - */ - template - T parallelCallDetectorMember(T (slsDetector::*somefunc)(P1), P1 value); - - /** - * Loop serially through all the detectors in calling a particular method - * with two extra arguments - * @param somefunc function pointer - * @param par1 argument for calling method - * @param par2 second argument for calling method - * @returns -1 if values are different, otherwise result in calling method - */ - template - T parallelCallDetectorMember(T (slsDetector::*somefunc)(P1, P2), P1 par1, P2 par2); - - /** - * Loop serially through all the detectors in calling a particular method - * with three int arguments - * @param somefunc function pointer - * @param v0 argument for calling method - * @param v1 second argument for calling method - * @param v2 third argument for calling method - * @returns -1 if values are different, otherwise result in calling method - */ - int parallelCallDetectorMember(int (slsDetector::*somefunc)(int, int, int), - int v0, int v1, int v2); - - /** - * Loop serially through all results and - * return a value if they are all same, else return -1 - * @param return_values vector of results - * @returns -1 if values are different, otherwise result - */ - template - T minusOneIfDifferent(const std::vector&); - - /** - * Calculate the detector position index in multi vector and the module index - * using an index for all entire modules in list (Mythen) - * @param i position index of all modules in list - * @param idet position index in multi vector list - * @param imod module index in the sls detector - */ - int decodeNMod(int i, int &idet, int &imod); - - /** - * Decodes which detector and the corresponding channel numbers for it - * Mainly useful in a multi detector setROI (Gotthard, Mythen?) - * @param offsetX channel number or total channel offset in x direction - * @param offsetY channel number or total channel offset in y direction - * @param channelX channel number from detector offset in x direction - * @param channelY channel number from detector offset in x direction - * @returns detector id or -1 if channel number out of range - */ - int decodeNChannel(int offsetX, int offsetY, int &channelX, int &channelY); - - /** - * Decode data from the detector converting them to an array of doubles, - * one for each channel (Mythen only) - * @param datain data from the detector - * @param nn size of datain array - * @param fdata double array of decoded data - * @returns pointer to a double array with a data per channel - */ - double* decodeData(int *datain, int &nn, double *fdata=NULL); - - /** - * Writes a data file - * @param name of the file to be written - * @param data array of data values - * @param err array of errors on the data. If NULL no errors will be written - * @param ang array of angular values. If NULL data will be in the form - * chan-val(-err) otherwise ang-val(-err) - * @param dataformat format of the data: can be 'i' integer or 'f' double (default) - * @param nch number of channels to be written to file. if -1 defaults to - * the number of installed channels of the detector - * @returns OK or FAIL if it could not write the file or data=NULL - * \sa mythenDetector::writeDataFile - */ - int writeDataFile(std::string fname, double *data, double *err=NULL, - double *ang=NULL, char dataformat='f', int nch=-1); - - /** - * Writes a data file with an integer pointer to an array - * @param name of the file to be written - * @param data array of data values - * @returns OK or FAIL if it could not write the file or data=NULL - * \sa mythenDetector::writeDataFile - */ - int writeDataFile(std::string fname, int *data); - - /** - * Reads a data file - * @param name of the file to be read - * @param data array of data values to be filled - * @param err array of arrors on the data. If NULL no errors are expected - * on the file - * @param ang array of angular values. If NULL data are expected in the - * form chan-val(-err) otherwise ang-val(-err) - * @param dataformat format of the data: can be 'i' integer or 'f' double (default) - * @param nch number of channels to be written to file. if <=0 defaults - * to the number of installed channels of the detector - * @returns OK or FAIL if it could not read the file or data=NULL - *\sa mythenDetector::readDataFile - */ - int readDataFile(std::string fname, double *data, double *err=NULL, - double *ang=NULL, char dataformat='f'); - - - /** - * Reads a data file - * @param name of the file to be read - * @param data array of data values - * @returns OK or FAIL if it could not read the file or data=NULL - * \sa mythenDetector::readDataFile - */ - int readDataFile(std::string fname, int *data); - - /** - * Checks error mask and returns error message and its severity if it exists - * @param critical is 1 if any of the messages is critical - * @returns error message else an empty std::string - */ - std::string getErrorMessage(int &critical); - - /** - * Clears error mask of both multi and sls - * @returns error mask - */ - int64_t clearAllErrorMask(); - - /** - * Set Error Mask from all detectors - * if each had errors in the mask already - */ - void setErrorMaskFromAllDetectors(); - - /** - * Set acquiring flag in shared memory - * @param b acquiring flag - */ - void setAcquiringFlag(bool b=false); - - /** - * Get acquiring flag from shared memory - * @returns acquiring flag - */ - bool getAcquiringFlag(); - - /** - * Check if acquiring flag is set, set error if set - * @returns FAIL if not ready, OK if ready - */ - bool isAcquireReady(); - - /** - * Check version compatibility with detector/receiver software - * (if hostname/rx_hostname has been set/ sockets created) - * @param p port type control port or receiver port - * @returns FAIL for incompatibility, OK for compatibility - */ - int checkVersionCompatibility(portType t); - - /** - * Get ID or version numbers - * @param mode version type - * @param imod module number in entire module list (gets decoded) (-1 for all) - * @returns Id or version number of that type - */ - int64_t getId(idMode mode, int imod=0); - - /** - * Get sls detector object from position in detectors array - * @param pos position in detectors array - * @returns pointer to sls detector object - */ - slsDetector* getSlsDetector(unsigned int pos); - - /** - * Accessing the sls detector from the multi list using position - * @param pos position in the multi list - * @returns slsDetector object - */ - slsDetector *operator()(int pos) const; - - /** - * Free shared memory from the command line - * avoiding creating the constructor classes and mapping - * @param multiId multi detector Id - */ - static void freeSharedMemory(int multiId); - - /** - * Free shared memory and delete shared memory structure - * occupied by the sharedMultiSlsDetector structure - * Clears all the vectors and destroys threadpool to bring - * object back to state before object creation amap - */ - void freeSharedMemory(); - - /** - * Get user details of shared memory - * @returns string with user details - */ - std::string getUserDetails(); - - /** - * Sets the hostname of all sls detectors in shared memory - * Connects to them to set up online flag - * @param name concatenated hostname of all the sls detectors - */ - void setHostname(const char* name); - - /** - * Gets the hostname of detector at particular position - * or concatenated hostnames of all the sls detectors - * @param pos position of detector in array, -1 for all detectors - * @returns concatenated hostnames of all detectors or hostname of specific one - */ - std::string getHostname(int pos = -1); - - /** - * Appends detectors to the end of the list in shared memory - * Connects to them to set up online flag - * @param name concatenated hostname of the sls detectors to be appended to the list - */ - void addMultipleDetectors(const char* name); - - - using slsDetectorBase::getDetectorType; - /** - * Get Detector type for a particular sls detector or get the first one - * @param pos position of sls detector in array, if -1, returns first detector type - * @returns detector type of sls detector in position pos, if -1, returns the first det type - */ - detectorType getDetectorsType(int pos = -1); - - /** - * Concatenates string types of all sls detectors or - * returns the detector type of the first sls detector - * @param pos position of sls detector in array, if -1, returns first detector type - * @returns detector type of sls detector in position pos, if -1, concatenates - */ - std::string sgetDetectorsType(int pos=-1); - - /** - * Just to overload getDetectorType from users - * Concatenates string types of all sls detectors or - * returns the detector type of the first sls detector - * @returns detector type of sls detector in position pos, if -1, concatenates - */ - std::string getDetectorType(); - - /** - * Creates all the threads in the threadpool - * throws an exception if it cannot create threads - */ - void createThreadPool(); - - /** - * Destroys all the threads in the threadpool - */ - void destroyThreadPool(); - - /** - * Returns the number of detectors in the multidetector structure - * @returns number of detectors - */ - int getNumberOfDetectors(); - - /** - * Returns number of detectors in dimension d - * @param d dimension d - * @returns number of detectors in dimension d - */ - int getNumberOfDetectors(dimension d); - - /** - * Returns the number of detectors in each direction - @param nx number of detectors in x direction - @param ny number of detectors in y direction - */ - void getNumberOfDetectors(int& nx, int& ny); - - /** - * Returns sum of all modules per sls detector from shared memory (Mythen) - * Other detectors, it is 1 - * @returns sum of all modules per sls detector - */ - int getNMods(); - - /** - * Returns sum of all modules per sls detector in dimension d from shared memory (Mythen) - * Other detectors, it is 1 - * @param d dimension d - * @returns sum of all modules per sls detector in dimension d - */ - int getNMod(dimension d); - - /** - * Returns sum of all maximum modules per sls detector from shared memory (Mythen) - * Other detectors, it is 1 - * @returns sum of all maximum modules per sls detector - */ - int getMaxMods(); - - /** - * Returns sum of all maximum modules per sls detector in dimension d from shared memory (Mythen) - * Other detectors, it is 1 - * @param d dimension d - * @returns sum of all maximum modules per sls detector in dimension d - */ - int getMaxMod(dimension d); - - /** - * Returns the sum of all maximum modules per sls detector in dimension d Mythen) - * from the detector directly. - * Other detectors, it is 1 - * @param d dimension d - * @returns sum of all maximum modules per sls detector in dimension d - */ - int getMaxNumberOfModules(dimension d=X); - - /** - * Sets/Gets the sum of all modules per sls detector in dimension d (Mythen) - * from the detector directly. - * Other detectors, it is 1 - * @param i the number of modules to set to - * @param d dimension d - * @returns sum of all modules per sls detector in dimension d - */ - int setNumberOfModules(int i=-1, dimension d=X); - - /** - * Using module id, returns the number of channels per that module - * from shared memory (Mythen) - * @param imod module number of entire multi detector list - * @returns number of channels per module imod - */ - int getChansPerMod(int imod=0); - - /** - * Returns the total number of channels of all sls detectors from shared memory - * @returns the total number of channels of all sls detectors - */ - int getTotalNumberOfChannels(); - - /** - * Returns the total number of channels of all sls detectors in dimension d - * from shared memory - * @param d dimension d - * @returns the total number of channels of all sls detectors in dimension d - */ - int getTotalNumberOfChannels(dimension d); - - /** - * Returns the total number of channels of all sls detectors in dimension d - * including gap pixels from shared memory - * @param d dimension d - * @returns the total number of channels of all sls detectors in dimension d - * including gap pixels - */ - int getTotalNumberOfChannelsInclGapPixels(dimension d); - - /** - * Returns the maximum number of channels of all sls detectors - * from shared memory (Mythen) - * @returns the maximum number of channels of all sls detectors - */ - int getMaxNumberOfChannels(); - - /** - * Returns the maximum number of channels of all sls detectors in dimension d - * from shared memory (Mythen) - * @param d dimension d - * @returns the maximum number of channels of all sls detectors in dimension d - */ - int getMaxNumberOfChannels(dimension d); - - /** - * Returns the total number of channels of all sls detectors in dimension d - * including gap pixels from shared memory(Mythen) - * @param d dimension d - * @returns the maximum number of channels of all sls detectors in dimension d - * including gap pixels - */ - int getMaxNumberOfChannelsInclGapPixels(dimension d); - - /** - * Returns the maximum number of channels of all sls detectors in each dimension d - * from shared memory. multi detector shared memory variable to calculate - * offsets for each sls detector - * @param d dimension d - * @returns the maximum number of channels of all sls detectors in dimension d - */ - int getMaxNumberOfChannelsPerDetector(dimension d); - - /** - * Sets the maximum number of channels of all sls detectors in each dimension d - * from shared memory, multi detector shared memory variable to calculate - * offsets for each sls detector - * @param d dimension d - * @param i maximum number of channels for multi structure in dimension d - * @returns the maximum number of channels of all sls detectors in dimension d - */ - int setMaxNumberOfChannelsPerDetector(dimension d,int i); - - /** - * Get Detector offset from shared memory in dimension d - * @param d dimension d - * @param pos detector position in multi detector list - * @returns offset in dimension d, -1 if pos is not an actual position in list - */ - int getDetectorOffset(dimension d, int pos); - - /** - * Set Detector offset in shared memory in dimension d - * @param d dimension d - * @param off offset for detector - * @param pos detector position in multi detector list - */ - void setDetectorOffset(dimension d, int off, int pos); - - /** - * Updates the channel offsets in X and Y dimension for all the sls detectors - * It is required for decodeNMod and setting ROI - */ - void updateOffsets(); - - /** - * Checks if the multi detectors are online and sets the online flag - * @param online if GET_ONLINE_FLAG, only returns shared memory online flag, - * else sets the detector in online/offline state - * if OFFLINE_FLAG, (i.e. no communication to the detector - using only local structure - no data acquisition possible!); - * if ONLINE_FLAG, detector in online state (i.e. communication to the detector updating the local structure) - * @returns online/offline status - */ - int setOnline(int const online=GET_ONLINE_FLAG); - - /** - * Checks if each of the detectors are online/offline - * @returns empty string if they are all online, - * else returns concatenation of strings of all detectors that are offline - */ - std::string checkOnline(); - - /** - * Set/Gets TCP Port of detector or receiver - * @param t port type - * @param p port number (-1 gets) - * @returns port number - */ - int setPort(portType t, int p); - - /** - * Lock server for this client IP - * @param p 0 to unlock, 1 to lock - * @returns 1 for locked or 0 for unlocked - */ - int lockServer(int p); - - /** - * Get last client IP saved on detector server - * @returns last client IP saved on detector server - */ - std::string getLastClientIP(); - - /** - * Exit detector server - * @returns OK or FAIL - */ - int exitServer(); - - /** - * Load configuration from a configuration File - * @param fname configuration file name - * @return OK or FAIL - */ - int readConfigurationFile(std::string const fname); - - /** - * Write current configuration to a file - * @param fname configuration file name - * @returns OK or FAIL - */ - int writeConfigurationFile(std::string const fname); - - /** - * Returns the trimfile or settings file name (Useless??) - * @returns the trimfile or settings file name - */ - std::string getSettingsFile(); - - /** - * Get detector settings - * @param ipos position in multi list (-1 all) - * @returns current settings - */ - detectorSettings getSettings(int pos=-1); - - /** - * Load detector settings from the settings file picked from the trimdir/settingsdir - * Eiger only stores in shared memory ( a get will overwrite this) - * For Eiger, one must use threshold - * @param isettings settings - * @param ipos position in multi list (-1 all) - * @returns current settings - */ - detectorSettings setSettings(detectorSettings isettings, int pos=-1); - - /** - * Get threshold energy (Mythen and Eiger) - * @param imod module number (-1 all) - * @returns current threshold value for imod in ev (-1 failed) - */ - int getThresholdEnergy(int imod=-1); - - /** - * Set threshold energy (Mythen and Eiger) - * @param e_eV threshold in eV - * @param imod module number (-1 all) - * @param isettings ev. change settings - * @param tb 1 to include trimbits, 0 to exclude - * @returns current threshold value for imod in ev (-1 failed) - */ - int setThresholdEnergy(int e_eV, int imod=-1, detectorSettings isettings=GET_SETTINGS,int tb=1); - - /** - * Returns the detector trimbit/settings directory \sa sharedSlsDetector - * @returns the trimbit/settings directory - */ - std::string getSettingsDir(); - - /** - * Sets the detector trimbit/settings directory \sa sharedSlsDetector - * @param s trimbits/settings directory - * @returns the trimbit/settings directory - */ - std::string setSettingsDir(std::string s); - - /** - * Returns the calibration files directory \sa sharedSlsDetector (Mythen) - * @returns the calibration files directory - */ - std::string getCalDir(); - - /** - * Sets the calibration files directory \sa sharedSlsDetector (Mythen) - * @param s the calibration files directory - * @returns the calibration files directory - */ - std::string setCalDir(std::string s); - - /** - * Loads the modules settings/trimbits reading from a specific file - * file name extension is automatically generated. - * @param fname specific settings/trimbits file - * @param imod module number (-1 for all) - * returns OK or FAIL - */ - int loadSettingsFile(std::string fname, int imod=-1); - - /** - * Saves the modules settings/trimbits to a specific file - * file name extension is automatically generated. - * @param fname specific settings/trimbits file - * @param imod module number (-1 for all) - * returns OK or FAIL - */ - int saveSettingsFile(std::string fname, int imod=-1); - - /** - * Loads the modules calibration data reading from a specific file (Mythen) - * file name extension is automatically generated. - * @param fname specific calibration file - * @param imod module number (-1 for all) - * returns OK or FAIL - */ - int loadCalibrationFile(std::string fname, int imod=-1); - - /** - * Saves the modules calibration data to a specific file (Mythen) - * file name extension is automatically generated. - * @param fname specific calibration file - * @param imod module number (-1 for all) - * returns OK or FAIL - */ - int saveCalibrationFile(std::string fname, int imod=-1); - - /** - * Sets/gets the detector in position i as master of the structure (Mythen) - * (e.g. it gates the other detectors and therefore must be started as last. - * Assumes that signal 0 is gate in, signal 1 is trigger in, signal 2 is gate out - * @param i position of master (-1 gets, -2 unset) - * @return master's position (-1 none) - */ - int setMaster(int i=-1); - - /** - * Sets/gets the synchronization mode of the various detector (Mythen) - * @param sync syncronization mode - * @returns current syncronization mode - */ - synchronizationMode setSynchronization(synchronizationMode sync=GET_SYNCHRONIZATION_MODE); - - /** - * Get Detector run status - * @returns status - */ - runStatus getRunStatus(); - - /** - * Prepares detector for acquisition (Eiger and Gotthard) - * For Gotthard, it sets the detector data transmission mode (CPU or receiver) - * @returns OK if all detectors are ready for acquisition, FAIL otherwise - */ - int prepareAcquisition(); - - /** - * Cleans up after acquisition (Gotthard only) - * For Gotthard, it sets the detector data transmission to default (via CPU) - * @returns OK or FAIL - */ - int cleanupAcquisition(); - - /** - * Start detector acquisition (Non blocking) - * @returns OK or FAIL if even one does not start properly - */ - int startAcquisition(); - - /** - * Stop detector acquisition - * @returns OK or FAIL - */ - int stopAcquisition(); - - /** - * Give an internal software trigger to the detector (Eiger only) - * @return OK or FAIL - */ - int sendSoftwareTrigger(); - - /** - * Start readout (without exposure or interrupting exposure) (Mythen) - * @returns OK or FAIL - */ - int startReadOut(); - - /** - * Start detector acquisition and read all data (Blocking until end of acquisition) - * (Mythen, puts all data into a data queue. Others, data at receiver via udp packets) - * @returns pointer to the front of the data queue (return significant only for Mythen) - * \sa startAndReadAllNoWait getDataFromDetector dataQueue - */ - int* startAndReadAll(); - - /** - * Start detector acquisition and call read out, but not reading (data for Mythen, - * and status for other detectors) from the socket. - * (startAndReadAll calls this and getDataFromDetector. Client is not blocking, - * but server is blocked until getDataFromDetector is called. so not recommended - * for users) - * @returns OK or FAIL - */ - int startAndReadAllNoWait(); - - /** - * Reads from the detector socket (data frame for Mythen and status for other - * detectors) - * @returns pointer to the data or NULL. If NULL disconnects the socket - * (return significant only for Mythen) - * Other detectors return NULL - * \sa getDataFromDetector - */ - int* getDataFromDetector(); - - /** - * Requests and receives a single data frame from the detector - * (Mythen: and puts it in the data queue) - * @returns pointer to the data or NULL. (return Mythen significant) - * Other detectors return NULL - * \sa getDataFromDetector - */ - int* readFrame(); - - /** - * Requests and receives all data from the detector - * (Mythen: and puts them in a data queue) - * @returns pointer to the front of the queue or NULL (return Mythen significant) - * Other detectors return NULL - * \sa getDataFromDetector dataQueue - */ - int* readAll(); - - /** - * Pops the data from the data queue (Mythen) - * @returns pointer to the popped data or NULL if the queue is empty. - * \sa dataQueue - */ - int* popDataQueue(); - - /** - * Pops the data from the postprocessed data queue (Mythen) - * @returns pointer to the popped data or NULL if the queue is empty. - * \sa finalDataQueue - */ - detectorData* popFinalDataQueue(); - - /** - * Resets the raw data queue (Mythen) - * \sa dataQueue - */ - void resetDataQueue(); - - /** - * Resets the post processed data queue (Mythen) - * \sa finalDataQueue - */ - void resetFinalDataQueue(); - - /** - * Configures in detector the destination for UDP packets (Not Mythen) - * @returns OK or FAIL - */ - int configureMAC(); - - /** - * Set/get timer value (not all implemented for all detectors) - * @param index timer index - * @param t time in ns or number of...(e.g. frames, gates, probes) - * @param imod module number (gotthard delay can have different values) - * @returns timer set value in ns or number of...(e.g. frames, gates, probes) - */ - int64_t setTimer(timerIndex index, int64_t t=-1, int imod = -1); - - /** - * Set/get timer value left in acquisition (not all implemented for all detectors) - * @param index timer index - * @param t time in ns or number of...(e.g. frames, gates, probes) - * @param imod module number - * @returns timer set value in ns or number of...(e.g. frames, gates, probes) - */ - int64_t getTimeLeft(timerIndex index, int imod = -1); - - /** - * Set speed - * @param sp speed type (clkdivider option for Jungfrau and Eiger, others for Mythen/Gotthard) - * @param value (clkdivider 0,1,2 for full, half and quarter speed). Other values check manual - * @returns value of speed set - */ - int setSpeed(speedVariable sp, int value=-1); - - /** - * Set/get dynamic range and updates the number of dataBytes - * (Eiger: If i is 32, also sets clkdivider to 2, if 16, sets clkdivider to 1) - * @param i dynamic range (-1 get) - * @returns current dynamic range - * \sa sharedSlsDetector - */ - int setDynamicRange(int i=-1); - - /** - * Recalculated number of data bytes for multi detector - * @returns tota number of data bytes for multi detector - */ - int getDataBytes(); - - /** - * Set/get dacs value - * @param val value (in V) - * @param index DAC index - * @param mV 0 in dac units or 1 in mV - * @param imod module number (if -1 all modules) - * @returns current DAC value - */ - dacs_t setDAC(dacs_t val, dacIndex index , int mV, int imod=-1); - - /** - * Get adc value - * @param index adc(DAC) index - * @param imod module number (if -1 all modules) - * @returns current adc value (temperature for eiger and jungfrau in millidegrees) - */ - dacs_t getADC(dacIndex index, int imod=-1); - - /** - * Set/get timing mode - * @param pol timing mode (-1 gets) - * @returns current timing mode - */ - externalCommunicationMode setExternalCommunicationMode(externalCommunicationMode pol=GET_EXTERNAL_COMMUNICATION_MODE); - - /** - * Set/get external signal flags (to specify triggerinrising edge etc) (Gotthard, Mythen) - * @param pol external signal flag (-1 gets) - * @param signalindex singal index (0 - 3) - * @returns current timing mode - */ - externalSignalFlag setExternalSignalFlags(externalSignalFlag pol=GET_EXTERNAL_SIGNAL_FLAG , int signalindex=0); - - /** - * Set/get readout flags (Eiger, Mythen) - * @param flag readout flag (Eiger options: parallel, nonparallel, safe etc.) (-1 gets) - * @returns readout flag - */ - int setReadOutFlags(readOutFlags flag=GET_READOUT_FLAGS); - - /** - * Write in a register. For Advanced users - * @param addr address of register - * @param val value to write into register - * @returns value read after writing - */ - uint32_t writeRegister(uint32_t addr, uint32_t val); - - /** - * Read from a register. For Advanced users - * @param addr address of register - * @returns value read from register - */ - uint32_t readRegister(uint32_t addr); - - /** - * Set bit in a register. For Advanced users - * @param addr address of register - * @param n nth bit - * @returns value read from register - */ - uint32_t setBit(uint32_t addr, int n); - - /** - * Clear bit in a register. For Advanced users - * @param addr address of register - * @param n nth bit - * @returns value read from register - */ - uint32_t clearBit(uint32_t addr, int n); - - /** - * Set network parameter - * @param p network parameter type - * @param s network parameter value - * @returns network parameter value set (from getNetworkParameter) - */ - std::string setNetworkParameter(networkParameter p, std::string s); - - /** - * Get network parameter - * @param p network parameter type - * @returns network parameter value set (from getNetworkParameter) - */ - std::string getNetworkParameter(networkParameter); - - /** - * Execute a digital test (Gotthard, Mythen) - * @param mode testmode type - * @param imod module index (-1 for all) - * @returns result of test - */ - int digitalTest(digitalTestMode mode, int imod=0); - - /** - * Execute trimming (Mythen) - * @param mode trimming mode type - * @param par1 parameter 1 - * @param par2 parameter 2 - * @param imod module index (-1 for all) - * @returns result of trimming - */ - int executeTrimming(trimMode mode, int par1, int par2, int imod=-1); - - /** - * Load dark or gain image to detector (Gotthard) - * @param index image type - * @param fname file name from which to load image - * @returns OK or FAIL - */ - int loadImageToDetector(imageType index,std::string const fname); - - /** - * Writes the counter memory block from the detector (Gotthard) - * @param fname file name to load data from - * @param startACQ is 1 to start acquisition after reading counter - * @returns OK or FAIL - */ - int writeCounterBlockFile(std::string const fname,int startACQ=0); - - /** - * Resets counter in detector (Gotthard) - * @param startACQ is 1 to start acquisition after resetting counter - * @returns OK or FAIL - */ - int resetCounterBlock(int startACQ=0); - - /** - * Set/get counter bit in detector (Gotthard) - * @param i is -1 to get, 0 to reset and any other value to set the counter bit - * @returns the counter bit in detector - */ - int setCounterBit(int i = -1); - - /** - * Ensures that min is less than max in both dimensions (Gotthard) - * @param n number of rois - * @param r array of rois - */ - void verifyMinMaxROI(int n, ROI r[]); - - /** - * Set ROI (Gotthard) - * At the moment only one set allowed - * @param n number of rois - * @param roiLimits array of roi - * @param imod module number (-1 for all) - * @returns OK or FAIL - */ - int setROI(int n=-1,ROI roiLimits[]=NULL, int imod = -1); - - /** - * Get ROI from each detector and convert it to the multi detector scale (Gotthard) - * @param n number of rois - * @param imod module number (-1 for all) - * @returns pointer to array of ROI structure - */ - ROI* getROI(int &n, int imod = -1); - - /** - * Write to ADC register (Gotthard, Jungfrau, ChipTestBoard). For expert users - * @param addr address of adc register - * @param val value - * @returns return value (mostly -1 as it can't read adc register) - */ - int writeAdcRegister(int addr, int val); - - /** - * Activates/Deactivates the detector (Eiger only) - * @param enable active (1) or inactive (0), -1 gets - * @returns 0 (inactive) or 1 (active)for activate mode - */ - int activate(int const enable=-1); - - /** - * Set deactivated Receiver padding mode (Eiger only) - * @param padding padding option for deactivated receiver. Can be 1 (padding), 0 (no padding), -1 (gets) - * @returns 1 (padding), 0 (no padding), -1 (inconsistent values) for padding option - */ - int setDeactivatedRxrPaddingMode(int padding=-1); - - /** - * Returns the enable if data will be flipped across x or y axis (Eiger) - * @param d axis across which data is flipped - * @returns 1 for flipped, else 0 - */ - int getFlippedData(dimension d=X); - - /** - * Sets the enable which determines if - * data will be flipped across x or y axis (Eiger) - * @param d axis across which data is flipped - * @param value 0 or 1 to reset/set or -1 to get value - * @returns enable flipped data across x or y axis - */ - int setFlippedData(dimension d=X, int value=-1); - - /** - * Sets all the trimbits to a particular value (Eiger) - * @param val trimbit value - * @param imod module number, -1 means all modules - * @returns OK or FAIL - */ - int setAllTrimbits(int val, int imod=-1); - - /** - * Enable gap pixels, only for Eiger and for 8,16 and 32 bit mode. (Eiger) - * 4 bit mode gap pixels only in gui call back - * @param val 1 sets, 0 unsets, -1 gets - * @returns gap pixel enable or -1 for error - */ - int enableGapPixels(int val=-1); - - /** - * Sets the number of trim energies and their value (Eiger) - * \sa sharedSlsDetector - * @param nen number of energies - * @param en array of energies - * @returns number of trim energies - */ - int setTrimEn(int nen, int *en=NULL); - - /** - * Returns the number of trim energies and their value (Eiger) - * \sa sharedSlsDetector - * @param en array of energies - * @returns number of trim energies - */ - int getTrimEn(int *en=NULL); - - /** - * Pulse Pixel (Eiger) - * @param n is number of times to pulse - * @param x is x coordinate - * @param y is y coordinate - * @returns OK or FAIL - */ - int pulsePixel(int n=0,int x=0,int y=0); - - /** - * Pulse Pixel and move by a relative value (Eiger) - * @param n is number of times to pulse - * @param x is relative x value - * @param y is relative y value - * @returns OK or FAIL - */ - int pulsePixelNMove(int n=0,int x=0,int y=0); - - /** - * Pulse Chip (Eiger) - * @param n is number of times to pulse - * @returns OK or FAIL - */ - int pulseChip(int n=0); - - /** - * Set/gets threshold temperature (Jungfrau) - * @param val value in millidegrees, -1 gets - * @param imod module number, -1 is all - * @returns threshold temperature in millidegrees - */ - int setThresholdTemperature(int val=-1, int imod=-1); - - /** - * Enables/disables temperature control (Jungfrau) - * @param val value, -1 gets - * @param imod module number, -1 is all - * @returns temperature control enable - */ - int setTemperatureControl(int val=-1, int imod=-1); - - /** - * Resets/ gets over-temperature event (Jungfrau) - * @param val value, -1 gets - * @param imod module number, -1 is all - * @returns over-temperature event - */ - int setTemperatureEvent(int val=-1, int imod=-1); - - /** - * Set storage cell that stores first acquisition of the series (Jungfrau) - * @param value storage cell index. Value can be 0 to 15. (-1 gets) - * @returns the storage cell that stores the first acquisition of the series - */ - int setStoragecellStart(int pos=-1); - - /** - * Programs FPGA with pof file (Jungfrau) - * @param fname file name - * @returns OK or FAIL - */ - int programFPGA(std::string fname); - - /** - * Resets FPGA (Jungfrau) - * @returns OK or FAIL - */ - int resetFPGA(); - - /** - * Power on/off Chip (Jungfrau) - * @param ival on is 1, off is 0, -1 to get - * @returns OK or FAIL - */ - int powerChip(int ival= -1); - - /** - * Automatic comparator disable (Jungfrau) - * @param ival on is 1, off is 0, -1 to get - * @returns OK or FAIL - */ - int setAutoComparatorDisableMode(int ival= -1); - - /** - * Get Scan steps (Mythen) - * @param index scan index - * @param istep step index - * @returns scan step value - */ - double getScanStep(int index, int istep); - - /** - * Returns the trimbits from the detector's shared memmory (Mythen, Eiger) - * @param retval is the array with the trimbits - * @param fromDetector is true if the trimbits shared memory have to be - * uploaded from detector - * @returns total number of channels for the detector - */ - int getChanRegs(double* retval,bool fromDetector); - - /** - * Configure channel (Mythen) - * @param reg channel register - * @param ichan channel number (-1 all) - * @param ichip chip number (-1 all) - * @param imod module number (-1 all) - * \sa ::sls_detector_channel - * @returns current register value - */ - int setChannel(int64_t reg, int ichan=-1, int ichip=-1, int imod=-1); - - /** - * Get Move Flag (Mythen) - * @param imod module number (-1 all) - * @param istep step index - * @returns move flag - */ - int getMoveFlag(int imod); - - /** - * Fill Module mask for flat field corrections (Mythen) - * @param mM array - * @returns number of modules - */ - int fillModuleMask(int *mM); - - /** - * Calibrate Pedestal (ChipTestBoard) - * Starts acquisition, calibrates pedestal and writes to fpga - * @param frames number of frames - * @returns number of frames - */ - int calibratePedestal(int frames = 0); - - /** - * Set Rate correction (Mythen, Eiger) - * @param t dead time in ns - if 0 disable correction, - * if >0 set dead time to t, if < 0 set deadtime to default dead time - * for current settings - * @returns 0 if rate correction disabled, >0 otherwise - */ - int setRateCorrection(double t=0); - - /** - * Get rate correction (Mythen, Eiger) - * @param t reference for dead time - * @returns 0 if rate correction disabled, > 0 otherwise - */ - int getRateCorrection(double &t); - - /** - * Get rate correction tau (Mythen, Eiger) - * @returns 0 if rate correction disabled, otherwise the tau used for the correction - */ - double getRateCorrectionTau(); - - /** - * Get rate correction (Mythen, Eiger) - * @returns 0 if rate correction disabled, > 0 otherwise - */ - int getRateCorrection(); - - /** - * Rate correct data (Mythen) - * @param datain data array - * @param errin error array on data (if NULL will default to sqrt(datain) - * @param dataout array of corrected data - * @param errout error on corrected data (if not NULL) - * @returns 0 - */ - int rateCorrect(double* datain, double *errin, double* dataout, double *errout); - - /** - * Set flat field corrections (Mythen) - * @param fname name of the flat field file (or "" if disable) - * @returns 0 if disable (or file could not be read), >0 otherwise - */ - int setFlatFieldCorrection(std::string fname=""); - - /** - * Set flat field corrections (Mythen) - * @param corr if !=NULL the flat field corrections will be filled with - * corr (NULL usets ff corrections) - * @param ecorr if !=NULL the flat field correction errors will be filled - * with ecorr (1 otherwise) - * @returns 0 if ff correction disabled, >0 otherwise - */ - int setFlatFieldCorrection(double *corr, double *ecorr=NULL); - - /** - * Get flat field corrections (Mythen) - * @param corr if !=NULL will be filled with the correction coefficients - * @param ecorr if !=NULL will be filled with the correction coefficients errors - * @returns 0 if ff correction disabled, >0 otherwise - */ - int getFlatFieldCorrection(double *corr=NULL, double *ecorr=NULL); - - /** - * Flat field correct data (Mythen) - * @param datain data array - * @param errin error array on data (if NULL will default to sqrt(datain) - * @param dataout array of corrected data - * @param errout error on corrected data (if not NULL) - * @returns 0 - */ - int flatFieldCorrect(double* datain, double *errin, double* dataout, double *errout); - - /** - * Set bad channels correction (Mythen) - * @param fname file with bad channel list ("" disable) - * @returns 0 if bad channel disabled, >0 otherwise - */ - int setBadChannelCorrection(std::string fname=""); - - /** - * Set bad channels correction (Mythen) - * @param nch number of bad channels - * @param chs array of channels - * @param ff 0 if normal bad channels, 1 if ff bad channels - * @returns 0 if bad channel disabled, >0 otherwise - */ - int setBadChannelCorrection(int nch, int *chs, int ff); - - /** - * Get bad channels correction (Mythen) - * @param bad pointer to array that if bad!=NULL will be filled with the - * bad channel list - * @returns 0 if bad channel disabled or no bad channels, >0 otherwise - */ - int getBadChannelCorrection(int *bad=NULL); - - /** - * Reads an angular conversion file (Mythen, Gotthard) - * \sa angleConversionConstant mythenDetector::readAngularConversion - * @param fname file to be read - * @returns 0 if angular conversion disabled, >0 otherwise - */ - int readAngularConversionFile(std::string fname); - - /** - * Writes an angular conversion file (Mythen, Gotthard) - * \sa angleConversionConstant mythenDetector::writeAngularConversion - * @param fname file to be written - * @returns 0 if angular conversion disabled, >0 otherwise - */ - int writeAngularConversion(std::string fname); - - /** - * Get angular conversion (Mythen, Gotthard) - * \sa angleConversionConstant mythenDetector::getAngularConversion - * @param direction reference to diffractometer - * @param angconv array that will be filled with the angular conversion constants - * @returns 0 if angular conversion disabled, >0 otherwise - */ - int getAngularConversion(int &direction, angleConversionConstant *angconv=NULL) ; - - /** - * Sets the value of angular conversion parameter (Mythen, Gotthard) - * @param c can be ANGULAR_DIRECTION, GLOBAL_OFFSET, FINE_OFFSET, BIN_SIZE - * @param v the value to be set - * @returns the actual value - */ - double setAngularConversionParameter(angleConversionParameter c, double v); - - /** - * Gets the value of angular conversion parameter (Mythen, Gotthard) - * @param imod module index (-1 for all) - * @returns the actual value - */ - angleConversionConstant *getAngularConversionPointer(int imod=0); - - /** - * Prints receiver configuration - * @returns OK or FAIL - */ - int printReceiverConfiguration(); - - /** - * Sets up receiver socket if online and sets the flag - * @param online online/offline flag (-1 gets) - * @returns online/offline flag - */ - int setReceiverOnline(int const online=GET_ONLINE_FLAG); - - /** - * Checks if the receiver is really online - * @returns empty string if all online, else concatenates hostnames of all - * detectors that are offline - */ - std::string checkReceiverOnline(); - - /** - * Locks/Unlocks the connection to the receiver - * @param lock sets (1), usets (0), gets (-1) the lock - * @returns lock status of the receiver - */ - int lockReceiver(int lock=-1); - - /** - * Returns the IP of the last client connecting to the receiver - * @returns IP of last client connecting to receiver - */ - std::string getReceiverLastClientIP(); - - /** - * Turns off the receiver server! - * @returns OK or FAIL - */ - int exitReceiver(); - - /** - * Returns output file directory - * @returns output file directory - */ - std::string getFilePath(); - - /** - * Sets up the file directory - * @param s file directory - * @returns file dir - */ - std::string setFilePath(std::string s=""); - - /** - * Returns file name prefix - * @returns file name prefix - */ - std::string getFileName(); - - /** - * Sets up the file name prefix - * @param s file name prefix - * @returns file name prefix - */ - std::string setFileName(std::string s=""); - - /** - * Sets the max frames per file in receiver - * @param f max frames per file - * @returns max frames per file in receiver - */ - int setReceiverFramesPerFile(int f = -1); - - /** - * Sets the frames discard policy in receiver - * @param f frames discard policy - * @returns frames discard policy set in receiver - */ - frameDiscardPolicy setReceiverFramesDiscardPolicy(frameDiscardPolicy f = GET_FRAME_DISCARD_POLICY); - - /** - * Sets the partial frames padding enable in receiver - * @param f partial frames padding enable - * @returns partial frames padding enable in receiver - */ - int setReceiverPartialFramesPadding(int f = -1); - - /** - * Returns file format - * @returns file name - */ - fileFormat getFileFormat(); - - /** - * Sets up the file format - * @param f file format - * @returns file format - */ - fileFormat setFileFormat(fileFormat f=GET_FILE_FORMAT); - - /** - * Returns file index - * @returns file index - */ - int getFileIndex(); - - /** - * Sets up the file index - * @param i file index - * @returns file index - */ - int setFileIndex(int i=-1); - - /** - * Receiver starts listening to packets - * @returns OK or FAIL - */ - int startReceiver(); - - /** - * Stops the listening mode of receiver - * @returns OK or FAIL - */ - int stopReceiver(); - - /** - * Sets the receiver to start any readout remaining in the fifo and - * change status to transmitting (Mythen) - * The status changes to run_finished when fifo is empty - */ - runStatus startReceiverReadout(); - - /** - * Gets the status of the listening mode of receiver - * @returns status - */ - runStatus getReceiverStatus(); - - /** - * Gets the number of frames caught by receiver - * @returns number of frames caught by receiver - */ - int getFramesCaughtByReceiver(); - - /** - * Gets the number of frames caught by any one receiver (to avoid using threadpool) - * @returns number of frames caught by any one receiver (master receiver if exists) - */ - int getFramesCaughtByAnyReceiver(); - - /** - * Gets the current frame index of receiver - * @returns current frame index of receiver - */ - int getReceiverCurrentFrameIndex(); - - /** - * Resets framescaught in receiver - * Use this when using startAcquisition instead of acquire - * @returns OK or FAIL - */ - int resetFramesCaught(); - - /** - * Create Receiving Data Sockets - * @param destroy is true to destroy all the sockets - * @returns OK or FAIL - */ - int createReceivingDataSockets(const bool destroy = false); - - /** - * Reads frames from receiver through a constant socket - * Called during acquire() when call back registered or when using gui - */ - void readFrameFromReceiver(); - - /** - * Sets/Gets receiver file write enable - * @param enable 1 or 0 to set/reset file write enable - * @returns file write enable - */ - int enableWriteToFile(int enable=-1); - - /** - * Sets/Gets file overwrite enable - * @param enable 1 or 0 to set/reset file overwrite enable - * @returns file overwrite enable - */ - int overwriteFile(int enable=-1); - - /** - * Sets the read receiver frequency - * if data required from receiver randomly readRxrFrequency=0, - * else every nth frame to be sent to gui/callback - * @param freq is the receiver read frequency. Value 0 is 200 ms timer (other - * frames not sent), 1 is every frame, 2 is every second frame etc. - * @returns read receiver frequency - */ - int setReadReceiverFrequency(int freq=-1); - - /** - * Sets the read receiver timer - * if data required from receiver randomly readRxrFrequency=0, - * then the timer between each data stream is set with time_in_ms - * @param time_in_ms timer between frames - * @returns read receiver timer - */ - int setReceiverReadTimer(int time_in_ms=500); - - /** - * Enable data streaming to client - * @param enable 0 to disable, 1 to enable, -1 to get the value - * @returns data streaming to client enable - */ - int enableDataStreamingToClient(int enable=-1); - - /** - * Enable or disable streaming data from receiver to client - * @param enable 0 to disable 1 to enable -1 to only get the value - * @returns data streaming from receiver enable - */ - int enableDataStreamingFromReceiver(int enable=-1); - - /** - * Enable/disable or get data compression in receiver - * @param i is -1 to get, 0 to disable and 1 to enable - * @returns data compression in receiver - */ - int enableReceiverCompression(int i = -1); - - /** - * Enable/disable or 10Gbe - * @param i is -1 to get, 0 to disable and 1 to enable - * @returns if 10Gbe is enabled - */ - int enableTenGigabitEthernet(int i = -1); - - /** - * Set/get receiver fifo depth - * @param i is -1 to get, any other value to set the fifo deph - * @returns the receiver fifo depth - */ - int setReceiverFifoDepth(int i = -1); - - /** - * Set/get receiver silent mode - * @param i is -1 to get, 0 unsets silent mode, 1 sets silent mode - * @returns the receiver silent mode enable - */ - int setReceiverSilentMode(int i = -1); - - /** - * Opens pattern file and sends pattern to CTB - * @param fname pattern file to open - * @returns OK/FAIL - */ - int setCTBPattern(std::string fname); - - /** - * Writes a pattern word to the CTB - * @param addr address of the word, -1 is I/O control register, - * -2 is clk control register - * @param word 64bit word to be written, -1 gets - * @returns actual value - */ - uint64_t setCTBWord(int addr,uint64_t word=-1); - - /** - * Sets the pattern or loop limits in the CTB - * @param level -1 complete pattern, 0,1,2, loop level - * @param start start address if >=0 - * @param stop stop address if >=0 - * @param n number of loops (if level >=0) - * @returns OK/FAIL - */ - int setCTBPatLoops(int level,int &start, int &stop, int &n); - - /** - * Sets the wait address in the CTB - * @param level 0,1,2, wait level - * @param addr wait address, -1 gets - * @returns actual value - */ - int setCTBPatWaitAddr(int level, int addr=-1); - - /** - * Sets the wait time in the CTB - * @param level 0,1,2, wait level - * @param t wait time, -1 gets - * @returns actual value - */ - int setCTBPatWaitTime(int level, uint64_t t=-1); - - -private: - /** - * Initialize (open/create) shared memory for the sharedMultiDetector structure - * @param verify true to verify if shm size matches existing one - * @param update true to update last user pid, date etc - * @returns true if shared memory was created in this call, else false - */ - bool initSharedMemory(bool verify = true); - - /** - * Initialize detector structure for the shared memory just created - */ - void initializeDetectorStructure(); - - /** - * Initialize class members (and from parent classes) - * @param verify true to verify if shm size matches existing one - */ - void initializeMembers(bool verify = true); - - /** - * Update user details in detector structure - */ - void updateUserdetails(); - - /** - * Execute in command line and return result - * @param cmd command - * @returns result - */ - std::string exec(const char* cmd); - - /** - * Add sls detector - * @param s hostname of the single detector - */ - void addSlsDetector (std::string s); - - /** - * add gap pixels to the image (only for Eiger in 4 bit mode) - * @param image pointer to image without gap pixels - * @param gpImage poiner to image with gap pixels, if NULL, allocated inside function - * @returns number of data bytes of image with gap pixels - */ - int processImageWithGapPixels(char* image, char*& gpImage); - - - /** Multi detector Id */ - int detId; - - /** Shared Memory object */ - SharedMemory* sharedMemory; - - /** Shared memory structure */ - sharedMultiSlsDetector *thisMultiDetector; - - /** pointers to the slsDetector structures */ - std::vector detectors; - - /** data streaming (down stream) enabled in client (zmq sckets created) */ - bool client_downstream; - - /** ZMQ Socket - Receiver to Client */ - std::vector zmqSocket; - - /** Threadpool */ - ThreadPool* threadpool; -}; - - - -#endif diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetectorClient.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetectorClient.h deleted file mode 100644 index 3711ac583..000000000 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetectorClient.h +++ /dev/null @@ -1,162 +0,0 @@ -#include -#include - - -#include "multiSlsDetector.h" -#include "multiSlsDetectorCommand.h" -#include "sls_receiver_exceptions.h" - - -#include - - -int dummyCallback(detectorData* d, int p,void*) { - cout << "got data " << p << endl; - return 0; -}; - -class multiSlsDetectorClient { - -public: - multiSlsDetectorClient(int argc, char *argv[], int action, multiSlsDetector *myDetector=NULL) { \ - std::string answer; \ - multiSlsDetectorCommand *myCmd; \ - int id = -1, pos = -1, iv = 0; \ - bool verify = true, update = true; \ - int del = 0; \ - char cmd[100] = ""; \ - - if (action==slsDetectorDefs::PUT_ACTION && argc<2) { \ - cout << "Wrong usage - should be: "<< argv[0] << \ - "[id-][pos:]channel arg" << endl; \ - cout << endl; \ - return; \ - if (del) delete myDetector; \ - }; \ - if (action==slsDetectorDefs::GET_ACTION && argc<1) { \ - cout << "Wrong usage - should be: "<< argv[0] << \ - "[id-][pos:]channel arg" << endl; \ - cout << endl; \ - if (del) delete myDetector; \ - return; \ - }; \ - - if (action==slsDetectorDefs::READOUT_ACTION) { \ - id = 0; \ - pos = -1; \ - if (argc) { \ - // multi id scanned - if (strchr(argv[0],'-')) { \ - iv=sscanf(argv[0],"%d-%s",&id, cmd); \ - //%s needn't be there (if not 1:), so 1 or 2 arguments scanned - if (iv >= 1 && id >= 0) { \ - argv[0] = cmd; \ - cout << id << "-" ; \ - } else { \ - id = 0; \ - } \ - } \ - // single id scanned - if (strchr(argv[0],':')) { \ - iv=sscanf(argv[0],"%d:",&pos); \ - if (iv == 1 && pos >= 0) { \ - cout << "pos " << pos << " is not allowed for readout!" << endl; \ - return; \ - } \ - } \ - } \ - } else { \ - // multi id scanned - iv=sscanf(argv[0],"%d-%s",&id, cmd); \ - // scan success - if (iv == 2 && id >= 0) { \ - argv[0] = cmd; \ - cout << id << "-" ; \ - } else { \ - id = 0; \ - } \ - // sls pos scanned - iv=sscanf(argv[0],"%d:%s", &pos, cmd); \ - // scan success - if (iv == 2 && pos >= 0) { \ - argv[0] = cmd; \ - cout << pos << ":" ; \ - } \ - if (iv != 2) { \ - pos = -1; \ - } \ - // remove the %d- and %d: - if (!strlen(cmd)) { \ - strcpy(cmd, argv[0]); \ - } \ - // special commands - std::string scmd = cmd; \ - // free without calling multiSlsDetector constructor - if (scmd == "free") { \ - if (pos != -1) \ - slsDetector::freeSharedMemory(id, pos); \ - else \ - multiSlsDetector::freeSharedMemory(id); \ - return; \ - } \ - // get user details without verify sharedMultiSlsDetector version - else if ((scmd == "user") && (action==slsDetectorDefs::GET_ACTION)) { \ - verify = false; \ - update = false; \ - myDetector=NULL; \ - } \ - } \ - - - - //cout<<"id:"<executeLine(argc, argv, action, pos); \ - } catch (const SlsDetectorPackageExceptions & e) { \ - /*cout << e.GetMessage() << endl; */ \ - delete myCmd; \ - if (del) delete myDetector; \ - return; \ - } catch (...) { \ - cout << " caught exception" << endl; \ - delete myCmd; \ - if (del) delete myDetector; \ - return; \ - } \ - if (action!=slsDetectorDefs::READOUT_ACTION) { \ - cout << argv[0] << " " ; \ - } \ - cout << answer<< endl; \ - delete myCmd; \ - if (del) delete myDetector; \ - }; - -}; - - - - - - - - - - - diff --git a/slsDetectorSoftware/multiSlsDetector/multiSlsDetectorCommand.h b/slsDetectorSoftware/multiSlsDetector/multiSlsDetectorCommand.h deleted file mode 100644 index f30d807f8..000000000 --- a/slsDetectorSoftware/multiSlsDetector/multiSlsDetectorCommand.h +++ /dev/null @@ -1,72 +0,0 @@ - -#ifndef MULTI_SLS_DETECTOR_COMMAND_H -#define MULTI_SLS_DETECTOR_COMMAND_H - - -#include "slsDetector.h" -#include "multiSlsDetector.h" -#include "slsDetectorCommand.h" - - - -/** @short This class handles the command line I/Os, help etc. of the text clients */ - - -class multiSlsDetectorCommand : public slsDetectorCommand { - - public: - - - multiSlsDetectorCommand(multiSlsDetector *det) : slsDetectorCommand(det) {myDet=det;}; - - - /* /\** */ -/* executes a set of string arguments according to a given format. It is used to read/write configuration file, dump and retrieve detector settings and for the command line interface command parsing */ -/* \param narg number of arguments */ -/* \param args array of string arguments */ -/* \param action can be PUT_ACTION or GET_ACTION (from text client even READOUT_ACTION for acquisition) */ -/* \returns answer string */ -/* *\/ */ - - std::string executeLine(int narg, char *args[], int action, int id=-1) { \ - std::string s; \ - if (id>=0) { - slsDetector *d=myDet->getSlsDetector(id); \ - if (d) { \ - slsDetectorCommand *cmd=new slsDetectorCommand(d); \ - s=cmd->executeLine(narg, args, action); \ - if(d->getErrorMask()) \ - myDet->setErrorMask((myDet->getErrorMask())|(1< REQUIRED_FIRMWARE_VERSION){ - cprintf(RED,"FATAL ERROR: This software version is incompatible.\n" - "Please update it to be compatible with this firmware\n\n"); - cprintf(RED,"Exiting Server. Goodbye!\n\n"); - exit(-1); - } - - //check for firmware compatibility - old firmware - if( REQUIRED_FIRMWARE_VERSION > fwversion){ - cprintf(RED,"FATAL ERROR: This firmware version is incompatible.\n" - "Please update it to v%d to be compatible with this server\n\n", REQUIRED_FIRMWARE_VERSION); - cprintf(RED,"Exiting Server. Goodbye!\n\n"); - exit(-1); - } -*/ -} - - -int checkType() { - volatile u_int32_t type = ((bus_r(FPGA_VERSION_REG) & DETECTOR_TYPE_MSK) >> DETECTOR_TYPE_OFST); - if (type != JUNGFRAUCTB){ - cprintf(BG_RED,"This is not a Mythen 3 Server (read %d, expected %d)\n",type, JUNGFRAUCTB); - return FAIL; - } - - return OK; -} - - - -u_int32_t testFpga(void) { - printf("\nTesting FPGA...\n"); - - //fixed pattern - int ret = OK; - volatile u_int32_t val = bus_r(FIX_PATT_REG); - if (val == FIX_PATT_VAL) { - printf("Fixed pattern: successful match 0x%08x\n",val); - } else { - cprintf(RED,"Fixed pattern does not match! Read 0x%08x, expected 0x%08x\n", val, FIX_PATT_VAL); - ret = FAIL; - } - return ret; -} - - -int testBus() { - printf("\nTesting Bus...\n"); - - int ret = OK; - u_int32_t addr = SET_DELAY_LSB_REG; - int times = 1000 * 1000; - int i = 0; - - for (i = 0; i < times; ++i) { - bus_w(addr, i * 100); - if (i * 100 != bus_r(SET_DELAY_LSB_REG)) { - cprintf(RED,"ERROR: Mismatch! Wrote 0x%x, read 0x%x\n", i * 100, bus_r(SET_DELAY_LSB_REG)); - ret = FAIL; - } - } - - if (ret == OK) - printf("Successfully tested bus %d times\n", times); - return ret; -} - - - - -int detectorTest( enum digitalTestMode arg){ - switch(arg){ - case DETECTOR_FIRMWARE_TEST: return testFpga(); - case DETECTOR_BUS_TEST: return testBus(); - default: - cprintf(RED,"Warning: Test not implemented for this detector %d\n", (int)arg); - break; - } - return OK; -} - - - - - -/* Ids */ - -int64_t getDetectorId(enum idMode arg){ - int64_t retval = -1; - - switch(arg){ - case DETECTOR_SERIAL_NUMBER: - retval = getDetectorMAC(); - break; - case DETECTOR_FIRMWARE_VERSION: - retval = getFirmwareVersion(); - break; - //case SOFTWARE_FIRMWARE_API_VERSION: - //return GetFirmwareSoftwareAPIVersion(); - case DETECTOR_SOFTWARE_VERSION: - retval= GITREV; - retval= (retval <<32) | GITDATE; - break; - default: - break; - } - - return retval; -} - -u_int64_t getFirmwareVersion() { - return ((bus_r(FPGA_VERSION_REG) & BOARD_REVISION_MSK) >> BOARD_REVISION_OFST); -} - - - -u_int64_t getDetectorMAC() { - char output[255],mac[255]=""; - u_int64_t res=0; - FILE* sysFile = popen("ifconfig eth0 | grep HWaddr | cut -d \" \" -f 11", "r"); - fgets(output, sizeof(output), sysFile); - pclose(sysFile); - //getting rid of ":" - char * pch; - pch = strtok (output,":"); - while (pch != NULL){ - strcat(mac,pch); - pch = strtok (NULL, ":"); - } - sscanf(mac,"%llx",&res); - return res; -} - -u_int32_t getDetectorIP(){ - char temp[50]=""; - u_int32_t res=0; - //execute and get address - char output[255]; - FILE* sysFile = popen("ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2", "r"); - fgets(output, sizeof(output), sysFile); - pclose(sysFile); - - //converting IPaddress to hex. - char* pcword = strtok (output,"."); - while (pcword != NULL) { - sprintf(output,"%02x",atoi(pcword)); - strcat(temp,output); - pcword = strtok (NULL, "."); - } - strcpy(output,temp); - sscanf(output, "%x", &res); - //printf("ip:%x\n",res); - - return res; -} - - - - - - - - -/* initialization */ - -void initControlServer(){ - clkPhase[0] = 0; clkPhase[1] = 0; - setupDetector(); - printf("\n"); -} - - - -void initStopServer() { - - usleep(CTRL_SRVR_INIT_TIME_US); - if (mapCSP0() == FAIL) { - cprintf(BG_RED, "Stop Server: Map Fail. Dangerous to continue. Goodbye!\n"); - exit(EXIT_FAILURE); - } -} - - - - - - -/* set up detector */ - -void allocateDetectorStructureMemory(){ - printf("This Server is for 1 Jungfrau module (500k)\n"); - - //Allocation of memory - if (detectorModules!=NULL) free(detectorModules); - if (detectorChans!=NULL) free(detectorChans); - if (detectorChips!=NULL) free(detectorChips); - if (detectorDacs!=NULL) free(detectorDacs); - if (detectorAdcs!=NULL) free(detectorAdcs); - detectorModules=malloc(sizeof(sls_detector_module)); - detectorChips=malloc(NCHIP*sizeof(int)); - detectorChans=malloc(NCHIP*NCHAN*sizeof(int)); - detectorDacs=malloc(NDAC*sizeof(dacs_t)); - detectorAdcs=malloc(NADC*sizeof(dacs_t)); -#ifdef VERBOSE - printf("modules from 0x%x to 0x%x\n",detectorModules, detectorModules+n); - printf("dacs from 0x%x to 0x%x\n",detectorDacs, detectorDacs+n*NDAC); - printf("adcs from 0x%x to 0x%x\n",detectorAdcs, detectorAdcs+n*NADC); -#endif - (detectorModules)->dacs=detectorDacs; - (detectorModules)->adcs=detectorAdcs; - (detectorModules)->ndac=NDAC; - (detectorModules)->nadc=NADC; - (detectorModules)->nchip=NCHIP; - (detectorModules)->nchan=NCHIP*NCHAN; - (detectorModules)->module=0; - (detectorModules)->gain=0; - (detectorModules)->offset=0; - (detectorModules)->reg=0; - thisSettings = UNINITIALIZED; - - // if trimval requested, should return -1 to acknowledge unknown - int ichan=0; - for (ichan=0; ichan<(detectorModules->nchan); ichan++) { - *((detectorModules->chanregs)+ichan) = -1; - } -} - - - -void setupDetector() { - - allocateDetectorStructureMemory(); - - resetPLL(); - resetCore(); - resetPeripheral(); - cleanFifos(); - - //initialize dac series - initDac(0); - initDac(8); - initDac(16); - - //set dacs - printf("Setting Default Dac values\n"); - { - int i = 0; - int retval[2]={-1,-1}; - const int defaultvals[NDAC] = DEFAULT_DAC_VALS; - for(i = 0; i < NDAC; ++i) { - setDAC((enum DACINDEX)i,defaultvals[i],0,0,retval); - if (retval[0] != defaultvals[i]) - cprintf(RED, "Warning: Setting dac %d failed, wrote %d, read %d\n",i ,defaultvals[i], retval[0]); - } - } - - /*setSamples(1); - bus_w(DAC_REG,0xffff); - setSpeed - cleanFifos(); /* todo might work without - resetCore(); /* todo might work without */ - - //Initialization of acquistion parameters - setTimer(FRAME_NUMBER, DEFAULT_NUM_FRAMES); - setTimer(CYCLES_NUMBER, DEFAULT_NUM_CYCLES); - setTimer(ACQUISITION_TIME, DEFAULT_EXPTIME); - setTimer(FRAME_PERIOD, DEFAULT_PERIOD); - setTimer(DELAY_AFTER_TRIGGER, DEFAULT_DELAY); -} - - - - - - - -/* firmware functions (resets) */ - -int powerChip (int on){ - - /* set all the required voltages */ - return 0; -} - - -void cleanFifos() { printf("\nClearing Acquisition Fifos - Not doing anything\n"); - /* printf("\nClearing Acquisition Fifos\n"); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_ACQ_FIFO_CLR_MSK); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_ACQ_FIFO_CLR_MSK);*/ -} - -void resetCore() {printf("\nResetting Core - Not doing anything\n"); - /*printf("\nResetting Core\n"); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_CORE_RST_MSK); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_CORE_RST_MSK);*/ -} - -void resetPeripheral() {printf("\nResetting Peripheral - Not doing anything\n"); - /* printf("\nResetting Peripheral\n"); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_PERIPHERAL_RST_MSK); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_PERIPHERAL_RST_MSK);*/ -} - -int getPhase(int i) { - if (i>=0 && i<4) - return clkPhase[i]; - else - return -1; -} - - -int configurePhase(int val, int i) { /** compare with old jungfrau software and add in */ - - u_int32_t l=0x0c; - u_int32_t h=0x0d; - u_int32_t vv; - int32_t phase=0, inv=0; - - u_int32_t tot; - u_int32_t odd=1;//0; - - if (i<0 || i>3) - return -1; - - if (val>65535 || val<-65535) - return clkPhase[i]; - - resetPLL(); - - setPllReconfigReg(PLL_MODE_REG, 1, 0); - printf("phase in %d\n",clkPhase[1]); - - if (val>0) { - inv=0; - phase=val&0xffff; - } else { - inv=0; - val=-1*val; - phase=(~val)&0xffff; - } - - - vv=phase | (i<<16);// | (inv<<21); - - setPllReconfigReg(PLL_PHASE_SHIFT_REG,vv,0); - - clkPhase[i]=val; - return clkPhase[i]; -} - - - -int configureFrequency(int val, enum CLKINDEX i) { /** compare with old jungfrau software and add in */ - - - u_int32_t l=0x0c; - u_int32_t h=0x0d; - u_int32_t vv; - int32_t phase=0, inv=0; - - u_int32_t tot; - u_int32_t odd=1;//0; - printf("Want to configure frequency of counter %d to %d\n",i,val); - // printf("PLL reconfig reset\N"); bus_w(PLL_CNTRL_REG,(1<3) { - printf("wrong counter number %d\n",i); - return -1; - } - - if (val<=0) { - - printf("get value %d %d \n",i,clkDivider[i]); - return clkDivider[i]; - } - if (i==adc_clk_c){ - if (val>40) - { - printf("Too high frequency %d MHz for these ADCs!\n", val); - return clkDivider[i]; - } - } - - tot= PLL_VCO_FREQ_MHZ/val; - l=tot/2; - h=l; - if (tot>2*l) { - h=l+1; - odd=1; - } - else - { - odd=0; - } - - printf("Counter %d: Low is %d, High is %d\n",i, l,h); - - - vv= (i<<18)| (odd<<17) | l | (h<<8); - - printf("Counter %d, val: %08x\n", i, vv); - setPllReconfigReg(PLL_C_COUNTER_REG, vv,0); - - - usleep(10000); - - resetPLL(); - - clkDivider[i]=PLL_VCO_FREQ_MHZ/(l+h); - - printf("Frequency of clock %d is %d\n", i, clkDivider[i]); - - return clkDivider[i]; -} - - - - - - - - -/* set parameters - nmod, dr, roi */ - -int setNMod(int nm, enum dimension dim){ - return NMOD; -} - - -int getNModBoard(enum dimension arg){ - return NMAXMOD; -} - - -int setDynamicRange(int dr){ - /* edit functionality */ - return 16; -} - - - - -/* parameters - readout */ - -int setSpeed(enum speedVariable arg, int val) { - int retval = -1; - - switch (arg) { - case DBIT_PHASE: - if (val==-1) - retval=getPhase(DBIT_CLK_C); - else - retval=configurePhase(val,DBIT_CLK_C); - break; - case DBIT_CLOCK: - retval=configureFrequency(val,DBIT_CLK_C); - if (configureFrequency(-1,SYNC_CLK_C)>retval){ - configureFrequency(retval,SYNC_CLK_C); - printf("--Configuring sync clk to %d MHz\n",val); - } else if (configureFrequency(-1,ADC_CLK_C)>retval && configureFrequency(-1,RUN_CLK_C)>retval) { - printf("++Configuring sync clk to %d MHz\n",val); - configureFrequency(retval,SYNC_CLK_C); - } - break; - default: - sprintf(mess,"Unknown speed parameter %d",arg); - break; - } - return retval; -} - - - - - - -/* parameters - timer */ - -int64_t setTimer(enum timerIndex ind, int64_t val) { - - int64_t retval = -1; - switch(ind){ - - case FRAME_NUMBER: - if(val >= 0) - printf("\nSetting #frames: %lld\n",(long long int)val); - retval = set64BitReg(val, SET_FRAMES_LSB_REG, SET_FRAMES_MSB_REG); - printf("Getting #frames: %lld\n",(long long int)retval); - break; - - case ACQUISITION_TIME: - if(val >= 0){ - printf("\nSetting exptime: %lldns\n", (long long int)val); - val *= (1E-3 * CLK_RUN); /* ?? */ - } - retval = set64BitReg(val, SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG) / (1E-3 * CLK_RUN); - printf("Getting exptime: %lldns\n", (long long int)retval); - break; - - case FRAME_PERIOD: - if(val >= 0){ - printf("\nSetting period to %lldns\n",(long long int)val); - val *= (1E-3 * CLK_SYNC); /* ?? */ - } - retval = set64BitReg(val, SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG )/ (1E-3 * CLK_SYNC); - printf("Getting period: %lldns\n", (long long int)retval); - break; - - case DELAY_AFTER_TRIGGER: - if(val >= 0){ - printf("\nSetting delay to %lldns\n", (long long int)val); - val *= (1E-3 * CLK_SYNC); /* ?? */ - } - retval = set64BitReg(val, SET_DELAY_LSB_REG, SET_DELAY_MSB_REG) / (1E-3 * CLK_SYNC); - printf("Getting delay: %lldns\n", (long long int)retval); - break; - - case CYCLES_NUMBER: - if(val >= 0) - printf("\nSetting #cycles to %lld\n", (long long int)val); - retval = set64BitReg(val, SET_CYCLES_LSB_REG, SET_CYCLES_MSB_REG); - printf("Getting #cycles: %lld\n", (long long int)retval); - break; - - case GATES_NUMBER: - if(val >= 0) - printf("\nSetting #gates to %lld\n", (long long int)val); - retval = set64BitReg(val, SET_GATES_LSB_REG, SET_GATES_MSB_REG); - printf("Getting #gates: %lld\n", (long long int)retval); - break; - - case PROBES_NUMBER: /* does not exist in firmware_funcs.c*/ - /*if(val >= 0) - printf("\nSetting #probes to %lld\n", (long long int)val); - retval = set64BitReg(val, SET_PROBES_LSB_REG, SET_PROBES_MSB_REG); - printf("Getting #probes: %lld\n", (long long int)retval); - */ - break; - - case SAMPLES_JCTB: - if(val >= 0) - printf("\nSetting #samples to %lld\n", (long long int)val); - retval = bus_w(NSAMPLES_REG, val); - printf("Getting #samples: %lld\n", (long long int)retval); - - break; - - default: - cprintf(RED,"Warning: Timer Index not implemented for this detector: %d\n", ind); - break; - } - - return retval; - -} - - - -int64_t getTimeLeft(enum timerIndex ind){ - int64_t retval = -1; - switch(ind){ - - case FRAME_NUMBER: - retval = get64BitReg(GET_FRAMES_LSB_REG, GET_FRAMES_MSB_REG); - printf("Getting number of frames left: %lld\n",(long long int)retval); - break; - - case FRAME_PERIOD: - retval = get64BitReg(GET_PERIOD_LSB_REG, GET_PERIOD_MSB_REG) / (1E-3 * CLK_SYNC); - printf("Getting period left: %lldns\n", (long long int)retval); - break; - - case DELAY_AFTER_TRIGGER: - retval = get64BitReg(GET_DELAY_LSB_REG, GET_DELAY_MSB_REG) / (1E-3 * CLK_SYNC); - printf("Getting delay left: %lldns\n", (long long int)retval); - break; - - /** acquisition time and period gives in time left in func.c, pls check with anna */ - - case CYCLES_NUMBER: - retval = get64BitReg(GET_CYCLES_LSB_REG, GET_CYCLES_MSB_REG); - printf("Getting number of cycles left: %lld\n", (long long int)retval); - break; - - case ACTUAL_TIME: - retval = get64BitReg(GET_ACTUAL_TIME_LSB_REG, GET_ACTUAL_TIME_MSB_REG) / (1E-9 * CLK_SYNC); - printf("Getting actual time (time from start): %lld\n", (long long int)retval); - break; - - case MEASUREMENT_TIME: - retval = get64BitReg(GET_MEASUREMENT_TIME_LSB_REG, GET_MEASUREMENT_TIME_MSB_REG) / (1E-9 * CLK_SYNC); - printf("Getting measurement time (timestamp/ start frame time): %lld\n", (long long int)retval); - break; - - case FRAMES_FROM_START: - retval = get64BitReg(FRAMES_FROM_START_LSB_REG, FRAMES_FROM_START_MSB_REG); - printf("Getting frames from start run control %lld\n", (long long int)retval); - break; - - case FRAMES_FROM_START_PG: /** ask anna, seems to be calling previous function (frames_from_start) */ - retval = get64BitReg(FRAMES_FROM_START_PG_LSB_REG, FRAMES_FROM_START_PG_MSB_REG); - printf("Getting frames from start run control %lld\n", (long long int)retval); - break; - - default: - cprintf(RED, "Warning: Remaining Timer index not implemented for this detector: %d\n", ind); - break; - } - - return retval; -} - - - - - - -/* parameters - channel, chip, module, settings */ - - -int setModule(sls_detector_module myMod){ - return thisSettings; -} - - -int getModule(sls_detector_module *myMod){ - return OK; -} - - - -enum detectorSettings setSettings(enum detectorSettings sett, int imod){ - return getSettings(); - -} - - -enum detectorSettings getSettings(){ - return thisSettings; -} - - - - - -/* parameters - dac, adc, hv */ - - - - - - -void initDac(int dacnum) { - printf("\nInitializing dac for %d to \n",dacnum); - - u_int32_t codata; - int csdx = dacnum / NDAC_PER_SET + DAC_SERIAL_CS_OUT_OFST; //,so can be DAC_SERIAL_CS_OUT_OFST or +1 - int dacchannel = 0xf; // all channels - int dacvalue = 0x6; // can be any random value (just writing to power up) - printf(" Write to Input Register\n" - " Chip select bit:%d\n" - " Dac Channel:0x%x\n" - " Dac Value:0x%x\n", - csdx, dacchannel, dacvalue); - - codata = LTC2620_DAC_CMD_WRITE + // command to write to input register - ((dacchannel << LTC2620_DAC_ADDR_OFST) & LTC2620_DAC_ADDR_MSK) + // all channels - ((dacvalue << LTC2620_DAC_DATA_OFST) & LTC2620_DAC_DATA_MSK); // any random value - serializeToSPI(SPI_REG, codata, (0x1 << csdx), LTC2620_DAC_NUMBITS, - DAC_SERIAL_CLK_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_OFST); -} - - - - - - - - - -int voltageToDac(int value){ - int vmin = 0; - int vmax = MAX_DACVOLTVAL; - int nsteps = MAX_DACVAL; - if ((value < vmin) || (value > vmax)) { - cprintf(RED,"Voltage value (to convert to dac value) is outside bounds: %d\n", value); - return -1; - } - return (int)(((value - vmin) / (vmax - vmin)) * (nsteps - 1) + 0.5); -} - -int dacToVoltage(unsigned int digital){ - int vmin = 0; - int vmax = MAX_DACVOLTVAL; - int nsteps = MAX_DACVAL; - int v = vmin + (vmax - vmin) * digital / (nsteps - 1); - if((v < 0) || (v > nsteps - 1)) { - cprintf(RED,"Voltage value (converted from dac value) is outside bounds: %d\n", v); - return -1; - } - return v; -} - -int powerToDac(int value, int chip) { - int nsteps = MAX_DACVAL; - int vchip = MAX_VCHIPVAL - (getDacRegister(V_CHIP)*1000)/(nsteps -1); - printf("Current V_Chip: %d mV\n",vchip); - - int vmax = vchip - MIN_VCHIP_OFSTVAL; - int vmin = MIN_VCHIP_VAL; - - // recalculating only for v_chip - if (chip) { - printf("vchip\n"); - vmax = MAX_VCHIPVAL; - vmin = MAX_VCHIPVAL - 1000; - } - else - printf("vpower\n"); - - int v = (int)(((vmax - value) * (nsteps - 1) / (vmax - vmin)) ); /***+0.5 removed is this correct? seems different from voltageToDac maybe get rid of 0.5*/ - - - if (v < 0) v = 0; - if (v > nsteps - 1) v = nsteps - 1; - if (value == -100) v = -100; - - return v; -} - -int dacToPower(int value, int chip) { - int retval1 = -1; - int nsteps = MAX_DACVAL; - int vchip = MAX_VCHIPVAL - (getDacRegister(V_CHIP)*1000)/(nsteps -1); - printf("Vchip id %d mV\n",vmax); - int vmax = vchip - MIN_VCHIP_OFSTVAL; - int vmin = MIN_VCHIP_VAL; - - // recalculating only for v_chip - if (chip) { - printf("vchip\n"); - vmax = MAX_VCHIPVAL; - vmin = MAX_VCHIPVAL - 1000; - } - else - printf("vpower\n"); - - retval1 = vmax - (value * (vmax - vmin)) / (nsteps - 1); - if (retval1 > vmax) retval1 = vmax; - if (retval1 < vmin) retval1 = vmin; - if (value < 0) retval1 = value; - return retval1; -} - - - -void setDAC(enum DACINDEX ind, int val, int imod, int mV, int retval[]){ - - int dacval = val; - - // dacs: if set and mv, convert to dac - if (ind < val > 0 && mV) { - val = voltageToDac(val); //gives -1 on error - } - - - if ( (val >= 0) || (val == -100)) { - - - u_int32_t ichip = 2 - ind / NDAC_PER_SET; - u_int32_t valw = 0; - int i; - - // start and chip select bar down ----------------- - SPIChipSelect (&valw, SPI_REG, (0x1 << csdx)); - - - // next dac -------------------------------------- - for (i = 0; i < ichip; ++i) { - printf("%d next DAC\n", i); - sendDataToSPI (&valw, SPI_REG, LTC2620_DAC_CMD_MSK, LTC2620_DAC_NUMBITS, - DAC_SERIAL_CLK_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_OFST); - } - - - // this dac ---------------------------------------- - u_int32_t codata; - int csdx = DAC_SERIAL_CS_OUT_OFST; - int dacchannel = ind % NDAC_PER_SET; - - printf("\nSetting of DAC %d : %d dac units (%d mV)\n",ind, dacval, val); - // command - if (val >= 0) { - printf(" Write to Input Register and Update\n"); - codata = LTC2620_DAC_CMD_SET; - - } else if (val == -100) { - printf(" POWER DOWN\n"); - codata = LTC2620_DAC_CMD_POWER_DOWN; - } - // address - printf(" Chip select bit:%d\n" - " Dac Channel:0x%x\n" - " Dac Value:0x%x\n", - csdx, dacchannel, val); - codata += ((dacchannel << LTC2620_DAC_ADDR_OFST) & LTC2620_DAC_ADDR_MSK) + - ((val << LTC2620_DAC_DATA_OFST) & LTC2620_DAC_DATA_MSK); - // to spi - serializeToSPI(SPI_REG, codata, (0x1 << csdx), LTC2620_DAC_NUMBITS, - DAC_SERIAL_CLK_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_OFST); - - - printf("--------done setting dac set %d \n",i); - - // next dac ----------------------------------------------------------- - for (i = ichip+1; i < (N_DAC / NDAC_PER_SET); ++i) { - printf("%d next DAC\n", i); - sendDataToSPI (&valw, SPI_REG, LTC2620_DAC_CMD_MSK, LTC2620_DAC_NUMBITS, - DAC_SERIAL_CLK_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_MSK, DAC_SERIAL_DIGITAL_OUT_OFST); - } - - - //chip select bar up, clk down and stop -------------------------------- - SPIChipDeselect (&valw, SPI_REG, (0x1 << csdx), DAC_SERIAL_CLK_OUT_MSK); - - // writes to register - setDacRegister(ind, dacval); - } - - // reading dac value from register - printf("Getting DAC %d : ",ind); - retval[0] = getDacRegister(ind); printf("%d dac units ", retval[0]); - retval[1] = dacToVoltage(retval[0]);printf("(%d mV)\n", retval[1]); -} - - -int setPower(enum DACINDEX ind, int val) { - - // not implemented yet - if ((ind == V_D) || (ind == V_C)) - return -1; - - // vlimit software limit - else if (ind == V_LIMIT) { - if (val >= 0) - vlimit = val; - return vlimit; - } - - int pwrindex = -1; - int dacval = val; - int retval=-1, retval1=-1; - u_int32_t preg = 0; - int temp[2] = {-1,-1}; - - // get - if (val == -1) - dacval = -1; - - // vchip - else if (ind == V_CHIP) - dacval = powerToDac(val, 1); - - // power a, b, c , d, io - else { - dacval = powerToDac(val, 0); - - switch (ind) { - case V_IO: pwrindex = 0;break; - case V_A: pwrindex = 1; break; - case V_B: pwrindex = 2; break; - default:break; - } - - // shut down - preg = bus_r(POWER_ON_REG); - printf("power reg is %08x\n",bus_r(POWER_ON_REG)); - printf("Switching off power %d\n", ind); - bus_w(POWER_ON_REG,preg &(~(1 << (POWER_ENABLE_OFST + pwrindex)))); - setDac(ind,-100, 0, 1, temp); - printf("power reg is %08x\n",bus_r(POWER_ON_REG)); - retval=0; - } - - // actual setting - if (val != -100) { - printf("Setting power %d to %d mV (%d dac val)\n",ind, val, dacval); - retval = setDac(ind, dacval); - // setting power a, b, c, d, io - if (pwrindex >= 0 && dacval >= 0 ) { - preg = bus_r(POWER_ON_REG); - printf("power reg is %08x\n", bus_r(POWER_ON_REG)); - printf("Switching on power %d\n", pwrindex); - bus_w(POWER_ON_REG, preg | ((1 << (POWER_ENABLE_OFST + pwrindex)))); - printf("power reg is %08x\n",bus_r(POWER_ON_REG)); - } - } - - if (pwrindex >= 0) { - if (bus_r(POWER_ON_REG) & (1 << (POWER_ENABLE_OFST + pwrindex))) { - retval1 = dacToPower(retval, 0); - printf("Vdac id %d mV\n",retval1); - } else - retval1 = 0; - } else { - if (retval >= 0) { - retval1 = dacToPower(retval, 1); - /*printf("Vchip is %d mV\n",vmax); makes no sense.. should be printing retval1??? */ - } else - retval1=-1; - } - - return retval1; -} - -int getVLimit() { - return vlimit; -} - -void setDacRegister(int dacnum,int dacvalue) { - bus_w(DAC_NUM_REG, dacnum); - bus_w(DAC_VAL_REG, dacvalue); - bus_w(DAC_NUM_REG, dacnum | (1<<16));/** super strange writing dac num in weird ways */ - bus_w(DAC_NUM_REG, dacnum); - printf("Wrote dac register value %d address %d\n",bus_r(DAC_VAL_REG),bus_r(DAC_NUM_REG)) ; -} - -int getDacRegister(int dacnum) {/** super strange, reading out in some other register than written */ - bus_w(DAC_NUM_REG, dacnum); - printf("READ dac register value %d address %d\n",(int16_t)bus_r(DAC_VAL_OUT_REG),bus_r(DAC_NUM_REG)) ; - return (int16_t)bus_r(DAC_VAL_OUT_REG); -} - - - - - -/* parameters - timing, extsig */ - - -enum externalCommunicationMode setTiming( enum externalCommunicationMode arg){ - return AUTO_TIMING; -} - - - - -/* jungfrau specific - pll, flashing fpga */ - - - -void resetPLL() { - // reset PLL Reconfiguration and PLL - bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) | PLL_CTRL_RECONFIG_RST_MSK | PLL_CTRL_RST_MSK); - usleep(100); - bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) & ~PLL_CTRL_RECONFIG_RST_MSK & ~PLL_CTRL_RST_MSK); -} - - -u_int32_t setPllReconfigReg(u_int32_t reg, u_int32_t val) { - - // set parameter - bus_w(PLL_PARAM_REG, val); - - // set address - bus_w(PLL_CONTROL_REG, (reg << PLL_CTRL_ADDR_OFST) & PLL_CTRL_ADDR_MSK); - usleep(10*1000); - - //write parameter - bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) | PLL_CTRL_WR_PARAMETER_MSK); - bus_w(PLL_CONTROL_REG, bus_r(PLL_CONTROL_REG) & ~PLL_CTRL_WR_PARAMETER_MSK); - usleep(10*1000); - - return val; -} - - - - -void configurePll() { - u_int32_t val; - int32_t phase=0, inv=0; - - printf(" phase in %d\n", clkPhase[1]); - if (clkPhase[1]>0) { - inv=0; - phase=clkPhase[1]; - } else { - inv=1; - phase=-1*clkPhase[1]; - } - printf(" phase out %d (0x%08x)\n", phase, phase); - - if (inv) { - val = ((phase << PLL_SHIFT_NUM_SHIFTS_OFST) & PLL_SHIFT_NUM_SHIFTS_MSK) + PLL_SHIFT_CNT_SLCT_C1_VAL + PLL_SHIFT_UP_DOWN_NEG_VAL; - printf(" phase word 0x%08x\n", val); - setPllReconfigReg(PLL_PHASE_SHIFT_REG, val); - } else { - val = ((phase << PLL_SHIFT_NUM_SHIFTS_OFST) & PLL_SHIFT_NUM_SHIFTS_MSK) + PLL_SHIFT_CNT_SLCT_C0_VAL + PLL_SHIFT_UP_DOWN_NEG_VAL; - printf(" phase word 0x%08x\n", val); - setPllReconfigReg(PLL_PHASE_SHIFT_REG, val); - - printf(" phase word 0x%08x\n", val); - val = ((phase << PLL_SHIFT_NUM_SHIFTS_OFST) & PLL_SHIFT_NUM_SHIFTS_MSK) + PLL_SHIFT_CNT_SLCT_C2_VAL; - setPllReconfigReg(PLL_PHASE_SHIFT_REG, val); - } - usleep(10000); -} - - - - -/* aquisition */ - -int startStateMachine(){ - printf("*******Starting State Machine*******\n"); - - cleanFifos(); - - //start state machine - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_START_ACQ_MSK); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_START_ACQ_MSK); - - printf("Status Register: %08x\n",bus_r(STATUS_REG)); - return OK; -} - - -int stopStateMachine(){ - cprintf(BG_RED,"*******Stopping State Machine*******\n"); - - //stop state machine - bus_w(CONTROL_REG, bus_r(CONTROL_REG) | CONTROL_STOP_ACQ_MSK); - usleep(100); - bus_w(CONTROL_REG, bus_r(CONTROL_REG) & ~CONTROL_STOP_ACQ_MSK); - - printf("Status Register: %08x\n",bus_r(STATUS_REG)); - return OK; -} - - - - - -enum runStatus getRunStatus(){ -#ifdef VERBOSE - printf("Getting status\n"); -#endif - - enum runStatus s; - u_int32_t retval = bus_r(STATUS_REG); - printf("Status Register: %08x\n",retval); - - //running - if(((retval & RUN_BUSY_MSK) >> RUN_BUSY_OFST)) { - if ((retval & WAITING_FOR_TRIGGER_MSK) >> WAITING_FOR_TRIGGER_OFST) { - printf("-----------------------------------WAITING-----------------------------------\n"); - s=WAITING; - } - else{ - printf("-----------------------------------RUNNING-----------------------------------\n"); - s=RUNNING; - } - } - - //not running - else { - if ((retval & STOPPED_MSK) >> STOPPED_OFST) { - printf("-----------------------------------STOPPED--------------------------\n"); - s=STOPPED; - } else if ((retval & RUNMACHINE_BUSY_MSK) >> RUNMACHINE_BUSY_OFST) { - printf("-----------------------------------READ MACHINE BUSY--------------------------\n"); - s=TRANSMITTING; - } else if (!retval) { - printf("-----------------------------------IDLE--------------------------------------\n"); - s=IDLE; - } else { - printf("-----------------------------------Unknown status %08x--------------------------------------\n", retval); - s=ERROR; - } - } - - return s; -} - - - -void readFrame(int *ret, char *mess){ - - // wait for status to be done - while(runBusy()){ - usleep(500); - } - - // frames left to give status - int64_t retval = getTimeLeft(FRAME_NUMBER) + 1; - if ( retval > 0) { - *ret = (int)FAIL; - sprintf(mess,"no data and run stopped: %lld frames left\n",retval); - cprintf(RED,"%s\n",mess); - } else { - *ret = (int)FINISHED; - sprintf(mess,"acquisition successfully finished\n"); - printf("%s",mess); - } -} - - - -u_int32_t runBusy(void) { - u_int32_t s = ((bus_r(STATUS_REG) & RUN_BUSY_MSK) >> RUN_BUSY_OFST); -#ifdef VERBOSE - printf("Status Register: %08x\n", s); -#endif - return s; -} - - - - - - - - -/* common */ - -//jungfrau doesnt require chips and chans (save memory) -int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod){ - - int idac, iadc; - int ret=OK; - -#ifdef VERBOSE - printf("Copying module %x to module %x\n",srcMod,destMod); -#endif - - if (srcMod->module>=0) { -#ifdef VERBOSE - printf("Copying module number %d to module number %d\n",srcMod->module,destMod->module); -#endif - destMod->module=srcMod->module; - } - if (srcMod->serialnumber>=0){ - - destMod->serialnumber=srcMod->serialnumber; - } - if ((srcMod->nchip)>(destMod->nchip)) { - printf("Number of chip of source is larger than number of chips of destination\n"); - return FAIL; - } - if ((srcMod->nchan)>(destMod->nchan)) { - printf("Number of channels of source is larger than number of channels of destination\n"); - return FAIL; - } - if ((srcMod->ndac)>(destMod->ndac)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - if ((srcMod->nadc)>(destMod->nadc)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - -#ifdef VERBOSE - printf("DACs: src %d, dest %d\n",srcMod->ndac,destMod->ndac); - printf("ADCs: src %d, dest %d\n",srcMod->nadc,destMod->nadc); - printf("Chips: src %d, dest %d\n",srcMod->nchip,destMod->nchip); - printf("Chans: src %d, dest %d\n",srcMod->nchan,destMod->nchan); - -#endif - destMod->ndac=srcMod->ndac; - destMod->nadc=srcMod->nadc; - destMod->nchip=srcMod->nchip; - destMod->nchan=srcMod->nchan; - if (srcMod->reg>=0) - destMod->reg=srcMod->reg; -#ifdef VERBOSE - printf("Copying register %x (%x)\n",destMod->reg,srcMod->reg ); -#endif - if (srcMod->gain>=0) - destMod->gain=srcMod->gain; - if (srcMod->offset>=0) - destMod->offset=srcMod->offset; - - for (idac=0; idac<(srcMod->ndac); idac++) { - if (*((srcMod->dacs)+idac)>=0) - *((destMod->dacs)+idac)=*((srcMod->dacs)+idac); - } - for (iadc=0; iadc<(srcMod->nadc); iadc++) { - if (*((srcMod->adcs)+iadc)>=0) - *((destMod->adcs)+iadc)=*((srcMod->adcs)+iadc); - } - return ret; -} - - -int calculateDataBytes(){ - return DATA_BYTES; -} - -int getTotalNumberOfChannels(){return ((int)getNumberOfChannelsPerModule() * (int)getTotalNumberOfModules());} -int getTotalNumberOfChips(){return ((int)getNumberOfChipsPerModule() * (int)getTotalNumberOfModules());} -int getTotalNumberOfModules(){return NMOD;} -int getNumberOfChannelsPerModule(){return ((int)getNumberOfChannelsPerChip() * (int)getTotalNumberOfChips());} -int getNumberOfChipsPerModule(){return NCHIP;} -int getNumberOfDACsPerModule(){return NDAC;} -int getNumberOfADCsPerModule(){return NADC;} -int getNumberOfChannelsPerChip(){return NCHAN;} - - - -/* sync */ - -enum masterFlags setMaster(enum masterFlags arg){ - return NO_MASTER; -} - -enum synchronizationMode setSynchronization(enum synchronizationMode arg){ - return NO_SYNCHRONIZATION; -} - - - - - - -//#endif diff --git a/slsDetectorSoftware/mythen3DetectorServer/slsDetectorServer_defs.h b/slsDetectorSoftware/mythen3DetectorServer/slsDetectorServer_defs.h deleted file mode 100644 index e638f840e..000000000 --- a/slsDetectorSoftware/mythen3DetectorServer/slsDetectorServer_defs.h +++ /dev/null @@ -1,167 +0,0 @@ -/* - * mythen3Server_defs.h - * - * Created on: Jan 24, 2013 - * Author: l_maliakal_d, changed my Marie A. - */ - -#ifndef SLSDETECTORSERVER_DEFS_H_ -#define SLSDETECTORSERVER_DEFS_H_ - -#include "sls_detector_defs.h" -#include - -/** This is only an example file!!! */ - - - -#define GOODBYE (-200) -enum DACINDEX {vIpre, vIbias, Vrf, VrfSh, vIinSh, VdcSh, Vth2, VPL, Vth1, Vth3, Vtrim, casSh, cas, vIbiasSh, vIcin, VPH, NC, vIpreOut, V_D, V_CHIP, V_C, V_B, V_A, V_IO, V_LIM}; // Mythen 3.01 -enum PWRINDEX {PWR_IO, PWR_A, PWR_B, PWR_C, PWR_D, PWR_CHIP=-1, PWR_LIMIT=-1}; -enum CLKINDEX {RUN_CLK_C, ADC_CLK_C, SYNC_CLK_C, DBIT_CLK_C}; - -#define DEFAULT_DAC_VALS { 2150, /* vIpre */ \ - 1200, /* vIbias */ \ - 900, /* Vrf */ \ - 1050, /* VrfSh */ \ - 1400, /* vIinSh */ \ - 655, /* VdcSh */ \ - 850, /* Vth2 */ \ - 1400, /* VPL */ \ - 850, /* Vth1 */ \ - 850, /* Vth3 */ \ - 2294, /* Vtrim */ \ - 983, /* casSh */ \ - 1474, /* cas */ \ - 1200, /* vIbiasSh */ \ - 1600, /* vIcin */ \ - 1520, /* VPH */ \ - 0, /* NC */ \ - 1000 /* vIpreOut */ \ - 0 /* V_D */ \ - 0 /* V_CHIP */ \ - 0 /* V_C */ \ - 1335 /* V_B */ \ - 1335 /* V_A */ \ - 1350 /* V_IO */ \ - }; - -#define DEFAULT_DAC_NAMES { "vIpre", \ - "vIbias", \ - "Vrf", \ - "VrfSh", \ - "vIinSh", \ - "VdcSh", \ - "Vth2", \ - "VPL", \ - "Vth1", \ - "Vth3", \ - "Vtrim", \ - "casSh", \ - "cas", \ - "vIbiasSh", \ - "vIcin", \ - "VPH", \ - "NC", \ - "vIpreOut" \ - "v_d" \ - "v_chip" \ - "v_c" \ - "v_b" \ - "v_a" \ - "v_io" \ - }; - -/*Hardware Definitions */ -#define NMAXMOD (1) -#define NMOD (1) -#define NCHAN (32) -#define NCHIP (1) -#define NADC (0) -#define NDAC (24) -#define NDAC_PER_SET (8) - - -#define NPWR (5) -#define MAX_DACVOLTVAL (2500) //mV -#define MAX_DACVAL (4096) // dac val -#define MAX_VCHIPVAL (2700) //mV /** name ???? */ -#define MIN_VCHIP_OFSTVAL (200) //mV /** name ???? */ -#define MIN_VCHIP_VAL (600) //mV /** name ???? */ - - -/** Default Parameters */ -#define DEFAULT_NUM_FRAMES (1) -#define DEFAULT_NUM_CYCLES (1) -#define DEFAULT_EXPTIME (200*1000) //ns -#define DEFAULT_PERIOD (1*1000*1000) //ns -#define DEFAULT_DELAY (0) -#define DEFAULT_HIGH_VOLTAGE (0) -#define DEFAULT_TIMING_MODE (AUTO_TIMING) - - -/* Defines in the Firmware */ -#define FIX_PATT_VAL (0xACDC1980) - -/* LTC2620 DAC DEFINES */ -#define LTC2620_DAC_CMD_OFST (20) -#define LTC2620_DAC_CMD_MSK (0x0000000F << LTC2620_DAC_CMD_OFST) -#define LTC2620_DAC_ADDR_OFST (16) -#define LTC2620_DAC_ADDR_MSK (0x0000000F << LTC2620_DAC_ADDR_OFST) -#define LTC2620_DAC_DATA_OFST (4) -#define LTC2620_DAC_DATA_MSK (0x00000FFF << LTC2620_DAC_DATA_OFST) - -#define LTC2620_DAC_CMD_WRITE (0x00000000 << LTC2620_DAC_CMD_OFST) -#define LTC2620_DAC_CMD_SET (0x00000003 << LTC2620_DAC_CMD_OFST) -#define LTC2620_DAC_CMD_POWER_DOWN (0x00000004 << LTC2620_DAC_CMD_OFST) -#define LTC2620_DAC_NUMBITS (24) - -/** PLL Reconfiguration Registers */ -//https://www.altera.com/documentation/mcn1424769382940.html -#define PLL_MODE_REG (0x00) -#define PLL_STATUS_REG (0x01) -#define PLL_START_REG (0x02) -#define PLL_N_COUNTER_REG (0x03) -#define PLL_M_COUNTER_REG (0x04) -#define PLL_C_COUNTER_REG (0x05) -#define PLL_PHASE_SHIFT_REG (0x06) - -#define PLL_SHIFT_NUM_SHIFTS_OFST (0) -#define PLL_SHIFT_NUM_SHIFTS_MSK (0x0000FFFF << PLL_SHIFT_NUM_SHIFTS_OFST) - -#define PLL_SHIFT_CNT_SELECT_OFST (16) -#define PLL_SHIFT_CNT_SELECT_MSK (0x0000001F << PLL_SHIFT_CNT_SELECT_OFST) -#define PLL_SHIFT_CNT_SLCT_C0_VAL ((0x0 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C1_VAL ((0x1 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C2_VAL ((0x2 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C3_VAL ((0x3 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C4_VAL ((0x4 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C5_VAL ((0x5 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C6_VAL ((0x6 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C7_VAL ((0x7 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C8_VAL ((0x8 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C9_VAL ((0x9 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C10_VAL ((0x10 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C11_VAL ((0x11 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C12_VAL ((0x12 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C13_VAL ((0x13 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C14_VAL ((0x14 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C15_VAL ((0x15 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C16_VAL ((0x16 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) -#define PLL_SHIFT_CNT_SLCT_C17_VAL ((0x17 << PLL_SHIFT_CNT_SELECT_OFST) & PLL_SHIFT_CNT_SELECT_MSK) - -#define PLL_SHIFT_UP_DOWN_OFST (21) -#define PLL_SHIFT_UP_DOWN_MSK (0x00000001 << PLL_SHIFT_UP_DOWN_OFST) -#define PLL_SHIFT_UP_DOWN_NEG_VAL ((0x0 << PLL_SHIFT_UP_DOWN_OFST) & PLL_SHIFT_UP_DOWN_MSK) -#define PLL_SHIFT_UP_DOWN_POS_VAL ((0x1 << PLL_SHIFT_UP_DOWN_OFST) & PLL_SHIFT_UP_DOWN_MSK) - -#define PLL_K_COUNTER_REG (0x07) -#define PLL_BANDWIDTH_REG (0x08) -#define PLL_CHARGEPUMP_REG (0x09) -#define PLL_VCO_DIV_REG (0x1c) -#define PLL_MIF_REG (0x1f) - -#define PLL_VCO_FREQ_MHZ 400 - - -#endif /* SLSDETECTORSERVER_DEFS_H_ */ diff --git a/slsDetectorSoftware/mythen3DetectorServer/sls_detector_defs.h b/slsDetectorSoftware/mythen3DetectorServer/sls_detector_defs.h deleted file mode 120000 index c5062e03f..000000000 --- a/slsDetectorSoftware/mythen3DetectorServer/sls_detector_defs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/mythen3DetectorServer/sls_detector_funcs.h b/slsDetectorSoftware/mythen3DetectorServer/sls_detector_funcs.h deleted file mode 120000 index 844b67129..000000000 --- a/slsDetectorSoftware/mythen3DetectorServer/sls_detector_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/mythen3DetectorServer/sls_receiver_defs.h b/slsDetectorSoftware/mythen3DetectorServer/sls_receiver_defs.h deleted file mode 120000 index 1de31caf5..000000000 --- a/slsDetectorSoftware/mythen3DetectorServer/sls_receiver_defs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/mythen3DetectorServer/sls_receiver_funcs.h b/slsDetectorSoftware/mythen3DetectorServer/sls_receiver_funcs.h deleted file mode 120000 index c2ea4ded9..000000000 --- a/slsDetectorSoftware/mythen3DetectorServer/sls_receiver_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/mythen3DetectorServer/updateGitVersion.sh b/slsDetectorSoftware/mythen3DetectorServer/updateGitVersion.sh deleted file mode 100755 index 0c25e7f1e..000000000 --- a/slsDetectorSoftware/mythen3DetectorServer/updateGitVersion.sh +++ /dev/null @@ -1,31 +0,0 @@ -SERVER=jungfrauDetectorServer -MAINDIR=slsDetectorsPackage -SPECDIR=slsDetectorSoftware/$SERVER -TMPFILE=gitInfoJungfrauTmp.h -INCLFILE=gitInfoJungfrau.h - - -#evaluate the variables -EVALFILE=../../evalVersionVariables.sh -source $EVALFILE - - -#get modified date -#RDATE1='git log --pretty=format:"%ci" -1' -RDATE1="find ../slsDetectorServer . -type f -exec stat --format '%Y :%y %n' '{}' \; | sort -nr | cut -d: -f2- | egrep -v 'gitInfo|bin|.git|updateGitVersion|.o' | head -n 1" -RDATE=`eval $RDATE1` -NEWDATE=$(sed "s/-//g" <<< $RDATE | awk '{print $1;}') -NEWDATE=${NEWDATE/#/0x} - - -#get old date from INCLFILE -OLDDATE=$(more $INCLFILE | grep '#define GITDATE' | awk '{print $3}') - - -#update INCLFILE if changes -if [ "$OLDDATE" != "$NEWDATE" ]; then - echo Path: ${MAINDIR}/${SPECDIR} $'\n'URL: ${GITREPO} $'\n'Repository Root: ${GITREPO} $'\n'Repsitory UUID: ${REPUID} $'\n'Revision: ${FOLDERREV} $'\n'Branch: ${BRANCH} $'\n'Last Changed Author: ${AUTH1}_${AUTH2} $'\n'Last Changed Rev: ${REV} $'\n'Last Changed Date: ${RDATE} > gitInfo.txt - cd ../../ - ./genVersionHeader.sh $SPECDIR/gitInfo.txt $SPECDIR/$TMPFILE $SPECDIR/$INCLFILE - cd $WD -fi \ No newline at end of file diff --git a/slsDetectorSoftware/mythenDetectorServer/.target-makefrag b/slsDetectorSoftware/mythenDetectorServer/.target-makefrag deleted file mode 100755 index ce093ecac..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/.target-makefrag +++ /dev/null @@ -1 +0,0 @@ -AXIS_BUILDTYPE ?= cris-axis-linux-gnu diff --git a/slsDetectorSoftware/mythenDetectorServer/Makefile b/slsDetectorSoftware/mythenDetectorServer/Makefile deleted file mode 100755 index b72e33681..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/Makefile +++ /dev/null @@ -1,46 +0,0 @@ -# $Id: Makefile,v 1.1.1.1 2006/02/04 03:35:01 freza Exp $ -# first compile -# make cris-axis-linux-gnu - -AXIS_USABLE_LIBS = UCLIBC GLIBC -include $(AXIS_TOP_DIR)/tools/build/Rules.axis - -PROGS= mythenDetectorServer - -INSTDIR= $(prefix)/bin -INSTMODE= 0777 - -SRCS= server.c server_funcs.c communication_funcs.c firmware_funcs.c mcb_funcs.c trimming_funcs.c sharedmemory.c -OBJS= $(SRCS:%.c=%.o) - -VFLAGS= -#-DVERBOSE -#-DVERYVERBOSE -CFLAGS+= -Wall -DC_ONLY -DMCB_FUNCS -DDACS_INT $(VFLAGS) -#-Werror - -LDLIBS+= -lm - -mythen: clean versioning $(PROGS) -all: versioning $(PROGS) - -boot: $(OBJS) - -versioning: - @echo `tput setaf 6; ./updateGitVersion.sh; tput sgr0;` - - -$(PROGS): $(OBJS) - echo $(OBJS) - $(CC) $(LDFLAGS) $^ $(LDLIBS) $(CFLAGS) -o $@ -DVERBOSE - -install: $(PROGS) - $(INSTALL) -d $(INSTDIR) - $(INSTALL) -m $(INSTMODE) $(PROGS) $(INSTDIR) - -clean: - rm -rf $(PROGS) $(PICASSO) *.o - -depend: - makedepend -Y -- $(CFLAGS) -- $(SRCS) 2>/dev/null - \ No newline at end of file diff --git a/slsDetectorSoftware/mythenDetectorServer/Makefile.dum b/slsDetectorSoftware/mythenDetectorServer/Makefile.dum deleted file mode 100644 index 4656a39bf..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/Makefile.dum +++ /dev/null @@ -1,40 +0,0 @@ -# $Id: Makefile,v 1.1.1.1 2006/02/04 03:35:01 freza Exp $ -# first compile -# make cris-axis-linux-gnu - -AXIS_USABLE_LIBS = UCLIBC GLIBC -include $(AXIS_TOP_DIR)/tools/build/Rules.axis - -PROGS= dummy - -INSTDIR= $(prefix)/bin -INSTMODE= 0777 - -SRCS= dummy_main.c server_funcs.c communication_funcs.c firmware_funcs.c mcb_funcs.c trimming_funcs.c sharedmemory.c -OBJS= $(SRCS:%.c=%.o) - -CFLAGS+= -Wall -DC_ONLY -DVERBOSE -#-Werror - -LDLIBS+= -lm - -all: versioning $(PROGS) - -boot: $(OBJS) - -$(PROGS): $(OBJS) - echo $(OBJS) - $(CC) $(LDFLAGS) $^ $(LDLIBS) -o $@ - -install: $(PROGS) - $(INSTALL) -d $(INSTDIR) - $(INSTALL) -m $(INSTMODE) $(PROGS) $(INSTDIR) - -clean: - rm -rf $(PROGS) *.o - -depend: - makedepend -Y -- $(CFLAGS) -- $(SRCS) 2>/dev/null - -versioning: - @echo `tput setaf 6; ./updateGitVersion.sh; tput sgr0;` \ No newline at end of file diff --git a/slsDetectorSoftware/mythenDetectorServer/Makefile.picasso b/slsDetectorSoftware/mythenDetectorServer/Makefile.picasso deleted file mode 100644 index 48d204135..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/Makefile.picasso +++ /dev/null @@ -1,49 +0,0 @@ -# $Id: Makefile,v 1.1.1.1 2006/02/04 03:35:01 freza Exp $ -# first compile -# make cris-axis-linux-gnu - -AXIS_USABLE_LIBS = UCLIBC GLIBC -include $(AXIS_TOP_DIR)/tools/build/Rules.axis - -PROGS= mythenDetectorServer -PICASSO= picassoDetectorServer -PICASSOFLAGS= -DPICASSOD - -INSTDIR= $(prefix)/bin -INSTMODE= 0777 - -SRCS= server.c server_funcs.c communication_funcs.c firmware_funcs.c mcb_funcs.c trimming_funcs.c sharedmemory.c -OBJS= $(SRCS:%.c=%.o) - -CFLAGS+= -Wall -DC_ONLY -DMCB_FUNCS -DVERBOSE -DVERYVERBOSE -DPICASSOD -#-Werror - -LDLIBS+= -lm - -picasso: $(PICASSO) -mythen: versioning $(PROGS) -all: versioning $(PROGS) $(PICASSO) - -boot: $(OBJS) - -$(PROGS): $(OBJS) - echo $(OBJS) - $(CC) $(LDFLAGS) $^ $(LDLIBS) $(CFLAGS) -o $@ - -$(PICASSO): $(OBJS) - echo $(OBJS) - $(CC) $(LDFLAGS) $^ $(LDLIBS) $(CFLAGS) $(PICASSOFLAGS) -o $@ - - -install: $(PROGS) - $(INSTALL) -d $(INSTDIR) - $(INSTALL) -m $(INSTMODE) $(PROGS) $(INSTDIR) - -clean: - rm -rf $(PROGS) $(PICASSO) *.o - -depend: - makedepend -Y -- $(CFLAGS) -- $(SRCS) 2>/dev/null - -versioning: - @echo `tput setaf 6; ./updateGitVersion.sh; tput sgr0;` \ No newline at end of file diff --git a/slsDetectorSoftware/mythenDetectorServer/Makefile.virtual b/slsDetectorSoftware/mythenDetectorServer/Makefile.virtual deleted file mode 100755 index f3cb34b21..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/Makefile.virtual +++ /dev/null @@ -1,18 +0,0 @@ -DESTDIR?= ./ -PROGS= $(DESTDIR)/mythenVirtualServer - -SRCS= server.c server_funcs.c communication_funcs.c firmware_funcs.c mcb_funcs.c trimming_funcs.c sharedmemory.c - -OBJS= $(SRCS:%.c=%.o) - -CFLAGS+= -Wall -DC_ONLY -DMCB_FUNCS -DDACS_INT $(VFLAGS) -DVIRTUAL -DVERBOSE - -LDLIBS+= -lm -mythenVirtualServer : clean $(PROGS) - -$(PROGS): $(SRCS) - gcc $(LDFLAGS) $(SRCS) $(LDLIBS) $(CFLAGS) -o $@ - -clean: - rm -f *.o $(PROGS) - diff --git a/slsDetectorSoftware/mythenDetectorServer/ansi.h b/slsDetectorSoftware/mythenDetectorServer/ansi.h deleted file mode 120000 index a122db0ad..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/ansi.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/ansi.h \ No newline at end of file diff --git a/slsDetectorSoftware/mythenDetectorServer/communication_funcs.c b/slsDetectorSoftware/mythenDetectorServer/communication_funcs.c deleted file mode 120000 index 87a4f95d1..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/communication_funcs.c +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.c \ No newline at end of file diff --git a/slsDetectorSoftware/mythenDetectorServer/communication_funcs.h b/slsDetectorSoftware/mythenDetectorServer/communication_funcs.h deleted file mode 120000 index f220903b2..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/communication_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/mythenDetectorServer/firmware_funcs.c b/slsDetectorSoftware/mythenDetectorServer/firmware_funcs.c deleted file mode 100755 index 6e90105cb..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/firmware_funcs.c +++ /dev/null @@ -1,1765 +0,0 @@ -#ifndef PICASSOD -#include "server_defs.h" -#else -#include "picasso_defs.h" -#endif - -#include "firmware_funcs.h" -#include "mcb_funcs.h" -#include "registers.h" - -#ifdef SHAREDMEMORY -#include "sharedmemory.h" -#endif - -#include -#include -#include - -#include -//#define VERBOSE - -//for memory mapping -u_int64_t CSP0BASE; - -FILE *debugfp, *datafp; - -int fr; -int wait_time; -int *fifocntrl; -int *values; -int *statusreg; -const int nModY=1; -int nModBoard; -int nModX=NMAXMOD; -int dynamicRange=32; -int dataBytes=NMAXMOD*NCHIP*NCHAN*4; -int storeInRAM=0; -int *ram_values=NULL; -char *now_ptr=NULL; -int ram_size=0; - -int64_t totalTime=1; -u_int32_t progressMask=0; - - - -int ififostart, ififostop, ififostep, ififo; - -int masterMode=NO_MASTER, syncMode=NO_SYNCHRONIZATION, timingMode=AUTO_TIMING; - -enum externalSignalFlag signals[4]={GATE_IN_ACTIVE_HIGH, TRIGGER_IN_RISING_EDGE, SIGNAL_OFF, SIGNAL_OFF}; - - -#ifdef MCB_FUNCS -extern const int nChans; -extern const int nChips; -extern const int nDacs; -extern const int nAdcs; -#endif -#ifndef MCB_FUNCS - -const int nChans=NCHAN; -const int nChips=NCHIP; -const int nDacs=NDAC; -const int nAdcs=NADC; -#endif - -//int mybyte; -//int mysize=dataBytes/8; - -int mapCSP0(void) { - printf("Mapping memory\n"); -#ifndef VIRTUAL - int fd; - fd = open("/dev/mem", O_RDWR | O_SYNC, 0); - if (fd == -1) { - printf("\nCan't find /dev/mem!\n"); - return FAIL; - } - printf("/dev/mem opened\n"); - CSP0BASE = (u_int32_t)mmap(0, MEM_SIZE, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, CSP0); - if (CSP0BASE == (u_int32_t)MAP_FAILED) { - printf("\nCan't map memmory area!!\n"); - return FAIL; - } - printf("CSP0 mapped\n"); - -#endif -#ifdef VIRTUAL - CSP0BASE = malloc(MEM_SIZE); - printf("memory allocated\n"); -#endif -#ifdef SHAREDMEMORY - if ( (res=inism(SMSV))<0) { - printf("error attaching shared memory! %i",res); - return FAIL; - } -#endif - printf("CSPOBASE=from %08x to %x\n",CSP0BASE,CSP0BASE+MEM_SIZE); - - values=(u_int32_t*)(CSP0BASE+FIFO_DATA_REG_OFF); - printf("values=%08x\n",values); - fifocntrl=(u_int32_t*)(CSP0BASE+FIFO_CNTRL_REG_OFF); - printf("fifcntrl=%08x\n",fifocntrl); - statusreg=(u_int32_t*)(CSP0BASE+STATUS_REG); - printf("statusreg=%08x\n",statusreg); - - return OK; -} - - -u_int32_t bus_w(u_int32_t offset, u_int32_t data) { - u_int32_t *ptr1; - - - ptr1=(u_int32_t*)(CSP0BASE+offset); - *ptr1=data; - - return OK; -} - - -u_int32_t bus_r(u_int32_t offset) { - u_int32_t *ptr1; - - ptr1=(u_int32_t*)(CSP0BASE+offset); - return *ptr1; -} - -// direct pattern output -u_int32_t putout(char *s, int modnum) { - int i; - u_int32_t pat; - int addr; - - if (strlen(s)<16) { - fprintf(stdout," *** putout error: incorrect pattern length ***\n"); - fprintf(stdout," %s \n",s); - return FAIL; - } - - pat=0; - for (i=0;i<16;i++) { - if (s[i]=='1') pat=pat+(1<>CLK_DIVIDER_OFFSET); -} - -u_int32_t getClockDivider() { - u_int32_t clk_div; - clk_div=((bus_r(SPEED_REG)&CLK_DIVIDER_MASK)>>CLK_DIVIDER_OFFSET); - return clk_div; -} - -u_int32_t setSetLength(int d) { - u_int32_t c; - c=bus_r(SPEED_REG); - bus_w(SPEED_REG,(d<>SET_LENGTH_OFFSET); -} - -u_int32_t getSetLength() { - u_int32_t clk_div; - clk_div=((bus_r(SPEED_REG)& SET_LENGTH_MASK)>>SET_LENGTH_OFFSET); - return clk_div; -} - - -u_int32_t setWaitStates(int d1) { - u_int32_t c; - int d=d1-2; - //int d=d1-3; - char cmd[100]; - if (d1<=0xf) { - sprintf(cmd,"bus -a 0xb0000000 -w 0x%x0008",d1); - c=bus_r(SPEED_REG); - bus_w(SPEED_REG,(d<>WAIT_STATES_OFFSET)+2; -} - -u_int32_t getWaitStates() { - u_int32_t clk_div; - clk_div=((bus_r(SPEED_REG)& WAIT_STATES_MASK)>>WAIT_STATES_OFFSET); - return clk_div+2; -} - - -u_int32_t setTotClockDivider(int d) { - u_int32_t c; - c=bus_r(SPEED_REG); - bus_w(SPEED_REG,(d<>TOTCLK_DIVIDER_OFFSET); -} - -u_int32_t getTotClockDivider() { - u_int32_t clk_div; - clk_div=((bus_r(SPEED_REG)&TOTCLK_DIVIDER_MASK)>>TOTCLK_DIVIDER_OFFSET); - return clk_div; -} - - -u_int32_t setTotDutyCycle(int d) { - u_int32_t c; - c=bus_r(SPEED_REG); - bus_w(SPEED_REG,(d<>TOTCLK_DUTYCYCLE_OFFSET); -} - -u_int32_t getTotDutyCycle() { - u_int32_t clk_div; - clk_div=((bus_r(SPEED_REG)&TOTCLK_DUTYCYCLE_MASK)>>TOTCLK_DUTYCYCLE_OFFSET); - return clk_div; -} - - -u_int32_t setExtSignal(int d, enum externalSignalFlag mode) { - - - // int modes[]={EXT_SIG_OFF, EXT_GATE_IN_ACTIVEHIGH, EXT_GATE_IN_ACTIVELOW,EXT_TRIG_IN_RISING,EXT_TRIG_IN_FALLING,EXT_RO_TRIG_IN_RISING, EXT_RO_TRIG_IN_FALLING,EXT_GATE_OUT_ACTIVEHIGH, EXT_GATE_OUT_ACTIVELOW, EXT_TRIG_OUT_RISING, EXT_TRIG_OUT_FALLING, EXT_RO_TRIG_OUT_RISING, EXT_RO_TRIG_OUT_FALLING}; - - u_int32_t c; - // int off=d*SIGNAL_OFFSET; - c=bus_r(EXT_SIGNAL_REG); - - - - if (d>=0 && d<4) { - signals[d]=mode; -#ifdef VERBOSE - printf("settings signal variable number %d to value %04x\n", d, signals[d]); -#endif - - // if output signal, set it! - - switch (mode) { - case GATE_IN_ACTIVE_HIGH: - case GATE_IN_ACTIVE_LOW: - if (timingMode==GATE_FIX_NUMBER || timingMode==GATE_WITH_START_TRIGGER) - setFPGASignal(d,mode); - else - setFPGASignal(d,SIGNAL_OFF); - break; - case TRIGGER_IN_RISING_EDGE: - case TRIGGER_IN_FALLING_EDGE: - if (timingMode==TRIGGER_EXPOSURE || timingMode==GATE_WITH_START_TRIGGER) - setFPGASignal(d,mode); - else - setFPGASignal(d,SIGNAL_OFF); - break; - case RO_TRIGGER_IN_RISING_EDGE: - case RO_TRIGGER_IN_FALLING_EDGE: - if (timingMode==TRIGGER_READOUT) - setFPGASignal(d,mode); - else - setFPGASignal(d,SIGNAL_OFF); - break; - case MASTER_SLAVE_SYNCHRONIZATION: - setSynchronization(syncMode); - break; - default: - setFPGASignal(d,mode); - } - - setTiming(GET_EXTERNAL_COMMUNICATION_MODE); - } - - return getExtSignal(d); -} - -u_int32_t setFPGASignal(int d, enum externalSignalFlag mode) { - - - int modes[]={SIGNAL_OFF, GATE_IN_ACTIVE_HIGH, GATE_IN_ACTIVE_LOW,TRIGGER_IN_RISING_EDGE, TRIGGER_IN_FALLING_EDGE,RO_TRIGGER_IN_RISING_EDGE, RO_TRIGGER_IN_FALLING_EDGE, GATE_OUT_ACTIVE_HIGH, GATE_OUT_ACTIVE_LOW, TRIGGER_OUT_RISING_EDGE, TRIGGER_OUT_FALLING_EDGE, RO_TRIGGER_OUT_RISING_EDGE,RO_TRIGGER_OUT_FALLING_EDGE}; - - // int modes[]={EXT_SIG_OFF, EXT_GATE_IN_ACTIVEHIGH, EXT_GATE_IN_ACTIVELOW,EXT_TRIG_IN_RISING,EXT_TRIG_IN_FALLING,EXT_RO_TRIG_IN_RISING, EXT_RO_TRIG_IN_FALLING,EXT_GATE_OUT_ACTIVEHIGH, EXT_GATE_OUT_ACTIVELOW, EXT_TRIG_OUT_RISING, EXT_TRIG_OUT_FALLING, EXT_RO_TRIG_OUT_RISING, EXT_RO_TRIG_OUT_FALLING}; - - u_int32_t c; - int off=d*SIGNAL_OFFSET; - c=bus_r(EXT_SIGNAL_REG); - - - if (mode<=RO_TRIGGER_OUT_FALLING_EDGE && mode>=0) { -#ifdef VERBOSE - printf("writing signal register number %d mode %04x\n",d, modes[mode]); -#endif - bus_w(EXT_SIGNAL_REG,((modes[mode])<>off); */ - -/* if (mode=0 && d<4) { -#ifdef VERBOSE - printf("gettings signal variable number %d value %04x\n", d, signals[d]); -#endif - return signals[d]; - } else - return -1; - -} - - -int getFPGASignal(int d) { - - int modes[]={SIGNAL_OFF, GATE_IN_ACTIVE_HIGH, GATE_IN_ACTIVE_LOW,TRIGGER_IN_RISING_EDGE, TRIGGER_IN_FALLING_EDGE,RO_TRIGGER_IN_RISING_EDGE, RO_TRIGGER_IN_FALLING_EDGE, GATE_OUT_ACTIVE_HIGH, GATE_OUT_ACTIVE_LOW, TRIGGER_OUT_RISING_EDGE, TRIGGER_OUT_FALLING_EDGE, RO_TRIGGER_OUT_RISING_EDGE,RO_TRIGGER_OUT_FALLING_EDGE}; - - int off=d*SIGNAL_OFFSET; - int mode=((bus_r(EXT_SIGNAL_REG)&(SIGNAL_MASK<>off); - - if (mode<=RO_TRIGGER_OUT_FALLING_EDGE) { - if (modes[mode]!=SIGNAL_OFF && signals[d]!=MASTER_SLAVE_SYNCHRONIZATION) - signals[d]=modes[mode]; -#ifdef VERBOSE - printf("gettings signal register number %d value %04x\n", d, modes[mode]); -#endif - return modes[mode]; - } else - return -1; - -} - - -/* -enum externalCommunicationMode{ - GET_EXTERNAL_COMMUNICATION_MODE, - AUTO, - TRIGGER_EXPOSURE_SERIES, - TRIGGER_EXPOSURE_BURST, - TRIGGER_READOUT, - TRIGGER_COINCIDENCE_WITH_INTERNAL_ENABLE, - GATE_FIX_NUMBER, - GATE_FIX_DURATION, - GATE_WITH_START_TRIGGER, - GATE_COINCIDENCE_WITH_INTERNAL_ENABLE -}; -*/ - - -int setTiming(int ti) { - - - int ret=GET_EXTERNAL_COMMUNICATION_MODE; - - int g=-1, t=-1, rot=-1; - - int i; - printf("*********************************Setting timing mode %d!\n", ti); - switch (ti) { - case AUTO_TIMING: - timingMode=ti; - // disable all gates/triggers in except if used for master/slave synchronization - for (i=0; i<4; i++) { - if (getFPGASignal(i)>0 && getFPGASignal(i)=0 && t>=0 && rot<0) { - ret=GATE_WITH_START_TRIGGER; - } else if (g<0 && t>=0 && rot<0) { - ret=TRIGGER_EXPOSURE; - } else if (g>=0 && t<0 && rot<0) { - ret=GATE_FIX_NUMBER; - } else if (g<0 && t<0 && rot>0) { - ret=TRIGGER_READOUT; - } else if (g<0 && t<0 && rot<0) { - ret=AUTO_TIMING; - } - - // timingMode=ret; - - return ret; - -} - - - - -int setConfigurationRegister(int d) { -#ifdef VERBOSE - printf("Setting configuration register to %x",d); -#endif - if (d>=0) { - bus_w(CONFIG_REG,d); - } -#ifdef VERBOSE - printf("configuration register is %x", bus_r(CONFIG_REG)); -#endif - return bus_r(CONFIG_REG); -} - -int setToT(int d) { - // int ret=0; - int reg; -#ifdef VERBOSE - printf("Setting ToT to %d\n",d); -#endif - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Before: ToT is %x\n", reg); -#endif - if (d>0) { - bus_w(CONFIG_REG,reg|TOT_ENABLE_BIT); - } else if (d==0) { - bus_w(CONFIG_REG,reg&(~TOT_ENABLE_BIT)); - } - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("ToT is %x\n", reg); -#endif - if (reg&TOT_ENABLE_BIT) - return 1; - else - return 0; -} - -int setContinousReadOut(int d) { - // int ret=0; - int reg; -#ifdef VERBOSE - printf("Setting Continous readout to %d\n",d); -#endif - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Before: Continous readout is %x\n", reg); -#endif - if (d>0) { - bus_w(CONFIG_REG,reg|CONT_RO_ENABLE_BIT); - } else if (d==0) { - bus_w(CONFIG_REG,reg&(~CONT_RO_ENABLE_BIT)); - } - reg=bus_r(CONFIG_REG); -#ifdef VERBOSE - printf("Continous readout is %x\n", reg); -#endif - if (reg&CONT_RO_ENABLE_BIT) - return 1; - else - return 0; -} - - -u_int64_t getMcsNumber() { - - FILE *fp=NULL; - u_int64_t res; - char line[150]; - int a[6]; - - int n=0, i; - //u_int64_t a0,a1,a2,a3,a4,a5,n=0; - fp=fopen("/etc/conf.d/mac","r"); - if (fp==NULL) { - printf("could not ope MAC file\n");; - return -1; - } - while (fgets(line,150,fp)) { - //MAC="00:40:8C:CD:00:00" - printf(line); - if (strstr(line,"MAC=")) - n=sscanf(line,"MAC=\"%x:%x:%x:%x:%x:%x\"",a+5,a+4,a+3,a+2,a+1,a); - } - fclose(fp); - if (n!=6){ - printf("could not scan MAC address\n");; - return -1; - } - res=0; - for (i=0; i=(FPGA_VERSION_VAL&0x00ffffff)) { - printf("FPGA version ok!! %06x\n",val); - } else { - printf("FPGA version too old! %06x\n",val); - return FAIL; - } - //dummy register - val=0xF0F0F0F0; - bus_w(DUMMY_REG, val); - val=bus_r(DUMMY_REG); - if (val==0xF0F0F0F0) { - printf("FPGA dummy register ok!! %x\n",val); - } else { - printf("FPGA dummy register wrong!! %x instead of 0xF0F0F0F0 \n",val); - result=FAIL; - // return FAIL; - } - //dummy register - val=0x0F0F0F0F; - bus_w(DUMMY_REG, val); - val=bus_r(DUMMY_REG); - if (val==0x0F0F0F0F) { - printf("FPGA dummy register ok!! %x\n",val); - } else { - printf("FPGA dummy register wrong!! %x instead of 0x0F0F0F0F \n",val); - result=FAIL; - // return FAIL; - } - // } - return result; -} - - -// for fpga test -u_int32_t testRAM(void) { - int result=OK; - int i=0; - allocateRAM(); - // while(i<100000) { - memcpy(ram_values, values, dataBytes); - printf ("%d: copied fifo %x to memory %x size %d\n",i++, values, ram_values, dataBytes); - // } - return result; -} - -int getNModBoard() { - int nmodboard; - u_int32_t val; - val=bus_r(FPGA_VERSION_REG)&0xff000000; - - // printf("version register %08x\n",val); - nmodboard=val >> 24; - #ifdef VERY_VERBOSE - printf("The board hosts %d modules\n",nmodboard); - #endif - nModBoard=nmodboard; - //getNModBoard()=nmodboard; - return nmodboard; -} - -int setNMod(int n) { - - // int fifo; - // int ifsta, ifsto, ifste; - int imod; - int rval; - int reg; - int nf=0; - int shiftfifo=SHIFTFIFO; - int ntot=getNModBoard(); - if (getProbes()==0) { - switch (dynamicRange) { - case 16: - shiftfifo=SHIFTFIFO-1; - break; - case 8: - shiftfifo=SHIFTFIFO-2; - break; - case 4: - shiftfifo=SHIFTFIFO-3; - break; - case 1: - shiftfifo=SHIFTFIFO-5; - break; - default: - shiftfifo=SHIFTFIFO; - } - } else - shiftfifo=SHIFTFIFO; - - - //#ifdef VERBOSE - printf("SetNMod called arg %d -- dr %d shiftfifo %d\n",n,dynamicRange,shiftfifo); - //#endif - if (n>=0 && n<=ntot) { - nModX=n; - - /*d isable the fifos relative to the unused modules */ - for (ififo=0; ififo>FIFO_NM_OFF, (reg&FIFO_NC_MASK)>>FIFO_NC_OFF, FIFO_COUNTR_REG_OFF+(ififo<>FIFO_NM_OFF, (reg&FIFO_NC_MASK)>>FIFO_NC_OFF, FIFO_COUNTR_REG_OFF+(ififo<> 32; - vMSB=v64&(0xffffffff); - bus_w(aMSB,vMSB); - } - return get64BitReg(aLSB, aMSB); - -} - -int64_t get64BitReg(int aLSB, int aMSB){ - int64_t v64; - u_int32_t vLSB,vMSB; - vMSB=bus_r(aMSB); - vLSB=bus_r(aLSB); - v64=vMSB; - v64=(v64<<32) | vLSB; -#ifdef VERBOSE - printf("MSB %08x LSB %08x, %016llx\n", vMSB, vLSB, v64); -#endif - - return v64; -} - -int64_t setFrames(int64_t value){ - return set64BitReg(value, SET_FRAMES_LSB_REG, SET_FRAMES_MSB_REG); -} - -int64_t getFrames(){ - return get64BitReg(GET_FRAMES_LSB_REG, GET_FRAMES_MSB_REG); -} - -int64_t setExposureTime(int64_t value){ - /* time is in ns */ - if (value!=-1) - value*=(1E-9*CLK_FREQ); - - if (masterMode==IS_SLAVE && syncMode==MASTER_GATES) - setGates(1); - - return set64BitReg(value,SET_EXPTIME_LSB_REG, SET_EXPTIME_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t getExposureTime(){ - return get64BitReg(GET_EXPTIME_LSB_REG, GET_EXPTIME_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t setGates(int64_t value){ - return set64BitReg(value, SET_GATES_LSB_REG, SET_GATES_MSB_REG); -} - -int64_t getGates(){ - return get64BitReg(GET_GATES_LSB_REG, GET_GATES_MSB_REG); -} - -int64_t setPeriod(int64_t value){ - /* time is in ns */ - if (value!=-1) { - value*=(1E-9*CLK_FREQ); - } - - - - return set64BitReg(value,SET_PERIOD_LSB_REG, SET_PERIOD_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t getPeriod(){ - return get64BitReg(GET_PERIOD_LSB_REG, GET_PERIOD_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t setDelay(int64_t value){ - /* time is in ns */ - if (value!=-1) { - value*=(1E-9*CLK_FREQ); - } - return set64BitReg(value,SET_DELAY_LSB_REG, SET_DELAY_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t getDelay(){ - return get64BitReg(GET_DELAY_LSB_REG, GET_DELAY_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t setTrains(int64_t value){ - return set64BitReg(value, SET_TRAINS_LSB_REG, SET_TRAINS_MSB_REG); -} - -int64_t getTrains(){ - return get64BitReg(GET_TRAINS_LSB_REG, GET_TRAINS_MSB_REG); -} - - -int64_t setProbes(int64_t value){ - int ow; - int nm=setNMod(-1); - switch (getDynamicRange()) { - case 32: - ow=1; - break; - case 16: - ow=2; - break; - case 8: - ow=3; - break; - case 4: - ow=4; - break; - case 1: - ow=5; - break; - default: - ow=1; - } - if (value>=0) { - setCSregister(ALLMOD); - initChipWithProbes(0, ow,value, ALLMOD); - putout("0000000000000000",ALLMOD); - setNMod(nm); - getDynamicRange(); // needed to change dataBytes - } - return getProbes(); -} - - -int64_t setProgress() { - - //????? eventually call after setting the registers - return 100; -} - - -int64_t getProgress() { - - - //should be done in firmware!!!! - return 0; - -} - - -int64_t getActualTime(){ - return get64BitReg(GET_ACTUAL_TIME_LSB_REG, GET_ACTUAL_TIME_MSB_REG)/(1E-9*CLK_FREQ); -} - -int64_t getMeasurementTime(){ - int64_t v=get64BitReg(GET_MEASUREMENT_TIME_LSB_REG, GET_MEASUREMENT_TIME_MSB_REG); - int64_t mask=0x8000000000000000; - - if (v & mask ) { -#ifdef VERBOSE - printf("no measurement time left\n"); -#endif - return -1E+9; - } else - return v/(1E-9*CLK_FREQ); -} - - - -int64_t getProbes(){ - u_int32_t shiftin=bus_r(GET_SHIFT_IN_REG); - u_int32_t np=(shiftin >>PROBES_OFF) & PROBES_MASK; -#ifdef VERYVERBOSE - printf("%08x ",shiftin); - printf("probes==%01x\n",np); -#endif - - return np; - -} - - -int setDACRegister(int idac, int val, int imod) { - u_int32_t addr, reg, mask; - int off; -#ifdef VERBOSE - printf("Settings dac %d module %d register to %d\n",idac,imod,val); -#endif - if ((idac%2)==0) { - addr=MOD_DACS1_REG; - } else { - addr=MOD_DACS2_REG; - } - off=(idac%3)*10; - mask=~((0x3ff)<=0 && val>off)&0x3ff; -#ifdef VERBOSE - printf("Dac %d module %d register is %d\n",idac,imod,val); -#endif - return val; -} - - - - -u_int32_t runBusy(void) { - return bus_r(STATUS_REG)&RUN_BUSY_BIT; -} - -u_int32_t dataPresent(void) { - return bus_r(LOOK_AT_ME_REG); -} - -u_int32_t runState(void) { - int s=bus_r(STATUS_REG); -#ifdef SHAREDMEMORY - if (s&RUN_BUSY_BIT) - write_status_sm("Running"); - else - write_status_sm("Stopped"); - - write_istatus_sm(s); - -#endif -#ifdef VERBOSE - printf("status %08x\n",s); -#endif - return s; -} - - -// State Machine - -u_int32_t startStateMachine(){ -#ifdef VERBOSE - printf("Starting State Machine\n"); -#endif - fifoReset(); - now_ptr=(char*)ram_values; -#ifdef SHAREDMEMORY - write_stop_sm(0); - write_status_sm("Started"); -#endif -#ifdef MCB_FUNCS - setCSregister(ALLMOD); - clearSSregister(ALLMOD); -#endif - putout("0000000000000000",ALLMOD); - bus_w(CONTROL_REG, START_ACQ_BIT | START_EXPOSURE_BIT); - return OK; -} - - - - -u_int32_t stopStateMachine(){ - -#ifdef VERBOSE - printf("Stopping State Machine\n"); -#endif -#ifdef SHAREDMEMORY - write_stop_sm(1); - write_status_sm("Stopped"); -#endif - bus_w(CONTROL_REG, STOP_ACQ_BIT); - usleep(500); - if (!runBusy()) - return OK; - else - return FAIL; -} - - -u_int32_t startReadOut(){ - u_int32_t status; -#ifdef VERBOSE - printf("Starting State Machine Readout\n"); -#endif - status=bus_r(STATUS_REG)&RUN_BUSY_BIT; -#ifdef DEBUG - printf("State machine status is %08x\n",bus_r(STATUS_REG)); -#endif - bus_w(CONTROL_REG, START_ACQ_BIT |START_READOUT_BIT); // start readout - return OK; -} - - -// fifo routines - -u_int32_t fifoReset(void) { -#ifdef DEBUG - printf("resetting fifo\n"); -#endif - bus_w(FIFO_CNTRL_REG_OFF+(ALLFIFO<128) - printf("chip %d ch %d %d\n",ichip/128, ichip%128, (fifoReadCounter(ichip/128)&FIFO_COUNTER_MASK)); -#endif - } - //#endif - */ - - - -#ifdef VERYVERBOSE - printf("Copying to ptr %x %d\n",now_ptr, dataBytes); - printf("after readout %08x %08x\n", runState(), bus_r(LOOK_AT_ME_REG)); - for (ichip=0; ichip0) { - now_ptr+=dataBytes; - } - return ram_values; -} - - - -u_int32_t* decode_data(int *datain) -{ - u_int32_t *dataout; - // const char one=1; - const int bytesize=8; - char *ptr=(char*)datain; - //int nbits=dynamicRange; - int ipos=0, ichan=0;; - //int nch, boff=0; - int ibyte;//, ibit; - char iptr; - -#ifdef VERBOSE - printf("Decoding data for DR %d\n",dynamicRange); -#endif - dataout=malloc(nChans*nChips*nModX*4); - ichan=0; - switch (dynamicRange) { - case 1: - for (ibyte=0; ibyte>(ipos))&0x1; - ichan++; - } - } - break; - case 4: - for (ibyte=0; ibyte>(ipos*4))&0xf; - ichan++; - } - } - break; - case 8: - for (ichan=0; ichan0) { - nm=setNMod(-1); - if (dr==1) { - dynamicRange=1; - ow=5; - } else if (dr<=4) { - dynamicRange=4; - ow=4; - } else if (dr<=8) { - dynamicRange=8; - ow=3; - } else if (dr<=16) { - dynamicRange=16; - ow=2; - } else { - dynamicRange=32; - ow=0; //or 1? - } - setCSregister(ALLMOD); - initChipWithProbes(0, ow,np, ALLMOD); - putout("0000000000000000",ALLMOD); - setNMod(nm); - } - - - return getDynamicRange(); -} - - - - - - -int getDynamicRange() { - int dr; - u_int32_t shiftin=bus_r(GET_SHIFT_IN_REG); - u_int32_t outmux=(shiftin >> OUTMUX_OFF) & OUTMUX_MASK; - u_int32_t probes=(shiftin >> PROBES_OFF) & PROBES_MASK; -#ifdef VERYVERBOSE - printf("%08x ",shiftin); - printf("outmux=%02x probes=%d\n",outmux,probes); -#endif - - switch (outmux) { - case 2: - dr=16; - break; - case 4: - dr=8; - break; - case 8: - dr=4; - break; - case 16: - dr=1; - break; - default: - dr=32; - } - dynamicRange=dr; - if (probes==0) { - dataBytes=nModX*nModY*NCHIP*NCHAN*dynamicRange/8; - } else { - dataBytes=nModX*nModY*NCHIP*NCHAN*4;/// - } -#ifdef VERBOSE - printf("Number of data bytes %d - probes %d dr %d\n", dataBytes, probes, dr); -#endif - if (allocateRAM()==OK) { - ; - } else - printf("ram not allocated\n"); - - return dynamicRange; - -} - -int testBus() { - u_int32_t j; - u_int64_t i, n, nt; - //char cmd[100]; - u_int32_t val=0x0; - int ifail=OK; - // printf("%s\n",cmd); - // system(cmd); - i=0; - - n=1000000; - nt=n/100; - printf("testing bus %d times\n",n); - while (i0) - storeInRAM=1; - else - storeInRAM=0; - return allocateRAM(); -} - - -int allocateRAM() { - size_t size; - u_int32_t nt, nf; - nt=setTrains(-1); - nf=setFrames(-1); - if (nt==0) nt=1; - if (nf==0) nf=1; - // ret=clearRAM(); - if (storeInRAM) { - size=dataBytes*nf*nt; - if (size -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -int mapCSP0(void); -u_int32_t bus_w(u_int32_t offset, u_int32_t data); -u_int32_t bus_r(u_int32_t offset); - - -u_int32_t putout(char *s, int modnum); -u_int32_t readin(int modnum); -u_int32_t setClockDivider(int d); -u_int32_t getClockDivider(); -u_int32_t setSetLength(int d); -u_int32_t getSetLength(); -u_int32_t setWaitStates(int d); -u_int32_t getWaitStates(); -u_int32_t setTotClockDivider(int d); -u_int32_t getTotClockDivider(); -u_int32_t setTotDutyCycle(int d); -u_int32_t getTotDutyCycle(); - -u_int32_t setExtSignal(int d, enum externalSignalFlag mode); -int getExtSignal(int d); - -u_int32_t setFPGASignal(int d, enum externalSignalFlag mode); -int getFPGASignal(int d); - -int setTiming(int t); - - - - - - -int setConfigurationRegister(int d); -int setToT(int d); -int setContinousReadOut(int d); - -int setDACRegister(int idac, int val, int imod); - - -u_int64_t getMcsNumber(); -u_int32_t getMcsVersion(); -u_int32_t testFifos(void); -u_int32_t testFpga(void); -u_int32_t testRAM(void); -int testBus(void); -int64_t set64BitReg(int64_t value, int aLSB, int aMSB); -int64_t get64BitReg(int aLSB, int aMSB); - -int64_t setFrames(int64_t value); -int64_t getFrames(); - -int64_t setExposureTime(int64_t value); -int64_t getExposureTime(); - -int64_t setGates(int64_t value); -int64_t getGates(); - -int64_t setDelay(int64_t value); -int64_t getDelay(); - -int64_t setPeriod(int64_t value); -int64_t getPeriod(); - -int64_t setTrains(int64_t value); -int64_t getTrains(); - -int64_t setProbes(int64_t value); -int64_t getProbes(); - -int64_t getProgress(); -int64_t setProgress(); - -int64_t getActualTime(); -int64_t getMeasurementTime(); - -u_int32_t runBusy(void); -u_int32_t runState(void); -u_int32_t dataPresent(void); - - -u_int32_t startStateMachine(); -u_int32_t stopStateMachine(); -u_int32_t startReadOut(); -u_int32_t fifoReset(void); -u_int32_t fifoReadCounter(int fifonum); -u_int32_t fifoReadStatus(); - - -u_int32_t fifo_full(void); - - - -u_int32_t* fifo_read_event(); -u_int32_t* decode_data(int* datain); -//u_int32_t move_data(u_int64_t* datain, u_int64_t* dataout); -int setDynamicRange(int dr); -int getDynamicRange(); -int getNModBoard(); -int setNMod(int n); -int setStoreInRAM(int b); -int allocateRAM(); -int clearRAM(); - - -int setMaster(int f); -int setSynchronization(int s); - - -/* - -u_int32_t setNBits(u_int32_t); -u_int32_t getNBits(); -*/ - -/* -//move to mcb_funcs? - -int readOutChan(int *val); -u_int32_t getModuleNumber(int modnum); -int testShiftIn(int imod); -int testShiftOut(int imod); -int testShiftStSel(int imod); -int testDataInOut(int num, int imod); -int testExtPulse(int imod); -int testExtPulseMux(int imod, int ow); -int testDataInOutMux(int imod, int ow, int num); -int testOutMux(int imod); -int testFpgaMux(int imod); -int calibration_sensor(int num, int *values, int *dacs) ; -int calibration_chip(int num, int *values, int *dacs); -*/ - - -#endif diff --git a/slsDetectorSoftware/mythenDetectorServer/gitInfo.txt b/slsDetectorSoftware/mythenDetectorServer/gitInfo.txt deleted file mode 100644 index ac5d755fc..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/gitInfo.txt +++ /dev/null @@ -1,9 +0,0 @@ -Path: slsDetectorsPackage/slsDetectorSoftware/mythenDetectorServer -URL: -Repository Root: -Repsitory UUID: -Revision: 0 -Branch: -Last Changed Author: _ -Last Changed Rev: 0 -Last Changed Date: 2018-01-30 10:42:45.000000000 +0100 ./Makefile diff --git a/slsDetectorSoftware/mythenDetectorServer/gitInfoMythen.h b/slsDetectorSoftware/mythenDetectorServer/gitInfoMythen.h deleted file mode 100644 index 5fefed3fd..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/gitInfoMythen.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "URL:" -#define GITREPUUID "UUID:" -#define GITAUTH "_" -#define GITREV 0x0 -#define GITDATE 0x20180130 -#define GITBRANCH "Branch:" diff --git a/slsDetectorSoftware/mythenDetectorServer/gitInfoMythenTmp.h b/slsDetectorSoftware/mythenDetectorServer/gitInfoMythenTmp.h deleted file mode 100644 index dfd9bb246..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/gitInfoMythenTmp.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "" -#define GITREPUUID "" -#define GITAUTH "" -#define GITREV "" -#define GITDATE "" -#define GITBRANCH "" diff --git a/slsDetectorSoftware/mythenDetectorServer/mcb_funcs.c b/slsDetectorSoftware/mythenDetectorServer/mcb_funcs.c deleted file mode 100755 index 70a995cd0..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/mcb_funcs.c +++ /dev/null @@ -1,2716 +0,0 @@ -#ifdef MCB_FUNCS - -#include -#include -#include -#include -#include -#include "registers.h" - -#ifndef PICASSOD -#include "server_defs.h" -#else -#include "picasso_defs.h" -#endif -#include "firmware_funcs.h" -#include "mcb_funcs.h" - -/* global variables */ -#undef DEBUG -#undef DEBUGOUT - -extern int nModX; -extern int nModBoard; -extern int dataBytes; -extern int dynamicRange; -const int nChans=NCHAN; -const int nChips=NCHIP; -const int nDacs=NDAC; -const int nAdcs=NADC; -const enum detectorType myDetectorType=MYTHEN; -enum detectorSettings thisSettings; - -int sChan, sChip, sMod, sDac, sAdc; -const int allSelected=-2; -const int noneSelected=-1; - - -sls_detector_module *detectorModules=NULL; -int *detectorChips=NULL; -int *detectorChans=NULL; -dacs_t *detectorDacs=NULL; -dacs_t *detectorAdcs=NULL; -//int numberOfProbes; - - - - - - - - -int initDetector() { - int imod; - // sls_detector_module *myModule; - int n=getNModBoard(); - nModX=n; - //#ifdef VERBOSE - printf("Board is for %d modules\n",n); - //#endif - detectorModules=malloc(n*sizeof(sls_detector_module)); - detectorChips=malloc(n*NCHIP*sizeof(int)); - - detectorChans=malloc(n*NCHIP*NCHAN*sizeof(int)); - detectorDacs=malloc(n*NDAC*sizeof(dacs_t)); - detectorAdcs=malloc(n*NADC*sizeof(dacs_t)); - //#ifdef VERBOSE - printf("modules from 0x%x to 0x%x\n",detectorModules, detectorModules+n); - printf("chips from 0x%x to 0x%x\n",detectorChips, detectorChips+n*NCHIP); - printf("chans from 0x%x to 0x%x\n",detectorChans, detectorChans+n*NCHIP*NCHAN); - printf("dacs from 0x%x to 0x%x\n",detectorDacs, detectorDacs+n*NDAC); - printf("adcs from 0x%x to 0x%x\n",detectorAdcs, detectorAdcs+n*NADC); - //#endif - for (imod=0; imoddacs=detectorDacs+imod*NDAC; - (detectorModules+imod)->adcs=detectorAdcs+imod*NADC; - (detectorModules+imod)->chipregs=detectorChips+imod*NCHIP; - (detectorModules+imod)->chanregs=detectorChans+imod*NCHIP*NCHAN; - (detectorModules+imod)->ndac=NDAC; - (detectorModules+imod)->nadc=NADC; - (detectorModules+imod)->nchip=NCHIP; - (detectorModules+imod)->nchan=NCHIP*NCHAN; - (detectorModules+imod)->module=imod; - (detectorModules+imod)->gain=0; - (detectorModules+imod)->offset=0; - (detectorModules+imod)->reg=0; - /* initialize registers, dacs, retrieve sn, adc values etc */ - } - printf("modules done\n"); - thisSettings=UNINITIALIZED; - sChan=noneSelected; - sChip=noneSelected; - sMod=noneSelected; - sDac=noneSelected; - sAdc=noneSelected; - setCSregister(ALLMOD); - setSSregister(ALLMOD); - counterClear(ALLMOD); - clearSSregister(ALLMOD); - putout("0000000000000000",ALLMOD); - - printf("dr\n"); - /* initialize dynamic range etc. */ - dynamicRange=getDynamicRange(); - printf("nmod\n"); - nModX=setNMod(-1); - printf("done\n"); - - - - - - //dataBytes=nModX*NCHIP*NCHAN*4; - // dynamicRange=32; - // initChip(0, 0,ALLMOD); - //nModX=n; - // - // allocateRAM(); - - - - - return OK; -} - - - - -int copyChannel(sls_detector_channel *destChan, sls_detector_channel *srcChan) { - destChan->chan=srcChan->chan; - destChan->chip=srcChan->chip; - destChan->module=srcChan->module; - destChan->reg=srcChan->reg; - return OK; -} - - -int copyChip(sls_detector_chip *destChip, sls_detector_chip *srcChip) { - - int ichan; - int ret=OK; - if ((srcChip->nchan)>(destChip->nchan)) { - printf("Number of channels of source is larger than number of channels of destination\n"); - return FAIL; - } - - destChip->nchan=srcChip->nchan; - destChip->reg=srcChip->reg; - destChip->chip=srcChip->chip; - destChip->module=srcChip->module; - for (ichan=0; ichan<(srcChip->nchan); ichan++) { - *((destChip->chanregs)+ichan)=*((srcChip->chanregs)+ichan); - } - return ret; -} - - -int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod) { - - int ichip, idac, ichan, iadc; - - int ret=OK; - -#ifdef VERBOSE - printf("Copying module %x to module %x\n",srcMod,destMod); -#endif - - if (srcMod->module>=0) { -#ifdef VERBOSE - printf("Copying module number %d to module number %d\n",srcMod->module,destMod->module); -#endif - destMod->module=srcMod->module; - } - if (srcMod->serialnumber>=0){ -/* #ifdef VERBOSE */ -/* printf("Copying module serial number %x to module serial number %x\n",srcMod->serialnumber,destMod->serialnumber); */ -/* #endif */ - destMod->serialnumber=srcMod->serialnumber; - } - if ((srcMod->nchip)>(destMod->nchip)) { - printf("Number of chip of source is larger than number of chips of destination\n"); - return FAIL; - } - if ((srcMod->nchan)>(destMod->nchan)) { - printf("Number of channels of source is larger than number of channels of destination\n"); - return FAIL; - } - if ((srcMod->ndac)>(destMod->ndac)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - if ((srcMod->nadc)>(destMod->nadc)) { - printf("Number of dacs of source is larger than number of dacs of destination\n"); - return FAIL; - } - -#ifdef VERBOSE - printf("DACs: src %d, dest %d\n",srcMod->ndac,destMod->ndac); - printf("ADCs: src %d, dest %d\n",srcMod->nadc,destMod->nadc); - printf("Chips: src %d, dest %d\n",srcMod->nchip,destMod->nchip); - printf("Chans: src %d, dest %d\n",srcMod->nchan,destMod->nchan); - -#endif - - - - destMod->ndac=srcMod->ndac; - destMod->nadc=srcMod->nadc; - destMod->nchip=srcMod->nchip; - destMod->nchan=srcMod->nchan; - if (srcMod->reg>=0) - destMod->reg=srcMod->reg; -#ifdef VERBOSE - printf("Copying register %x (%x)\n",destMod->reg,srcMod->reg ); -#endif - if (srcMod->gain>=0) - destMod->gain=srcMod->gain; - if (srcMod->offset>=0) - destMod->offset=srcMod->offset; - - // printf("copying gain and offset %f %f to %f %f\n",srcMod->gain,srcMod->offset,destMod->gain,destMod->offset); - - for (ichip=0; ichip<(srcMod->nchip); ichip++) { - if (*((srcMod->chipregs)+ichip)>=0) - *((destMod->chipregs)+ichip)=*((srcMod->chipregs)+ichip); - } - for (ichan=0; ichan<(srcMod->nchan); ichan++) { - if (*((srcMod->chanregs)+ichan)>=0) - *((destMod->chanregs)+ichan)=*((srcMod->chanregs)+ichan); - } - for (idac=0; idac<(srcMod->ndac); idac++) { - if (*((srcMod->dacs)+idac)>=0) - *((destMod->dacs)+idac)=*((srcMod->dacs)+idac); - } - for (iadc=0; iadc<(srcMod->nadc); iadc++) { - if (*((srcMod->adcs)+iadc)>=0) - *((destMod->adcs)+iadc)=*((srcMod->adcs)+iadc); - } - return ret; -} - - - -/* Register commands */ - - -int clearDACSregister(int imod) { - putout("0000000001000000",imod); - putout("0000000101000000",imod); - putout("0000000101000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Clearing DAC shiftregister\n"); -#endif - /* - sChan=noneSelected; - sChip=noneSelected; - sMod=noneSelected; - sDac=noneSelected; - sAdc=noneSelected; - */ - sDac=0; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return OK; -} - -int nextDAC(int imod) { - putout("0000000001000000",imod); - putout("0000000001001000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Next DAC\n"); -#endif - sDac++; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return OK; -} - - -int clearCSregister(int imod) { - - putout("0000000001000000",imod); - putout("0000100001000000",imod); - putout("0000100001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Clearing CS shiftregister\n"); -#endif - /* - sChan=noneSelected; - sMod=noneSelected; - sDac=noneSelected; - sAdc=noneSelected; - */ - sChip=noneSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - //putout("0000000000000000",imod); - return 0; -} - -int setCSregister(int imod){ - - putout("0000000001000000",imod); - putout("0001000001000000",imod); - putout("0001000001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Setting CS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChip=allSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int nextChip(int imod){ - - putout("0000000001000000",imod); - putout("0010000001000000",imod); - putout("0000000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "Next Chip\n"); -#endif - sChip++; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int firstChip(int imod){ - - putout("0100000001000000",imod); - putout("0110000001000000",imod); - putout("0100000001000000",imod); -#ifdef DEBUG - fprintf(stdout, "First Chip\n"); -#endif - sChip=0; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int clearSSregister(int imod){ - int i; - putout("0000011000000000",imod); - for (i=0; i<10; i++) - putout("0000111000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"Clearing SS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChan=noneSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int setSSregister(int imod){ - int i; - putout("0000011000000000",imod); - for (i=0; i<10; i++) - putout("0001011000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"Setting SS shiftregister\n"); -#endif - putout("0000000000000000",imod); - sChan=allSelected; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int nextStrip(int imod){ - putout("0000011000000000",imod); - putout("0010011000000000",imod); - putout("0000011000000000",imod); -#ifdef DEBUG - fprintf(stdout,"|-"); -#endif - sChan++; - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - return 0; -} - -int selChannel(const int strip,int imod) { - int istrip; - clearSSregister(imod); - nextStrip(imod); - for (istrip=0; istrip=0 && imoddacs[idac]=v; - detectorDacs[ireg+NDAC*imod]=v; - //#ifdef VERBOSE -#ifdef VERBOSE - printf("module=%d index=%d, val=%d addr=%x\n",imod, idac, v, detectorDacs+idac+NDAC*imod); -#endif - - setDACRegister(ireg,v,imod); - - /* - - reg=bus_r(MOD_DACS1_REG+(imod<dacs[idac]=v; - - - - reg=bus_r(MOD_DACS1_REG+(imod<=0) { - initDAC(cs, addr,val, imod); - /*#ifdef VERBOSE - iv=detectorDacs[ind+imod*NDAC]; - printf("module=%d index=%d, cs=%d, addr=%d, dacu=%d, set to %d",imod, ind,cs,addr,val,iv); -#endif - */ - //return val; - } - if (imod>=0 && imodgain,(detectorModules+imod)->offset); -#endif - if ((detectorModules+imod)->gain>0) - myg=(detectorModules+imod)->gain; - else { - if (thisSettings>=0 && thisSettings<3) - myg=g[thisSettings]; - // else - //myg=-1; - } - - if ((detectorModules+imod)->offset>0) - myo=(detectorModules+imod)->offset; - else { - if (thisSettings>=0 && thisSettings<3) - myo=o[thisSettings]; - // else - //myo=-1; - } - - if (myg>0 && myo>0) { - //ethr=(myo-detectorDacs[VTHRESH+imod*NDAC])*1000/myg; - - ethr=(myo-setDACRegister(VTHRESH,-1,imod))*1000/myg; - // else - // ethr=-1; - - } -#ifdef VERBOSE -#ifdef DACS_INT - printf("module=%d gain=%f, offset=%f, dacu=%d\n",imod, myg, myo,setDACRegister(VTHRESH,-1,imod)); -#else - printf("module=%d gain=%f, offset=%f, dacu=%f\n",imod, myg, myo,setDACRegister(VTHRESH,-1,imod)); -#endif - printf("Threshold energy of module %d is %d eV\n", imod, ethr); -#endif - - if (imod==0) - ret=ethr; - else { - if (ethr>(ret+100) || ethr<(ret-100)) - return FAIL; - } - } - } - return ret; -} - -int setThresholdEnergy(int ethr) { - float g[3]=DEFAULTGAIN; - float o[3]=DEFAULTOFFSET; - float myg=-1, myo=-1; - int dacu; - int imod; - int ret=ethr; - - setSettings(GET_SETTINGS); - if (thisSettings>=0 || thisSettings<3){ - myg=g[thisSettings]; - myo=o[thisSettings]; - } - for (imod=0; imodgain>0) - myg=(detectorModules+imod)->gain; - else - if (thisSettings>=0 && thisSettings<3) - myg=g[thisSettings]; - else - myg=-1; - if ((detectorModules+imod)->offset>0) - myo=(detectorModules+imod)->offset; - else - if (thisSettings>=0 && thisSettings<3) - myo=o[thisSettings]; - else - myo=-1; - } else { - if (thisSettings>=0 && thisSettings<3) - myo=o[thisSettings]; - else - myo=-1; - if (thisSettings>=0 && thisSettings<3) - myg=g[thisSettings]; - else - myg=-1; - } - if (myg>0 && myo>0) { - dacu=myo-myg*((float)ethr)/1000.; -#ifdef VERBOSE - printf("module %d (%x): gain %f, off %f, energy %d eV, dac %d\n",imod,(detectorModules+imod),(detectorModules+imod)->gain,(detectorModules+imod)->offset, ethr,dacu); -#endif - } else { - dacu=ethr; -#ifdef VERBOSE - printf("could not set threshold energy for module %d, settings %d (offset is %f; gain is %f)\n",imod,thisSettings,myo,myg); -#endif - } - initDACbyIndexDACU(VTHRESH, dacu, imod); - } - return ret; -} - - - -dacs_t getDACbyIndexDACU(int ind, int imod) { - /* - if (detectorDacs) { - if (imodndac) - return (detectorDacs[ind+imod*NDAC]); - } - return FAIL; - */ - return setDACRegister(ind, -1, imod); -} - - - -int initDAC(int dac_cs, int dac_addr, int value, int imod) { - int i; -#ifdef VERBOSE - printf("Programming dac %d %d with value %d\n", dac_cs, dac_addr, value); -#endif - clearDACSregister(imod); - /*if (dac_cs>0) {*/ - for (i=0; i0) {*/ - for (i=0; i=0) { -#ifdef VERBOSE - fprintf(stdout, "voltage %d\n", *(v+i)); -#endif - program_one_dac(iaddr, *(v+i),imod); - } - nextDAC(imod); - } - } - clearDACSregister(imod); - for (ichip=0; ichip<3; ichip++) { - set_one_dac(imod); - nextDAC(imod); - } - - return 0; -} - - - - -int setSettings(int i) { - int imod, isett, is; - int rgpr[]=RGPRVALS; - int rgsh1[]=RGSH1VALS; - int rgsh2[]=RGSH2VALS; - int irgpr, irgsh1, irgsh2; - - int v[NDAC]; - int ind; - for (ind=0; ind>(NTRIMBITS))&1; - int ae=(reg>>(NTRIMBITS+1))&1; - int coe=(reg>>(NTRIMBITS+2))&1; - int ocoe=(reg>>(NTRIMBITS+3))&1; - int counts=(reg>>(NTRIMBITS+4)); -#ifdef VERBOSE - printf("Initializing channel %d chip %d module %d reg %x\n",myChan.chan,myChan.chip,myChan.module, reg); - printf("trim %d, cae %d, ae %d, coe %d, ocoe %d, counts %d\n",ft, cae, ae, coe, ocoe, counts); -#endif - - if (myChan.chip<0) - setCSregister(myChan.module); - else - selChip(myChan.chip,myChan.module); - - if (myChan.chan<0) - setSSregister(myChan.module); - else - selChannel(myChan.chan,myChan.module); - - initChannel(ft,cae,ae, coe, ocoe, counts,myChan.module); - - setDynamicRange(dynamicRange); - - setCSregister(ALLMOD); - clearSSregister(ALLMOD); - putout("0000000000000000",ALLMOD); - - return myChan.reg; - -} - -int getChannelbyNumber(sls_detector_channel* myChan) { - int imod, ichip, ichan; - imod=myChan->module; - ichip=myChan->chip; - ichan=myChan->chan; - - if (detectorChans) { - if (imod=0) { - if (ichip<(detectorModules+imod)->nchip && ichan<(detectorModules+imod)->nchan/(detectorModules+imod)->nchip) - myChan->reg=detectorChans[imod*NCHAN*NCHIP+ichip*NCHAN+ichan]; - return OK; - } - } - return FAIL; - -} - -int getTrimbit(int imod, int ichip, int ichan) { - if (detectorChans) { - if (imod=0) - if (ichip<(detectorModules+imod)->nchip && ichan<(detectorModules+imod)->nchan/(detectorModules+imod)->nchip) - return (detectorChans[imod*NCHAN*NCHIP+ichip*NCHAN+ichan] & TRIM_DR); - } //else - return -1; - - -} - -int initChannel(int ft,int cae, int ae, int coe, int ocoe, int counts, int imod){ - - int ibit, bit, i, im, ichip, ichan; - int chanmi, chanma, chipmi, chipma, modmi, modma; - - - - sMod=imod; - // printf("initializing module %d\n",sMod); - if (imod==ALLMOD) { - sMod=allSelected; - - // printf("initializing all modules\n"); - } - - if (sChan==allSelected) { - // printf("initializing all channels ft=%d coe=%d\n",ft,coe); - chanmi=0; - chanma=NCHAN; - } else if (sChan==noneSelected || sChan>NCHAN || sChan<0) { - // printf("initializing no channels ft=%d coe=%d\n",ft,coe); - chanmi=0; - chanma=-1; - } else { - // printf("initializing channel %d ft=%d coe=%d\n",sChan, ft,coe); - chanmi=sChan; - chanma=sChan+1; - } - - if (sChip==allSelected) { - // printf("initializing all chips\n"); - chipmi=0; - chipma=NCHIP; - } else if (sChip==noneSelected || sChip>NCHIP || sChip<0) { - // printf("initializing no chips\n"); - chipmi=0; - chipma=-1; - } else { - // printf("initializing chip %d\n",sChip); - chipmi=sChip; - chipma=sChip+1; - } - - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - return 1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorChans) { - for (im=modmi; im63 || ft<0) { - fprintf(stdout,"Fine Threshold is %d while should be between 0 and 63!",ft); - return 1; - } - /*cal_enable*/ - if (cae) { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - } else { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - } - /*n_an_enable*/ - if (ae) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } else { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - putout("0100000000000000",imod); - } - /*trb5*/ - ibit=5; - bit=ft & (1<>1; - int nchan, ichan; - int ft, cae, ae, coe, ocoe, counts, chanreg; - - - - nchan=myChip.nchan; - if (ichip<0) - setCSregister(imod); - else - selChip(ichip,imod); - - clearSSregister(imod); - for (ichan=0; ichan>(NTRIMBITS+1))&1; - ae=(chanreg>>(NTRIMBITS+2))&1; - coe=((chanreg)>>(NTRIMBITS+3))&1; - ocoe=((chanreg)>>(NTRIMBITS+4))&1; - counts=((chanreg)>>(NTRIMBITS+5)); - nextStrip(imod); - initChannel(ft,cae,ae, coe, ocoe, counts,imod); - } - initChip(obe,ow,imod); - return myChip.reg; - -} - -int getChipbyNumber(sls_detector_chip* myChip){ - int imod, ichip; - imod=myChip->module; - ichip=myChip->chip; - - if (detectorChips) { - if (imodnchip) { - myChip->reg=detectorChips[ichip+imod*NCHIP]; - myChip->nchan=NCHAN; - myChip->chanregs=detectorChans+imod*NCHAN*NCHIP+ichip*NCHIP; - return OK; - } - } - return FAIL; - -} - - - -int initChip(int obe, int ow,int imod){ - int i; - int im, ichip; - int chipmi, chipma, modmi, modma; - /* switch (ow) { - case 0:; - case 1: - setDynamicRange(32); - break; - case 2: - setDynamicRange(16); - break; - case 3: - setDynamicRange(8); - break; - case 4: - setDynamicRange(4); - break; - case 5: - setDynamicRange(1); - break; - default: - setDynamicRange(32); - break; - } - */ - -#ifdef DEBUGOUT - printf("Initializing chip\n"); -#endif - putout("0000000000000000",imod); -#ifdef DEBUGOUT - printf("Output mode= %d\n", ow); -#endif - - /* clearing shift in register */ - for (i=0; i<10; i++) - putout("0000100000000000",imod); - putout("0000000000000000",imod); - - if (ow>0) { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - putout("0100000000000000",imod); - for (i=0; i<(OUTMUX_OFFSET-1); i++) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>1) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>2) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>3) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - if (ow>4) { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - } -#ifdef DEBUGOUT - printf("Output buffer enable= %d\n", obe); -#endif - if (obe) { - putout("0100000000000000",imod); - putout("0110000000000000",imod); - putout("0100000000000000",imod); - } else { - putout("0000000000000000",imod); - putout("0010000000000000",imod); - putout("0000000000000000",imod); - } - /*}*/ - putout("0000000000000000",imod); - - - - - - sMod=imod; - if (imod==ALLMOD) - sMod=allSelected; - - - if (sChip==allSelected) { - chipmi=0; - chipma=NCHIP; - } else if (sChip==noneSelected || sChip>NCHIP || sChip<0) { - chipmi=0; - chipma=-1; - } else { - chipmi=sChip; - chipma=sChip+1; - } - - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorChips) { - for (im=modmi; imNCHIP || sChip<0) { - chipmi=0; - chipma=-1; - } else { - chipmi=sChip; - chipma=sChip+1; - } - - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorChips) { - for (im=modmi; imnModX || sMod<0) {//(sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - if (detectorModules) { - for (im=modmi; imreg)=cm; -#ifdef VERBOSE - printf("imod=%d reg=%d (%x)\n",im,(detectorModules+im)->reg,(detectorModules+im)); -#endif - } - } - return 0; -} - -int initModulebyNumber(sls_detector_module myMod) { - - - int ichip, nchip, ichan, nchan; - int im, modmi,modma; - int ft, cae, ae, coe, ocoe, counts, chanreg; - int imod; - int obe; - int ow; - int v[NDAC]; - - - nchip=myMod.nchip; - nchan=(myMod.nchan)/nchip; - - imod=myMod.module; - sMod=imod; - - if (sMod==ALLMOD) - sMod=allSelected; - - if (sMod==allSelected) { - modmi=0; - modma=nModX;//getNModBoard(); - } else if (sMod==noneSelected || sMod>nModX || sMod<0) {// (sMod==noneSelected || sMod>getNModBoard() || sMod<0) { - modmi=0; - modma=-1; - } else { - modmi=sMod; - modma=sMod+1; - } - - - /* - for (idac=0; idac>(NTRIMBITS+1))&1; - ae=(chanreg>>(NTRIMBITS+2))&1; - coe=((chanreg)>>(NTRIMBITS+3))&1; - ocoe=((chanreg)>>(NTRIMBITS+4))&1; - counts=((chanreg)>>(NTRIMBITS+5)); - nextStrip(imod); - initChannel(ft,cae,ae, coe, ocoe, counts,imod); - } - obe=((myMod.chipregs)[ichip])&1; - ow=1;//((myMod.chipregs)[ichip])>>1; - initChip(obe,ow,imod); - nextChip(imod); - } - - - initMCBregisters(myMod.reg,imod); - - if (detectorModules) { - for (im=modmi; immodule; -#ifdef VERBOSE - printf("Getting module %d\n",imod); -#endif - if (detectorModules) { - copyModule(myMod,detectorModules+imod); - ; - } else - return FAIL; - - return OK; -} - -/* To chips */ -int clearCounter(int imod){ - int i; -#ifdef DEBUG - printf("Clearing counter with contclear\n"); -#endif - putout("0000000000000000",imod); - for (i=0; i<10; i++) - putout("0000000000010000",imod); - putout("0000000000000000",imod); - - return 0; -} - -int clearOutReg(int imod){ - int i; -#ifdef DEBUG - printf("Clearing output register\n"); -#endif - putout("0000010000000000",imod); - for (i=0; i<10; i++) - putout("0000110000000000",imod); - putout("0000010000000000",imod); - return 0; -} -int setOutReg(int imod){ - int i; -#ifdef DEBUG - printf("Setting output register\n"); -#endif - putout("0000010000000000",imod); - for (i=0; i<10; i++) - putout("0001010000000000",imod); - putout("0000010000000000",imod); - return 0; -} - - -int extPulse(int ncal, int imod) { - int ical; -#ifdef DEBUG - printf("Giving a clock pulse to the counter\n"); -#endif - for (ical=0; ical0 && i%2==0) { - printf("Shift in: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, i%2); - result++; - } - if (i%2>0 && (val & 1<0 && (dum & (1<0) { - printf("Shift out: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, (dum &1<0 && i%2==0) { - printf("Shift stsel: module %d chip %i bit %d read %d instead of %d \n",k,j,i,val & 1<< j, i%2); - result++; - } - if (i%2>0 && (val & 1<> 1; - - - putout("0000000000000000",imod); - putout("0010000000000000",imod); //change mux setting - putout("0000000000000000",imod); - } - - printf("Test FpgaMux module %d : %d errors\n", imod,result); - if (result) - return 1; - else - return 0; -} - - - - - - - - - -int calibration_sensor(int num, int *v, int *dacs) { - int ich, ichip, imod; - int val[10]; - - - printf("calibrating sensor..."); - for (imod=0; imod - - -// Hardware definitions - -#define NCHAN 128 -#define NCHIP 12 //10 modified for PICASSO -#define NMAXMODX 24 -#define NMAXMODY 1 -#define NMAXMOD NMAXMODX*NMAXMODY -#define NDAC 6 -#define NADC 0 - -#define NCHANS NCHAN*NCHIP*NMAXMOD -#define NDACS NDAC*NMAXMOD - -#define NTRIMBITS 6 -#define NCOUNTBITS 24 - -//#define TRIM_DR ((2**NTRIMBITS)-1) -//#define COUNT_DR ((2**NCOUNTBITS)-1) -#define TRIM_DR (((int)pow(2,NTRIMBITS))-1) -#define COUNT_DR (((int)pow(2,NCOUNTBITS))-1) - - -#define ALLMOD 0xffff -#define ALLFIFO 0xffff - -#ifdef VIRTUAL -#define DEBUGOUT -#endif - -#define CLK_FREQ 100E+6 - - -#define THIS_SOFTWARE_VERSION 0x20090205 -#endif diff --git a/slsDetectorSoftware/mythenDetectorServer/registers.h b/slsDetectorSoftware/mythenDetectorServer/registers.h deleted file mode 100755 index 32f479c3a..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/registers.h +++ /dev/null @@ -1,184 +0,0 @@ -#ifndef REGISTERS_H -#define REGISTERS_H - - - -/* Definitions for FPGA*/ -#define CSP0 0x90000000 // Base Addresse CSP0 -#define CSP4 0xa0000000 // Base Addresse CSP4 - -//#define MEM_SIZE 0xFFFFFF // map so much memory -#define MEM_SIZE 0xFFFFFFF // map so much memory - - - -/* registers defined in FPGA */ -#define FIX_PATT_REG 0x000000 -#define FPGA_VERSION_REG 0x001000 -#define DUMMY_REG 0x002000 -#define CONTROL_REG 0x003000 -#define STATUS_REG 0x004000 -#define CONFIG_REG 0x005000 -#define SPEED_REG 0x006000 -#define EXT_SIGNAL_REG 0x007000 -#define SET_NBITS_REG 0x008000 -#define LOOK_AT_ME_REG 0x009000 - -#define SET_FRAMES_LSB_REG 0x00A000 -#define SET_FRAMES_MSB_REG 0x00B000 -#define GET_FRAMES_LSB_REG 0x00C000 -#define GET_FRAMES_MSB_REG 0x00D000 - -#define SET_EXPTIME_LSB_REG 0x00E000 -#define SET_EXPTIME_MSB_REG 0x00F000 -#define GET_EXPTIME_LSB_REG 0x010000 -#define GET_EXPTIME_MSB_REG 0x011000 - -#define SET_GATES_LSB_REG 0x012000 -#define SET_GATES_MSB_REG 0x013000 -#define GET_GATES_LSB_REG 0x014000 -#define GET_GATES_MSB_REG 0x015000 - -#define SET_PERIOD_LSB_REG 0x016000 -#define SET_PERIOD_MSB_REG 0x017000 -#define GET_PERIOD_LSB_REG 0x018000 -#define GET_PERIOD_MSB_REG 0x019000 - -#define SET_DELAY_LSB_REG 0x01A000 -#define SET_DELAY_MSB_REG 0x01B000 -#define GET_DELAY_LSB_REG 0x01C000 -#define GET_DELAY_MSB_REG 0x01D000 - -#define SET_TRAINS_LSB_REG 0x01E000 -#define SET_TRAINS_MSB_REG 0x01F000 -#define GET_TRAINS_LSB_REG 0x020000 -#define GET_TRAINS_MSB_REG 0x021000 - - -#define GET_SHIFT_IN_REG 0x022000 - -#define GET_MEASUREMENT_TIME_LSB_REG 0x023000 -#define GET_MEASUREMENT_TIME_MSB_REG 0x024000 - -#define GET_ACTUAL_TIME_LSB_REG 0x025000 -#define GET_ACTUAL_TIME_MSB_REG 0x026000 - -#define MOD_DACS1_REG 0x030000 -#define MOD_DACS2_REG 0x040000 - -#define MCB_CNTRL_REG_OFF 0x100000 -#define MCB_DOUT_REG_OFF 0x200000 -#define FIFO_CNTRL_REG_OFF 0x300000 -#define FIFO_COUNTR_REG_OFF 0x400000 -#define FIFO_DATA_REG_OFF 0x800000 - -#define SHIFTMOD 2 -#define SHIFTFIFO 9 - - - -/* values defined for FPGA */ -#define MCSNUM 0x0 -#define MCSVERSION 0x101 -#define FIXED_PATT_VAL 0xacdc1980 -#define FPGA_VERSION_VAL 0x00090514 -#define FPGA_INIT_PAT 0x60008 -#define FPGA_INIT_ADDR 0xb0000000 - -/* for control register */ -#define START_ACQ_BIT 0x00000001 -#define STOP_ACQ_BIT 0x00000002 -#define START_FIFOTEST_BIT 0x00000004 // ????? -#define STOP_FIFOTEST_BIT 0x00000008 // ?????? -#define START_READOUT_BIT 0x00000010 -#define STOP_READOUT_BIT 0x00000020 -#define START_EXPOSURE_BIT 0x00000040 -#define STOP_EXPOSURE_BIT 0x00000080 -#define START_TRAIN_BIT 0x00000100 -#define STOP_TRAIN_BIT 0x00000200 -#define SYNC_RESET 0x80000000 - -/* for status register */ -#define RUN_BUSY_BIT 0x00000001 -#define READOUT_BUSY_BIT 0x00000002 -#define FIFOTEST_BUSY_BIT 0x00000004 //???? -#define WAITING_FOR_TRIGGER_BIT 0x00000008 -#define DELAYBEFORE_BIT 0x00000010 -#define DELAYAFTER_BIT 0x00000020 -#define EXPOSING_BIT 0x00000040 -#define COUNT_ENABLE_BIT 0x00000080 -#define SOME_FIFO_FULL_BIT 0x00008000 // error! -#define ALL_FIFO_EMPTY_BIT 0x00010000 // data ready - -/* for fifo status register */ -#define FIFO_ENABLED_BIT 0x80000000 -#define FIFO_DISABLED_BIT 0x01000000 -#define FIFO_ERROR_BIT 0x08000000 -#define FIFO_EMPTY_BIT 0x04000000 -#define FIFO_DATA_READY_BIT 0x02000000 -#define FIFO_COUNTER_MASK 0x000001ff -#define FIFO_NM_MASK 0x00e00000 -#define FIFO_NM_OFF 21 -#define FIFO_NC_MASK 0x001ffe00 -#define FIFO_NC_OFF 9 - -/* for config register */ - -#define TOT_ENABLE_BIT 0x00000002 -#define TIMED_GATE_BIT 0x00000004 -#define CONT_RO_ENABLE_BIT 0x00080000 - - - -/* for speed register */ - -#define CLK_DIVIDER_MASK 0x000000ff -#define CLK_DIVIDER_OFFSET 0 -#define SET_LENGTH_MASK 0x00000f00 -#define SET_LENGTH_OFFSET 8 -#define WAIT_STATES_MASK 0x0000f000 -#define WAIT_STATES_OFFSET 12 -#define TOTCLK_DIVIDER_MASK 0xff000000 -#define TOTCLK_DIVIDER_OFFSET 24 -#define TOTCLK_DUTYCYCLE_MASK 0x00ff0000 -#define TOTCLK_DUTYCYCLE_OFFSET 16 - -/* for external signal register */ - -#define SIGNAL_OFFSET 4 -#define SIGNAL_MASK 0xF -#define EXT_SIG_OFF 0x0 -#define EXT_GATE_IN_ACTIVEHIGH 0x1 -#define EXT_GATE_IN_ACTIVELOW 0x2 -#define EXT_TRIG_IN_RISING 0x3 -#define EXT_TRIG_IN_FALLING 0x4 -#define EXT_RO_TRIG_IN_RISING 0x5 -#define EXT_RO_TRIG_IN_FALLING 0x6 -#define EXT_GATE_OUT_ACTIVEHIGH 0x7 -#define EXT_GATE_OUT_ACTIVELOW 0x8 -#define EXT_TRIG_OUT_RISING 0x9 -#define EXT_TRIG_OUT_FALLING 0xA -#define EXT_RO_TRIG_OUT_RISING 0xB -#define EXT_RO_TRIG_OUT_FALLING 0xC -#define EXT_OUT_LOW 0xD // to be implemented in firmware (and corrected in software) -#define EXT_OUT_HIGH 0xE // to be implemented in firmware (and corrected in software) -#define EXT_MASTER_SLAVE_SYNC 0xF // to be implemented in firmware (and corrected in software) - - - -/* fifo control register */ -#define FIFO_RESET_BIT 0x00000001 -#define FIFO_DISABLE_TOGGLE_BIT 0x00000002 - - -//chip shiftin register meaning - -#define OUTMUX_OFF 20 -#define OUTMUX_MASK 0x1f -#define PROBES_OFF 4 -#define PROBES_MASK 0x7f -#define OUTBUF_OFF 0 -#define OUTBUF_MASK 1 - - -#endif diff --git a/slsDetectorSoftware/mythenDetectorServer/server.c b/slsDetectorSoftware/mythenDetectorServer/server.c deleted file mode 100755 index f39b221f5..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/server.c +++ /dev/null @@ -1,91 +0,0 @@ -/* A simple server in the internet domain using TCP - The port number is passed as an argument */ -#include "communication_funcs.h" -#include "server_funcs.h" -#include - - -extern int sockfd; - - -void error(char *msg) -{ - perror(msg); -} - -int main(int argc, char *argv[]) -{ - int portno, b; - char cmd[100]; - int retval=OK; - int sd, fd; - - - if (argc==1) { - portno = DEFAULT_PORTNO; - sprintf(cmd,"%s %d &",argv[0],DEFAULT_PORTNO+1); - printf("opening control server on port %d\n",portno ); - system(cmd); - b=1; - } else { - portno = DEFAULT_PORTNO+1; - if ( sscanf(argv[1],"%d",&portno) ==0) { - printf("could not open stop server: unknown port\n"); - return 1; - } - b=0; - printf("opening stop server on port %d\n",portno); - } - - - - init_detector(b); //defined in server_funcs - - - sd=bindSocket(portno); //defined in communication_funcs - - sockfd=sd; - - - if (getServerError(sd)) { //defined in communication_funcs - printf("server error!\n"); - return -1; - } - - /* assign function table */ - function_table(); //defined in server_funcs -#ifdef VERBOSE - printf("function table assigned \n"); -#endif - - - /* waits for connection */ - while(retval!=GOODBYE) { -#ifdef VERBOSE - printf("\n"); -#endif -#ifdef VERY_VERBOSE - printf("Waiting for client call\n"); -#endif - fd=acceptConnection(sockfd); //defined in communication_funcs -#ifdef VERY_VERBOSE - printf("Conenction accepted\n"); -#endif - if (fd>0) { - retval=decode_function(fd); //defined in server_funcs -#ifdef VERY_VERBOSE - printf("function executed\n"); -#endif - closeConnection(fd); //defined in communication_funcs -#ifdef VERY_VERBOSE - printf("connection closed\n"); -#endif - } - } - - exitServer(sockfd); //defined in communication_funcs - printf("Goodbye!\n"); - - return 0; -} - diff --git a/slsDetectorSoftware/mythenDetectorServer/server_defs.h b/slsDetectorSoftware/mythenDetectorServer/server_defs.h deleted file mode 100755 index e91bb5685..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/server_defs.h +++ /dev/null @@ -1,43 +0,0 @@ -#ifndef SERVER_DEFS_H -#define SERVER_DEFS_H - -#include "sls_detector_defs.h" - -#include - - -// Hardware definitions - -#define NCHAN 128 -#define NCHIP 10 -#define NMAXMODX 24 -#define NMAXMODY 1 -#define NMAXMOD NMAXMODX*NMAXMODY -#define NDAC 6 -#define NADC 0 - -#define NCHANS NCHAN*NCHIP*NMAXMOD -#define NDACS NDAC*NMAXMOD - -#define NTRIMBITS 6 -#define NCOUNTBITS 24 - -//#define TRIM_DR ((2**NTRIMBITS)-1) -//#define COUNT_DR ((2**NCOUNTBITS)-1) -#define TRIM_DR (((int)pow(2,NTRIMBITS))-1) -#define COUNT_DR (((int)pow(2,NCOUNTBITS))-1) - - -#define ALLMOD 0xffff -#define ALLFIFO 0xffff - -#ifdef VIRTUAL -#define DEBUGOUT -#endif - -#define CLK_FREQ 100E+6 - - -#define THIS_SOFTWARE_VERSION 0x20120419 -#define THIS_REVISION "$Rev: 379 $" -#endif diff --git a/slsDetectorSoftware/mythenDetectorServer/server_funcs.c b/slsDetectorSoftware/mythenDetectorServer/server_funcs.c deleted file mode 100755 index ce0b86fef..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/server_funcs.c +++ /dev/null @@ -1,2857 +0,0 @@ -#include "sls_detector_defs.h" -#include "server_funcs.h" -#ifndef PICASSOD -#include "server_defs.h" -#else -#include "picasso_defs.h" -#endif -#include "firmware_funcs.h" -#include "mcb_funcs.h" -#include "trimming_funcs.h" -#include "gitInfoMythen.h" - -// Global variables - -int (*flist[256])(int); - - - -#ifdef MCB_FUNCS -extern const enum detectorType myDetectorType; -#endif -#ifndef MCB_FUNCS -const enum detectorType myDetectorType=MYTHEN; -#endif -extern int nModX; -extern int nModY; -extern int dataBytes; -extern int dynamicRange; -extern int storeInRAM; - -extern int lockStatus; -extern char lastClientIP[INET_ADDRSTRLEN]; -extern char thisClientIP[INET_ADDRSTRLEN]; -extern int differentClients; - -/* global variables for optimized readout */ -extern int *ram_values; -char *dataretval=NULL; -int nframes, iframes, dataret; -char mess[MAX_STR_LENGTH]; - - - - - -int init_detector( int b) { -#ifndef PICASSOD - printf("This is a MYTHEN detector with %d chips per module\n", NCHIP); -#else - printf("This is a PICASSO detector with %d chips per module\n", NCHIP); -#endif - mapCSP0(); -#ifndef VIRTUAL - system("bus -a 0xb0000000 -w 0xd0008"); -#ifdef VERBOSE - printf("setting wait states \n"); - system("bus -a 0xb0000000"); -#endif -#endif - testFpga(); - if (b) { -#ifdef MCB_FUNCS - initDetector(); - printf("init \n"); - setSettings(GET_SETTINGS); - printf("get settings \n"); - testRAM(); - printf("test ram \n"); -#endif - setTiming(GET_EXTERNAL_COMMUNICATION_MODE); - printf("timing \n"); - setMaster(GET_MASTER); - printf("master \n"); - setSynchronization(GET_SYNCHRONIZATION_MODE); - printf("sync \n"); - } - strcpy(mess,"dummy message"); - strcpy(lastClientIP,"none"); - strcpy(thisClientIP,"none1"); - lockStatus=0; - return OK; -} - - -int decode_function(int file_des) { - int fnum,n; - int retval=FAIL; -#ifdef VERBOSE - printf( "receive data\n"); -#endif - n = receiveDataOnly(file_des,&fnum,sizeof(fnum)); - if (n <= 0) { - printf("ERROR reading from socket %d, %d %d\n", n, fnum, file_des); - return FAIL; - } -#ifdef VERBOSE - else - printf("size of data received %d\n",n); -#endif - -#ifdef VERBOSE - printf( "calling function fnum = %d %x\n",fnum,flist[fnum]); -#endif - if (fnum<0 || fnum>255) - fnum=255; - retval=(*flist[fnum])(file_des); - if (retval==FAIL) - printf( "Error executing the function = %d \n",fnum); - return retval; -} - - -int function_table() { - int i; - for (i=0;i<256;i++){ - flist[i]=&M_nofunc; - } - flist[F_EXIT_SERVER]=&exit_server; - flist[F_EXEC_COMMAND]=&exec_command; - flist[F_GET_DETECTOR_TYPE]=&get_detector_type; - flist[F_SET_NUMBER_OF_MODULES]=&set_number_of_modules; - flist[F_GET_MAX_NUMBER_OF_MODULES]=&get_max_number_of_modules; - flist[F_SET_EXTERNAL_SIGNAL_FLAG]=&set_external_signal_flag; - flist[F_SET_EXTERNAL_COMMUNICATION_MODE]=&set_external_communication_mode; - flist[F_GET_ID]=&get_id; - flist[F_DIGITAL_TEST]=&digital_test; - flist[F_WRITE_REGISTER]=&write_register; - flist[F_READ_REGISTER]=&read_register; - flist[F_SET_DAC]=&set_dac; - flist[F_GET_ADC]=&get_adc; - flist[F_SET_CHANNEL]=&set_channel; - flist[F_SET_CHIP]=&set_chip; - flist[F_SET_MODULE]=&set_module; - flist[F_GET_CHANNEL]=&get_channel; - flist[F_GET_CHIP]=&get_chip; - flist[F_GET_MODULE]=&get_module; - flist[F_GET_THRESHOLD_ENERGY]=&get_threshold_energy; - flist[F_SET_THRESHOLD_ENERGY]=&set_threshold_energy; - flist[F_SET_SETTINGS]=&set_settings; - flist[F_START_ACQUISITION]=&start_acquisition; - flist[F_STOP_ACQUISITION]=&stop_acquisition; - flist[F_START_READOUT]=&start_readout; - flist[F_GET_RUN_STATUS]=&get_run_status; - flist[F_READ_FRAME]=&read_frame; - flist[F_READ_ALL]=&read_all; - flist[F_START_AND_READ_ALL]=&start_and_read_all; - flist[F_SET_TIMER]=&set_timer; - flist[F_GET_TIME_LEFT]=&get_time_left; - flist[F_SET_DYNAMIC_RANGE]=&set_dynamic_range; - flist[F_SET_ROI]=&set_roi; - flist[F_SET_SPEED]=&set_speed; - flist[F_SET_READOUT_FLAGS]=&set_readout_flags; - flist[F_EXECUTE_TRIMMING]=&execute_trimming; - flist[F_LOCK_SERVER]=&lock_server; - flist[F_SET_PORT]=&set_port; - flist[F_GET_LAST_CLIENT_IP]=&get_last_client_ip; - flist[F_UPDATE_CLIENT]=&update_client; - flist[F_SET_MASTER]=&set_master; - flist[F_SET_SYNCHRONIZATION_MODE]=&set_synchronization; -#ifdef VERBOSE - /* for (i=0;i<256;i++){ - printf("function %d located at %x\n",i,flist[i]); - }*/ -#endif - return OK; -} - - -int M_nofunc(int file_des){ - - int retval=FAIL; - sprintf(mess,"Unrecognized Function\n"); - printf(mess); - sendDataOnly(file_des,&retval,sizeof(retval)); - sendDataOnly(file_des,mess,sizeof(mess)); - return GOODBYE; -} - - -int exit_server(int file_des) { - int retval=FAIL; - sendDataOnly(file_des,&retval,sizeof(retval)); - printf("closing server."); - sprintf(mess,"closing server"); - sendDataOnly(file_des,mess,sizeof(mess)); - return GOODBYE; -} - -int exec_command(int file_des) { - char cmd[MAX_STR_LENGTH]; - char answer[MAX_STR_LENGTH]; - int retval=OK; - int sysret=0; - int n=0; - - /* receive arguments */ - n = receiveDataOnly(file_des,cmd,MAX_STR_LENGTH); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - - /* execute action if the arguments correctly arrived*/ - if (retval==OK) { -#ifdef VERBOSE - printf("executing command %s\n", cmd); -#endif - if (lockStatus==0 || differentClients==0) - sysret=system(cmd); - - //should be replaced by popen - if (sysret==0) { - sprintf(answer,"Succeeded\n"); - if (lockStatus==1 && differentClients==1) - sprintf(answer,"Detector locked by %s\n", lastClientIP); - } else { - sprintf(answer,"Failed\n"); - retval=FAIL; - } - } else { - sprintf(answer,"Could not receive the command\n"); - } - - /* send answer */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - n = sendDataOnly(file_des,answer,MAX_STR_LENGTH); - if (n < 0) { - sprintf(mess,"Error writing to socket"); - retval=FAIL; - } - - - /*return ok/fail*/ - return retval; - -} - - - -int get_detector_type(int file_des) { - int n=0; - enum detectorType ret; - int retval=OK; - - sprintf(mess,"Can't return detector type\n"); - - - /* receive arguments */ - /* execute action */ - ret=myDetectorType; - -#ifdef VERBOSE - printf("Returning detector type %d\n",ret); -#endif - - /* send answer */ - /* send OK/failed */ - if (differentClients==1) - retval=FORCE_UPDATE; - - n += sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - /*return ok/fail*/ - return retval; - - -} - - -int set_number_of_modules(int file_des) { - int n; - int arg[2], ret=0; - int retval=OK; - int dim, nm; - - sprintf(mess,"Can't set number of modules\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket %d", n); - retval=GOODBYE; - } - if (retval==OK) { - dim=arg[0]; - nm=arg[1]; - - /* execute action */ -#ifdef VERBOSE - printf("Setting the number of modules in dimension %d to %d\n",dim,nm ); -#endif - - //if (nm!=GET_FLAG) { - if (dim!=X && nm!=GET_FLAG) { - retval=FAIL; - sprintf(mess,"Can't change module number in dimension %d\n",dim); - } else { - if (lockStatus==1 && differentClients==1 && nm!=GET_FLAG) { - sprintf(mess,"Detector locked by %s\n", lastClientIP); - retval=FAIL; - } else { - ret=setNMod(nm); - if (nModX==nm || nm==GET_FLAG) { - retval=OK; - if (differentClients==1) - retval=FORCE_UPDATE; - } else - retval=FAIL; - } - } - } - /*} else { - if (dim==Y) { - ret=nModY; - } else if (dim==X) { - ret=setNMod(-1); - } - } - */ - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - /*return ok/fail*/ - return retval; - -} - - -int get_max_number_of_modules(int file_des) { - int n; - int ret; - int retval=OK; - enum dimension arg; - - sprintf(mess,"Can't get max number of modules\n"); - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - /* execute action */ -#ifdef VERBOSE - printf("Getting the max number of modules in dimension %d \n",arg); -#endif - - - switch (arg) { - case X: - ret=getNModBoard(); - break; - case Y: - ret=NMAXMODY; - break; - default: - ret=FAIL; - retval=FAIL; - } -#ifdef VERBOSE - printf("Max number of module in dimension %d is %d\n",arg,ret ); -#endif - - - - if (differentClients==1 && retval==OK) { - retval=FORCE_UPDATE; - } - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - - /*return ok/fail*/ - return retval; -} - - -//index 0 is in gate -//index 1 is in trigger -//index 2 is out gate -//index 3 is out trigger - -int set_external_signal_flag(int file_des) { - int n; - int arg[2]; - int ret=OK; - int signalindex; - enum externalSignalFlag flag, retval; - - sprintf(mess,"Can't set external signal flag\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - retval=SIGNAL_OFF; - if (ret==OK) { - signalindex=arg[0]; - flag=arg[1]; - /* execute action */ - switch (flag) { - case GET_EXTERNAL_SIGNAL_FLAG: - retval=getExtSignal(signalindex); - break; - - default: - if (differentClients==0 || lockStatus==0) { - retval=setExtSignal(signalindex,flag); - } else { - if (lockStatus!=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n", lastClientIP); - } - } - - - } - -#ifdef VERBOSE - printf("Setting external signal %d to flag %d\n",signalindex,flag ); - printf("Set to flag %d\n",retval); -#endif - - } else { - ret=FAIL; - } - - if (ret==OK && differentClients!=0) - ret=FORCE_UPDATE; - - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - /*return ok/fail*/ - return ret; - -} - - -int set_external_communication_mode(int file_des) { - int n; - enum externalCommunicationMode arg, ret=GET_EXTERNAL_COMMUNICATION_MODE; - int retval=OK; - - sprintf(mess,"Can't set external communication mode\n"); - - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } - /* -enum externalCommunicationMode{ - GET_EXTERNAL_COMMUNICATION_MODE, - AUTO, - TRIGGER_EXPOSURE_SERIES, - TRIGGER_EXPOSURE_BURST, - TRIGGER_READOUT, - TRIGGER_COINCIDENCE_WITH_INTERNAL_ENABLE, - GATE_FIX_NUMBER, - GATE_FIX_DURATION, - GATE_WITH_START_TRIGGER, - GATE_COINCIDENCE_WITH_INTERNAL_ENABLE -}; - */ - if (retval==OK) { - /* execute action */ - - ret=setTiming(arg); - -/* switch(arg) { */ -/* default: */ -/* sprintf(mess,"The meaning of single signals should be set\n"); */ -/* retval=FAIL; */ -/* } */ - - -#ifdef VERBOSE - printf("Setting external communication mode to %d\n", arg); -#endif - } else - ret=FAIL; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&retval,sizeof(retval)); - if (retval!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&ret,sizeof(ret)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return retval; - - -} - - - -int get_id(int file_des) { - // sends back 64 bits! - int64_t retval, rev, dat; - int ret=OK; - int imod=-1; - int n=0; - int rev1; - enum idMode arg; - - sprintf(mess,"Can't return id\n"); - - /* receive arguments */ - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - -#ifdef VERBOSE - printf("Getting id %d\n", arg); -#endif - - switch (arg) { - case MODULE_SERIAL_NUMBER: - n = receiveDataOnly(file_des,&imod,sizeof(imod)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } else { -#ifdef VERBOSE - printf("of module %d\n", imod); -#endif - if (imod>=0 && imod<=getNModBoard()) { -#ifdef MCB_FUNCS - retval=getModuleNumber(imod); -#endif - ; - } - else { - sprintf(mess,"Module number %d out of range\n",imod); - ret=FAIL; - } - } - break; - case MODULE_FIRMWARE_VERSION: - retval=0x1; - break; - case DETECTOR_SERIAL_NUMBER: - retval=getMcsNumber(); - break; - case DETECTOR_FIRMWARE_VERSION: - retval=getMcsVersion(); - break; - case DETECTOR_SOFTWARE_VERSION: - retval= GITREV; - retval= (retval <<32) | GITDATE; -/* sscanf(THIS_REVISION,"$Rev : %x",&rev1); - rev=((int64_t)rev1); - dat=THIS_SOFTWARE_VERSION; - retval=(dat<<32) | rev; - */ - break; - default: - printf("Required unknown id %d \n", arg); - ret=FAIL; - retval=FAIL; - } - -#ifdef VERBOSE - printf("Id is %llx\n", retval); -#endif - - if (differentClients==1) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - -int digital_test(int file_des) { - - int retval; - int ret=OK; - int imod=-1; - int n=0; - int ibit=0; - int ow; - enum digitalTestMode arg; - - sprintf(mess,"Can't send digital test\n"); - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - -#ifdef VERBOSE - printf("Digital test mode %d\n",arg ); -#endif - - switch (arg) { - case CHIP_TEST: - n = receiveDataOnly(file_des,&imod,sizeof(imod)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - retval=FAIL; - } -#ifdef VERBOSE - printf("of module %d\n", imod); -#endif - retval=0; -#ifdef MCB_FUNCS - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - break; - } - if (imod >= nModX) { - ret=FAIL; - sprintf(mess,"Module %d disabled\n",imod); - break; - } - if (testShiftIn(imod)) retval|=(1<<(ibit)); - ibit++; - if (testShiftOut(imod)) retval|=(1<<(ibit)); - ibit++; - if (testShiftStSel(imod)) retval|=(1<<(ibit)); - ibit++; - //if ( testDataInOut(0x123456, imod)) retval|=(1<<(ibit++)); - //if ( testExtPulse(imod)) retval|=(1<<(ibit++)); - // for (ow=0; ow<6; ow++) - // ow=1; - //#ifndef PICASSOD - for (ow=0; ow<5; ow++) { - //#endif - if (testDataInOutMux(imod, ow, 0x789abc)) retval|=(1<=getNModBoard()) - ret=FAIL; - if (imod<0) - imod=ALLMOD; - -#ifdef MCB_FUNCS - switch (ind) { - case TRIMBIT_SIZE: - idac=VTRIM; - break; - case THRESHOLD: - idac=VTHRESH; - break; - case SHAPER1: - idac=RGSH1; - break; - case SHAPER2: - idac=RGSH2; - break; - case CALIBRATION_PULSE: - idac=VCAL; - break; - case PREAMP: - idac=RGPR; - break; - /*************************************************************** -add possible potentiometers like in chiptest board!!!!!!!!!!!!!!! - - ****************************************************************/ - - - - - default: - printf("Unknown DAC index %d\n",ind); - sprintf(mess,"Unknown DAC index %d\n",ind); - ret=FAIL; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1 && val!=-1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else - retval=initDACbyIndexDACU(idac,val,imod); - } -#endif - -#ifdef VERBOSE - printf("DAC set to %f V\n", retval); -#endif - if (retval==val || val==-1) { - ret=OK; - if (differentClients) - ret=FORCE_UPDATE; - } else { - ret=FAIL; - printf("Setting dac %d of module %d: wrote %f but read %f\n", ind, imod, val, retval); - } - - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /* Maybe this is done inside the initialization funcs */ - //detectorDacs[imod][ind]=val; - /*return ok/fail*/ - return ret; - -} - - - -int get_adc(int file_des) { - - dacs_t retval; - int ret=OK; - int arg[2]; - enum dacIndex ind; - int imod; - int n; - int idac=0; - - sprintf(mess,"Can't read ADC\n"); - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ind=arg[0]; - imod=arg[1]; - - - if (imod>=getNModBoard() || imod<0) - ret=FAIL; - -#ifdef MCB_FUNCS - switch (ind) { - case TRIMBIT_SIZE: - idac=VTRIM; - break; - case THRESHOLD: - idac=VTHRESH; - break; - case SHAPER1: - idac=RGSH1; - break; - case SHAPER2: - idac=RGSH2; - break; - case CALIBRATION_PULSE: - idac=VCAL; - break; - case PREAMP: - idac=RGPR; - break; - default: - printf("Unknown DAC index %d\n",ind); - ret=FAIL; - sprintf(mess,"Unknown DAC index %d\n",ind); - } - - if (ret==OK) { - retval=getDACbyIndexDACU(idac,imod); - } - #endif -#ifdef VERBOSE - printf("Getting ADC %d of module %d\n", ind, imod); -#endif - -#ifdef VERBOSE - printf("ADC is %f V\n", retval); -#endif - if (ret==FAIL) { - printf("Getting adc %d of module %d failed\n", ind, imod); - } - - - if (differentClients) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - /*return ok/fail*/ - return ret; - -} - -int set_channel(int file_des) { - int ret=OK; - sls_detector_channel myChan; - int retval; - int n; - - - sprintf(mess,"Can't set channel\n"); - -#ifdef VERBOSE - printf("Setting channel\n"); -#endif - ret=receiveChannel(file_des, &myChan); - if (ret>=0) - ret=OK; - else - ret=FAIL; -#ifdef VERBOSE - printf("channel number is %d, chip number is %d, module number is %d, register is %lld\n", myChan.chan,myChan.chip, myChan.module, myChan.reg); -#endif - - if (ret==OK) { - if (myChan.module>=getNModBoard()) - ret=FAIL; - if (myChan.chip>=NCHIP) - ret=FAIL; - if (myChan.chan>=NCHAN) - ret=FAIL; - if (myChan.module<0) - myChan.module=ALLMOD; - } - - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef MCB_FUNCS - retval=initChannelbyNumber(myChan); -#endif - } - } - /* Maybe this is done inside the initialization funcs */ - //copyChannel(detectorChans[myChan.module][myChan.chip]+(myChan.chan), &myChan); - - - - if (differentClients==1 && ret==OK) - ret=FORCE_UPDATE; - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - /*return ok/fail*/ - return ret; - -} - - - - -int get_channel(int file_des) { - - int ret=OK; - sls_detector_channel retval; - - int arg[3]; - int ichan, ichip, imod; - int n; - - sprintf(mess,"Can't get channel\n"); - - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ichan=arg[0]; - ichip=arg[1]; - imod=arg[2]; - - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod=0 && ichip=0 && ichan=0) - ret=OK; - else - ret=FAIL; -#ifdef VERBOSE - printf("chip number is %d, module number is %d, register is %d, nchan %d\n",myChip.chip, myChip.module, myChip.reg, myChip.nchan); -#endif - - if (ret==OK) { - if (myChip.module>=getNModBoard()) - ret=FAIL; - if (myChip.module<0) - myChip.module=ALLMOD; - if (myChip.chip>=NCHIP) - ret=FAIL; - } - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef MCB_FUNCS - retval=initChipbyNumber(myChip); -#endif - } - /* Maybe this is done inside the initialization funcs */ - //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); - - if (differentClients && ret==OK) - ret=FORCE_UPDATE; - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - return ret; -} - -int get_chip(int file_des) { - - - int ret=OK; - sls_detector_chip retval; - int arg[2]; - int ichip, imod; - int n; - - - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - ichip=arg[0]; - imod=arg[1]; - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod=0 && ichip=0) - ret=OK; - else - ret=FAIL; - - -#ifdef VERBOSE - printf("module number is %d,register is %d, nchan %d, nchip %d, ndac %d, nadc %d, gain %f, offset %f\n",myModule.module, myModule.reg, myModule.nchan, myModule.nchip, myModule.ndac, myModule.nadc, myModule.gain,myModule.offset); -#endif - - if (ret==OK) { - if (myModule.module>=getNModBoard()) { - ret=FAIL; - printf("Module number is too large %d\n",myModule.module); - } - if (myModule.module<0) - myModule.module=ALLMOD; - } - - if (ret==OK) { - if (differentClients==1 && lockStatus==1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { -#ifdef MCB_FUNCS - retval=initModulebyNumber(myModule); -#endif - } - } - - if (differentClients==1 && ret==OK) - ret=FORCE_UPDATE; - - /* Maybe this is done inside the initialization funcs */ - //copyChip(detectorChips[myChip.module]+(myChip.chip), &myChip); - - /* send answer */ - /* send OK/failed */ - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret!=FAIL) { - /* send return argument */ - n += sendDataOnly(file_des,&retval,sizeof(retval)); - } else { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - free(myChip); - free(myChan); - free(myDac); - free(myAdc); - - setDynamicRange(dr); - - - return ret; -} - - - - -int get_module(int file_des) { - - - int ret=OK; - - - int arg; - int imod; - int n; - - - - sls_detector_module myModule; - int *myChip=malloc(NCHIP*sizeof(int)); - int *myChan=malloc(NCHIP*NCHAN*sizeof(int)); - dacs_t *myDac=malloc(NDAC*sizeof(dacs_t)); - dacs_t *myAdc=malloc(NADC*sizeof(dacs_t)); - - - if (myDac) - myModule.dacs=myDac; - else { - sprintf(mess,"could not allocate dacs\n"); - ret=FAIL; - } - if (myAdc) - myModule.adcs=myAdc; - else { - sprintf(mess,"could not allocate adcs\n"); - ret=FAIL; - } - if (myChip) - myModule.chipregs=myChip; - else { - sprintf(mess,"could not allocate chips\n"); - ret=FAIL; - } - if (myChan) - myModule.chanregs=myChan; - else { - sprintf(mess,"could not allocate chans\n"); - ret=FAIL; - } - - myModule.ndac=NDAC; - myModule.nchip=NCHIP; - myModule.nchan=NCHAN*NCHIP; - myModule.nadc=NADC; - - - - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - imod=arg; - - if (ret==OK) { - ret=FAIL; - if (imod>=0 && imod-2) { - dataret=FAIL; - sprintf(mess,"no data and run stopped: %d frames left\n",getFrames()+2); - printf("%s\n",mess); - } else { - dataret=FINISHED; - sprintf(mess,"acquisition successfully finished\n"); - printf("%s\n",mess); - } -#ifdef VERYVERBOSE - printf("%d %d %x %s\n",sizeof(mess),strlen(mess), mess,mess); -#endif - sendDataOnly(file_des,&dataret,sizeof(dataret)); - sendDataOnly(file_des,mess,sizeof(mess));//sizeof(mess));//sizeof(mess)); -#ifdef VERYVERBOSE - printf("message sent\n",mess); -#endif - printf("dataret %d\n",dataret); - return dataret; - } - } else { - nframes=0; - while(fifo_read_event()) { - nframes++; - } - dataretval=(char*)ram_values; - dataret=OK; -#ifdef VERBOSE - printf("sending data of %d frames\n",nframes); -#endif - for (iframes=0; iframes-2) { - dataret=FAIL; - sprintf(mess,"no data and run stopped: %d frames left\n",getFrames()+2); - printf("%s\n",mess); - } else { - dataret=FINISHED; - sprintf(mess,"acquisition successfully finished\n"); - printf("%s\n",mess); - if (differentClients) - dataret=FORCE_UPDATE; - } -#ifdef VERBOSE - printf("Frames left %d\n",getFrames()); -#endif - sendDataOnly(file_des,&dataret,sizeof(dataret)); - sendDataOnly(file_des,mess,sizeof(mess)); - printf("dataret %d\n",dataret); - return dataret; - } - printf("dataret %d\n",dataret); - return dataret; -} - - - - - - - - -int read_all(int file_des) { - - - while(read_frame(file_des)==OK) { -#ifdef VERBOSE - printf("frame read\n"); -#endif - ; - } - -#ifdef VERBOSE - printf("Frames finished\n"); -#endif - return OK; - - -} - -int start_and_read_all(int file_des) { - //int dataret=OK; -#ifdef VERBOSE - printf("Starting and reading all frames\n"); -#endif - - if (differentClients==1 && lockStatus==1) { - dataret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - sendDataOnly(file_des,&dataret,sizeof(dataret)); - sendDataOnly(file_des,mess,sizeof(mess)); - return dataret; - - } - - - startStateMachine(); - /* ret=startStateMachine(); - if (ret!=OK) { - sprintf(mess,"could not start state machine\n"); - sendDataOnly(file_des,&ret,sizeof(ret)); - sendDataOnly(file_des,mess,sizeof(mess)); - - #ifdef VERBOSE - printf("could not start state machine\n"); -#endif -} else {*/ - read_all(file_des); -#ifdef VERBOSE - printf("Frames finished\n"); -#endif - //} - - - return OK; - - -} - -int set_timer(int file_des) { - enum timerIndex ind; - int64_t tns; - int n; - int64_t retval; - int ret=OK; - - - sprintf(mess,"can't set timer\n"); - - n = receiveDataOnly(file_des,&ind,sizeof(ind)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,&tns,sizeof(tns)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - if (ret!=OK) { - printf(mess); - } - -#ifdef VERBOSE - printf("setting timer %d to %lld ns\n",ind,tns); -#endif - if (ret==OK) { - - if (differentClients==1 && lockStatus==1 && tns!=-1) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - switch(ind) { - case FRAME_NUMBER: - retval=setFrames(tns); - break; - case ACQUISITION_TIME: - retval=setExposureTime(tns); - break; - case FRAME_PERIOD: - retval=setPeriod(tns); - break; - case DELAY_AFTER_TRIGGER: - retval=setDelay(tns); - break; - case GATES_NUMBER: - retval=setGates(tns); - break; - case PROBES_NUMBER: - retval=setProbes(tns); - break; - case CYCLES_NUMBER: - retval=setTrains(tns); - break; - default: - ret=FAIL; - sprintf(mess,"timer index unknown %d\n",ind); - } - } - } - if (ret!=OK) { - printf(mess); - if (differentClients) - ret=FORCE_UPDATE; - } - - if (ret!=OK) { - printf(mess); - printf("set timer failed\n"); - sprintf(mess, "set timer %d failed\n", ind); - } else if (ind==FRAME_NUMBER) { - ret=allocateRAM(); - if (ret!=OK) - sprintf(mess, "could not allocate RAM for %lld frames\n", tns); - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { -#ifdef VERBOSE - printf("returning ok %d\n",sizeof(retval)); -#endif - - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - - return ret; - -} - - - - - - - - -int get_time_left(int file_des) { - - enum timerIndex ind; - int n; - int64_t retval; - int ret=OK; - - sprintf(mess,"can't get timer\n"); - n = receiveDataOnly(file_des,&ind,sizeof(ind)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - -#ifdef VERBOSE - - printf("getting time left on timer %d \n",ind); -#endif - - if (ret==OK) { - switch(ind) { - case FRAME_NUMBER: - retval=getFrames(); - break; - case ACQUISITION_TIME: - retval=getExposureTime(); - break; - case FRAME_PERIOD: - retval=getPeriod(); - break; - case DELAY_AFTER_TRIGGER: - retval=getDelay(); - break; - case GATES_NUMBER: - retval=getGates(); - break; - case PROBES_NUMBER: - retval=getProbes(); - break; - case CYCLES_NUMBER: - retval=getTrains(); - break; - case PROGRESS: - retval=getProgress(); - break; - case ACTUAL_TIME: - retval=getActualTime(); - break; - case MEASUREMENT_TIME: - retval=getMeasurementTime(); - break; - default: - ret=FAIL; - sprintf(mess,"timer index unknown %d\n",ind); - } - } - - - if (ret!=OK) { - printf("get time left failed\n"); - } else if (differentClients) - ret=FORCE_UPDATE; - -#ifdef VERBOSE - - printf("time left on timer %d is %lld\n",ind, retval); -#endif - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n += sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } -#ifdef VERBOSE - - printf("data sent\n"); -#endif - - return ret; - - -} - -int set_dynamic_range(int file_des) { - - - - int dr; - int n; - int retval; - int ret=OK; - - - sprintf(mess,"can't set dynamic range\n"); - - - n = receiveDataOnly(file_des,&dr,sizeof(dr)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - - if (differentClients==1 && lockStatus==1 && dr>=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=setDynamicRange(dr); - } - - if (dr>=0 && retval!=dr) - ret=FAIL; - if (ret!=OK) { - sprintf(mess,"set dynamic range failed\n"); - } else { - ret=allocateRAM(); - if (ret!=OK) - sprintf(mess,"Could not allocate RAM for the dynamic range selected\n"); - else if (differentClients) - ret=FORCE_UPDATE; - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - -int set_roi(int file_des) { - - - int arg=-1; - int n; - ROI roiLimits[MAX_ROIS]; - int ret=OK; - ROI retval; - - int nm=setNMod(-1), nmax=getNModBoard(), nroi; - - - sprintf(mess,"can't set ROI\n"); - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if(arg>0){ - n+=receiveDataOnly(file_des,roiLimits,arg*sizeof(ROI)); - } - - if (arg>1) { - ret=FAIL; - sprintf(mess,"can't set more than 1 ROI per detector\n"); - - } else - ret=OK; - - if (arg>0) { - - nm=(roiLimits[0].xmax-1)/1280+1; - - if (roiLimits[0].xmin>0) { - roiLimits[0].xmin=0; - ret=FAIL; - sprintf(mess,"ROI starts at 0\n"); - } - - if (nm>nmax) { - retval.xmax=setNMod(-1)*1280; - ret=FAIL; - sprintf(mess,"ROI max larger than detector size\n"); - } - - } else if (arg==0) { - setNMod(nmax); - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - retval.xmin=0; - retval.xmax=setNMod(-1)*1280; - retval.ymin=0; - retval.ymax=0; - if (setNMod(-1)=0) { - if (differentClients==1 && lockStatus==1 && val>=0) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - switch (arg) { - case CLOCK_DIVIDER: - retval=setClockDivider(val); - break; - case WAIT_STATES: - retval=setWaitStates(val); - break; - case SET_SIGNAL_LENGTH: - retval=setSetLength(val); - break; - case TOT_CLOCK_DIVIDER: - retval=setTotClockDivider(val); - break; - case TOT_DUTY_CYCLE: - retval=setTotDutyCycle(val); - break; - default: - ret=FAIL; - } - } - } else { - - switch (arg) { - case CLOCK_DIVIDER: - retval=getClockDivider(); - break; - case WAIT_STATES: - retval=getWaitStates(); - break; - case SET_SIGNAL_LENGTH: - retval=getSetLength(); - break; - case TOT_CLOCK_DIVIDER: - retval=getTotClockDivider(); - break; - case TOT_DUTY_CYCLE: - retval=getTotDutyCycle(); - break; - default: - ret=FAIL; - } - } - } - - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - - - -int set_readout_flags(int file_des) { - - enum readOutFlags retval; - enum readOutFlags arg; - int n; - int ret=OK; - int regret=OK; - - - sprintf(mess,"can't set readout flags\n"); - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - -#ifdef VERBOSE - printf("setting readout flags to %d\n",arg); -#endif - - if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - //ret=setStoreInRAM(0); - // initChipWithProbes(0,0,0, ALLMOD); - switch(arg) { - case GET_READOUT_FLAGS: - break; - case STORE_IN_RAM: - if (setStoreInRAM(1)==OK) - ret=OK; - else - ret=FAIL; - break; - case TOT_MODE: - if(setToT(1)) - ret=OK; - else - ret=FAIL; - break; - case CONTINOUS_RO: - if (setContinousReadOut(1)) - ret=OK; - else - ret=FAIL; - break; - // case PUMP_PROBE_MODE: - //set number of probes - //initChipWithProbes(0,0,2, ALLMOD); - //break; - default: - ret=setStoreInRAM(0); - regret=setConfigurationRegister(0); - ret=OK; - } - } - retval=NORMAL_READOUT; - - if (storeInRAM) - retval=STORE_IN_RAM; - //else if (getProbes()) - // retval=PUMP_PROBE_MODE; - //else - if (setToT(-1)) - retval|=TOT_MODE; - if (setContinousReadOut(-1)) - retval|=CONTINOUS_RO; - if (ret!=OK) { - printf("set readout flags failed\n"); - sprintf(mess,"Could not allocate RAM\n"); - } else if (differentClients) - ret=FORCE_UPDATE; - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - - - - - -int execute_trimming(int file_des) { - - int arg[3]; - int n; - int ret=OK; - int imod, par1,par2; - enum trimMode mode; - - printf("called function execute trimming\n"); - - sprintf(mess,"can't set execute trimming\n"); - - n = receiveDataOnly(file_des,&mode,sizeof(mode)); - printf("mode received\n"); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (mode)\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,arg,sizeof(arg)); - printf("arg received\n"); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (args)\n"); - ret=FAIL; - } - - imod=arg[0]; - - if (imod>=getNModBoard()) - ret=FAIL; - - if (imod<0) - imod=ALLMOD; - - par1=arg[1]; - par2=arg[2]; - -#ifdef VERBOSE - printf("trimming module %d mode %d, parameters %d %d \n",imod,mode, par1, par2); -#endif - - if (differentClients==1 && lockStatus==1 ) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - - if (ret==OK) { - switch(mode) { - case NOISE_TRIMMING: - // par1 is countlim; par2 is nsigma - ret=trim_with_noise(par1, par2, imod); - break; - case BEAM_TRIMMING: - // par1 is countlim; par2 is nsigma - ret=trim_with_beam(par1,par2,imod); - break; - case IMPROVE_TRIMMING: - // par1 is maxit; if par2!=0 vthresh will be optimized - ret=trim_improve(par1, par2,imod); - break; - case FIXEDSETTINGS_TRIMMING: - // par1 is countlim; if par2<0 then trimwithlevel else trim with median - ret=trim_fixed_settings(par1,par2,imod); - break; - // case OFFLINE_TRIMMING: - - //break; - default: - printf("Unknown trimming mode\n"); - sprintf(mess,"Unknown trimming mode\n"); - ret=FAIL; - } - } - } - - - if (ret<0) { - sprintf(mess,"can't set execute trimming\n"); - ret=FAIL; - } else if (ret>0) { - sprintf(mess,"Could not trim %d channels\n", ret); - ret=FAIL; - } else if (differentClients) - ret=FORCE_UPDATE; - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } - - return ret; -} - - -int lock_server(int file_des) { - - - int n; - int ret=OK; - - int lock; - n = receiveDataOnly(file_des,&lock,sizeof(lock)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (lock)\n"); - ret=FAIL; - } - if (lock>=0) { - if (lockStatus==0 || strcmp(lastClientIP,thisClientIP)==0 || strcmp(lastClientIP,"none")==0) { - lockStatus=lock; - - } else { - ret=FAIL; - sprintf(mess,"Server already locked by %s\n", lastClientIP); - } - } - if (differentClients && ret==OK) - ret=FORCE_UPDATE; - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else - n = sendDataOnly(file_des,&lockStatus,sizeof(lockStatus)); - - return ret; - -} - -int set_port(int file_des) { - int n; - int ret=OK; - int sd=-1; - - enum portType p_type; /** data? control? stop? Unused! */ - int p_number; /** new port number */ - - n = receiveDataOnly(file_des,&p_type,sizeof(p_type)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (ptype)\n"); - ret=FAIL; - } - - n = receiveDataOnly(file_des,&p_number,sizeof(p_number)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - printf("Error reading from socket (pnum)\n"); - ret=FAIL; - } - if (differentClients==1 && lockStatus==1 ) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - if (p_number<1024) { - sprintf(mess,"Too low port number %d\n", p_number); - printf("\n"); - ret=FAIL; - } - - printf("set port %d to %d\n",p_type, p_number); - - sd=bindSocket(p_number); - } - if (sd>=0 || sd==-10) { - ret=OK; - if (differentClients ) - ret=FORCE_UPDATE; - } else { - ret=FAIL; - sprintf(mess,"Could not bind port %d\n", p_number); - printf("Could not bind port %d\n", p_number); - - } - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&p_number,sizeof(p_number)); - if (sd>=0) { - closeConnection(file_des); - exitServer(sockfd); - sockfd=sd; - } - - } - - return ret; - -} - -int get_last_client_ip(int file_des) { - int ret=OK; - int n; - if (differentClients ) - ret=FORCE_UPDATE; - n = sendDataOnly(file_des,&ret,sizeof(ret)); - n = sendDataOnly(file_des,lastClientIP,sizeof(lastClientIP)); - - return ret; - -} - - -int send_update(int file_des) { - - int ret=OK; - enum detectorSettings t; - int thr, n; - // int it; - int64_t retval, tns=-1; - - - n = sendDataOnly(file_des,lastClientIP,sizeof(lastClientIP)); - n = sendDataOnly(file_des,&nModX,sizeof(nModX)); - // n = sendDataOnly(file_des,&nModY,sizeof(nModY)); - //sends back max modules instead of nmodulesY! - - thr = getNModBoard(); - sendDataOnly(file_des,&thr,sizeof(thr)); - - n = sendDataOnly(file_des,&dynamicRange,sizeof(dynamicRange)); - n = sendDataOnly(file_des,&dataBytes,sizeof(dataBytes)); - t=setSettings(GET_SETTINGS); - n = sendDataOnly(file_des,&t,sizeof(t)); - thr=getThresholdEnergy(); - n = sendDataOnly(file_des,&thr,sizeof(thr)); - retval=setFrames(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setExposureTime(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setPeriod(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setDelay(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setGates(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setProbes(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - retval=setTrains(tns); - n = sendDataOnly(file_des,&retval,sizeof(int64_t)); - - if (lockStatus==0) { - strcpy(lastClientIP,thisClientIP); - } - - return ret; - - -} -int update_client(int file_des) { - - int ret=OK; - - sendDataOnly(file_des,&ret,sizeof(ret)); - return send_update(file_des); - - - -} - - -int set_master(int file_des) { - - enum masterFlags retval=GET_MASTER; - enum masterFlags arg; - int n; - int ret=OK; - // int regret=OK; - - - sprintf(mess,"can't set master flags\n"); - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } - - -#ifdef VERBOSE - printf("setting master flags to %d\n",arg); -#endif - - if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - retval=setMaster(arg); - - } - if (retval==GET_MASTER) { - ret=FAIL; - } - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} - - - - - - -int set_synchronization(int file_des) { - - enum synchronizationMode retval=GET_MASTER; - enum synchronizationMode arg; - int n; - int ret=OK; - //int regret=OK; - - - sprintf(mess,"can't set synchronization mode\n"); - - - n = receiveDataOnly(file_des,&arg,sizeof(arg)); - if (n < 0) { - sprintf(mess,"Error reading from socket\n"); - ret=FAIL; - } -#ifdef VERBOSE - printf("setting master flags to %d\n",arg); -#endif - - if (differentClients==1 && lockStatus==1 && arg!=GET_READOUT_FLAGS) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } else { - //ret=setStoreInRAM(0); - // initChipWithProbes(0,0,0, ALLMOD); - retval=setSynchronization(arg); - } - if (retval==GET_SYNCHRONIZATION_MODE) { - ret=FAIL; - } - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) { - n = sendDataOnly(file_des,mess,sizeof(mess)); - } else { - n = sendDataOnly(file_des,&retval,sizeof(retval)); - } - return ret; -} diff --git a/slsDetectorSoftware/mythenDetectorServer/server_funcs.h b/slsDetectorSoftware/mythenDetectorServer/server_funcs.h deleted file mode 100755 index 7a458e9cd..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/server_funcs.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef SERVER_FUNCS_H -#define SERVER_FUNCS_H -#include -/* -#include -#include -#include -*/ -#include "communication_funcs.h" - - - - -#define GOODBYE -200 - -int sockfd; - -int function_table(); - -int decode_function(int); - -int init_detector(int); - -int M_nofunc(int); -int exit_server(int); - - - - - // General purpose functions -int get_detector_type(int); -int set_number_of_modules(int); -int get_max_number_of_modules(int); - - -int exec_command(int); -int set_external_signal_flag(int); -int set_external_communication_mode(int); -int get_id(int); -int digital_test(int); -int write_register(int); -int read_register(int); -int set_dac(int); -int get_adc(int); -int set_channel(int); -int set_chip(int); -int set_module(int); -int get_channel(int); -int get_chip(int); -int get_module(int); - -int get_threshold_energy(int); -int set_threshold_energy(int); -int set_settings(int); -int start_acquisition(int); -int stop_acquisition(int); -int start_readout(int); -int get_run_status(int); -int read_frame(int); -int read_all(int); -int start_and_read_all(int); -int set_timer(int); -int get_time_left(int); -int set_dynamic_range(int); -int set_roi(int); -int get_roi(int); -int set_speed(int); -int set_readout_flags(int); -int execute_trimming(int); -int lock_server(int); -int set_port(int); -int get_last_client_ip(int); -int set_master(int); -int set_synchronization(int); - -int update_client(int); -int send_update(int); - -#endif diff --git a/slsDetectorSoftware/mythenDetectorServer/sharedmemory.c b/slsDetectorSoftware/mythenDetectorServer/sharedmemory.c deleted file mode 100755 index 302a0308c..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/sharedmemory.c +++ /dev/null @@ -1,46 +0,0 @@ -#include "sharedmemory.h" - -struct statusdata *stdata; - -int inism(int clsv) { - -static int scansmid; - - if (clsv==SMSV) { - if ( (scansmid=shmget(SMKEY,1024,IPC_CREAT | 0666 ))==-1 ) { - return -1; - } - if ( (stdata=shmat(scansmid,NULL,0))==(void*)-1) { - return -2; - } - } - - if (clsv==SMCL) { - if ( (scansmid=shmget(SMKEY,0,0) )==-1 ) { - return -3; - } - if ( (stdata=shmat(scansmid,NULL,0))==(void*)-1) { - return -4; - } - } - return 1; -} - -void write_status_sm(char *status) { - strcpy(stdata->status,status); -} - -void write_istatus_sm(int i) { - stdata->istatus=i; -} -int read_istatus_sm() { - return stdata->istatus; -} - -void write_stop_sm(int v) { - stdata->stop=v; -} - -void write_runnumber_sm(int v) { - stdata->runnumber=v; -} diff --git a/slsDetectorSoftware/mythenDetectorServer/sharedmemory.h b/slsDetectorSoftware/mythenDetectorServer/sharedmemory.h deleted file mode 100755 index d50eb5047..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/sharedmemory.h +++ /dev/null @@ -1,52 +0,0 @@ -#ifndef SM -#define SM - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -#include - -#include -#include - -/* key for shared memory */ -#define SMKEY 10001 - -#define SMSV 1 -#define SMCL 2 - - -struct statusdata { - int runnumber; - int stop; - int istatus; - char status[20]; -} ; - - -/* for shared memory */ - -int inism(int clsv); -void write_status_sm(char *status); -void write_stop_sm(int v); -void write_runnumber_sm(int v); - -void write_istatus_sm(int v); - -int read_istatus_sm(); - -#endif diff --git a/slsDetectorSoftware/mythenDetectorServer/sls_detector_defs.h b/slsDetectorSoftware/mythenDetectorServer/sls_detector_defs.h deleted file mode 120000 index c5062e03f..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/sls_detector_defs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/mythenDetectorServer/sls_detector_funcs.h b/slsDetectorSoftware/mythenDetectorServer/sls_detector_funcs.h deleted file mode 120000 index 844b67129..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/sls_detector_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/mythenDetectorServer/sls_receiver_defs.h b/slsDetectorSoftware/mythenDetectorServer/sls_receiver_defs.h deleted file mode 120000 index 1de31caf5..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/sls_receiver_defs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/mythenDetectorServer/sls_receiver_funcs.h b/slsDetectorSoftware/mythenDetectorServer/sls_receiver_funcs.h deleted file mode 120000 index c2ea4ded9..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/sls_receiver_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../../slsReceiverSoftware/include/sls_receiver_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/mythenDetectorServer/stop_server.c b/slsDetectorSoftware/mythenDetectorServer/stop_server.c deleted file mode 100755 index 571c9a978..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/stop_server.c +++ /dev/null @@ -1,41 +0,0 @@ -/* A simple server in the internet domain using TCP - The port number is passed as an argument */ -#include "communication_funcs.h" -#include "firmware_funcs.h" - - -int sockfd; - -int main(int argc, char *argv[]) -{ - int portno; - int retval=0; - - portno = DEFAULT_PORTNO; - - - bindSocket(portno); - if (getServerError()) - return -1; - - - - /* waits for connection */ - while(retval!=GOODBYE) { -#ifdef VERBOSE - printf("\n"); -#endif -#ifdef VERY_VERBOSE - printf("Stop server: waiting for client call\n"); -#endif - acceptConnection(); - retval=stopStateMachine(); - closeConnection(); - } - - exitServer(); - printf("Goodbye!\n"); - - return 0; -} - diff --git a/slsDetectorSoftware/mythenDetectorServer/trimming_funcs.c b/slsDetectorSoftware/mythenDetectorServer/trimming_funcs.c deleted file mode 100755 index b86e9f3f4..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/trimming_funcs.c +++ /dev/null @@ -1,789 +0,0 @@ -#ifndef PICASSOD -#include "server_defs.h" -#else -#include "picasso_defs.h" -#endif -#include "trimming_funcs.h" -#include "mcb_funcs.h" -#include "firmware_funcs.h" -#include - - - -extern int nModX; -//extern int *values; - -extern const int nChans; -extern const int nChips; -extern const int nDacs; -extern const int nAdcs; - - -int trim_fixed_settings(int countlim, int par2, int im) -{ - - int retval=OK; -#ifdef VERBOSE - printf("Trimming with fixed settings\n"); -#endif -#ifdef VIRTUAL - return OK; -#endif - - if (par2<=0) - retval=trim_with_level(countlim, im); - else - retval=trim_with_median(countlim,im); - - - return retval; -} - - -int trim_with_noise(int countlim, int nsigma, int im) -{ - - - int retval1=OK, retval2=OK; -#ifdef VERBOSE - printf("Trimming using noise\n"); -#endif -#ifdef VIRTUAL - return OK; -#endif - - /* threshold scan */ - -#ifdef VERBOSE - printf("chosing vthresh and vtrim....."); -#endif - retval1=choose_vthresh_and_vtrim(countlim,nsigma, im); - -#ifdef VERBOSE - printf("trimming with noise.....\n"); -#endif - if (retval1==OK) - retval2=trim_with_level(countlim, im); - else - retval2=-1; - -#ifdef DEBUGOUT - printf("done\n"); -#endif - //if (retval1==OK && retval2==OK) - // retval=OK; - //else - // retval=FAIL; - - return retval2; - -} - -int trim_with_beam(int countlim, int nsigma, int im) //rpc -{ - - - int retval1=OK, retval2=OK; - - printf("Trimming using beam\n"); - //return OK; -#ifdef VIRTUAL - printf("Trimming using beam\n"); - return OK; -#endif - /* threshold scan */ -#ifdef DEBUGOUT - printf("chosing vthresh and vtrim....."); -#endif - - retval1=choose_vthresh_and_vtrim(countlim,nsigma,im); - if (retval1==OK) - retval2=trim_with_median(TRIM_DR, im); - else return -1; - -#ifdef DEBUGOUT - printf("done\n"); -#endif - - // if (retval1==OK && retval2==OK) - // retval=OK; - //else - // retval=FAIL; - - return retval2; - -} - - -int trim_improve(int maxit, int par2, int im) //rpc -{ - - int retval1=OK, retval2=OK; - - -#ifdef VERBOSE - printf("Improve the trimming\n"); -#endif -#ifdef VIRTUAL - return OK; -#endif - - - if (par2!=0 && im==ALLMOD) - retval1=choose_vthresh(); - if (retval1==OK) - retval2=trim_with_median(2*maxit+1, im); - else - return -1; -#ifdef DEBUGOUT - printf("done\n"); -#endif - // if (retval1==OK && retval2==OK) - // retval=OK; - //else - //retval=FAIL; - - return retval2; - -} - -int calcthr_from_vcal(int vcal) { - int thrmin; - //thrmin=140+3*vcal/5; - thrmin=180+3*vcal/5; - return thrmin; -} - -int calccal_from_vthr(int vthr) { - int vcal; - vcal=5*(vthr-140)/3; - return vcal; -} - -int choose_vthresh_and_vtrim(int countlim, int nsigma, int im) { - int retval=OK; -#ifdef MCB_FUNCS - int modma, modmi, nm; - int thr, thrstep=5, nthr=31; - - int *fifodata; - - float vthreshmean, vthreshSTDev; - int *thrmi, *thrma; - float c; - float b=BVTRIM; - float a=AVTRIM; - int *trim; - int ich, imod, ichan; - int nvalid=0; - u_int32_t *scan; - int ithr; - sls_detector_channel myChan; - - - - setFrames(1); - // setNMod(getNModBoard()); - - if (im==ALLMOD){ - modmi=0; - modma=nModX; - } else { - modmi=im; - modma=im+1; - } - nm=modma-modmi; - - trim=malloc(sizeof(int)*nChans*nChips*nModX); - thrmi=malloc(sizeof(int)*nModX); - thrma=malloc(sizeof(int)*nModX); - - - for (ich=0; ichcountlim && trim[ich]==-1) { - trim[ich]=getDACbyIndexDACU(VTHRESH,imod); -#ifdef VERBOSE - // printf("yes: %d %d %d\n",ich,ithr,scan[ich]); -#endif - } -#ifdef VERBOSE - /* else { - printf("no: %d %d %d\n",ich,ithr,scan[ich]); - }*/ -#endif - } - } - free(scan); - } - - for (imod=modmi; imodthrmi[imod] && trim[ich]0) { - vthreshmean=vthreshmean/nvalid; - vthreshSTDev=sqrt((vthreshSTDev/nvalid)-vthreshmean*vthreshmean); - } else { - vthreshmean=thrmi[imod]; - vthreshSTDev=nthr*thrstep; - printf("No valid channel for module %d\n",imod); - retval=FAIL; - } - -#ifdef DEBUGOUT - printf("module= %d nvalid = %d mean=%f RMS=%f\n",imod, nvalid, vthreshmean,vthreshSTDev); -#endif - // *vthresh=round(vthreshmean-nsigma*vthreshSTDev); - thr=(int)(vthreshmean-nsigma*vthreshSTDev); - if (thr<0 || thr>(DAC_DR-1)) { - thr=thrmi[imod]/2; - printf("Can't find correct threshold for module %d\n",imod); - retval=FAIL; - } - initDACbyIndexDACU(VTHRESH,thr,imod); -#ifdef VERBOSE - printf("vthresh=%d \n",thr); -#endif - c=CVTRIM-2.*nsigma*vthreshSTDev/63.; - thr=(int)((-b-sqrt(b*b-4*a*c))/(2*a)); - if (thr<500 || thr>(DAC_DR-1)) { - thr=750; - printf("Can't find correct trimbit size for module %d\n",imod); - retval=FAIL; - } - - initDACbyIndexDACU(VTRIM,thr,imod); - -#ifdef VERBOSE - printf("vtrim=%d \n",thr); -#endif - - } - free(trim); - free(thrmi); - free(thrma); - -#endif - return retval; -} - - - - - -int trim_with_level(int countlim, int im) { - int ich, itrim, ichan, ichip, imod; - u_int32_t *scan; - int *inttrim; - int modma, modmi, nm; - int retval=0; - int *fifodata; - sls_detector_channel myChan; - printf("trimming module number %d", im); - - -#ifdef MCB_FUNCS - setFrames(1); - // setNMod(getNModBoard()); - - if (im==ALLMOD){ - modmi=0; - modma=nModX; - } else { - modmi=im; - modma=im+1; - } - nm=modma-modmi; - - inttrim=malloc(sizeof(int)*nChips*nChans*nModX); - printf("countlim=%d\n",countlim); - for (ich=0; ichcountlim){ - inttrim[ich]=itrim; - if (scan[ich]>2*countlim && itrim>0) { - //if (scan[ich]>2*countlim || itrim==0) { - inttrim[ich]=itrim-1; - } -#ifdef VERBOSE - printf("Channel %d trimbit %d counted %d (%08x) countlim %d\n",ich,itrim,scan[ich],fifodata[ich],countlim); -#endif - } - } -#ifdef VERBOSE - /* else - printf("Channel %d trimbit %d counted %d countlim %d\n",ich,itrim,scan[ich],countlim);*/ -#endif - } - } - free(scan); - } - - for (imod=modmi; imod0) - direction[ichan]=1; - else - direction[ichan]=-1; - } - vthresh=getDACbyIndexDACU(VTHRESH,imod); - if ( direction[ichan]!=-3) { - if (abs(diff)>abs(olddiff[ichan])) { - vthresh=vthresh-direction[ichan]; - if (vthresh>(DAC_DR-1)) { - vthresh=(DAC_DR-1); - printf("can't equalize threshold for module %d\n", ichan); - retval=FAIL; - } - if (vthresh<0) { - vthresh=0; - printf("can't equalize threshold for module %d\n", ichan); - retval=FAIL; - } - direction[ichan]=-3; - } else { - vthresh=vthresh+direction[ichan]; - olddiff[ichan]=diff; - change_flag=1; - } - initDACbyIndex(VTHRESH,vthresh, ichan); - } - } - iteration++; - free(scan); - free(scan1); - } -#endif - return retval; -} - - - - - -int trim_with_median(int stop, int im) { - - - int retval=0; - -#ifdef MCB_FUNCS - int ichan, imod, ichip, ich; - u_int32_t *scan, *scan1; - int *olddiff, *direction; - int med, diff; - int change_flag=1; - int iteration=0; - int me[nModX], me1[nModX]; - int modma, modmi, nm; - int trim; - int *fifodata; - - setFrames(1); - // setNMod(getNModBoard()); - - if (im==ALLMOD){ - modmi=0; - modma=nModX; - } else { - modmi=im; - modma=im+1; - } - nm=modma-modmi; - - olddiff=malloc(4*nModX*nChips*nChans); - direction=malloc(4*nModX*nChips*nChans); - for (imod=modmi; imod0) { - direction[ichan]=1; - } else { - direction[ichan]=-1; - } - } - if ( direction[ichan]!=-3) { - if (abs(diff)>abs(olddiff[ichan])) { - trim=getTrimbit(imod,ichip,ich)+direction[ichan]; - printf("%d old diff %d < new diff %d %d - trimbit %d\n",ichan, olddiff[ichan], diff, direction[ichan], trim); - direction[ichan]=-3; - } else { - trim=getTrimbit(imod,ichip,ich)-direction[ichan]; - olddiff[ichan]=diff; - change_flag=1; - } - if (trim>TRIM_DR) { - trim=63; - printf("can't trim channel %d chip %d module %d to trim %d\n",ich, ichip, imod, trim); - retval++; - } - if (trim<0) { - printf("can't trim channel %d chip %d module %d to trim %d\n",ich, ichip, imod, trim); - trim=0; - retval++; - } - initChannel(trim,0,0,1,0,0,imod); - } - } - } - } - iteration++; - free(scan); - free(scan1); - } - free(olddiff); - free(direction); -#endif - return retval; -} diff --git a/slsDetectorSoftware/mythenDetectorServer/trimming_funcs.h b/slsDetectorSoftware/mythenDetectorServer/trimming_funcs.h deleted file mode 100755 index ac73dcaa1..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/trimming_funcs.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef TRIMMING_FUNCS_H -#define TRIMMING_FUNCS_H -int trim_fixed_settings(int countlim, int par2, int imod); -int trim_with_noise(int countlim, int nsigma, int imod); -int trim_with_beam(int countlim, int nsigma, int imod); -int trim_improve(int maxit, int par2, int imod); -int calcthr_from_vcal(int vcal); -int calccal_from_vthr(int vthr); -int choose_vthresh_and_vtrim(int countlim, int nsigma, int imod); - -int choose_vthresh(); -int trim_with_level(int countlim, int imod); -int trim_with_median(int stop, int imod); -int calcthr_from_vcal(int vcal); -int calccal_from_vthr(int vthr); -int median(int *a,int n); -#endif diff --git a/slsDetectorSoftware/mythenDetectorServer/updateGitVersion.sh b/slsDetectorSoftware/mythenDetectorServer/updateGitVersion.sh deleted file mode 100755 index 74dcf8dc4..000000000 --- a/slsDetectorSoftware/mythenDetectorServer/updateGitVersion.sh +++ /dev/null @@ -1,31 +0,0 @@ -SERVER=mythenDetectorServer -MAINDIR=slsDetectorsPackage -SPECDIR=slsDetectorSoftware/$SERVER -TMPFILE=gitInfoMythenTmp.h -INCLFILE=gitInfoMythen.h - - -#evaluate the variables -EVALFILE=../../evalVersionVariables.sh -source $EVALFILE - - -#get modified date -#RDATE1='git log --pretty=format:"%ci" -1' -RDATE1="find ../slsDetectorServer . -type f -exec stat --format '%Y :%y %n' '{}' \; | sort -nr | cut -d: -f2- | egrep -v 'gitInfo|bin|.git|updateGitVersion|.o' | head -n 1" -RDATE=`eval $RDATE1` -NEWDATE=$(sed "s/-//g" <<< $RDATE | awk '{print $1;}') -NEWDATE=${NEWDATE/#/0x} - - -#get old date from INCLFILE -OLDDATE=$(more $INCLFILE | grep '#define GITDATE' | awk '{print $3}') - - -#update INCLFILE if changes -if [ "$OLDDATE" != "$NEWDATE" ]; then - echo Path: ${MAINDIR}/${SPECDIR} $'\n'URL: ${GITREPO} $'\n'Repository Root: ${GITREPO} $'\n'Repsitory UUID: ${REPUID} $'\n'Revision: ${FOLDERREV} $'\n'Branch: ${BRANCH} $'\n'Last Changed Author: ${AUTH1}_${AUTH2} $'\n'Last Changed Rev: ${REV} $'\n'Last Changed Date: ${RDATE} > gitInfo.txt - cd ../../ - ./genVersionHeader.sh $SPECDIR/gitInfo.txt $SPECDIR/$TMPFILE $SPECDIR/$INCLFILE - cd $WD -fi \ No newline at end of file diff --git a/slsDetectorSoftware/patternGenerator/generate.sh b/slsDetectorSoftware/patternGenerator/generate.sh deleted file mode 100755 index f7aac61c4..000000000 --- a/slsDetectorSoftware/patternGenerator/generate.sh +++ /dev/null @@ -1,30 +0,0 @@ -if [ "$#" -eq 0 ]; then - echo "Wrong number of arguments: usage should be $0 patname" - exit 1 -fi -infile=$1 -outfile=$infile"at" -outfilebin=$infile"bin" -if [ "$#" -ge 2 ]; then - outfile=$2 -fi -exe=$infile"exe" -if [ "$#" -ge 4 ]; then - exe=$4 -fi - -if [ "$#" -ge 3 ]; then - outfilebin=$3 -fi - -if [ -f "$infile" ] -then -gcc -DINFILE="\"$infile\"" -DOUTFILE="\"$outfile\"" -DOUTFILEBIN="\"$outfilebin\"" -o $exe generator.c ; -echo compiling -$exe ; -echo cleaning -rm $exe -echo done -else - echo "$infile not found." -fi diff --git a/slsDetectorSoftware/patternGenerator/generator.c b/slsDetectorSoftware/patternGenerator/generator.c deleted file mode 100755 index 24b192844..000000000 --- a/slsDetectorSoftware/patternGenerator/generator.c +++ /dev/null @@ -1,162 +0,0 @@ -/**************************************************************************** -usage to generate a patter test.pat from test.p - -gcc -DINFILE="\"test.p\"" -DOUTFILE="\"test.pat\"" -o test.exe generator.c ; ./test.exe ; rm test.exe - - -*************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define MAXLOOPS 3 -#define MAXTIMERS 3 -#define MAXWORDS 1024 - - - -uint64_t pat=0; -uint64_t iopat=0; -uint64_t clkpat=0; - -int iaddr=0; -int waitaddr[3]={MAXWORDS,MAXWORDS,MAXWORDS}; -int startloopaddr[3]={MAXWORDS,MAXWORDS,MAXWORDS}; -int stoploopaddr[3]={MAXWORDS,MAXWORDS,MAXWORDS}; -int start=0, stop=0; -uint64_t waittime[3]={0,0,0}; -int nloop[3]={0,0,0}; - -char infile[10000], outfile[10000]; - -FILE *fd, *fd1; -uint64_t PAT[MAXWORDS]; - - -int i,ii,iii,j,jj,jjj,pixx,pixy,memx,memy,muxout,memclk,colclk,rowclk,muxclk,memcol,memrow,loopcounter; - -void setstart() { - start=iaddr; -} - -void setstop() { - stop=iaddr; -} - -void setinput(int bit) { - uint64_t mask=1; - mask=mask<>bit; -} - -void setstartloop(int iloop) { - if (iloop>=0 && iloop=0 && iloop=0 && iloop=0 && iloop=0 && iloop=MAXWORDS) printf("ERROR: too many word in the pattern (%d instead of %d)!",iaddr, MAXWORDS); -} - - - - -main(void) { - int iloop=0; - fd=fopen(OUTFILE,"w"); -#include INFILE - - fprintf(fd,"patioctrl %016llx\n",iopat); - fprintf(fd,"patclkctrl %016llx\n",clkpat); - fprintf(fd,"patlimits %04x %04x\n",start, stop); - - for (iloop=0; iloop -#include // printf -#include // errno -#include // strerror -#include -#include // O_CREAT, O_TRUNC.. -#include // fstat -#include // shared memory -#include -#include "stdlib.h" - -#define SHM_MULTI_PREFIX "/slsDetectorPackage_multi_" -#define SHM_SLS_PREFIX "_sls_" -#define SHM_ENV_NAME "SLSDETNAME" - -SharedMemory::SharedMemory(int multiId, int slsId): - fd(-1), - shmSize(0) -{ - name = ConstructSharedMemoryName(multiId, slsId); -} - - - -SharedMemory::~SharedMemory(){ - if (fd >= 0) - close(fd); -} - - -bool SharedMemory::IsExisting() { - bool ret = true; - int tempfd = shm_open(name.c_str(), O_RDWR, 0); - if ((tempfd < 0) && (errno == ENOENT)) { - ret = false; - } - close(tempfd); - return ret; -} - -std::string SharedMemory::GetName() { - return name; -} - - -void* SharedMemory::CreateSharedMemory(size_t sz){ - // create - fd = shm_open(name.c_str(), O_CREAT | O_TRUNC | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); - if (fd < 0) { - cprintf(RED, "Error: Create shared memory %s failed: %s\n", - name.c_str(), strerror(errno)); - throw SharedMemoryException(); - } - - // resize - if (ftruncate(fd, sz) < 0) { - cprintf(RED, "Error: Create shared memory %s failed at ftruncate: %s\n", - name.c_str(), strerror(errno)); - close(fd); - RemoveSharedMemory(); - throw SharedMemoryException(); - } - - // map - void* addr = MapSharedMemory(sz); - printf("Shared memory created %s \n", name.c_str()); - return addr; -} - -void* SharedMemory::OpenSharedMemory(size_t sz){ - // open - fd = shm_open(name.c_str(), O_RDWR, 0); - if (fd < 0) { - cprintf(RED, "Error: Open existing shared memory %s failed: %s\n", - name.c_str(), strerror(errno)); - throw SharedMemoryException(); - } - - return MapSharedMemory(sz); -} - - -void SharedMemory::UnmapSharedMemory(void* addr) { - if (munmap(addr, shmSize) < 0) { - cprintf(RED, "Error: Unmapping shared memory %s failed: %s\n", - name.c_str(), strerror(errno)); - close(fd); - throw SharedMemoryException(); - } -} - -void SharedMemory::RemoveSharedMemory() { - if (shm_unlink(name.c_str()) < 0) { - // silent exit if shm did not exist anyway - if (errno == ENOENT) - return; - cprintf(RED, "Error: Free Shared Memory %s Failed: %s\n", - name.c_str(), strerror(errno)); - throw SharedMemoryException(); - } - printf("Shared memory deleted %s \n", name.c_str()); -} - - -void* SharedMemory::MapSharedMemory(size_t sz) { - void* addr = mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - if (addr == MAP_FAILED) { - cprintf(RED, "Error: Mapping shared memory %s failed: %s\n", - name.c_str(), strerror(errno)); - close(fd); - throw SharedMemoryException(); - } - shmSize = sz; - close(fd); - return addr; -} - - -std::string SharedMemory::ConstructSharedMemoryName(int multiId, int slsId) { - - // using environment path - std::string sEnvPath = ""; - char* envpath = getenv(SHM_ENV_NAME); - if (envpath != NULL) { - sEnvPath.assign(envpath); - sEnvPath.insert(0,"_"); - } - - std::stringstream ss; - if (slsId < 0) - ss << SHM_MULTI_PREFIX << multiId << sEnvPath; - else - ss << SHM_MULTI_PREFIX << multiId << SHM_SLS_PREFIX << slsId << sEnvPath; - - std::string temp = ss.str(); - if (temp.length() > NAME_MAX) { - cprintf(RED, "Error: Shared memory initialization failed. " - "%s has %lu characters. \n" - "Maximum is %d. Change the environment variable %s\n", - temp.c_str(), temp.length(), NAME_MAX, SHM_ENV_NAME); - throw SharedMemoryException(); - } - return temp; -} - - -int SharedMemory::VerifySizeMatch(size_t expectedSize) { - struct stat sb; - // could not fstat - if (fstat(fd, &sb) < 0) { - cprintf(RED, "Error: Could not verify existing shared memory %s size match " - "(could not fstat): %s\n", name.c_str(), strerror(errno)); - close(fd); - throw SharedMemoryException(); - } - - //size does not match - long unsigned int sz = (long unsigned int)sb.st_size; - if (sz != expectedSize) { - cprintf(RED, "Warning: Existing shared memory %s size does not match.\n", - name.c_str()); -#ifdef VERBOSE - cprintf(RED, " Expected %ld, found %ld\n", expectedSize, sz); -#endif - throw SharedMemoryException(); - return 1; - } - return 0; -} - diff --git a/slsDetectorSoftware/sharedMemory/SharedMemory.h b/slsDetectorSoftware/sharedMemory/SharedMemory.h deleted file mode 100644 index ebec18606..000000000 --- a/slsDetectorSoftware/sharedMemory/SharedMemory.h +++ /dev/null @@ -1,105 +0,0 @@ -#pragma once -/************************************************ - * @file SharedMemory.h - * @short functions basic implemenation of - * shared memory - ***********************************************/ -/** - *@short functions basic implemenation of shared memory - */ - -#include -#include - -class SharedMemory{ -public: - /** - * Constructor - * creates the single/multi detector shared memory name - * @param multiId multi detector id - * @param slsId sls detector id, -1 if a multi detector shared memory - */ - SharedMemory(int multiId, int slsId); - - /** - * Destructor - */ - ~SharedMemory(); - - /** - * Verify if it exists - * @param name of shared memory - * @return true if exists, else false - */ - bool IsExisting(); - - /** - * Get shared memory name - */ - std::string GetName(); - - /** - * Create Shared memory and call MapSharedMemory to map it to an address - * throws a SharedMemoryException exception on failure to create, ftruncate or map - * @param sz of shared memory - */ - void* CreateSharedMemory(size_t sz); - - /** - * Open existing Shared memory and call MapSharedMemory to map it to an address - * throws a SharedMemoryException exception on failure to open or map - * @param sz of shared memory - */ - void* OpenSharedMemory(size_t sz); - - /** - * Unmap shared memory from an address - * throws a SharedMemoryException exception on failure - * @param addr double pointer to address to be mapped - */ - void UnmapSharedMemory(void* addr); - - /** - * Remove existing Shared memory - */ - void RemoveSharedMemory(); - - /** - * Maximum length of name as from man pages - */ - static const int NAME_MAX = 255; - -private: - /** - * Create Shared memory name - * throws exception if name created is longer than required 255(manpages) - * @param multiId multi detector id - * @param slsId sls detector id, -1 if a multi detector shared memory - * @returns shared memory name - */ - std::string ConstructSharedMemoryName(int multiId, int slsId); - - /** - * Map shared memory to an address - * throws a SharedMemoryException exception on failure - * @param sz of shared memory - */ - void* MapSharedMemory(size_t sz); - - /** - * Verify if existing shared memory size matches expected size - * @param expectedSize expected size of shared memory, replaced with smaller size if size does not match - * @return 0 for success, 1 for fail - */ - int VerifySizeMatch(size_t expectedSize); - - /** Shared memory name */ - std::string name; - - /** File descriptor */ - int fd; - - /** shm size */ - size_t shmSize; - -}; diff --git a/slsDetectorSoftware/slsADCReader/Makefile b/slsDetectorSoftware/slsADCReader/Makefile deleted file mode 100644 index ce48d2874..000000000 --- a/slsDetectorSoftware/slsADCReader/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -CC = g++ -#CC = bfin-uclinux- -SRC = slsADCReader.cpp -INCLUDES = -I ../../slsReceiverSoftware/include -I ../commonFiles -CFLAGS = -Wall -lm -lstdc++ - - -all: clean slsADCReader - - -slsADCReader: $(SRC) - echo "creating adc reader" - $(CC) -o $@ $^ $(CFLAGS) $(INCLUDES) - - -clean: - echo "cleaning" - rm -rf *.o - - - diff --git a/slsDetectorSoftware/slsADCReader/slsADCReader b/slsDetectorSoftware/slsADCReader/slsADCReader deleted file mode 100755 index 3117fc8bf..000000000 Binary files a/slsDetectorSoftware/slsADCReader/slsADCReader and /dev/null differ diff --git a/slsDetectorSoftware/slsADCReader/slsADCReader.cpp b/slsDetectorSoftware/slsADCReader/slsADCReader.cpp deleted file mode 100644 index 8d9911dee..000000000 --- a/slsDetectorSoftware/slsADCReader/slsADCReader.cpp +++ /dev/null @@ -1,120 +0,0 @@ -#include "MySocketTCP.h" - -#include "sls_detector_defs.h" -#include "sls_receiver_defs.h" - -#include "sls_detector_funcs.h" - -#include -#include - -#define INVALID -999 - -enum detectorFunctions{ - F_GET_ADC=13 -}; - -void help() { - cerr << "Usage:\n" - "slsAdcReader [hostname] [adcval]" << endl; - exit(EXIT_FAILURE); -} - - -slsDetectorDefs::dacIndex getADCEnum(char* cval){ - int idac; - string cmd; - cmd.assign(cval); - - if (sscanf(cval,"adc:%d",&idac)==1) { - return (slsDetectorDefs::dacIndex)(idac+1000); - } else if (cmd=="temp_adc") - return slsDetectorDefs::TEMPERATURE_ADC; - else if (cmd=="temp_fpga") - return slsDetectorDefs::TEMPERATURE_FPGA; - else if (cmd=="temp_fpgaext") - return slsDetectorDefs::TEMPERATURE_FPGAEXT; - else if (cmd=="temp_10ge") - return slsDetectorDefs::TEMPERATURE_10GE; - else if (cmd=="temp_dcdc") - return slsDetectorDefs::TEMPERATURE_DCDC; - else if (cmd=="temp_sodl") - return slsDetectorDefs::TEMPERATURE_SODL; - else if (cmd=="temp_sodr") - return slsDetectorDefs::TEMPERATURE_SODR; - else if (cmd=="temp_fpgafl") - return slsDetectorDefs::TEMPERATURE_FPGA2; - else if (cmd=="temp_fpgafr") - return slsDetectorDefs::TEMPERATURE_FPGA3; - else if (cmd=="i_a") - return slsDetectorDefs::I_POWER_A; - else if (cmd=="i_b") - return slsDetectorDefs::I_POWER_B; - else if (cmd=="i_c") - return slsDetectorDefs::I_POWER_C; - else if (cmd=="i_d") - return slsDetectorDefs::I_POWER_D; - else if (cmd=="vm_a") - return slsDetectorDefs::V_POWER_A; - else if (cmd=="vm_b") - return slsDetectorDefs::V_POWER_B; - else if (cmd=="vm_c") - return slsDetectorDefs::V_POWER_C; - else if (cmd=="vm_d") - return slsDetectorDefs::V_POWER_D; - else if (cmd=="vm_io") - return slsDetectorDefs::V_POWER_IO; - else if (cmd=="i_io") - return slsDetectorDefs::I_POWER_IO; - else { - cerr << "cannot decode dac " << cmd << endl; - help(); - return slsDetectorDefs::I_POWER_IO; - } -}; - - - -int main(int argc, char* argv[]) -{ - if (argc < 3) - help(); - slsDetectorDefs::dacIndex idx=getADCEnum(argv[2]); - - - char mess[MAX_STR_LENGTH]=""; - detectorFunctions fnum=F_GET_ADC; - int retval=-1; - int ret=slsReceiverDefs::FAIL; - int arg[2]={idx,0}; - - MySocketTCP* mySocket = 0; - - try { - mySocket = new MySocketTCP(argv[1],1952); - } catch (...) { - cerr << "could not create socket with " << argv[1] << endl; - help(); - } - - if (mySocket->Connect()) { - mySocket->SendDataOnly(&fnum, sizeof(fnum)); - mySocket->SendDataOnly(arg,sizeof(arg)); - mySocket->ReceiveDataOnly(&ret, sizeof(ret)); - if (ret != slsReceiverDefs::FAIL) { - mySocket->ReceiveDataOnly(&retval, sizeof(retval)); - } else { - mySocket->ReceiveDataOnly(mess,sizeof(mess)); - printf("Detector returned Error: %s",mess); - } - mySocket->Disconnect(); - } else - cerr << "could not connect to " << argv[1] << endl; - - if (idx <= 100) { - printf("%.2f°C\n",(double)retval/1000.00); - }else - printf("%dmV\n",retval); - - return EXIT_SUCCESS; -} diff --git a/slsDetectorSoftware/slsDetector/gitInfoLib.h b/slsDetectorSoftware/slsDetector/gitInfoLib.h deleted file mode 100644 index 3c32a944b..000000000 --- a/slsDetectorSoftware/slsDetector/gitInfoLib.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "git@github.com:slsdetectorgroup/slsDetectorPackage.git" -#define GITREPUUID "907d1655d1f6cf2bb8cf6ccd7e91e82f479dd2ca" -#define GITAUTH "Dhanya_Thattil" -#define GITREV 0x4101 -#define GITDATE 0x20190211 -#define GITBRANCH "developer" diff --git a/slsDetectorSoftware/slsDetector/gitInfoLibTmp.h b/slsDetectorSoftware/slsDetector/gitInfoLibTmp.h deleted file mode 100644 index dfd9bb246..000000000 --- a/slsDetectorSoftware/slsDetector/gitInfoLibTmp.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "" -#define GITREPUUID "" -#define GITAUTH "" -#define GITREV "" -#define GITDATE "" -#define GITBRANCH "" diff --git a/slsDetectorSoftware/slsDetector/slsDetector.cpp b/slsDetectorSoftware/slsDetector/slsDetector.cpp deleted file mode 100644 index 24d435720..000000000 --- a/slsDetectorSoftware/slsDetector/slsDetector.cpp +++ /dev/null @@ -1,10177 +0,0 @@ -#include "slsDetector.h" -#include "multiSlsDetector.h" -#include "sls_receiver_exceptions.h" -#include "SharedMemory.h" -#include "receiverInterface.h" -#include "gitInfoLib.h" -#include "versionAPI.h" -#include "usersFunctions.h" -#include "slsDetectorCommand.h" -#include "postProcessingFuncs.h" - - -#include -#include -#include -#include -#include -#include -#include - - -using namespace std; - - -slsDetector::slsDetector(detectorType type, int multiId, int id, bool verify, multiSlsDetector* m) -: slsDetectorUtils(), - detId(id), - sharedMemory(0), - thisDetector(0), - multiDet(m), - thisReceiver(0), - controlSocket(0), - stopSocket(0), - dataSocket(0), - ffcoefficients(0), - fferrors(0), - detectorModules(0), - dacs(0), - adcs(0), - chipregs(0), - chanregs(0), - gain(0), - offset(0) { - /* called from put hostname command, - * so sls shared memory will be created */ - - // ensure shared memory was not created before - SharedMemory* shm = new SharedMemory(multiId, id); - if (shm->IsExisting()) { - cprintf(YELLOW BOLD,"Warning: Weird, this shared memory should have been " - "deleted before! %s. Freeing it again.\n", shm->GetName().c_str()); - freeSharedMemory(multiId, id); - } - delete shm; - - initSharedMemory(true, type, multiId, verify); - initializeDetectorStructure(type); - initializeMembers(); - initializeDetectorStructurePointers(); -} - -slsDetector::slsDetector(int multiId, int id, bool verify, multiSlsDetector* m) -: slsDetectorUtils(), - detId(id), - sharedMemory(0), - thisDetector(0), - multiDet(m), - thisReceiver(0), - controlSocket(0), - stopSocket(0), - dataSocket(0), - ffcoefficients(0), - fferrors(0), - detectorModules(0), - dacs(0), - adcs(0), - chipregs(0), - chanregs(0), - gain(0), - offset(0) { - /* called from multi constructor to populate structure, - * so sls shared memory will be opened, not created */ - - // getDetectorType Froom shm will check if it was already existing - detectorType type = getDetectorTypeFromShm(multiId, verify); - - initSharedMemory(false, type, multiId, verify); - initializeMembers(); -} - -slsDetector::~slsDetector() { - if (sharedMemory) { - sharedMemory->UnmapSharedMemory(thisDetector); - delete sharedMemory; - } - if(thisReceiver) - delete thisReceiver; - if(controlSocket) - delete controlSocket; - if(stopSocket) - delete stopSocket; - if(dataSocket) - delete dataSocket; - - /* detectorModules, dacs..ffoerrors are offsets from the - * shared memory and created within shared memory structure. - * Deleting shared memory will also delete memory pointed to - * by these pointers - */ -} - - -bool slsDetector::isMultiSlsDetectorClass() { - return false; -} - - -double* slsDetector::decodeData(int *datain, int &nn, double *fdata) { - - double *dataout = 0; - if (fdata) { - dataout=fdata; - nn=thisDetector->nChans*thisDetector->nChips*thisDetector->nMods; - if (thisDetector->myDetectorType == JUNGFRAUCTB) - nn=thisDetector->dataBytes/2; - } else { - if (thisDetector->myDetectorType == JUNGFRAUCTB) { - nn=thisDetector->dataBytes/2; - dataout=new double[nn]; - } else { - dataout=new double[thisDetector->nChans*thisDetector->nChips*thisDetector->nMods]; - nn=thisDetector->nChans*thisDetector->nChips*thisDetector->nMods; - } - } - - int ival = 0, ipos = 0, ichan=0, ibyte = 0; - char *ptr = (char*)datain; - char iptr = 0; - int nbits=thisDetector->dynamicRange; - int nch=thisDetector->nChans*thisDetector->nChips*thisDetector->nMods; - - if (thisDetector->timerValue[PROBES_NUMBER]==0) { - if (thisDetector->myDetectorType==JUNGFRAUCTB) { - for (ichan=0; ichandataBytes; ++ibyte) { - iptr=ptr[ibyte]; - for (ipos=0; ipos<8; ++ipos) { - ival=(iptr>>(ipos))&0x1; - dataout[ichan]=ival; - ++ichan; - } - } - break; - case 4: - for (ibyte=0; ibytedataBytes; ++ibyte) { - iptr=ptr[ibyte]; - for (ipos=0; ipos<2; ++ipos) { - ival=(iptr>>(ipos*4))&0xf; - dataout[ichan]=ival; - ++ichan; - } - } - break; - case 8: - for (ichan=0; ichandataBytes; ++ichan) { - ival=ptr[ichan]&0xff; - dataout[ichan]=ival; - } - break; - case 16: - for (ichan=0; ichanmyDetectorType == MYTHEN) mask=0xffffff; - for (ichan=0; ichangetNumberOfDetectors();++i){ - multiDet->setErrorMask(multiDet->getErrorMask()|(0<setAcquiringFlag(b); -} - -bool slsDetector::getAcquiringFlag() { - return multiDet->getAcquiringFlag(); -} - - -bool slsDetector::isAcquireReady() { - return multiDet->isAcquireReady(); -} - - -int slsDetector::checkVersionCompatibility(portType t) { - int fnum = F_CHECK_VERSION; - if (t == DATA_PORT) - fnum = F_RECEIVER_CHECK_VERSION; - int ret = FAIL; - char mess[MAX_STR_LENGTH]; - memset(mess, 0, MAX_STR_LENGTH); - int64_t arg = 0; - - // detector - if (t == CONTROL_PORT) { - - switch (thisDetector->myDetectorType) { - case EIGER: arg = APIEIGER; break; - case JUNGFRAU: arg = APIJUNGFRAU; break; - case GOTTHARD: arg = APIGOTTHARD; break; - default: - std::cout<< "Check version compatibility is not implemented for this " - "detector" << std::endl; - setErrorMask((getErrorMask())|(VERSION_COMPATIBILITY)); - return FAIL; - } - -#ifdef VERBOSE - std::cout<< std::endl<< "Checking version compatibility with detector with " - "value " << hex << arg << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - // control port - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&arg,sizeof(arg)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - cprintf(RED, "Detector returned error: (Control Server) %s", mess); - if(strstr(mess,"Unrecognized Function")!=NULL) - std::cout << "The detector server is too old to get API version. " - "Please update detector server!" << std::endl; - setErrorMask((getErrorMask())|(VERSION_COMPATIBILITY)); - thisDetector->detectorControlAPIVersion = 0; - } else { - thisDetector->detectorControlAPIVersion = arg; - } - disconnectControl(); - } - if (ret!= FAIL) { - ret = FAIL; - - // stop port - if (connectStop() == OK){ - stopSocket->SendDataOnly(&fnum,sizeof(fnum)); - stopSocket->SendDataOnly(&arg,sizeof(arg)); - stopSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) { - stopSocket->ReceiveDataOnly(mess,sizeof(mess)); - cprintf(RED, "Detector returned error: (Stop Server) %s", mess); - if(strstr(mess,"Unrecognized Function")!=NULL) - std::cout << "The detector server is too old to get API " - "version. Please update detector server!" << std::endl; - setErrorMask((getErrorMask())|(VERSION_COMPATIBILITY)); - thisDetector->detectorStopAPIVersion = 0; - } else { - thisDetector->detectorStopAPIVersion = arg; - } - disconnectStop(); - } - } - } - } - - // receiver - else { - arg = APIRECEIVER; -#ifdef VERBOSE - std::cout<< std::endl<< "Checking version compatibility with receiver with " - "value " << hex << arg << std::endl; -#endif - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG) { - // data port - if (connectData() == OK){ - // ignoring retval - int64_t retval = -1; - ret=thisReceiver->sendInt(fnum,retval,arg); - if (ret==FAIL){ - setErrorMask((getErrorMask())|(VERSION_COMPATIBILITY)); - if(strstr(mess,"Unrecognized Function")!=NULL) - std::cout << "The receiver software is too old to get API " - "version. Please update receiver software!" << std::endl; - thisDetector->receiverAPIVersion = 0; - } else { - thisDetector->receiverAPIVersion = arg; - } - disconnectData(); - } - } - } - - return ret; -} - - - - -int64_t slsDetector::getId( idMode mode, int imod) { - - int64_t retval=-1; - int fnum=F_GET_ID,fnum2 = F_GET_RECEIVER_ID; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - -#ifdef VERBOSE - std::cout<< std::endl; - if (mode==MODULE_SERIAL_NUMBER) - std::cout<< "Getting id of "<< imod << std::endl; - else - std::cout<< "Getting id type "<< mode << std::endl; -#endif - if (mode==THIS_SOFTWARE_VERSION) { - ret=OK; - retval=GITDATE; - } else if (mode==RECEIVER_VERSION) { - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG) { - if (connectData() == OK){ - ret=thisReceiver->getInt(fnum2,retval); - disconnectData(); - } - if(ret==FORCE_UPDATE) - ret=updateReceiver(); - } - } else { - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() != OK) - ret = FAIL; - else{ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&mode,sizeof(mode)); - if (mode==MODULE_SERIAL_NUMBER) - controlSocket->SendDataOnly(&imod,sizeof(imod)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - } - if (ret==FAIL) { - std::cout<< "Get id failed " << std::endl; - return ret; - } else { -#ifdef VERBOSE - if (mode==MODULE_SERIAL_NUMBER) - std::cout<< "Id of "<< imod <<" is " << hex <RemoveSharedMemory(); - delete shm; -} - -void slsDetector::freeSharedMemory() { - if (sharedMemory) { - sharedMemory->UnmapSharedMemory(thisDetector); - sharedMemory->RemoveSharedMemory(); - delete sharedMemory; - sharedMemory = 0; - } - thisDetector = 0; -} - -string slsDetector::getUserDetails() { - cprintf(RED, "Error: Get User details should not be called at this level\n"); - return string(""); -} - -void slsDetector::setHostname(const char *name) { - setTCPSocket(string(name)); - if (thisDetector->onlineFlag == ONLINE_FLAG) - updateDetector(); -} - -string slsDetector::getHostname(int pos) { - return string(thisDetector->hostname); -} - -void slsDetector::addMultipleDetectors(const char* name) { - cprintf(RED, "Error: Add Multiple Detectors should not be called at this level\n"); -} - -/* - * pre: sharedMemory=0, thisDetector = 0 - * exceptions are caught in calling function, shm unmapped and deleted - */ -void slsDetector::initSharedMemory(bool created, detectorType type, int multiId, - bool verify) { - try { - // calculate shared memory size - int sz = calculateSharedMemorySize(type); - - // shared memory object with name - sharedMemory = new SharedMemory(multiId, detId); - - // create - if (created) { - thisDetector = (sharedSlsDetector*)sharedMemory->CreateSharedMemory(sz); - } - // open and verify version - else { - thisDetector = (sharedSlsDetector*)sharedMemory->OpenSharedMemory(sz); - if (verify && thisDetector->shmversion != SLS_SHMVERSION) { - cprintf(RED, "Single shared memory (%d-%d:)version mismatch " - "(expected 0x%x but got 0x%x)\n", - multiId, detId, SLS_SHMVERSION, - thisDetector->shmversion); - throw SharedMemoryException(); - } - } - } catch(...) { - if (sharedMemory) { - // unmap - if (thisDetector) { - sharedMemory->UnmapSharedMemory(thisDetector); - thisDetector = 0; - } - // delete - delete sharedMemory; - sharedMemory = 0; - } - throw; - } -} - - -void slsDetector::setDetectorSpecificParameters(detectorType type, detParameterList& list) { - switch (type) { - case MYTHEN: - list.nModMaxX = 24; - list.nModMaxY = 1; - list.nChanX = 128; - list.nChanY = 1; - list.nChipX = 10; - list.nChipY = 1; - list.nDacs = 6; - list.nAdcs = 0; - list.nGain = 0; - list.nOffset = 0; - list.dynamicRange = 24; - list.moveFlag = 1; - list.nGappixelsX = 0; - list.nGappixelsY = 0; - break; - case PICASSO: /** is this needed?*/ - list.nModMaxX = 24; - list.nModMaxY = 1; - list.nChanX = 128; - list.nChanY = 1; - list.nChipX = 12; - list.nChipY = 1; - list.nDacs = 6; - list.nAdcs = 0; - list.nGain = 0; - list.nOffset = 0; - list.dynamicRange = 24; - list.moveFlag = 0; - list.nGappixelsX = 0; - list.nGappixelsY = 0; - break; - case GOTTHARD: - list.nModMaxX = 1; - list.nModMaxY = 1; - list.nChanX = 128; - list.nChanY = 1; - list.nChipX = 10; - list.nChipY = 1; - list.nDacs = 8; - list.nAdcs = 5; - list.nGain = 0; - list.nOffset = 0; - list.dynamicRange = 16; - list.moveFlag = 0; - list.nGappixelsX = 0; - list.nGappixelsY = 0; - break; - case PROPIX: - list.nModMaxX = 1; - list.nModMaxY = 1; - list.nChanX = 22; - list.nChanY = 22; - list.nChipX = 1; - list.nChipY = 1; - list.nDacs = 8; - list.nAdcs = 5; - list.nGain = 0; - list.nOffset = 0; - list.dynamicRange = 16; - list.moveFlag = 0; - list.nGappixelsX = 0; - list.nGappixelsY = 0; - break; - case MOENCH: - list.nModMaxX = 1; - list.nModMaxY = 1; - list.nChanX = 160; - list.nChanY = 160; - list.nChipX = 1; - list.nChipY = 1; - list.nDacs = 8; - list.nAdcs = 1; - list.nGain = 0; - list.nOffset = 0; - list.dynamicRange = 16; - list.moveFlag = 0; - list.nGappixelsX = 0; - list.nGappixelsY = 0; - break; - case JUNGFRAU: - list.nModMaxX = 1; - list.nModMaxY = 1; - list.nChanX = 256; - list.nChanY = 256; - list.nChipX = 4; - list.nChipY = 2; - list.nDacs = 16; - list.nAdcs = 0; - list.nGain = 0; - list.nOffset = 0; - list.dynamicRange = 16; - list.moveFlag = 0; - list.nGappixelsX = 0; - list.nGappixelsY = 0; - break; - case JUNGFRAUCTB: - list.nModMaxX = 1; - list.nModMaxY = 1; - list.nChanX = 36; - list.nChanY = 1; - list.nChipX = 1; - list.nChipY = 1; - list.nDacs = 16; - list.nAdcs = 9;//???? When calculating size, only d+a=16 how come?FIXME - list.nGain = 0; - list.nOffset = 0; - list.dynamicRange =16; - list.moveFlag = 0; - list.nGappixelsX = 0; - list.nGappixelsY = 0; - break; - case EIGER: - list.nModMaxX = 1; - list.nModMaxY = 1; - list.nChanX = 256; - list.nChanY = 256; - list.nChipX = 4; - list.nChipY = 1; - list.nDacs = 16; - list.nAdcs = 0; - list.nGain = 0; // can be set back to 4 in case we require it again - list.nOffset = 0; // can be set back to 4 in case we require it again - list.dynamicRange = 16; - list.moveFlag = 0; - list.nGappixelsX = 6; - list.nGappixelsY = 1; - break; - default: - cprintf(RED,"Unknown detector type!\n"); - throw exception(); - } -} - - -int slsDetector::calculateSharedMemorySize(detectorType type) { - // get the detector parameters based on type - detParameterList detlist; - setDetectorSpecificParameters(type, detlist); - int nm = detlist.nModMaxX * detlist.nModMaxY; - int nch = detlist.nChanX * detlist.nChanY; - int nc = detlist.nChipX * detlist.nChipY; - int nd = detlist.nDacs + detlist.nAdcs; - int ng = detlist.nGain; - int no = detlist.nOffset; - - /** The size of the shared memory is - * size of shared structure + - * ffcoefficents+fferrors+modules+dacs+adcs+chips+chans+gain+offset */ - int sz = sizeof(sharedSlsDetector) + - nm * ( - 2 * nch * nc * sizeof(double) + - sizeof(sls_detector_module) + - sizeof(int) * nc + - sizeof(dacs_t) * nd + - sizeof(int) * nch * nc + - sizeof(int) * ng + - sizeof(int) * no); -#ifdef VERBOSE - std::cout<<"Size of shared memory is " << sz << std::endl; -#endif - return sz; -} - - -void slsDetector::initializeDetectorStructure(detectorType type) { - thisDetector->shmversion = SLS_SHMVERSION; - thisDetector->onlineFlag = OFFLINE_FLAG; - thisDetector->stoppedFlag = 0; - strncpy(thisDetector->hostname, DEFAULT_HOSTNAME, MAX_STR_LENGTH-1); - thisDetector->hostname[MAX_STR_LENGTH-1] = 0; - thisDetector->offset[X] = 0; - thisDetector->offset[Y] = 0; - thisDetector->controlPort = DEFAULT_PORTNO; - thisDetector->stopPort = DEFAULT_PORTNO + 1; - thisDetector->myDetectorType = type; - strncpy(thisDetector->settingsDir, getenv("HOME"), MAX_STR_LENGTH-1); - thisDetector->settingsDir[MAX_STR_LENGTH-1] = 0; - strncpy(thisDetector->calDir, getenv("HOME"), MAX_STR_LENGTH-1); - thisDetector->calDir[MAX_STR_LENGTH-1] = 0; - thisDetector->nTrimEn = 0; - for(int i = 0; i < MAX_TRIMEN; ++i) - thisDetector->trimEnergies[i] = 0; - thisDetector->progressIndex = 0; - thisDetector->totalProgress = 1; - strcpy(thisDetector->filePath, "/"); - thisDetector->correctionMask = 0; - thisDetector->threadedProcessing = 1; - thisDetector->tDead = 0; - strncpy(thisDetector->flatFieldDir, getenv("HOME"), MAX_STR_LENGTH-1); - thisDetector->flatFieldDir[MAX_STR_LENGTH-1] = 0; - strcpy(thisDetector->flatFieldFile, "none"); - thisDetector->nBadChans = 0; - strcpy(thisDetector->badChanFile, "none"); - thisDetector->nBadFF = 0; - for (int i = 0; i < MAX_BADCHANS; ++i) { - thisDetector->badChansList[i] = 0; - thisDetector->badFFList[i] = 0; - } - strcpy(thisDetector->angConvFile, "none"); - memset(thisDetector->angOff, 0, MAXMODS * sizeof(angleConversionConstant)); - thisDetector->angDirection = 1; - thisDetector->fineOffset = 0; - thisDetector->globalOffset = 0; - thisDetector->numberOfPositions = 0; - for (int i = 0; i < MAXPOS; ++i) { - thisDetector->detPositions[i] = 0; - } - thisDetector->binSize = 0.001; - thisDetector->nROI = 0; - memset(thisDetector->roiLimits, 0, MAX_ROIS * sizeof(ROI)); - thisDetector->roFlags = NORMAL_READOUT; - strcpy(thisDetector->settingsFile, "none"); - thisDetector->currentSettings = UNINITIALIZED; - thisDetector->currentThresholdEV = -1; - thisDetector->timerValue[FRAME_NUMBER] = 1; - thisDetector->timerValue[ACQUISITION_TIME] = 0; - thisDetector->timerValue[FRAME_PERIOD] = 0; - thisDetector->timerValue[DELAY_AFTER_TRIGGER] = 0; - thisDetector->timerValue[GATES_NUMBER] = 0; - thisDetector->timerValue[PROBES_NUMBER] = 0; - thisDetector->timerValue[CYCLES_NUMBER] = 1; - thisDetector->timerValue[ACTUAL_TIME] = 0; - thisDetector->timerValue[MEASUREMENT_TIME] = 0; - thisDetector->timerValue[PROGRESS] = 0; - thisDetector->timerValue[MEASUREMENTS_NUMBER] = 1; - thisDetector->timerValue[FRAMES_FROM_START] = 0; - thisDetector->timerValue[FRAMES_FROM_START_PG] = 0; - thisDetector->timerValue[SAMPLES_JCTB] = 1; - thisDetector->timerValue[SUBFRAME_ACQUISITION_TIME] = 0; - thisDetector->timerValue[STORAGE_CELL_NUMBER] = 0; - thisDetector->timerValue[SUBFRAME_DEADTIME] = 0; - thisDetector->actionMask = 0; - for (int i = 0; i < MAX_ACTIONS; ++i) { - strcpy(thisDetector->actionScript[i], "none"); - strcpy(thisDetector->actionParameter[i], "none"); - } - for (int i = 0; i < MAX_SCAN_LEVELS; ++i) { - thisDetector->scanMode[i] = 0; - strcpy(thisDetector->scanScript[i], "none"); - strcpy(thisDetector->scanParameter[i], "none"); - thisDetector->nScanSteps[i] = 0; - { - double initValue = 0; - std::fill_n(thisDetector->scanSteps[i], MAX_SCAN_STEPS, initValue); - } - thisDetector->scanPrecision[i] = 0; - } - strcpy(thisDetector->receiver_hostname, "none"); - thisDetector->receiverTCPPort = DEFAULT_PORTNO+2; - thisDetector->receiverUDPPort = DEFAULT_UDP_PORTNO; - thisDetector->receiverUDPPort2 = DEFAULT_UDP_PORTNO + 1; - strcpy(thisDetector->receiverUDPIP, "none"); - strcpy(thisDetector->receiverUDPMAC, "none"); - strncpy(thisDetector->detectorMAC, DEFAULT_DET_MAC, MAX_STR_LENGTH-1); - thisDetector->detectorMAC[MAX_STR_LENGTH-1] = 0; - strncpy(thisDetector->detectorIP, DEFAULT_DET_IP, MAX_STR_LENGTH-1); - thisDetector->detectorIP[MAX_STR_LENGTH-1] = 0; - thisDetector->receiverOnlineFlag = OFFLINE_FLAG; - thisDetector->tenGigaEnable = 0; - thisDetector->flippedData[X] = 0; - thisDetector->flippedData[Y] = 0; - thisDetector->zmqport = DEFAULT_ZMQ_CL_PORTNO + - (detId * ((thisDetector->myDetectorType == EIGER) ? 2 : 1)); - thisDetector->receiver_zmqport = DEFAULT_ZMQ_RX_PORTNO + - (detId * ((thisDetector->myDetectorType == EIGER) ? 2 : 1)); - thisDetector->receiver_upstream = false; - thisDetector->receiver_read_freq = 0; - memset(thisDetector->zmqip, 0, MAX_STR_LENGTH); - memset(thisDetector->receiver_zmqip, 0, MAX_STR_LENGTH); - thisDetector->gappixels = 0; - memset(thisDetector->receiver_additionalJsonHeader, 0, MAX_STR_LENGTH); - thisDetector->receiver_framesPerFile = -1; - thisDetector->detectorControlAPIVersion = 0; - thisDetector->detectorStopAPIVersion = 0; - thisDetector->receiverAPIVersion = 0; - thisDetector->receiver_frameDiscardMode = NO_DISCARD; - thisDetector->receiver_framePadding = 1; - thisDetector->activated = true; - thisDetector->receiver_deactivatedPaddingEnable = true; - thisDetector->receiver_silentMode = false; - - // get the detector parameters based on type - detParameterList detlist; - setDetectorSpecificParameters(type, detlist); - thisDetector->nModMax[X] = detlist.nModMaxX; - thisDetector->nModMax[Y] = detlist.nModMaxY; - thisDetector->nChan[X] = detlist.nChanX; - thisDetector->nChan[Y] = detlist.nChanY; - thisDetector->nChip[X] = detlist.nChipX; - thisDetector->nChip[Y] = detlist.nChipY; - thisDetector->nDacs = detlist.nDacs; - thisDetector->nAdcs = detlist.nAdcs; - thisDetector->nGain = detlist.nGain; - thisDetector->nOffset = detlist.nOffset; - thisDetector->dynamicRange = detlist.dynamicRange; - thisDetector->moveFlag = detlist.moveFlag; - thisDetector->nGappixels[X] = detlist.nGappixelsX; - thisDetector->nGappixels[Y] = detlist.nGappixelsY; - - - // derived parameters - thisDetector->nModsMax = thisDetector->nModMax[X] * thisDetector->nModMax[Y]; - thisDetector->nChans = thisDetector->nChan[X] * thisDetector->nChan[Y]; - thisDetector->nChips = thisDetector->nChip[X] * thisDetector->nChip[Y]; - // number of modules is initally the maximum number of modules - thisDetector->nMod[X] = thisDetector->nModMax[X]; - thisDetector->nMod[Y] = thisDetector->nModMax[Y]; - thisDetector->nMods = thisDetector->nModsMax; - - // calculating databytes - thisDetector->dataBytes = thisDetector->nMods * thisDetector->nChips * - thisDetector->nChans * thisDetector->dynamicRange/8; - thisDetector->dataBytesInclGapPixels = - (thisDetector->nMod[X] * thisDetector->nChip[X] * thisDetector->nChan[X] + - thisDetector->gappixels * thisDetector->nGappixels[X]) * - (thisDetector->nMod[Y] * thisDetector->nChip[Y] * thisDetector->nChan[Y] + - thisDetector->gappixels * thisDetector->nGappixels[Y]) * - thisDetector->dynamicRange/8; - - // special for jctb and mythen in 24 bit/ with probes - if(thisDetector->myDetectorType==JUNGFRAUCTB){ - getTotalNumberOfChannels(); - } - else if(thisDetector->myDetectorType == MYTHEN){ - if (thisDetector->dynamicRange == 24 || thisDetector->timerValue[PROBES_NUMBER] > 0) { - thisDetector->dataBytes = thisDetector->nMods * thisDetector->nChips * - thisDetector->nChans * 4; - thisDetector->dataBytesInclGapPixels = - (thisDetector->nMod[X] * thisDetector->nChip[X] * thisDetector->nChan[X] + - thisDetector->gappixels * thisDetector->nGappixels[X]) * - (thisDetector->nMod[Y] * thisDetector->nChip[Y] * - thisDetector->nChan[Y] + - thisDetector->gappixels * thisDetector->nGappixels[Y]) * - 4; - } - } - - /** calculates the memory offsets for - * flat field coefficients and errors, - * module structures, dacs, adcs, chips and channels */ - thisDetector->ffoff = sizeof(sharedSlsDetector); - thisDetector->fferroff = thisDetector->ffoff + sizeof(double) * - thisDetector->nChans * thisDetector->nChips * thisDetector->nModsMax; - thisDetector->modoff = thisDetector->fferroff + sizeof(double) * - thisDetector->nChans * thisDetector->nChips * thisDetector->nModsMax; - thisDetector->dacoff = thisDetector->modoff + - sizeof(sls_detector_module) * thisDetector->nModsMax; - thisDetector->adcoff = thisDetector->dacoff + - sizeof(dacs_t) * thisDetector->nDacs * thisDetector->nModsMax; - thisDetector->chipoff = thisDetector->adcoff + - sizeof(dacs_t) * thisDetector->nAdcs * thisDetector->nModsMax; - thisDetector->chanoff = thisDetector->chipoff + - sizeof(int) * thisDetector->nChips * thisDetector->nModsMax; - thisDetector->gainoff = thisDetector->chanoff + - sizeof(int) * thisDetector->nGain * thisDetector->nModsMax; - thisDetector->offsetoff = thisDetector->gainoff + - sizeof(int) * thisDetector->nOffset * thisDetector->nModsMax; - -} - - -void slsDetector::initializeMembers() { - // slsdetector - // assign addresses - char *goff = (char*)thisDetector; - ffcoefficients = (double*)(goff + thisDetector->ffoff); - fferrors = (double*)(goff + thisDetector->fferroff); - detectorModules = (sls_detector_module*)(goff + thisDetector->modoff); - dacs = (dacs_t*)(goff + thisDetector->dacoff); - adcs = (dacs_t*)(goff + thisDetector->adcoff); - chipregs = (int*)(goff + thisDetector->chipoff); - chanregs = (int*)(goff + thisDetector->chanoff); - gain = (int*)(goff + thisDetector->gainoff); - offset = (int*)(goff + thisDetector->offsetoff); - if (thisReceiver) { - delete thisReceiver; - thisReceiver = 0; - } - thisReceiver = new receiverInterface(dataSocket); - - - // slsDetectorUtils - stoppedFlag = &thisDetector->stoppedFlag; - timerValue = thisDetector->timerValue; - currentSettings = &thisDetector->currentSettings; - currentThresholdEV = &thisDetector->currentThresholdEV; - - // fileIO - filePath = thisDetector->filePath; - fileName=multiDet->fileName; - fileIndex=multiDet->fileIndex; - framesPerFile=multiDet->framesPerFile; - fileFormatType=multiDet->fileFormatType; - - if (thisDetector->myDetectorType != MYTHEN) - fileIO::setFileFormat(BINARY); - switch(thisDetector->myDetectorType) { - case GOTTHARD: - case PROPIX: - fileIO::setFramesPerFile(MAX_FRAMES_PER_FILE); - break; - case EIGER: - fileIO::setFramesPerFile(EIGER_MAX_FRAMES_PER_FILE); - break; - case MOENCH: - fileIO::setFramesPerFile(MOENCH_MAX_FRAMES_PER_FILE); - break; - case JUNGFRAU: - fileIO::setFramesPerFile(JFRAU_MAX_FRAMES_PER_FILE); - break; - case JUNGFRAUCTB: - fileIO::setFramesPerFile(JFRAU_MAX_FRAMES_PER_FILE); - break; - default: - break; - } - - - //postProcessing - threadedProcessing = &thisDetector->threadedProcessing; - correctionMask = &thisDetector->correctionMask; - flatFieldDir = thisDetector->flatFieldDir; - flatFieldFile = thisDetector->flatFieldFile; - expTime = &timerValue[ACQUISITION_TIME]; - badChannelMask = NULL; - fdata = NULL; - thisData = NULL; - - - // slsDetectorActions - actionMask = &thisDetector->actionMask; - actionScript = thisDetector->actionScript; - actionParameter = thisDetector->actionParameter; - nScanSteps = thisDetector->nScanSteps; - scanSteps = thisDetector->scanSteps; - scanMode = thisDetector->scanMode; - scanPrecision = thisDetector->scanPrecision; - scanScript = thisDetector->scanScript; - scanParameter = thisDetector->scanParameter; - - // angularConversion - numberOfPositions = &thisDetector->numberOfPositions; - detPositions = thisDetector->detPositions; - angConvFile = thisDetector->angConvFile; - binSize = &thisDetector->binSize; - fineOffset = &thisDetector->fineOffset; - globalOffset = &thisDetector->globalOffset; - angDirection = &thisDetector->angDirection; - moveFlag = &thisDetector->moveFlag; - sampleDisplacement = NULL; - - // badChannelCorrections - badChanFile = thisDetector->badChanFile; - nBadChans = &thisDetector->nBadChans; - badChansList = thisDetector->badChansList; - nBadFF = &thisDetector->nBadFF; - badFFList = thisDetector->badFFList; - - //energyConversion - settingsFile = thisDetector->settingsFile; -} - - - - -void slsDetector::initializeDetectorStructurePointers() { - sls_detector_module* thisMod; - for (int imod = 0; imod < thisDetector->nModsMax; ++imod) { - - // initializes the ffcoefficients values to 0 - for (int i = 0; i < thisDetector->nChans * thisDetector->nChips; ++i) { - *(ffcoefficients + i + thisDetector->nChans * thisDetector->nChips * imod) = 0; - } - // initializes the fferrors values to 0 - for (int i = 0; i < thisDetector->nChans * thisDetector->nChips; ++i) { - *(fferrors + i + thisDetector->nChans * thisDetector->nChips * imod) = 0; - } - // set thisMod to point to one of the detector structure modules - thisMod = detectorModules + imod; - - thisMod->module = imod; - thisMod->serialnumber = 0; - thisMod->nchan = thisDetector->nChans*thisDetector->nChips; - thisMod->nchip = thisDetector->nChips; - thisMod->ndac = thisDetector->nDacs; - thisMod->nadc = thisDetector->nAdcs; - thisMod->reg = 0; - // dacs, adcs, chipregs and chanregs for thisMod is not allocated in - // detectorModules in shared memory as they are already allocated separately - // in shared memory (below) - thisMod->gain = -1.; - thisMod->offset = -1.; - - // initializes the dacs values to 0 - for (int i = 0; i < thisDetector->nDacs; ++i) { - *(dacs + i + thisDetector->nDacs * imod) = 0; - } - // initializes the adc values to 0 - for (int i = 0; i < thisDetector->nAdcs; ++i) { - *(adcs + i + thisDetector->nAdcs * imod) = 0; - } - // initializes the chip registers to 0 - for (int i = 0; i < thisDetector->nChips; ++i) { - *(chipregs + i + thisDetector->nChips * imod) = -1; - } - // initializes the channel registers to 0 - for (int i = 0; i < thisDetector->nChans * thisDetector->nChips; ++i) { - *(chanregs + i + thisDetector->nChans * thisDetector->nChips * imod) = -1; - } - // initializes the gain values to 0 - for (int i = 0; i < thisDetector->nGain; ++i) { - *(gain + i + thisDetector->nGain * imod) = 0; - } - // initializes the offset values to 0 - for (int i = 0; i < thisDetector->nOffset; ++i) { - *(offset + i + thisDetector->nOffset * imod) = 0; - } - } -} - - -slsDetectorDefs::sls_detector_module* slsDetector::createModule() { - return createModule(thisDetector->myDetectorType); -} - - -slsDetectorDefs::sls_detector_module* slsDetector::createModule(detectorType type) { - // get the detector parameters based on type - detParameterList detlist; - int nch = 0, nc = 0, nd = 0, na = 0; - try { - setDetectorSpecificParameters(type, detlist); - nch = detlist.nChanX * detlist.nChanY; - nc = detlist.nChipX * detlist.nChipY; - nd = detlist.nDacs; - na = detlist.nAdcs; - } catch(...) { - return NULL; - } - dacs_t *dacs=new dacs_t[nd]; - dacs_t *adcs=new dacs_t[na]; - int *chipregs=new int[nc]; - int *chanregs=new int[nch*nc]; - - sls_detector_module *myMod = (sls_detector_module*)malloc(sizeof(sls_detector_module)); - myMod->ndac=nd; - myMod->nadc=na; - myMod->nchip=nc; - myMod->nchan=nch*nc; - myMod->dacs=dacs; - myMod->adcs=adcs; - myMod->chipregs=chipregs; - myMod->chanregs=chanregs; - return myMod; -} - - -void slsDetector::deleteModule(sls_detector_module *myMod) { - delete [] myMod->dacs; - delete [] myMod->adcs; - delete [] myMod->chipregs; - delete [] myMod->chanregs; - delete myMod; -} - - - - -int slsDetector::connectControl() { - if (controlSocket){ - if (controlSocket->Connect() >= 0) - return OK; - else{ - std::cout << "cannot connect to detector" << endl; - setErrorMask((getErrorMask())|(CANNOT_CONNECT_TO_DETECTOR)); - return FAIL; - } - } - return UNDEFINED; -} - -void slsDetector::disconnectControl() { - if (controlSocket) - controlSocket->Disconnect(); -} - - - -int slsDetector::connectData() { - //cout << "connect" << endl; - if (dataSocket){ - if (dataSocket->Connect() >= 0) { - //cout << "ok" << endl; - return OK; - } else{ - std::cout << "cannot connect to receiver" << endl; - setErrorMask((getErrorMask())|(CANNOT_CONNECT_TO_RECEIVER)); - //cout << "fail" << endl; - return FAIL;} - } - //cout << "undefined" << endl; - return UNDEFINED; -} - -void slsDetector::disconnectData() { - if (dataSocket) - dataSocket->Disconnect(); -} - - - -int slsDetector::connectStop() { - if (stopSocket){ - if (stopSocket->Connect() >= 0) - return OK; - else{ - std::cout << "cannot connect to stop server" << endl; - setErrorMask((getErrorMask())|(CANNOT_CONNECT_TO_DETECTOR)); - return FAIL; - } - } - return UNDEFINED; -} - -void slsDetector::disconnectStop() { - if (stopSocket) - stopSocket->Disconnect(); -} - - - -int slsDetector::sendChannel(sls_detector_channel *myChan) { - int ts=0; - ts+=controlSocket->SendDataOnly(&(myChan->chan),sizeof(myChan->chan)); - ts+=controlSocket->SendDataOnly(&(myChan->chip),sizeof(myChan->chip)); - ts+=controlSocket->SendDataOnly(&(myChan->module),sizeof(myChan->module)); - ts=controlSocket->SendDataOnly(&(myChan->reg),sizeof(myChan->reg)); - return ts; -} - -int slsDetector::sendChip(sls_detector_chip *myChip) { - int ts=0; - //send chip structure - ts+=controlSocket->SendDataOnly(&(myChip->chip),sizeof(myChip->chip)); - ts+=controlSocket->SendDataOnly(&(myChip->module),sizeof(myChip->module)); - ts+=controlSocket->SendDataOnly(&(myChip->nchan),sizeof(myChip->nchan)); - ts+=controlSocket->SendDataOnly(&(myChip->reg),sizeof(myChip->reg)); - ts+=controlSocket->SendDataOnly(myChip->chanregs,sizeof(myChip->chanregs)); -#ifdef VERY_VERBOSE - std::cout<< "chip structure sent" << std::endl; - std::cout<< "now sending " << myChip->nchan << " channles" << std::endl; -#endif - ts=controlSocket->SendDataOnly(myChip->chanregs,sizeof(int)*myChip->nchan ); -#ifdef VERBOSE - std::cout<< "chip's channels sent " <SendDataOnly(&(myMod->module),sizeof(myMod->module)); - ts+=controlSocket->SendDataOnly(&(myMod->serialnumber),sizeof(myMod->serialnumber)); - ts+=controlSocket->SendDataOnly(&(myMod->nchan),sizeof(myMod->nchan)); - ts+=controlSocket->SendDataOnly(&(myMod->nchip),sizeof(myMod->nchip)); - ts+=controlSocket->SendDataOnly(&(myMod->ndac),sizeof(myMod->ndac)); - ts+=controlSocket->SendDataOnly(&(myMod->nadc),sizeof(myMod->nadc)); - ts+=controlSocket->SendDataOnly(&(myMod->reg),sizeof(myMod->reg)); - // only for sending structures like in old mythen server - if (thisDetector->myDetectorType == MYTHEN) { - ts+=controlSocket->SendDataOnly(myMod->dacs,sizeof(myMod->ndac)); - ts+=controlSocket->SendDataOnly(myMod->adcs,sizeof(myMod->nadc)); - ts+=controlSocket->SendDataOnly(myMod->chipregs,sizeof(myMod->nchip)); - ts+=controlSocket->SendDataOnly(myMod->chanregs,sizeof(myMod->nchan)); - } - ts+=controlSocket->SendDataOnly(&(myMod->gain),sizeof(myMod->gain)); - ts+=controlSocket->SendDataOnly(&(myMod->offset), sizeof(myMod->offset)); - - // actual data to the pointers - ts+=controlSocket->SendDataOnly(myMod->dacs,sizeof(dacs_t)*(myMod->ndac)); - ts+=controlSocket->SendDataOnly(myMod->adcs,sizeof(dacs_t)*(myMod->nadc)); - if(thisDetector->myDetectorType != JUNGFRAU){ - ts+=controlSocket->SendDataOnly(myMod->chipregs,sizeof(int)*(myMod->nchip)); - ts+=controlSocket->SendDataOnly(myMod->chanregs,sizeof(int)*(myMod->nchan)); - } - return ts; -} - -int slsDetector::receiveChannel(sls_detector_channel *myChan) { - int ts=0; - ts+=controlSocket->ReceiveDataOnly(&(myChan->chan),sizeof(myChan->chan)); - ts+=controlSocket->ReceiveDataOnly(&(myChan->chip),sizeof(myChan->chip)); - ts+=controlSocket->ReceiveDataOnly(&(myChan->module),sizeof(myChan->module)); - ts=controlSocket->ReceiveDataOnly(&(myChan->reg),sizeof(myChan->reg)); - return ts; -} - -int slsDetector::receiveChip(sls_detector_chip* myChip) { - int *ptr=myChip->chanregs; - int nchanold=myChip->nchan; - int ts=0; - int nch; - - //receive chip structure - ts+=controlSocket->ReceiveDataOnly(&(myChip->chip),sizeof(myChip->chip)); - ts+=controlSocket->ReceiveDataOnly(&(myChip->module),sizeof(myChip->module)); - ts+=controlSocket->ReceiveDataOnly(&(myChip->nchan),sizeof(myChip->nchan)); - ts+=controlSocket->ReceiveDataOnly(&(myChip->reg),sizeof(myChip->reg)); - ts+=controlSocket->ReceiveDataOnly(myChip->chanregs,sizeof(myChip->chanregs)); - - myChip->chanregs=ptr; - if (nchanold<(myChip->nchan)) { - nch=nchanold; - printf("number of channels received is too large!\n"); - } else - nch=myChip->nchan; - - ts+=controlSocket->ReceiveDataOnly(myChip->chanregs,sizeof(int)*nch); - - return ts; -} - -int slsDetector::receiveModule(sls_detector_module* myMod) { - - dacs_t *dacptr=myMod->dacs; - dacs_t *adcptr=myMod->adcs; - int *chipptr=myMod->chipregs; - int *chanptr=myMod->chanregs; - int ts=0; - //send module structure - ts+=controlSocket->ReceiveDataOnly(&(myMod->module),sizeof(myMod->module)); - ts+=controlSocket->ReceiveDataOnly(&(myMod->serialnumber),sizeof(myMod->serialnumber)); - ts+=controlSocket->ReceiveDataOnly(&(myMod->nchan),sizeof(myMod->nchan)); - ts+=controlSocket->ReceiveDataOnly(&(myMod->nchip),sizeof(myMod->nchip)); - ts+=controlSocket->ReceiveDataOnly(&(myMod->ndac),sizeof(myMod->ndac)); - ts+=controlSocket->ReceiveDataOnly(&(myMod->nadc),sizeof(myMod->nadc)); - ts+=controlSocket->ReceiveDataOnly(&(myMod->reg),sizeof(myMod->reg)); - // only for sending structures like in old mythen server - if (thisDetector->myDetectorType == MYTHEN) { - ts+=controlSocket->ReceiveDataOnly(myMod->dacs,sizeof(myMod->ndac)); - ts+=controlSocket->ReceiveDataOnly(myMod->adcs,sizeof(myMod->nadc)); - ts+=controlSocket->ReceiveDataOnly(myMod->chipregs,sizeof(myMod->nchip)); - ts+=controlSocket->ReceiveDataOnly(myMod->chanregs,sizeof(myMod->nchan)); - } - - ts+=controlSocket->ReceiveDataOnly(&(myMod->gain), sizeof(myMod->gain)); - ts+=controlSocket->ReceiveDataOnly(&(myMod->offset), sizeof(myMod->offset)); - - - myMod->dacs=dacptr; - myMod->adcs=adcptr; - myMod->chipregs=chipptr; - myMod->chanregs=chanptr; - -#ifdef VERBOSE - std::cout<< "received module " << myMod->module << " of size "<< ts - << " register " << myMod->reg << std::endl; -#endif - ts+=controlSocket->ReceiveDataOnly(myMod->dacs,sizeof(dacs_t)*(myMod->ndac)); -#ifdef VERBOSE - std::cout<< "received dacs " << myMod->module << " of size "<< ts << std::endl; -#endif - ts+=controlSocket->ReceiveDataOnly(myMod->adcs,sizeof(dacs_t)*(myMod->nadc)); -#ifdef VERBOSE - std::cout<< "received adcs " << myMod->module << " of size "<< ts << std::endl; -#endif - - if(thisDetector->myDetectorType != JUNGFRAU){ - ts+=controlSocket->ReceiveDataOnly(myMod->chipregs,sizeof(int)*(myMod->nchip)); -#ifdef VERBOSE - std::cout<< "received chips " << myMod->module << " of size "<< ts << std::endl; -#endif - ts+=controlSocket->ReceiveDataOnly(myMod->chanregs,sizeof(int)*(myMod->nchan)); -#ifdef VERBOSE - std::cout<< "nchans= " << thisDetector->nChans << " nchips= " << thisDetector->nChips; - std::cout<< "mod - nchans= " << myMod->nchan << " nchips= " <nchip; - std::cout<< "received chans " << myMod->module << " of size "<< ts << std::endl; -#endif - } - -#ifdef VERBOSE - std::cout<< "received module " << myMod->module << " of size "<< ts << " register " - << myMod->reg << std::endl; -#endif - - return ts; -} - - -slsReceiverDefs::detectorType slsDetector::getDetectorTypeFromShm(int multiId, bool verify) { - - detectorType type = GENERIC; - SharedMemory* shm = 0; - - try { - // create - shm = new SharedMemory(multiId, detId); - - // shm not created before - if (!shm->IsExisting()) { - cprintf(RED,"Shared memory %s does not exist.\n" - "Corrupted Multi Shared memory. Please free shared memory.\n", - shm->GetName().c_str()); - throw SharedMemoryException(); - } - - // only basic size of structure (just version is required) - sharedSlsDetector* sdet = 0; - size_t sz = sizeof(sharedSlsDetector); - - // open, map, verify version - sdet = (sharedSlsDetector*)shm->OpenSharedMemory(sz); - if (verify && sdet->shmversion != SLS_SHMVERSION) { - cprintf(RED, "Single shared memory (%d-%d:)version mismatch " - "(expected 0x%x but got 0x%x)\n", - multiId, detId, SLS_SHMVERSION, sdet->shmversion); - // unmap and throw - sharedMemory->UnmapSharedMemory(thisDetector); - throw SharedMemoryException(); - } - - // get type, unmap - type = sdet->myDetectorType; - shm->UnmapSharedMemory(sdet); - delete shm; - - } catch (...) { - if (shm) - delete shm; - throw; - } - - return type; -} - - -slsDetectorDefs::detectorType slsDetector::getDetectorType(const char *name, int cport) { - int fnum=F_GET_DETECTOR_TYPE; - int retval = FAIL; - detectorType t = GENERIC; - MySocketTCP* mySocket = 0; - - try { - mySocket = new MySocketTCP(name, cport); - } catch(...) { - cout << "Cannot create socket to server " << name << " over port " << cport << endl; - return t; - } - - - char m[MAX_STR_LENGTH]; -#ifdef VERBOSE - cout << "Getting detector type " << endl; -#endif - if (mySocket->Connect() >= 0) { - mySocket->SendDataOnly(&fnum,sizeof(fnum)); - mySocket->ReceiveDataOnly(&retval,sizeof(retval)); - if (retval!=FAIL) { - mySocket->ReceiveDataOnly(&t,sizeof(t)); -#ifdef VERBOSE - cout << "Detector type is "<< t << endl; -#endif - } else { - mySocket->ReceiveDataOnly(m,sizeof(m)); - std::cout<< "Detector returned error: " << m << std::endl; - } - mySocket->Disconnect(); - } else { - cout << "Cannot connect to server " << name << " over port " << cport << endl; - } - delete mySocket; - return t; -} - - -int slsDetector::setDetectorType(detectorType const type) { - - int arg, retval=FAIL; - int fnum=F_GET_DETECTOR_TYPE,fnum2=F_GET_RECEIVER_TYPE; - arg=int(type); - detectorType retType=type; - char mess[MAX_STR_LENGTH]; - memset(mess, 0, MAX_STR_LENGTH); - - -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Setting detector type to " << arg << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - if (retval!=FAIL) - controlSocket->ReceiveDataOnly(&retType,sizeof(retType)); - else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (retval==FORCE_UPDATE) - updateDetector(); - } - } else { - if (type==GET_DETECTOR_TYPE) - retType=thisDetector->myDetectorType;//FIXME: throw exception? - else { - retType=type; - thisDetector->myDetectorType=type; - } - retval=OK; - } -#ifdef VERBOSE - std::cout<< "Detector type set to " << retType << std::endl; -#endif - if (retval==FAIL) { - std::cout<< "Set detector type failed " << std::endl; - retType=GENERIC; - } - else - thisDetector->myDetectorType=retType; - - - //receiver - if((retType != GENERIC) && (thisDetector->receiverOnlineFlag==ONLINE_FLAG) - && (arg != GENERIC)) { - retval = FAIL; - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending detector type to Receiver " << - (int)thisDetector->myDetectorType << std::endl; -#endif - if (connectData() == OK){ - retval=thisReceiver->sendInt(fnum2,arg,(int)thisDetector->myDetectorType); - disconnectData(); - } - if(retval==FAIL){ - cout << "ERROR: Could not send detector type to receiver" << endl; - setErrorMask((getErrorMask())|(RECEIVER_DET_HOSTTYPE_NOT_SET)); - } - } - } - - return retType; -} - - - -int slsDetector::setDetectorType(string const stype) { - return setDetectorType(getDetectorType(stype)); -} - - -slsDetectorDefs::detectorType slsDetector::getDetectorsType(int pos) { - return thisDetector->myDetectorType; -} - -string slsDetector::sgetDetectorsType(int pos) { - return getDetectorType(getDetectorsType(pos)); -} - - -string slsDetector::getDetectorType() { - return sgetDetectorsType(); -} - - -int slsDetector::getNMods() { - return thisDetector->nMods; -} - -int slsDetector::getNMod(dimension d) { - return thisDetector->nMod[d]; -} - - -int slsDetector::getMaxMods() { - return thisDetector->nModsMax; -} - - -int slsDetector::getNMaxMod(dimension d) { - return thisDetector->nModMax[d]; -} - - - -int slsDetector::getMaxNumberOfModules(dimension d) { - - int retval; - int fnum=F_GET_MAX_NUMBER_OF_MODULES; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - - if (dY) { - std::cout<< "Get max number of modules in wrong dimension " << d << std::endl; - return ret; - } -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Getting max number of modules in dimension "<< d <onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&d,sizeof(d)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } else { - ret=OK; - retval=thisDetector->nModMax[d]; - } -#ifdef VERBOSE - std::cout<< "Max number of modules in dimension "<< d <<" is " << retval << std::endl; -#endif - if (ret==FAIL) { - std::cout<< "Get max number of modules failed " << retval << std::endl; - return retval; - } else { - thisDetector->nModMax[d]=retval; - thisDetector->nModsMax=thisDetector->nModMax[X]*thisDetector->nModMax[Y]; - - - - } - return thisDetector->nModMax[d]; -} - - - -int slsDetector::setNumberOfModules(int n, dimension d) { - - int arg[2], retval=1; - int fnum=F_SET_NUMBER_OF_MODULES; - int ret=FAIL; - char mess[MAX_STR_LENGTH]="dummy"; - int connect; - - arg[0]=d; - arg[1]=n; - - - if (dY) { - std::cout<< "Set number of modules in wrong dimension " << d << std::endl; - return ret; - } - - -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Setting number of modules of dimension "<< d << " to " << n << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - connect = connectControl(); - if (connect == UNDEFINED) - cout << "no control socket?" << endl; - else if (connect == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&arg,sizeof(arg)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - } else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } else { - cout << "offline" << endl; - ret=OK; - if (n==GET_FLAG) - ; - else { - if (n<=0 || n>thisDetector->nModMax[d]) { - ret=FAIL; - } else { - thisDetector->nMod[d]=n; - } - } - retval=thisDetector->nMod[d]; - } -#ifdef VERBOSE - std::cout<< "Number of modules in dimension "<< d <<" is " << retval << std::endl; -#endif - if (ret==FAIL) { - std::cout<< "Set number of modules failed " << std::endl; - } else { - thisDetector->nMod[d]=retval; - thisDetector->nMods=thisDetector->nMod[X]*thisDetector->nMod[Y]; - - - if (thisDetector->nModsMaxnMods) - thisDetector->nModsMax=thisDetector->nMods; - - if (thisDetector->nModMax[X]nMod[X]) - thisDetector->nModMax[X]=thisDetector->nMod[X]; - - if (thisDetector->nModMax[Y]nMod[Y]) - thisDetector->nModMax[Y]=thisDetector->nMod[Y]; - - int dr=thisDetector->dynamicRange; - if ((thisDetector->myDetectorType==MYTHEN) && (dr==24)) - dr=32; - - thisDetector->dataBytes=thisDetector->nMod[X]*thisDetector->nMod[Y]* - thisDetector->nChips*thisDetector->nChans*dr/8; - thisDetector->dataBytesInclGapPixels = - (thisDetector->nMod[X] * thisDetector->nChip[X] * - thisDetector->nChan[X] + thisDetector->gappixels * - thisDetector->nGappixels[X]) * - (thisDetector->nMod[Y] * thisDetector->nChip[Y] * - thisDetector->nChan[Y] + thisDetector->gappixels * - thisDetector->nGappixels[Y]) * - thisDetector->dynamicRange/8; - - if(thisDetector->myDetectorType==MYTHEN){ - if (thisDetector->timerValue[PROBES_NUMBER]!=0) { - thisDetector->dataBytes=thisDetector->nMod[X]* - thisDetector->nMod[Y]*thisDetector->nChips*thisDetector->nChans*4; - thisDetector->dataBytesInclGapPixels = - (thisDetector->nMod[X] * thisDetector->nChip[X] * thisDetector->nChan[X] + thisDetector->gappixels * thisDetector->nGappixels[X]) * - (thisDetector->nMod[Y] * thisDetector->nChip[Y] * thisDetector->nChan[Y] + thisDetector->gappixels * thisDetector->nGappixels[Y]) * - 4; - } - } - - if(thisDetector->myDetectorType==JUNGFRAUCTB){ - getTotalNumberOfChannels(); - } - - -#ifdef VERBOSE -std::cout<< "Data size is " << thisDetector->dataBytes << std::endl; -std::cout<< "nModX " << thisDetector->nMod[X] << " nModY " << thisDetector->nMod[Y] - << " nChips " << thisDetector->nChips << " nChans " << thisDetector->nChans - << " dr " << dr << std::endl; -#endif - } - - if(n != GET_FLAG){ - pthread_mutex_lock(&ms); - multiDet->updateOffsets(); - pthread_mutex_unlock(&ms); - } - - return thisDetector->nMod[d]; -} - - - -int slsDetector::getChansPerMod(int imod) { - return thisDetector->nChans*thisDetector->nChips; -} - -int slsDetector::getChansPerMod( dimension d,int imod) { - return thisDetector->nChan[d]*thisDetector->nChip[d]; -} - - -int slsDetector::getTotalNumberOfChannels() { -#ifdef VERBOSE - cout << "total number of channels" << endl; -#endif - if(thisDetector->myDetectorType==JUNGFRAUCTB){ - if (thisDetector->roFlags&DIGITAL_ONLY) - thisDetector->nChan[X]=4; - else if (thisDetector->roFlags&ANALOG_AND_DIGITAL) - thisDetector->nChan[X]=36; - else - thisDetector->nChan[X]=32; - - if (thisDetector->nChan[X]>=32) { - if (thisDetector->nROI>0) { - thisDetector->nChan[X]-=32; - for (int iroi=0; iroinROI; ++iroi) - thisDetector->nChan[X]+= - thisDetector->roiLimits[iroi].xmax- - thisDetector->roiLimits[iroi].xmin+1; - } - } - thisDetector->nChans=thisDetector->nChan[X]; - thisDetector->dataBytes=thisDetector->nChans*thisDetector->nChips* - thisDetector->nMods*2*thisDetector->timerValue[SAMPLES_JCTB]; - thisDetector->dataBytesInclGapPixels = thisDetector->dataBytes; - } else { -#ifdef VERBOSE -cout << "det type is "<< thisDetector->myDetectorType << endl; -cout << "Total number of channels is "<< thisDetector->nChans*thisDetector->nChips* - thisDetector->nMods << " data bytes is " << thisDetector->dataBytes << endl; -// excluding gap pixels -#endif -; - } - return thisDetector->nChans*thisDetector->nChips*thisDetector->nMods; -} - -int slsDetector::getTotalNumberOfChannels(dimension d) { - getTotalNumberOfChannels(); - return thisDetector->nChan[d]*thisDetector->nChip[d]*thisDetector->nMod[d]; -} - -int slsDetector::getTotalNumberOfChannelsInclGapPixels(dimension d) { - getTotalNumberOfChannels(); - return (thisDetector->nChan[d] * thisDetector->nChip[d] + thisDetector->gappixels - * thisDetector->nGappixels[d]) * thisDetector->nMod[d]; -} - - -int slsDetector::getMaxNumberOfChannels() { - if(thisDetector->myDetectorType==JUNGFRAUCTB) return 36*thisDetector->nChips* - thisDetector->nModsMax; - return thisDetector->nChans*thisDetector->nChips*thisDetector->nModsMax; -} - -int slsDetector::getMaxNumberOfChannels(dimension d) { - if(thisDetector->myDetectorType==JUNGFRAUCTB) { - if (d==X) return 36*thisDetector->nChip[d]*thisDetector->nModMax[d]; - else return 1*thisDetector->nChip[d]*thisDetector->nModMax[d]; - } - return thisDetector->nChan[d]*thisDetector->nChip[d]*thisDetector->nModMax[d]; -}; - -int slsDetector::getMaxNumberOfChannelsInclGapPixels(dimension d) { - if(thisDetector->myDetectorType==JUNGFRAUCTB) { - if (d==X) return 36*thisDetector->nChip[d]*thisDetector->nModMax[d]; - else return 1*thisDetector->nChip[d]*thisDetector->nModMax[d]; - } - return (thisDetector->nChan[d] * thisDetector->nChip[d] + thisDetector->gappixels * - thisDetector->nGappixels[d]) * thisDetector->nModMax[d]; -} - - -int slsDetector::getNChans() { - return thisDetector->nChans; -} - -int slsDetector::getNChans(dimension d) { - return thisDetector->nChan[d]; -} - -int slsDetector::getNChips() { - return thisDetector->nChips; -} - -int slsDetector::getNChips(dimension d) { - return thisDetector->nChip[d]; -} - -int slsDetector::getDetectorOffset(dimension d) { - return thisDetector->offset[d]; -} - -void slsDetector::setDetectorOffset(dimension d, int off) { - if (off >= 0) - thisDetector->offset[d] = off; -} - -int slsDetector::setOnline(int off) { - int old=thisDetector->onlineFlag; - if (off!=GET_ONLINE_FLAG) { - thisDetector->onlineFlag=off; - if (thisDetector->onlineFlag==ONLINE_FLAG) { - setTCPSocket(); - if (thisDetector->onlineFlag==ONLINE_FLAG && old==OFFLINE_FLAG) { - cout << "Detector connecting for the first time - updating!" << endl; - updateDetector(); - } - else if(thisDetector->onlineFlag==OFFLINE_FLAG){ - std::cout << "cannot connect to detector" << endl; - setErrorMask((getErrorMask())|(CANNOT_CONNECT_TO_DETECTOR)); - } - } - } - return thisDetector->onlineFlag; -} - - - -string slsDetector::checkOnline() { - string retval=""; - if(!controlSocket){ - //this already sets the online/offline flag - setTCPSocket(); - if(thisDetector->onlineFlag==OFFLINE_FLAG) - return string(thisDetector->hostname); - else - return string(""); - } - //still cannot connect to socket, controlSocket=0 - if(controlSocket){ - if (connectControl() == FAIL) { - controlSocket->SetTimeOut(5); - thisDetector->onlineFlag=OFFLINE_FLAG; - delete controlSocket; - controlSocket=0; - retval = string(thisDetector->hostname); -#ifdef VERBOSE - std::cout<< "offline!" << std::endl; -#endif - } else { - thisDetector->onlineFlag=ONLINE_FLAG; - controlSocket->SetTimeOut(100); - disconnectControl(); -#ifdef VERBOSE - std::cout<< "online!" << std::endl; -#endif - } - } - //still cannot connect to socket, stopSocket=0 - if(stopSocket){ - if (connectStop() == FAIL) { - stopSocket->SetTimeOut(5); - thisDetector->onlineFlag=OFFLINE_FLAG; - delete stopSocket; - stopSocket=0; - retval = string(thisDetector->hostname); -#ifdef VERBOSE - std::cout<< "stop offline!" << std::endl; -#endif - } else { - thisDetector->onlineFlag=ONLINE_FLAG; - stopSocket->SetTimeOut(100); - disconnectStop(); -#ifdef VERBOSE - std::cout<< "stop online!" << std::endl; -#endif - } - } - return retval; -} - - - - -int slsDetector::setTCPSocket(string const name, int const control_port, int const stop_port) { - char thisName[MAX_STR_LENGTH]; - int thisCP, thisSP; - int retval=OK; - - if (strcmp(name.c_str(),"")!=0) { -#ifdef VERBOSE - std::cout<< "setting hostname" << std::endl; -#endif - strcpy(thisName,name.c_str()); - strcpy(thisDetector->hostname,thisName); - if (controlSocket) { - delete controlSocket; - controlSocket=0; - } - if (stopSocket) { - delete stopSocket; - stopSocket=0; - } - } else - strcpy(thisName,thisDetector->hostname); - - if (control_port>0) { -#ifdef VERBOSE - std::cout<< "setting control port" << std::endl; -#endif - thisCP=control_port; - thisDetector->controlPort=thisCP; - if (controlSocket) { - delete controlSocket; - controlSocket=0; - } - } else - thisCP=thisDetector->controlPort; - - if (stop_port>0) { -#ifdef VERBOSE - std::cout<< "setting stop port" << std::endl; -#endif - thisSP=stop_port; - thisDetector->stopPort=thisSP; - if (stopSocket) { - delete stopSocket; - stopSocket=0; - } - } else - thisSP=thisDetector->stopPort; - - - // create control socket - if (!controlSocket) { - try { - controlSocket = new MySocketTCP(thisName, thisCP); -#ifdef VERYVERBOSE - std::cout<< "Control socket connected " << - thisName << " " << thisCP << std::endl; -#endif - } catch(...) { -#ifdef VERBOSE - std::cout<< "Could not connect Control socket " << - thisName << " " << thisCP << std::endl; -#endif - controlSocket = 0; - retval = FAIL; - } - } - - - // create stop socket - if (!stopSocket) { - try { - stopSocket = new MySocketTCP(thisName, thisSP); -#ifdef VERYVERBOSE - std::cout<< "Stop socket connected " << - thisName << " " << thisSP << std::endl; -#endif - } catch(...) { -#ifdef VERBOSE - std::cout<< "Could not connect Stop socket " << - thisName << " " << thisSP << std::endl; -#endif - stopSocket = 0; - retval = FAIL; - } - } - - - if (retval!=FAIL) { - checkOnline(); - - // check for version compatibility - switch (thisDetector->myDetectorType) { - case EIGER: - case JUNGFRAU: - case GOTTHARD: - if ((thisDetector->detectorControlAPIVersion == 0) || - (thisDetector->detectorStopAPIVersion == 0)) { - if (checkVersionCompatibility(CONTROL_PORT) == FAIL) - thisDetector->onlineFlag=OFFLINE_FLAG; - } - break; - default: - break; - } - - } else { - thisDetector->onlineFlag=OFFLINE_FLAG; -#ifdef VERBOSE - std::cout<< "offline!" << std::endl; -#endif - } - return retval; -} - - - -int slsDetector::setPort(portType index, int num) { - - int fnum=F_SET_PORT, fnum2 = F_SET_RECEIVER_PORT; - int retval; - // uint64_t ut; - char mess[MAX_STR_LENGTH]=""; - int ret=FAIL; - bool online=false; - MySocketTCP *s = 0; - - if (num>1024) { - switch(index) { - case CONTROL_PORT: - s=controlSocket; - retval=thisDetector->controlPort; -#ifdef VERBOSE - cout << "s="<< s<< endl; - cout << thisDetector->controlPort<< " " << " " << thisDetector->stopPort - << endl; -#endif - if (s==0) { - -#ifdef VERBOSE - cout << "s=NULL"<< endl; - cout << thisDetector->controlPort<< " " << " " << thisDetector->stopPort - << endl; -#endif - setTCPSocket("",DEFAULT_PORTNO); - } - if (controlSocket) { - s=controlSocket; - } else { -#ifdef VERBOSE - cout << "still cannot connect!"<< endl; - cout << thisDetector->controlPort<< " " << " " << thisDetector->stopPort - << endl; -#endif - - setTCPSocket("",retval); - } - online = (thisDetector->onlineFlag==ONLINE_FLAG); - - //not an error.could be from config file - if(num==thisDetector->controlPort) - return thisDetector->controlPort; - //reusable port, so print error - else if((num==thisDetector->stopPort)||(num==thisDetector->receiverTCPPort)){ - std::cout<< "Can not connect to port in use " << std::endl; - setErrorMask((getErrorMask())|(COULDNOT_SET_CONTROL_PORT)); - return thisDetector->controlPort; - } - break; - - - case DATA_PORT: - s=dataSocket; - retval=thisDetector->receiverTCPPort; - if(strcmp(thisDetector->receiver_hostname,"none")){ - if (s==0) setReceiverTCPSocket("",retval); - if (dataSocket)s=dataSocket; - } - online = (thisDetector->receiverOnlineFlag==ONLINE_FLAG); - - //not an error. could be from config file - if(num==thisDetector->receiverTCPPort) - return thisDetector->receiverTCPPort; - //reusable port, so print error - else if((num==thisDetector->stopPort)||(num==thisDetector->controlPort)){ - std::cout<< "Can not connect to port in use " << std::endl; - setErrorMask((getErrorMask())|(COULDNOT_SET_DATA_PORT)); - return thisDetector->receiverTCPPort; - } - break; - - - case STOP_PORT: - s=stopSocket; - retval=thisDetector->stopPort; - if (s==0) setTCPSocket("",-1,DEFAULT_PORTNO+1); - if (stopSocket) s=stopSocket; - else setTCPSocket("",-1,retval); - online = (thisDetector->onlineFlag==ONLINE_FLAG); - - //not an error. could be from config file - if(num==thisDetector->stopPort) - return thisDetector->stopPort; - //reusable port, so print error - else if((num==thisDetector->receiverTCPPort)||(num==thisDetector->controlPort)){ - std::cout<< "Can not connect to port in use " << std::endl; - setErrorMask((getErrorMask())|(COULDNOT_SET_STOP_PORT)); - return thisDetector->stopPort; - } - break; - - default: - s=0; - break; - } - - - - - //send to current port to change port - if (online) { - if (s) { - if (s->Connect()>=0) { - if(s==dataSocket) - fnum = fnum2; - s->SendDataOnly(&fnum,sizeof(fnum)); - s->SendDataOnly(&index,sizeof(index)); - s->SendDataOnly(&num,sizeof(num)); - s->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - s->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } else { - s->ReceiveDataOnly(&retval,sizeof(retval)); - } - s->Disconnect(); - }else{ - if (index == CONTROL_PORT){ - std::cout << "cannot connect to detector" << endl; - setErrorMask((getErrorMask())|(CANNOT_CONNECT_TO_DETECTOR)); - }else if (index == DATA_PORT){ - std::cout << "cannot connect to receiver" << endl; - setErrorMask((getErrorMask())|(CANNOT_CONNECT_TO_RECEIVER)); - } - } - } - } - - - - if (ret!=FAIL) { - switch(index) { - case CONTROL_PORT: - thisDetector->controlPort=retval; - break; - case DATA_PORT: - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ - thisDetector->receiverTCPPort=retval; - setReceiverOnline(ONLINE_FLAG); - setReceiver(thisDetector->receiver_hostname); - } - break; - case STOP_PORT: - thisDetector->stopPort=retval; - break; - default: - break; - } -#ifdef VERBOSE - cout << "ret is ok" << endl; -#endif - - } else { - switch(index) { - case CONTROL_PORT: - thisDetector->controlPort=num; - setErrorMask((getErrorMask())|(COULDNOT_SET_CONTROL_PORT)); - break; - case DATA_PORT: - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ - thisDetector->receiverTCPPort=retval; - setErrorMask((getErrorMask())|(COULDNOT_SET_DATA_PORT)); - }else{ - thisDetector->receiverTCPPort=num; - if(strcmp(thisDetector->receiver_hostname,"none")) - setReceiver(thisDetector->receiver_hostname); - } - break; - case STOP_PORT: - thisDetector->stopPort=num; - setErrorMask((getErrorMask())|(COULDNOT_SET_STOP_PORT)); - break; - default: - break; - } - } - } - - - - - switch(index) { - case CONTROL_PORT: - retval=thisDetector->controlPort; - break; - case DATA_PORT: - retval=thisDetector->receiverTCPPort; - break; - case STOP_PORT: - retval=thisDetector->stopPort; - break; - default: - retval=-1; - break; - } - - - -#ifdef VERBOSE - cout << thisDetector->controlPort<< " " << thisDetector->receiverTCPPort - << " " << thisDetector->stopPort << endl; -#endif - - - - return retval; - -} - -int slsDetector::getControlPort() { - return thisDetector->controlPort; -} -int slsDetector::getStopPort() { - return thisDetector->stopPort; -} -int slsDetector::getReceiverPort() { - return thisDetector->receiverTCPPort; -} - - -int slsDetector::lockServer(int lock) { - int fnum=F_LOCK_SERVER; - int retval=-1; - int ret=OK; - char mess[MAX_STR_LENGTH]=""; - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&lock,sizeof(lock)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } else { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - return retval; - - -} - - -string slsDetector::getLastClientIP() { - - int fnum=F_GET_LAST_CLIENT_IP; - char clientName[INET_ADDRSTRLEN]; - char mess[MAX_STR_LENGTH]=""; - int ret=OK; - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } else { - controlSocket->ReceiveDataOnly(clientName,sizeof(clientName)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - return string(clientName); - -} - - -int slsDetector::exitServer() { - - int retval = FAIL; - int fnum=F_EXIT_SERVER; - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (controlSocket) { - controlSocket->Connect(); - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - disconnectControl(); - } - } - if (retval!=OK) { - std::cout<< std::endl; - std::cout<< "Shutting down the server" << std::endl; - std::cout<< std::endl; - } - return retval; - -} - - -int slsDetector::execCommand(string cmd, string answer) { - - char arg[MAX_STR_LENGTH], retval[MAX_STR_LENGTH]; - int fnum=F_EXEC_COMMAND; - - int ret=FAIL; - - strcpy(arg,cmd.c_str()); - -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Sending command " << arg << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - if (controlSocket->SendDataOnly(&fnum,sizeof(fnum))>=0) { - if (controlSocket->SendDataOnly(arg,MAX_STR_LENGTH)>=0) { - if (controlSocket->ReceiveDataOnly(retval,MAX_STR_LENGTH)>=0) { - ret=OK; - answer=retval; - } - } - } - disconnectControl(); - } -#ifdef VERBOSE - std::cout<< "Detector answer is " << answer << std::endl; -#endif - } - return ret; -} - - -int slsDetector::updateDetectorNoWait() { - - enum readOutFlags ro; - // int ret=OK; - enum detectorSettings t; - int thr, n = 0, nm; - // int it; - int64_t retval;// tns=-1; - char lastClientIP[INET_ADDRSTRLEN]; - - n += controlSocket->ReceiveDataOnly(lastClientIP,sizeof(lastClientIP)); -#ifdef VERBOSE - cout << "Updating detector last modified by " << lastClientIP << std::endl; -#endif - n += controlSocket->ReceiveDataOnly(&nm,sizeof(nm)); - thisDetector->nMod[X]=nm; - n += controlSocket->ReceiveDataOnly( &nm,sizeof(nm)); - /// Should be overcome at a certain point! - - if (thisDetector->myDetectorType==MYTHEN) { - thisDetector->nModMax[X]=nm; - thisDetector->nModMax[Y]=1; - thisDetector->nModsMax=thisDetector->nModMax[Y]*thisDetector->nModMax[X]; - thisDetector->nMod[Y]=1; - } else { - thisDetector->nMod[Y]=nm; - } - - thisDetector->nMods=thisDetector->nMod[Y]*thisDetector->nMod[X]; - if (thisDetector->nModsMaxnMods) - thisDetector->nModsMax=thisDetector->nMods; - - if (thisDetector->nModMax[X]nMod[X]) - thisDetector->nModMax[X]=thisDetector->nMod[X]; - - if (thisDetector->nModMax[Y]nMod[Y]) - thisDetector->nModMax[Y]=thisDetector->nMod[Y]; - - n += controlSocket->ReceiveDataOnly( &nm,sizeof(nm)); - thisDetector->dynamicRange=nm; - - n += controlSocket->ReceiveDataOnly( &nm,sizeof(nm)); - thisDetector->dataBytes=nm; - - n += controlSocket->ReceiveDataOnly( &t,sizeof(t)); - thisDetector->currentSettings=t; - - if((thisDetector->myDetectorType == EIGER) || - (thisDetector->myDetectorType == MYTHEN)){ - n += controlSocket->ReceiveDataOnly( &thr,sizeof(thr)); - thisDetector->currentThresholdEV=thr; - } - - n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); - thisDetector->timerValue[FRAME_NUMBER]=retval; - - n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); - thisDetector->timerValue[ACQUISITION_TIME]=retval; - - if(thisDetector->myDetectorType == EIGER){ - n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); - thisDetector->timerValue[SUBFRAME_ACQUISITION_TIME]=retval; - - n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); - thisDetector->timerValue[SUBFRAME_DEADTIME]=retval; - } - - n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); - thisDetector->timerValue[FRAME_PERIOD]=retval; - - if(thisDetector->myDetectorType != EIGER) { - n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); - thisDetector->timerValue[DELAY_AFTER_TRIGGER]=retval; - } - - if ((thisDetector->myDetectorType != JUNGFRAU) && - (thisDetector->myDetectorType != EIGER)){ - n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); - thisDetector->timerValue[GATES_NUMBER]=retval; - } - - if (thisDetector->myDetectorType == MYTHEN){ - n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); - thisDetector->timerValue[PROBES_NUMBER]=retval; - } - - n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); - thisDetector->timerValue[CYCLES_NUMBER]=retval; - - if (thisDetector->myDetectorType == JUNGFRAUCTB){ - n += controlSocket->ReceiveDataOnly( &retval,sizeof(int64_t)); - if (retval>=0) - thisDetector->timerValue[SAMPLES_JCTB]=retval; - n += controlSocket->ReceiveDataOnly( &ro,sizeof(ro)); - - thisDetector->roFlags=ro; - - getTotalNumberOfChannels(); - } - - - if (!n) - printf("n: %d\n", n); - - return OK; - -} - - - - -int slsDetector::updateDetector() { - int fnum=F_UPDATE_CLIENT; - int ret=OK; - char mess[MAX_STR_LENGTH]=""; - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } else - updateDetectorNoWait(); - disconnectControl(); - } - } - return ret; -} - - -int slsDetector::readConfigurationFile(string const fname) { - - - - string ans; - string str; - ifstream infile; - //char *args[1000]; - - string sargname, sargval; -#ifdef VERBOSE - int iline=0; - std::cout<< "config file name "<< fname << std::endl; -#endif - infile.open(fname.c_str(), ios_base::in); - if (infile.is_open()) { -#ifdef VERBOSE - iline=readConfigurationFile(infile); -#else - readConfigurationFile(infile); -#endif - infile.close(); - } else { - std::cout<< "Error opening configuration file " << fname << - " for reading" << std::endl; - setErrorMask((getErrorMask())|(CONFIG_FILE)); - return FAIL; - } -#ifdef VERBOSE - std::cout<< "Read configuration file of " << iline << " lines" << std::endl; -#endif - return OK; - -} - - -int slsDetector::readConfigurationFile(ifstream &infile) { - - - - - slsDetectorCommand *cmd=new slsDetectorCommand(this); - - string ans; - string str; - int iargval; - int interrupt=0; - char *args[100]; - char myargs[1000][1000]; - - string sargname, sargval; - int iline=0; - while (infile.good() and interrupt==0) { - sargname="none"; - sargval="0"; - getline(infile,str); - ++iline; -#ifdef VERBOSE - std::cout<< str << std::endl; -#endif - if (str.find('#')!=string::npos) { -#ifdef VERBOSE - std::cout<< "Line is a comment " << std::endl; - std::cout<< str << std::endl; -#endif - continue; - } else if (str.length()<2) { -#ifdef VERBOSE - std::cout<< "Empty line " << std::endl; -#endif - continue; - } else { - istringstream ssstr(str); - iargval=0; - while (ssstr.good()) { - ssstr >> sargname; - //if (ssstr.good()) { -#ifdef VERBOSE - std::cout<< iargval << " " << sargname << std::endl; -#endif - strcpy(myargs[iargval],sargname.c_str()); - args[iargval]=myargs[iargval]; - ++iargval; - //} - } - ans=cmd->executeLine(iargval,args,PUT_ACTION); -#ifdef VERBOSE - std::cout<< ans << std::endl; -#endif - } - ++iline; - } - delete cmd; - return OK; - -} - - - - - - - - - - -int slsDetector::writeConfigurationFile(string const fname) { - - ofstream outfile; -#ifdef VERBOSE - int ret; -#endif - outfile.open(fname.c_str(),ios_base::out); - if (outfile.is_open()) { -#ifdef VERBOSE - ret=writeConfigurationFile(outfile); -#else - writeConfigurationFile(outfile); -#endif - outfile.close(); - } - else { - std::cout<< "Error opening configuration file " << fname << - " for writing" << std::endl; - setErrorMask((getErrorMask())|(CONFIG_FILE)); - return FAIL; - } -#ifdef VERBOSE - std::cout<< "wrote " <myDetectorType; - string names[100]; - int nvar=0; - - // common config - names[nvar++] = "hostname"; - names[nvar++] = "port"; - names[nvar++] = "stopport"; - names[nvar++] = "settingsdir"; - names[nvar++] = "caldir"; - names[nvar++] = "ffdir"; - names[nvar++] = "outdir"; - names[nvar++] = "angdir"; - names[nvar++] = "moveflag"; - names[nvar++] = "lock"; - - // receiver config - if (type != MYTHEN) { - names[nvar++] = "detectormac"; - names[nvar++] = "detectorip"; - names[nvar++] = "zmqport"; - names[nvar++] = "rx_zmqport"; - names[nvar++] = "zmqip"; - names[nvar++] = "rx_zmqip"; - names[nvar++] = "rx_tcpport"; - names[nvar++] = "rx_udpport"; - names[nvar++] = "rx_udpport2"; - names[nvar++] = "rx_udpip"; - names[nvar++] = "rx_hostname"; - names[nvar++] = "r_readfreq"; - } - - // detector specific config - switch (type) { - case MYTHEN: - names[nvar++] = "nmod"; - names[nvar++] = "waitstates"; - names[nvar++] = "setlength"; - names[nvar++] = "clkdivider"; - names[nvar++] = "extsig"; - break; - case GOTTHARD: - case PROPIX: - names[nvar++] = "extsig"; - names[nvar++] = "vhighvoltage"; - break; - break; - case MOENCH: - names[nvar++] = "extsig"; - names[nvar++] = "vhighvoltage"; - break; - case EIGER: - names[nvar++] = "vhighvoltage"; - names[nvar++] = "trimen"; - names[nvar++] = "iodelay"; - names[nvar++] = "tengiga"; - break; - case JUNGFRAU: - names[nvar++] = "powerchip"; - names[nvar++] = "vhighvoltage"; - break; - case JUNGFRAUCTB: - names[nvar++] = "powerchip"; - names[nvar++] = "vhighvoltage"; - break; - default: - std::cout << "detector type " << - getDetectorType(thisDetector->myDetectorType) << " not implemented in " - "writing config file" << std::endl; - nvar = 0; - break; - } - - - - int nsig=4; - int iv=0; - char *args[100]; - char myargs[100][1000]; - - for (int ia=0; ia<100; ++ia) { - args[ia]=myargs[ia]; - } - - - for (iv=0; iv=0) - outfile << id << ":"; - - outfile << args[0] << " " << cmd->executeLine(1,args,GET_ACTION) - << std::endl; - } - } else { - strcpy(args[0],names[iv].c_str()); - if (id>=0) - outfile << id << ":"; - outfile << names[iv] << " " << cmd->executeLine(1,args,GET_ACTION) - << std::endl; - } - } - - delete cmd; - return OK; -} - - - -string slsDetector::getSettingsFile() { - string s(thisDetector->settingsFile); - if (s.length()>6) { - if (s.substr(s.length()-6,3)==string(".sn") && s.substr(s.length()-3)!=string("xxx") ) - return s.substr(0,s.length()-6); - } - return string(thisDetector->settingsFile); -} - - -int slsDetector::writeSettingsFile(string fname, int imod, int iodelay, int tau) { - - return writeSettingsFile(fname,thisDetector->myDetectorType, detectorModules[imod], - iodelay, tau); - -} - -slsDetectorDefs::detectorSettings slsDetector::getSettings(int imod) { - - return sendSettingsOnly(GET_SETTINGS, imod); -} - - -slsDetectorDefs::detectorSettings slsDetector::setSettings( detectorSettings isettings, - int imod) { -#ifdef VERBOSE - std::cout<< "slsDetector setSettings " << isettings << std::endl; -#endif - - if (isettings == -1) - return getSettings(imod); - - detectorType detType = thisDetector->myDetectorType; - switch (detType) { - - // eiger: only set client shared memory variable for Eiger, - // settings threshold loads the module data (trimbits, dacs etc.) - case EIGER: - switch(isettings) { - case STANDARD: - case HIGHGAIN: - case LOWGAIN: - case VERYHIGHGAIN: - case VERYLOWGAIN: - thisDetector->currentSettings = isettings; - break; - default: - printf("Unknown settings %s for this detector!\n", - getDetectorSettings(isettings).c_str()); - setErrorMask((getErrorMask())|(SETTINGS_NOT_SET)); - break; - } - return thisDetector->currentSettings; - - // send only the settings, detector server will update dac values already in server - case GOTTHARD: - case PROPIX: - case JUNGFRAU: - case MOENCH: - return sendSettingsOnly(isettings); - break; - - // others send whole module to detector - default: - break; - } - - - - // MYTHEN ONLY (sends whole detector to module) - - sls_detector_module *myMod=createModule(); - int modmi=imod, modma=imod+1, im=imod; - string settingsfname, calfname; - string ssettings; - - //not included in module structure - int iodelay = -1; - int tau = -1; - int* gainval=0, *offsetval=0; - if(thisDetector->nGain) - gainval=new int[thisDetector->nGain]; - if(thisDetector->nOffset) - offsetval=new int[thisDetector->nOffset]; - - - switch (isettings) { - case STANDARD: - ssettings="/standard"; - thisDetector->currentSettings=STANDARD; - break; - case FAST: - ssettings="/fast"; - thisDetector->currentSettings=FAST; - break; - case HIGHGAIN: - ssettings="/highgain"; - thisDetector->currentSettings=HIGHGAIN; - break; - default: - break; - } - - - if (isettings != thisDetector->currentSettings) { - printf("Unknown settings %s for this detector!\n", - getDetectorSettings(isettings).c_str()); - setErrorMask((getErrorMask())|(SETTINGS_NOT_SET)); - }else{ - if (imod<0) { - modmi=0; - // modma=thisDetector->nModMax[X]*thisDetector->nModMax[Y]; - modma=thisDetector->nMod[X]*thisDetector->nMod[Y]; - } - - for (im=modmi; immodule=im; - - std::cout << std::endl << "Loading settings for module:" << im << std::endl; - - //create file names - ostfn << thisDetector->settingsDir << ssettings <<"/noise.sn" - << setfill('0') << setw(3) << hex << getId(MODULE_SERIAL_NUMBER, im) - << setbase(10); - oscfn << thisDetector->calDir << ssettings << "/calibration.sn" - << setfill('0') << setw(3) << hex << getId(MODULE_SERIAL_NUMBER, im) - << setbase(10); - - - //settings file**** - settingsfname=ostfn.str(); -#ifdef VERBOSE - cout << "the settings file name is "<settingsDir << ssettings - << ssettings << ".trim"; - settingsfname=ostfn_default.str(); -#ifdef VERBOSE - cout << settingsfname << endl; -#endif - if (NULL == readSettingsFile(settingsfname,detType, iodelay, tau, - myMod)) { - //if default doesnt work, return error - std::cout << "Could not open settings file" << endl; - setErrorMask((getErrorMask())|(SETTINGS_FILE_NOT_OPEN)); - return thisDetector->currentSettings; - } - } - - - - //calibration file**** - int ret=0; - calfname=oscfn.str(); -#ifdef VERBOSE - cout << "Specific file:"<< calfname << endl; -#endif - //extra gain and offset - if(thisDetector->nGain) - ret = readCalibrationFile(calfname,gainval, offsetval); - //normal gain and offset inside sls_detector_module - else - ret = readCalibrationFile(calfname,myMod->gain, myMod->offset); - - //if it didnt open, try default - if(ret != OK){ - ostringstream oscfn_default; - oscfn_default << thisDetector->calDir << ssettings << ssettings << ".cal"; - calfname=oscfn_default.str(); -#ifdef VERBOSE - cout << "Default file:" << calfname << endl; -#endif - //extra gain and offset - if(thisDetector->nGain) - ret = readCalibrationFile(calfname,gainval, offsetval); - //normal gain and offset inside sls_detector_module - else - ret = readCalibrationFile(calfname,myMod->gain, myMod->offset); - } - //if default doesnt work, return error - if(ret != OK){ - std::cout << "Could not open calibration file" << calfname << endl; - setErrorMask((getErrorMask())|(SETTINGS_FILE_NOT_OPEN)); - return thisDetector->currentSettings; - } - - - //if everything worked, set module**** - setModule(*myMod,iodelay,tau,-1,gainval,offsetval); - } - } - - - - deleteModule(myMod); - if(gainval) delete [] gainval; - if(offsetval) delete [] offsetval; - - if (thisDetector->correctionMask&(1<-1 && isett<3) { - thisDetector->tDead=t[isett]; - } - } - - - if (getSettings(imod) != isettings){ - std::cout << "Could not set settings" << endl; - setErrorMask((getErrorMask())|(SETTINGS_NOT_SET)); - } - - return thisDetector->currentSettings; -} - - - -slsDetectorDefs::detectorSettings slsDetector::sendSettingsOnly(detectorSettings isettings, - int imod) { - int fnum = F_SET_SETTINGS; - int ret = FAIL; - char mess[MAX_STR_LENGTH]; - memset(mess, 0, MAX_STR_LENGTH); - int retval = -1; - int arg[2]; - arg[0] = isettings; - arg[1] = imod; -#ifdef VERBOSE - std::cout<< "Setting settings of module " << arg[1] << " to " << arg[0] << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(arg,sizeof(arg)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(SETTINGS_NOT_SET)); - } else{ - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - thisDetector->currentSettings = (detectorSettings)retval; -#ifdef VERBOSE - std::cout<< "Settings are " << retval << std::endl; -#endif - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - return thisDetector->currentSettings; -} - - - -int slsDetector::getThresholdEnergy(int imod) { - - int fnum= F_GET_THRESHOLD_ENERGY; - int retval; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; -#ifdef VERBOSE - std::cout<< "Getting threshold energy "<< std::endl; -#endif - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&imod,sizeof(imod)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - std::cout<< "Detector returned error: "<< std::endl; - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< mess << std::endl; - } else { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - thisDetector->currentThresholdEV=retval; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - - - if(thisDetector->myDetectorType==JUNGFRAUCTB) { - - - int en=-1; - - string header=getNetworkParameter(ADDITIONAL_JSON_HEADER); - - - std::cout<< "Json header: " << header << std::endl; - - //must be in the format '\"label1\":\"value1\",\"label2\":\"value2\"' etc." - // - size_t pos0; - pos0=header.find("\"threshold\""); - if (pos0!=std::string::npos) { - if (sscanf(header.substr(pos0).c_str(),"\"threshold\":%d", &en)) - thisDetector->currentThresholdEV=en; - } - - } - - return thisDetector->currentThresholdEV; -} - -int slsDetector::setThresholdEnergy(int e_eV, int imod, detectorSettings isettings, int tb) { - - //currently only for eiger - if (thisDetector->myDetectorType == EIGER) { - setThresholdEnergyAndSettings(e_eV,isettings,tb); - return thisDetector->currentThresholdEV; - } - - int fnum= F_SET_THRESHOLD_ENERGY; - int retval; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; -#ifdef VERBOSE - std::cout<< "Setting threshold energy "<< std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&e_eV,sizeof(e_eV)); - controlSocket->SendDataOnly(&imod,sizeof(imod)); - controlSocket->SendDataOnly(&isettings,sizeof(isettings)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - std::cout<< "Detector returned error: "<< std::endl; - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< mess << std::endl; - } else { -#ifdef VERBOSE - std::cout<< "Detector returned OK "<< std::endl; -#endif - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - thisDetector->currentThresholdEV=retval; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } else { - thisDetector->currentThresholdEV=e_eV; - } - - /* add threshold to zmq header */ - - string header=getNetworkParameter(ADDITIONAL_JSON_HEADER); - - std::cout<< "Old json header: " << header << std::endl; - //must be in the format '\"label1\":\"value1\",\"label2\":\"value2\"' etc." - // - size_t pos0; - pos0=header.find(",\"threshold\""); - if (pos0==std::string::npos) { - pos0=header.find("\"threshold\""); - } - if (pos0!=std::string::npos) { - // remove old roi - // std::cout<< header.substr(0,pos) << std::endl; - // size_t pos0=header.find_last_of(",",0,pos); - // if (pos0==std::string::npos) { - // pos0=pos; - // } else - // std::cout<< header.substr(pos0) << std::endl; - size_t pos1=header.find_first_of(",",pos0+1); - // std::cout << pos0 << " " << pos1 << std::endl; - std::cout<< "Replacing old threshold: " << header.substr(pos0,pos1-pos0) << std::endl; - // if (pos1!=std::string::npos) - header.erase(pos0,pos1-pos0); - // else - // header.erase(pos0); - } - if (header.length()>0) { - if (header.at(0)==',') - header.erase(0,1); - if (header.length()>0) - header.append(","); - } - // std::cout<< "Left: " << header << std::endl; - char h[1000]; - sprintf(h,"\"threshold\":%d",e_eV); - // std::cout<< "new ROI: " << h << std::endl; - - header.append(h); - std::cout<< "New json header: " << header << std::endl; - setReceiverOnline(ONLINE_FLAG); - setNetworkParameter(ADDITIONAL_JSON_HEADER, header); - /***** END FOR ZMQ HEADER */ - ret=OK; - - if (thisDetector->myDetectorType==JUNGFRAUCTB) { - thisDetector->currentThresholdEV=e_eV; - } - - - - - - - return thisDetector->currentThresholdEV; -} - - - -int slsDetector::setThresholdEnergyAndSettings(int e_eV, detectorSettings isettings, int tb) { - - //if settings provided, use that, else use the shared memory variable - detectorSettings is = ((isettings != GET_SETTINGS) ? isettings: - thisDetector->currentSettings); - string ssettings; - switch (is) { - case STANDARD: - ssettings="/standard"; - thisDetector->currentSettings=STANDARD; - break; - case HIGHGAIN: - ssettings="/highgain"; - thisDetector->currentSettings=HIGHGAIN; - break; - case LOWGAIN: - ssettings="/lowgain"; - thisDetector->currentSettings=LOWGAIN; - break; - case VERYHIGHGAIN: - ssettings="/veryhighgain"; - thisDetector->currentSettings=VERYHIGHGAIN; - break; - case VERYLOWGAIN: - ssettings="/verylowgain"; - thisDetector->currentSettings=VERYLOWGAIN; - break; - default: - printf("Error: Unknown settings %s for this detector!\n", - getDetectorSettings(is).c_str()); - setErrorMask((getErrorMask())|(SETTINGS_NOT_SET)); - return FAIL; - } - - //verify e_eV exists in trimEneregies[] - if (!thisDetector->nTrimEn || - (e_eV < thisDetector->trimEnergies[0]) || - (e_eV > thisDetector->trimEnergies[thisDetector->nTrimEn-1]) ) { - printf("Error: This energy %d not defined for this module!\n", e_eV); - setErrorMask((getErrorMask())|(SETTINGS_NOT_SET)); - return FAIL; - } - - //find if interpolation required - bool interpolate = true; - for (int i = 0; i < thisDetector->nTrimEn; ++i) { - if (thisDetector->trimEnergies[i] == e_eV) { - interpolate = false; - break; - } - } - - //fill detector module structure - sls_detector_module *myMod = NULL; - int iodelay = -1; //not included in the module - int tau = -1; //not included in the module - - //normal - if(!interpolate) { - //find their directory names - ostringstream ostfn; - ostfn << thisDetector->settingsDir << ssettings << "/" << e_eV << "eV" - << "/noise.sn" << setfill('0') << setw(3) << dec << getId(DETECTOR_SERIAL_NUMBER) << setbase(10); - string settingsfname = ostfn.str(); -#ifdef VERBOSE - printf("Settings File is %s\n", settingsfname.c_str()); -#endif - //read the files - myMod=createModule(); - if (NULL == readSettingsFile(settingsfname,thisDetector->myDetectorType, - iodelay, tau, myMod, tb)) { - if(myMod)deleteModule(myMod); - return FAIL; - } - } - - - //interpolate - else { - //find the trim values - int trim1 = -1, trim2 = -1; - for (int i = 0; i < thisDetector->nTrimEn; ++i) { - if (e_eV < thisDetector->trimEnergies[i]) { - trim2 = thisDetector->trimEnergies[i]; - trim1 = thisDetector->trimEnergies[i-1]; - break; - } - } - //find their directory names - ostringstream ostfn; - ostfn << thisDetector->settingsDir << ssettings << "/" << trim1 << "eV" - << "/noise.sn" << setfill('0') << setw(3) << dec << - getId(DETECTOR_SERIAL_NUMBER) << setbase(10); - string settingsfname1 = ostfn.str(); - ostfn.str(""); ostfn.clear(); - ostfn << thisDetector->settingsDir << ssettings << "/" << trim2 << "eV" - << "/noise.sn" << setfill('0') << setw(3) << dec << - getId(DETECTOR_SERIAL_NUMBER) << setbase(10); - string settingsfname2 = ostfn.str(); - //read the files -#ifdef VERBOSE - printf("Settings Files are %s and %s\n",settingsfname1.c_str(), - settingsfname2.c_str()); -#endif - sls_detector_module *myMod1=createModule(); - sls_detector_module *myMod2=createModule(); - int iodelay1 = -1; //not included in the module - int tau1 = -1; //not included in the module - int iodelay2 = -1; //not included in the module - int tau2 = -1; //not included in the module - if (NULL == readSettingsFile(settingsfname1,thisDetector->myDetectorType, - iodelay1, tau1, myMod1, tb)) { - setErrorMask((getErrorMask())|(SETTINGS_FILE_NOT_OPEN)); - deleteModule(myMod1); - deleteModule(myMod2); - return FAIL; - } - if (NULL == readSettingsFile(settingsfname2,thisDetector->myDetectorType, - iodelay2, tau2, myMod2, tb)) { - setErrorMask((getErrorMask())|(SETTINGS_FILE_NOT_OPEN)); - deleteModule(myMod1); - deleteModule(myMod2); - return FAIL; - } - if (iodelay1 != iodelay2) { - printf("iodelays do not match between files\n"); - setErrorMask((getErrorMask())|(SETTINGS_NOT_SET)); - deleteModule(myMod1); - deleteModule(myMod2); - return FAIL; - } - iodelay = iodelay1; - - //interpolate module - myMod = interpolateTrim(thisDetector->myDetectorType, myMod1, myMod2, - e_eV, trim1, trim2, tb); - if (myMod == NULL) { - printf("Could not interpolate, different dac values in files\n"); - setErrorMask((getErrorMask())|(SETTINGS_NOT_SET)); - deleteModule(myMod1); - deleteModule(myMod2); - return FAIL; - } - //interpolate tau - tau = linearInterpolation(e_eV, trim1, trim2, tau1, tau2); - //printf("new tau:%d\n",tau); - - deleteModule(myMod1); - deleteModule(myMod2); - } - - - myMod->module=0; - myMod->reg=thisDetector->currentSettings; - setModule(*myMod, iodelay, tau, e_eV, 0, 0, tb); - deleteModule(myMod); - if (getSettings(-1) != is){ - std::cout << "Could not set settings in detector" << endl; - setErrorMask((getErrorMask())|(SETTINGS_NOT_SET)); - return FAIL; - } - - return OK; -} - - - - -string slsDetector::getSettingsDir() { - return std::string(thisDetector->settingsDir); -} -string slsDetector::setSettingsDir(string s) { - sprintf(thisDetector->settingsDir, "%s", s.c_str()); - return thisDetector->settingsDir; -} -string slsDetector::getCalDir() { - return thisDetector->calDir; -} -string slsDetector::setCalDir(string s) { - sprintf(thisDetector->calDir, "%s", s.c_str()); - return thisDetector->calDir; -} - - - - - -int slsDetector::loadSettingsFile(string fname, int imod) { - - sls_detector_module *myMod=NULL; - - int iodelay = -1; - int tau = -1; - - string fn=fname; - fn=fname; - int mmin=0, mmax=setNumberOfModules(); - if (imod>=0) { - mmin=imod; - mmax=imod+1; - } - for (int im=mmin; immyDetectorType) { - case MYTHEN: - if (fname.find(".sn")==string::npos && fname.find(".trim")== - string::npos && fname.find(".settings")==string::npos) { - ostfn << ".sn" << setfill('0') << setw(3) << hex << - getId(MODULE_SERIAL_NUMBER, im); - } - break; - case EIGER: - if (fname.find(".sn")==string::npos && fname.find(".trim")== - string::npos && fname.find(".settings")==string::npos) { - ostfn << ".sn" << setfill('0') << setw(3) << dec << - getId(DETECTOR_SERIAL_NUMBER, im); - } - break; - default: - break; - } - fn=ostfn.str(); - myMod=readSettingsFile(fn, thisDetector->myDetectorType,iodelay, tau, myMod); - - if (myMod) { - myMod->module=im; - //settings is saved in myMod.reg for all except mythen - if(thisDetector->myDetectorType!=MYTHEN) - myMod->reg=-1; - setModule(*myMod,iodelay,tau,-1,0,0); - deleteModule(myMod); - } else - return FAIL; - } - return OK; -} - - -int slsDetector::saveSettingsFile(string fname, int imod) { - - sls_detector_module *myMod=NULL; - int ret=FAIL; - int iodelay = -1; - int tau = -1; - - int mmin=0, mmax=setNumberOfModules(); - if (imod>=0) { - mmin=imod; - mmax=imod+1; - } - for (int im=mmin; immyDetectorType) { - case MYTHEN: - ostfn << ".sn" << setfill('0') << setw(3) << hex << - getId(MODULE_SERIAL_NUMBER,im); - break; - case EIGER: - ostfn << ".sn" << setfill('0') << setw(3) << dec << - getId(DETECTOR_SERIAL_NUMBER); - break; - default: - break; - } - fn=ostfn.str(); - if ((myMod=getModule(im))) { - - if(thisDetector->myDetectorType == EIGER){ - iodelay = (int)setDAC((dacs_t)-1,IO_DELAY,0,-1); - tau = (int64_t)getRateCorrectionTau(); - } - ret=writeSettingsFile(fn, thisDetector->myDetectorType, *myMod, - iodelay, tau); - deleteModule(myMod); - } - } - return ret; -} - - - - -int slsDetector::loadCalibrationFile(string fname, int imod) { - - if(thisDetector->myDetectorType == EIGER) { - std::cout << "Not required for this detector!" << std::endl; - return FAIL; - } - - sls_detector_module *myMod=NULL; - string fn=fname; - - int* gainval=0; int* offsetval=0; - if(thisDetector->nGain){ - gainval=new int[thisDetector->nGain]; - for(int i=0;inGain;++i) - gainval[i] = -1; - } - if(thisDetector->nOffset){ - offsetval=new int[thisDetector->nOffset]; - for(int i=0;inOffset;++i) - offsetval[i] = -1; - } - - fn=fname; - - - int mmin=0, mmax=setNumberOfModules(); - if (imod>=0) { - mmin=imod; - mmax=imod+1; - } - for (int im=mmin; immyDetectorType) { - case MYTHEN: - if (fname.find(".sn")==string::npos && fname.find(".cal")==string::npos) { - ostfn << ".sn" << setfill('0') << setw(3) << hex << - getId(MODULE_SERIAL_NUMBER, im); - } - break; - case EIGER: - if (fname.find(".sn")==string::npos && fname.find(".cal")==string::npos) { - ostfn << "." << setfill('0') << setw(3) << dec << - getId(DETECTOR_SERIAL_NUMBER); - } - break; - default: - break; - } - fn=ostfn.str(); - if((myMod=getModule(im))){ - //extra gain and offset - if(thisDetector->nGain){ - if(readCalibrationFile(fn, gainval, offsetval)==FAIL) - return FAIL; - } //normal gain and offset inside sls_detector_module - else{ - if(readCalibrationFile(fn,myMod->gain, myMod->offset)==FAIL) - return FAIL; - } - setModule(*myMod,-1,-1,-1,gainval,offsetval); - - deleteModule(myMod); - if(gainval) delete[]gainval; - if(offsetval) delete[] offsetval; - } else - return FAIL; - } - return OK; -} - - -int slsDetector::saveCalibrationFile(string fname, int imod) { - - - sls_detector_module *myMod=NULL; - int ret=FAIL; - - int mmin=0, mmax=setNumberOfModules(); - if (imod>=0) { - mmin=imod; - mmax=imod+1; - } - for (int im=mmin; immyDetectorType) { - case MYTHEN: - ostfn << ".sn" << setfill('0') << setw(3) << hex << - getId(MODULE_SERIAL_NUMBER,im); - break; - case EIGER: - ostfn << ".sn" << setfill('0') << setw(3) << dec << - getId(DETECTOR_SERIAL_NUMBER); - break; - default: - break; - } - fn=ostfn.str(); - if ((myMod=getModule(im))) { - //extra gain and offset - if(thisDetector->nGain) - ret=writeCalibrationFile(fn,gain, offset); - //normal gain and offset inside sls_detector_module - else - ret=writeCalibrationFile(fn,myMod->gain, myMod->offset); - - deleteModule(myMod); - }else - return FAIL; - } - return ret; -} - - - - -slsDetectorDefs::masterFlags slsDetector::setMaster(masterFlags flag) { - - - int fnum=F_SET_MASTER; - masterFlags retval=GET_MASTER; - char mess[MAX_STR_LENGTH]=""; - int ret=OK; - -#ifdef VERBOSE - std::cout<< "Setting master flags to "<< flag << std::endl; -#endif - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&flag,sizeof(flag)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } else { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - -#ifdef VERBOSE - std::cout<< "Master flag set to "<< retval << std::endl; -#endif - return retval; -} - - - - -slsDetectorDefs::synchronizationMode slsDetector::setSynchronization(synchronizationMode flag) { - - - - int fnum=F_SET_SYNCHRONIZATION_MODE; - synchronizationMode retval=GET_SYNCHRONIZATION_MODE; - char mess[MAX_STR_LENGTH]=""; - int ret=OK; - -#ifdef VERBOSE - std::cout<< "Setting synchronization mode to "<< flag << std::endl; -#endif - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&flag,sizeof(flag)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } else { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - -#ifdef VERBOSE - std::cout<< "Readout flag set to "<< retval << std::endl; -#endif - return retval; - -} - - -int slsDetector::setTotalProgress() { - - int nf=1, npos=1, nscan[MAX_SCAN_LEVELS]={1,1}, nc=1, nm=1, ns=1; - - if (thisDetector->timerValue[FRAME_NUMBER]) - nf=thisDetector->timerValue[FRAME_NUMBER]; - - if (thisDetector->timerValue[CYCLES_NUMBER]>0) - nc=thisDetector->timerValue[CYCLES_NUMBER]; - - if (thisDetector->timerValue[STORAGE_CELL_NUMBER]>0) - ns=thisDetector->timerValue[STORAGE_CELL_NUMBER]+1; - - if (thisDetector->numberOfPositions>0) - npos=thisDetector->numberOfPositions; - - if (timerValue[MEASUREMENTS_NUMBER]>0) - nm=timerValue[MEASUREMENTS_NUMBER]; - - - if ((thisDetector->nScanSteps[0]>0) && (thisDetector->actionMask & - (1 << MAX_ACTIONS))) - nscan[0]=thisDetector->nScanSteps[0]; - - if ((thisDetector->nScanSteps[1]>0) && (thisDetector->actionMask & - (1 << (MAX_ACTIONS+1)))) - nscan[1]=thisDetector->nScanSteps[1]; - - thisDetector->totalProgress=nf*nc*ns*npos*nm*nscan[0]*nscan[1]; - -#ifdef VERBOSE -cout << "nc " << nc << endl; -cout << "nm " << nm << endl; -cout << "nf " << nf << endl; -cout << "ns " << ns << endl; -cout << "npos " << npos << endl; -cout << "nscan[0] " << nscan[0] << endl; -cout << "nscan[1] " << nscan[1] << endl; - -cout << "Set total progress " << thisDetector->totalProgress << endl; -#endif -return thisDetector->totalProgress; -} - -double slsDetector::getCurrentProgress() { - - return 100.*((double)thisDetector->progressIndex)/((double)thisDetector->totalProgress); -} - - - -slsDetectorDefs::runStatus slsDetector::getRunStatus() { - int fnum=F_GET_RUN_STATUS; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - strcpy(mess,"could not get run status"); - runStatus retval=ERROR; -#ifdef VERBOSE - std::cout<< "Getting status "<< std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (stopSocket) { - if (connectStop() == OK) { - stopSocket->SendDataOnly(&fnum,sizeof(fnum)); - stopSocket->ReceiveDataOnly(&ret,sizeof(ret)); - - //cout << "________:::____________" << ret << endl; - - if (ret==FAIL) { - stopSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } else { - stopSocket->ReceiveDataOnly(&retval,sizeof(retval)); - //cout << "____________________" << retval << endl; - } - disconnectStop(); - } - } - } - return retval; - - -} - - -int slsDetector::prepareAcquisition() { - int fnum = F_PREPARE_ACQUISITION; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - - if (thisDetector->onlineFlag==ONLINE_FLAG) { -#ifdef VERBOSE - std::cout << "Preparing Detector for Acquisition" << std::endl; -#endif - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL){ - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(PREPARE_ACQUISITION)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - }else - std::cout << "cannot connect to detector" << endl; - - return ret; -} - -int slsDetector::cleanupAcquisition() { - int fnum = F_CLEANUP_ACQUISITION; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - - if (thisDetector->onlineFlag==ONLINE_FLAG) { -#ifdef VERBOSE - std::cout << "Cleaning up Detector after Acquisition " << std::endl; -#endif - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL){ - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(CLEANUP_ACQUISITION)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - }else - std::cout << "cannot connect to detector" << endl; - - return ret; - -} - - - -int slsDetector::startAcquisition() { - - int fnum=F_START_ACQUISITION; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - -#ifdef VERBOSE - std::cout<< "Starting acquisition "<< std::endl; -#endif - thisDetector->stoppedFlag=0; - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - return ret; -} - - -int slsDetector::stopAcquisition() { - - // get status before stopping acquisition - runStatus s = ERROR, r = ERROR; - if (thisDetector->receiver_upstream) { - s = getRunStatus(); - r = getReceiverStatus(); - } - - int fnum=F_STOP_ACQUISITION; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - -#ifdef VERBOSE - std::cout<< "Stopping acquisition "<< std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (stopSocket) { - if (connectStop() == OK) { - stopSocket->SendDataOnly(&fnum,sizeof(fnum)); - stopSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - stopSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectStop(); - } - } - } - thisDetector->stoppedFlag=1; - - // if rxr streaming and acquisition finished, restream dummy stop packet - if ((thisDetector->receiver_upstream) && (s == IDLE) && (r == IDLE)) { - restreamStopFromReceiver(); - } - - return ret; - - -} - - -int slsDetector::sendSoftwareTrigger() { - - int fnum=F_SOFTWARE_TRIGGER; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - -#ifdef VERBOSE - std::cout<< "Sending software trigger "<< std::endl; -#endif - thisDetector->stoppedFlag=0; - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - return ret; -} - - - -int slsDetector::startReadOut() { - - int fnum=F_START_READOUT; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - -#ifdef VERBOSE - std::cout<< "Starting readout "<< std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - return ret; -} - - - -int* slsDetector::startAndReadAll() { - //cout << "Start and read all "<< endl; - - int* retval; - //#ifdef VERBOSE -#ifdef VERBOSE - int i=0; - //#endif -#endif - if(thisDetector->myDetectorType == EIGER) { - if (prepareAcquisition() == FAIL) - return NULL; - } - startAndReadAllNoWait(); - //#ifdef VERBOSE - // std::cout<< "started" << std::endl; - //#endif - while ((retval=getDataFromDetector())){ - #ifdef VERBOSE - ++i; - // std::cout<< i << std::endl; - //#else - //std::cout<< "-" << flush; - #endif - dataQueue.push(retval); - - // std::cout<< "pushed" << retval << std::endl; - } - disconnectControl(); - -#ifdef VERBOSE - std::cout<< "received "<< i<< " frames" << std::endl; - //#else - // std::cout << std::endl; - #endif - return dataQueue.front(); // check what we return! - /* while ((retval=getDataFromDetectorNoWait())) - ++i; - #ifdef VERBOSE - std::cout<< "Received " << i << " frames"<< std::endl; - #endif - return dataQueue.front(); // check what we return! - */ - -} - - - -int slsDetector::startAndReadAllNoWait() { - - int fnum= F_START_AND_READ_ALL; - -#ifdef VERBOSE - std::cout<< "Starting and reading all frames "<< std::endl; -#endif - thisDetector->stoppedFlag=0; - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - //std::cout<< "connected" << std::endl; - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - return OK; - } - } - return FAIL; -} - - - - -int* slsDetector::getDataFromDetector(int *retval) { - int ret=FAIL; - char mess[MAX_STR_LENGTH]="Nothing"; - int nel=thisDetector->dataBytes/sizeof(int); - int n; - int *r=retval; - - int nodatadetectortype = false; - detectorType types = getDetectorsType(); - // cout << types << endl; - - if(types == EIGER || types == JUNGFRAU || types == GOTTHARD || types == PROPIX){ - nodatadetectortype = true; - } - - //cout << "nodata det" << nodatadetectortype << endl; - - if (!nodatadetectortype && retval==NULL) - retval=new int[nel]; - - -#ifdef VERBOSE - std::cout<< "getting data "<< thisDetector->dataBytes << " " << nel<< std::endl; -#endif - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); -#ifdef VERBOSE - cout << "ret=" << ret << endl; -#endif - - if (ret!=OK) { - n= controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - // if(thisDetector->receiverOnlineFlag == OFFLINE_FLAG) - if (ret==FAIL) { - thisDetector->stoppedFlag=1; - std::cout<< "Detector returned: " << mess << " " << n << std::endl; - } else { - ; - #ifdef VERBOSE - std::cout<< "Detector successfully returned: " << mess << " " << n - << std::endl; - #endif - } - if ((!nodatadetectortype) && (r==NULL)){ - delete [] retval; - } - return NULL; - } else if (!nodatadetectortype){ - // cout <<"??" << endl; - n=controlSocket->ReceiveDataOnly(retval,thisDetector->dataBytes); - - #ifdef VERBOSE - std::cout<< "Received "<< n << " data bytes" << std::endl; - #endif - if (n!=thisDetector->dataBytes) { - std::cout<< "wrong data size received from detector: received " << - n << " but expected " << thisDetector->dataBytes << std::endl; - thisDetector->stoppedFlag=1; - ret=FAIL; - if (r==NULL) { - delete [] retval; - } - return NULL; - } - // for (int ib=0; ibdataBytes/8; ++ib) - // cout << ((*(((u_int64_t*)retval)+ib))>>17&1) ; - - - } - - // cout << "get data returning " << retval << endl; - // cout << endl; - return retval; - -} - - - -int* slsDetector::readFrame() { - - int fnum=F_READ_FRAME; - int* retval=NULL; - -#ifdef VERBOSE - std::cout<< "slsDetector: Reading frame "<< std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - retval=getDataFromDetector(); - if (retval) { - dataQueue.push(retval); - disconnectControl(); - } - } - } - return retval; -} - - - - -int* slsDetector::readAll() { - - int fnum=F_READ_ALL; - int* retval; // check what we return! - -#ifdef VERBOSE - int i=0; - std::cout<< "Reading all frames "<< std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - - while ((retval=getDataFromDetector())){ -#ifdef VERBOSE - ++i; - std::cout<< i << std::endl; -#endif - dataQueue.push(retval); - } - disconnectControl(); - } - } -#ifdef VERBOSE - std::cout<< "received "<< i<< " frames" << std::endl; -#endif - return dataQueue.front(); // check what we return! - -} - - -int slsDetector::readAllNoWait() { - - int fnum= F_READ_ALL; - -#ifdef VERBOSE - std::cout<< "Reading all frames "<< std::endl; -#endif - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - return OK; - } - } - return FAIL; -} - - - -int slsDetector::configureMAC() { - int i; - int ret=FAIL; - int fnum=F_CONFIGURE_MAC; - char mess[MAX_STR_LENGTH]=""; - char arg[6][50];memset(arg,0,sizeof(char)*6*50); - int retval=-1; - - // to send 3d positions to detector - bool sendpos = 0; - int pos[3]={0,0,0}; - - // only jungfrau and eiger, send x, y and z in detector udp header - if (thisDetector->myDetectorType == JUNGFRAU || - thisDetector->myDetectorType == EIGER) { - sendpos = true; - int max = multiDet->getNumberOfDetectors(Y); - - pos[0] = (detId % max); // row - pos[1] = (detId / max) * ((thisDetector->myDetectorType == EIGER) ? 2 : 1);// col for horiz. udp ports - } -#ifdef VERBOSE - cout << "SLS [" << detId << "] - (" << pos[0] << "," << pos[1] << "," << - pos[2] << ")" << endl; -#endif - - - //if udpip wasnt initialized in config file - if(!(strcmp(thisDetector->receiverUDPIP,"none"))){ - //hostname is an ip address - if(strchr(thisDetector->receiver_hostname,'.')!=NULL) - strcpy(thisDetector->receiverUDPIP,thisDetector->receiver_hostname); - //if hostname not ip, convert it to ip - else{ - struct addrinfo *result; - if (!dataSocket->ConvertHostnameToInternetAddress( - thisDetector->receiver_hostname, &result)) { - // on success - memset(thisDetector->receiverUDPIP, 0, MAX_STR_LENGTH); - // on failure, back to none - if (dataSocket->ConvertInternetAddresstoIpString(result, - thisDetector->receiverUDPIP, MAX_STR_LENGTH)) { - strcpy(thisDetector->receiverUDPIP, "none"); - } - } - } - } - strcpy(arg[0],thisDetector->receiverUDPIP); - strcpy(arg[1],thisDetector->receiverUDPMAC); - sprintf(arg[2],"%x",thisDetector->receiverUDPPort); - strcpy(arg[3],thisDetector->detectorMAC); - strcpy(arg[4],thisDetector->detectorIP); - sprintf(arg[5],"%x",thisDetector->receiverUDPPort2); -#ifdef VERBOSE - std::cout<< "Configuring MAC"<< std::endl; -#endif - - - - for(i=0;i<2;++i){ - if(!strcmp(arg[i],"none")){ - std::cout<< "Configure MAC Error. IP/MAC Addresses not set"<< std::endl; - setErrorMask((getErrorMask())|(COULD_NOT_CONFIGURE_MAC)); - return FAIL; - } - } - -#ifdef VERBOSE - std::cout<< "IP/MAC Addresses valid "<< std::endl; -#endif - - - { - //converting IPaddress to hex - stringstream ss(arg[0]); - char cword[50]=""; - bzero(cword, 50); - string s; - while (getline(ss, s, '.')) { - sprintf(cword,"%s%02x",cword,atoi(s.c_str())); - } - bzero(arg[0], 50); - strcpy(arg[0],cword); -#ifdef VERBOSE - std::cout<<"receiver udp ip:"<onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(arg,sizeof(arg)); - if(sendpos) - controlSocket->SendDataOnly(pos,sizeof(pos)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL){ - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(COULD_NOT_CONFIGURE_MAC)); - } - else { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - if (thisDetector->myDetectorType == EIGER) { - //rewrite detectormac, detector ip - char arg[2][50]; - memset(arg,0,sizeof(arg)); - uint64_t idetectormac = 0; - uint32_t idetectorip = 0; - controlSocket->ReceiveDataOnly(arg,sizeof(arg)); - sscanf(arg[0], "%lx", &idetectormac); - sscanf(arg[1], "%x", &idetectorip); - sprintf(arg[0],"%02x:%02x:%02x:%02x:%02x:%02x", - (unsigned int)((idetectormac>>40)&0xFF), - (unsigned int)((idetectormac>>32)&0xFF), - (unsigned int)((idetectormac>>24)&0xFF), - (unsigned int)((idetectormac>>16)&0xFF), - (unsigned int)((idetectormac>>8)&0xFF), - (unsigned int)((idetectormac>>0)&0xFF)); - sprintf(arg[1],"%d.%d.%d.%d", - (idetectorip>>24)&0xff, - (idetectorip>>16)&0xff, - (idetectorip>>8)&0xff, - (idetectorip)&0xff); - if (strcasecmp(arg[0],thisDetector->detectorMAC)) { - memset(thisDetector->detectorMAC, 0, MAX_STR_LENGTH); - strcpy(thisDetector->detectorMAC, arg[0]); - cprintf(RESET,"%d: Detector MAC updated to %s\n", detId, - thisDetector->detectorMAC); - } - if (strcasecmp(arg[1],thisDetector->detectorIP)) { - memset(thisDetector->detectorIP, 0, MAX_STR_LENGTH); - strcpy(thisDetector->detectorIP, arg[1]); - cprintf(RESET,"%d: Detector IP updated to %s\n", detId, - thisDetector->detectorIP); - } - } - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - if (ret==FAIL) { - ret=FAIL; - std::cout<< "Configuring MAC failed " << std::endl; - setErrorMask((getErrorMask())|(COULD_NOT_CONFIGURE_MAC)); - } - - return ret; -} - - - - -int64_t slsDetector::setTimer(timerIndex index, int64_t t, int imod) { - - - int fnum=F_SET_TIMER,fnum2=F_SET_RECEIVER_TIMER; - int64_t retval = -1; - char mess[MAX_STR_LENGTH]=""; - int ret=OK; - - if (index!=MEASUREMENTS_NUMBER) { - - -#ifdef VERBOSE - std::cout<< "Setting timer "<< index << " to " << t << "ns/value" << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&index,sizeof(index)); - controlSocket->SendDataOnly(&t,sizeof(t)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(DETECTOR_TIMER_VALUE_NOT_SET)); - } else { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - thisDetector->timerValue[index]=retval; - } - disconnectControl(); - if (ret==FORCE_UPDATE) { - updateDetector(); -#ifdef VERBOSE - std::cout<< "Updated!" << std::endl; -#endif - - } - } - } else { - //std::cout<< "offline " << std::endl; - if (t>=0) - thisDetector->timerValue[index]=t; - if((thisDetector->myDetectorType==GOTTHARD)|| - (thisDetector->myDetectorType==PROPIX)|| - (thisDetector->myDetectorType==JUNGFRAU)|| - (thisDetector->myDetectorType==MOENCH)) - thisDetector->timerValue[PROBES_NUMBER]=0; - if(thisDetector->myDetectorType==JUNGFRAUCTB && index==SAMPLES_JCTB) { - getTotalNumberOfChannels(); - // thisDetector->dataBytes=getTotalNumberOfChannels()* - //thisDetector->dynamicRange/8*thisDetector->timerValue[SAMPLES_JCTB]; - } - - } - } else { - if (t>=0) - thisDetector->timerValue[index]=t; - } -#ifdef VERBOSE - std::cout<< "Timer " << index << " set to "<< thisDetector->timerValue[index] - << "ns" << std::endl; -#endif - - if ((thisDetector->myDetectorType==MYTHEN)&&(index==PROBES_NUMBER)) { - setDynamicRange(); - //cout << "Changing probes: data size = " << thisDetector->dataBytes <myDetectorType==JUNGFRAUCTB) && (index==SAMPLES_JCTB)) { - setDynamicRange(); - cout << "Changing samples: data size = " << thisDetector->dataBytes <myDetectorType==MYTHEN)&&(index==PROBES_NUMBER)) { - setDynamicRange(); - //cout << "Changing probes: data size = " << thisDetector->dataBytes <myDetectorType == EIGER) && - getRateCorrection(r) && - (t>=0) && - - (((index == SUBFRAME_ACQUISITION_TIME) && - (thisDetector->dynamicRange == 32))|| - ((index == ACQUISITION_TIME) && - (thisDetector->dynamicRange == 16))) - - && (t>=0) && getRateCorrection(r)){ - setRateCorrection(r); - } - } - - - - - //send acquisiton time/period/subexptime/frame/cycles/samples to receiver - if((index==FRAME_NUMBER)||(index==FRAME_PERIOD)||(index==CYCLES_NUMBER)|| - (index==ACQUISITION_TIME) || (index==SUBFRAME_ACQUISITION_TIME) || - (index==SUBFRAME_DEADTIME) || - (index==SAMPLES_JCTB) || (index==STORAGE_CELL_NUMBER)){ - string timername = getTimerType(index); - if(ret != FAIL){ - int64_t args[2]; - retval = -1; - args[0] = index; - args[1] = thisDetector->timerValue[index]; - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ - - //set #frames * #cycles - if((index==FRAME_NUMBER)||(index==CYCLES_NUMBER)|| - (index==STORAGE_CELL_NUMBER)){ - timername.assign("(Number of Frames) * (Number of cycles) " - "* (Number of storage cells)"); - args[1] = thisDetector->timerValue[FRAME_NUMBER] * - ((thisDetector->timerValue[CYCLES_NUMBER] > 0) ? - (thisDetector->timerValue[CYCLES_NUMBER]) : 1) * - ((thisDetector->timerValue[STORAGE_CELL_NUMBER] > 0) - ? (thisDetector->timerValue[STORAGE_CELL_NUMBER])+1 : 1); -#ifdef VERBOSE - std::cout << "Setting/Getting " << timername << " " << index - <<" to/from receiver " << args[1] << std::endl; -#endif - } -#ifdef VERBOSE - // set period/exptime/subexptime/subperiod - else std::cout << "Setting/Getting " << timername << " " << index - << " to/from receiver " << args[1] << std::endl; -#endif - - char mess[MAX_STR_LENGTH]=""; - if (connectData() == OK){ - ret=thisReceiver->sendIntArray(fnum2,retval,args,mess); - disconnectData(); - } - if((args[1] != retval)|| (ret==FAIL)){ - ret = FAIL; - cout << "ERROR: " << timername << " in receiver set incorrectly to " - << retval << " instead of " << args[1] << endl; - - if(strstr(mess,"receiver is not idle")==NULL) { - switch(index) { - case ACQUISITION_TIME: - setErrorMask((getErrorMask())|(RECEIVER_ACQ_TIME_NOT_SET)); - break; - case FRAME_PERIOD: - setErrorMask((getErrorMask())|(RECEIVER_ACQ_PERIOD_NOT_SET)); - break; - case SUBFRAME_ACQUISITION_TIME: - case SUBFRAME_DEADTIME: - case SAMPLES_JCTB: - setErrorMask((getErrorMask())|(RECEIVER_TIMER_NOT_SET)); - break; - default: - setErrorMask((getErrorMask())|(RECEIVER_FRAME_NUM_NOT_SET)); - break; - } - } - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - } - } - return thisDetector->timerValue[index]; -} - - - -int64_t slsDetector::getTimeLeft(timerIndex index, int imod) { - - - int fnum=F_GET_TIME_LEFT; - int64_t retval = FAIL; - char mess[MAX_STR_LENGTH]=""; - int ret=OK; - -#ifdef VERBOSE - std::cout<< "Getting timer "<< index << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (stopSocket) { - if (connectStop() == OK) { - stopSocket->SendDataOnly(&fnum,sizeof(fnum)); - stopSocket->SendDataOnly(&index,sizeof(index)); - stopSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - stopSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } else { - stopSocket->ReceiveDataOnly(&retval,sizeof(retval)); - } - disconnectStop(); - } - } - } -#ifdef VERBOSE - std::cout<< "Time left is "<< retval << std::endl; -#endif - return retval; - -} - - - -int slsDetector::setSpeed(speedVariable sp, int value) { - - - int fnum=F_SET_SPEED; - int retval=-1; - char mess[MAX_STR_LENGTH]=""; - int ret=OK; - -#ifdef VERBOSE - std::cout<< "Setting speed variable"<< sp << " to " << value << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&sp,sizeof(sp)); - controlSocket->SendDataOnly(&value,sizeof(value)); -#ifdef VERBOSE - std::cout<< "Sent "<< n << " bytes " << std::endl; -#endif - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(COULD_NOT_SET_SPEED_PARAMETERS)); - } else { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } -#ifdef VERBOSE - std::cout<< "Speed set to "<< retval << std::endl; -#endif - return retval; - -} - - -int slsDetector::setDynamicRange(int n) { - - // cout << "single " << endl; - int fnum=F_SET_DYNAMIC_RANGE,fnum2=F_SET_RECEIVER_DYNAMIC_RANGE; - int retval=-1,retval1; - char mess[MAX_STR_LENGTH]=""; - int ret=OK, rateret=OK; - -#ifdef VERBOSE - std::cout<< "Setting dynamic range to "<< n << std::endl; -#endif - if ((thisDetector->myDetectorType == MYTHEN) &&(n==24)) - n=32; - - - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&n,sizeof(n)); - //rate correction is switched off if not 32 bit mode - if(thisDetector->myDetectorType == EIGER){ - controlSocket->ReceiveDataOnly(&rateret,sizeof(rateret)); - if (rateret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - if(strstr(mess,"Rate Correction")!=NULL){ - if(strstr(mess,"32")!=NULL) - setErrorMask((getErrorMask())|(RATE_CORRECTION_NOT_32or16BIT)); - else - setErrorMask((getErrorMask())|(COULD_NOT_SET_RATE_CORRECTION)); - } - } - } - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } else { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } else if(thisDetector->myDetectorType==MYTHEN){ - if (n>0) - thisDetector->dynamicRange=n; - retval=thisDetector->dynamicRange; - } - //cout << "detector returned dynamic range " << retval << endl; - if (ret!=FAIL && retval>0) { - /* checking the number of probes to chose the data size */ - - - - thisDetector->dataBytes=thisDetector->nMod[X]*thisDetector->nMod[Y]* - thisDetector->nChips*thisDetector->nChans*retval/8; - thisDetector->dataBytesInclGapPixels = - (thisDetector->nMod[X] * thisDetector->nChip[X] * - thisDetector->nChan[X] + thisDetector->gappixels * - thisDetector->nGappixels[X]) * - (thisDetector->nMod[Y] * thisDetector->nChip[Y] * - thisDetector->nChan[Y] + thisDetector->gappixels * - thisDetector->nGappixels[Y]) * - retval/8; - if (thisDetector->myDetectorType==JUNGFRAUCTB) { - // thisDetector->nChip[X]=retval/16; - // thisDetector->nChips=thisDetector->nChip[X]*thisDetector->nChip[Y]; - // cout << thisDetector->nMod[X]*thisDetector->nMod[Y] << " " - //<< thisDetector->nChans*thisDetector->nChips << " " << retval<< " "; - getTotalNumberOfChannels(); - //thisDetector->dataBytes=getTotalNumberOfChannels()* - //retval/8*thisDetector->timerValue[SAMPLES_JCTB]; - //cout << "data bytes: "<< thisDetector->dataBytes << endl; - } - if(thisDetector->myDetectorType==MYTHEN){ - if (thisDetector->timerValue[PROBES_NUMBER]!=0) { - thisDetector->dataBytes=thisDetector->nMod[X]* - thisDetector->nMod[Y]*thisDetector->nChips*thisDetector->nChans*4; - thisDetector->dataBytesInclGapPixels = - (thisDetector->nMod[X] * thisDetector->nChip[X] * - thisDetector->nChan[X] + thisDetector->gappixels * - thisDetector->nGappixels[X]) * - (thisDetector->nMod[Y] * thisDetector->nChip[Y] * - thisDetector->nChan[Y] + thisDetector->gappixels * - thisDetector->nGappixels[Y]) * - 4; - } - - if (retval==32) - thisDetector->dynamicRange=24; - } - - thisDetector->dynamicRange=retval; - - -#ifdef VERBOSE - std::cout<< "Dynamic range set to "<< thisDetector->dynamicRange << std::endl; - std::cout<< "Data bytes "<< thisDetector->dataBytes << std::endl; -#endif - } - - - //receiver - if(ret != FAIL){ - retval = thisDetector->dynamicRange; - if((n==-1) && (ret!= FORCE_UPDATE)) n =-1; - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending/Getting dynamic range to/from receiver " << - n << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum2,retval1,n); - disconnectData(); - } - if ((ret==FAIL) || (retval1 != retval)){ - ret = FAIL; - cout << "ERROR:Dynamic range in receiver set incorrectly to " << - retval1 << " instead of " << retval << endl; - setErrorMask((getErrorMask())|(RECEIVER_DYNAMIC_RANGE)); - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - } - - return thisDetector->dynamicRange; -} - - -int slsDetector::getDataBytes() { - return thisDetector->dataBytes; -} - - -int slsDetector::getDataBytesInclGapPixels() { - return thisDetector->dataBytesInclGapPixels; -} - - -dacs_t slsDetector::setDAC(dacs_t val, dacIndex index, int mV, int imod) { - - dacs_t retval[2]; - retval[0] = -1; - retval[1] = -1; - if (index!=ZMQ_emin && index!=ZMQ_emax) { - int fnum=F_SET_DAC; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - int arg[3]; - - - if ( (index==HV_NEW) &&((thisDetector->myDetectorType == GOTTHARD) || - (thisDetector->myDetectorType == PROPIX))) - index=HV_POT; - - arg[0]=index; - arg[1]=imod; - arg[2]=mV; - - -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Setting DAC "<< index << " of module " << imod << " to " << - val << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(arg,sizeof(arg)); - controlSocket->SendDataOnly(&val,sizeof(val)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - controlSocket->ReceiveDataOnly(retval,sizeof(retval)); - if (index < thisDetector->nDacs){ - - if (dacs) { - if (imod>=0) { - *(dacs+index+imod*thisDetector->nDacs)=retval[0]; - } - else { - for (imod=0; imodnModsMax; ++imod) - *(dacs+index+imod*thisDetector->nDacs)=retval[0]; - } - } - } - } else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - - } - } -#ifdef VERBOSE - std::cout<< "Dac set to "<< retval[0] << " dac units (" << retval[1] << "mV)" - << std::endl; -#endif - if (ret==FAIL) { - std::cout<< "Set dac " << index << " of module " << imod << " to " << - val << " failed." << std::endl; - } - if(mV) - return retval[1]; - } else if(thisDetector->myDetectorType==JUNGFRAUCTB) { - - string header=getNetworkParameter(ADDITIONAL_JSON_HEADER); - - std::cout<< "Old json header: " << header << std::endl; - - if (index==ZMQ_emin) { - - size_t pos0, pos1; - pos0=header.find(",\"eMin\""); - if (pos0==std::string::npos) { - pos0=header.find("\"eMin\""); - } else pos0++; - if (pos0!=std::string::npos) { - pos1=header.find_first_of(",",pos0); - // std::cout << pos0 << " " << pos1 << std::endl; - std::cout<< "Replacing old eMin: " << header.substr(pos0,pos1-pos0) << std::endl; - // if (pos1!=std::string::npos) - if (val>=0) - header.erase(pos0,pos1-pos0); - // else - // header.erase(pos0); - } - if (val>=0) { - if (header.length()>0) { - if (header.at(0)==',') - header.erase(0,1); - if (header.length()>0) - header.append(","); - } - // std::cout<< "Left: " << header << std::endl; - char h[1000]; - sprintf(h,"\"eMin\":%d",val); - // std::cout<< "new ROI: " << h << std::endl; - - header.append(h); - } else { - sscanf(header.substr(pos0,pos1-pos0).c_str(),"\"eMin\":%d",&val); - } - - } else if (index==ZMQ_emax) { - - - size_t pos0, pos1; - pos0=header.find(",\"eMax\""); - if (pos0==std::string::npos) { - pos0=header.find("\"eMax\""); - } else pos0++; - if (pos0!=std::string::npos) { - pos1=header.find_first_of(",",pos0); - // std::cout << pos0 << " " << pos1 << std::endl; - std::cout<< "Replacing old eMax: " << header.substr(pos0,pos1-pos0) << std::endl; - // if (pos1!=std::string::npos) - if (val>=0) - header.erase(pos0,pos1-pos0); - // else - // header.erase(pos0); - } - if (val>=0) { - if (header.length()>0) { - if (header.at(0)==',') - header.erase(0,1); - if (header.length()>0) - header.append(","); - } - // std::cout<< "Left: " << header << std::endl; - char h[1000]; - sprintf(h,"\"eMax\":%d",val); - // std::cout<< "new ROI: " << h << std::endl; - - header.append(h); - } else { - sscanf(header.substr(pos0,pos1-pos0).c_str(),"\"eMax\":%d",&val); - } - - } - - std::cout<< "New json header: " << header << std::endl; - setReceiverOnline(ONLINE_FLAG); - setNetworkParameter(ADDITIONAL_JSON_HEADER, header); - /***** END FOR ZMQ HEADER */ - retval[0]=val; - } - - return retval[0]; -} - - - - -dacs_t slsDetector::getADC(dacIndex index, int imod) { - - dacs_t retval = 0; - int fnum=F_GET_ADC; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - - int arg[2]; - arg[0]=index; - arg[1]=imod; - - - -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Getting ADC "<< index << " of module " << imod << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectStop() == OK){ - stopSocket->SendDataOnly(&fnum,sizeof(fnum)); - stopSocket->SendDataOnly(arg,sizeof(arg)); - stopSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - stopSocket->ReceiveDataOnly(&retval,sizeof(retval)); - if (adcs) { - *(adcs+index+imod*thisDetector->nAdcs)=retval; - } - } else { - stopSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectStop(); - /*commented out to allow adc read during acquire, also not required - if (ret==FORCE_UPDATE) - updateDetector();*/ - } - } -#ifdef VERBOSE - std::cout<< "ADC returned "<< retval << std::endl; -#endif - if (ret==FAIL) { - std::cout<< "Get ADC failed " << std::endl; - } - - return retval; - - - -} - - - -slsDetectorDefs::externalCommunicationMode slsDetector::setExternalCommunicationMode( - externalCommunicationMode pol) { - - - - - int arg[1]; - externalCommunicationMode retval; - int fnum=F_SET_EXTERNAL_COMMUNICATION_MODE; - char mess[MAX_STR_LENGTH]=""; - - arg[0]=pol; - - int ret=FAIL; - retval=GET_EXTERNAL_COMMUNICATION_MODE; - -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Setting communication to mode " << pol << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&arg,sizeof(arg)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } else { - retval=GET_EXTERNAL_COMMUNICATION_MODE; - ret=FAIL; - } -#ifdef VERBOSE - std::cout<< "Communication mode "<< " set to" << retval << std::endl; -#endif - if (ret==FAIL) { - std::cout<< "Setting communication mode failed" << std::endl; - } - return retval; - -} - - - -slsDetectorDefs::externalSignalFlag slsDetector::setExternalSignalFlags( - externalSignalFlag pol, int signalindex) { - - - - - int arg[2]; - externalSignalFlag retval; - int ret=FAIL; - int fnum=F_SET_EXTERNAL_SIGNAL_FLAG; - char mess[MAX_STR_LENGTH]=""; - - arg[0]=signalindex; - arg[1]=pol; - - retval=GET_EXTERNAL_SIGNAL_FLAG; - -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Setting signal "<< signalindex << " to flag" << pol << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&arg,sizeof(arg)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } else { - retval=GET_EXTERNAL_SIGNAL_FLAG; - ret=FAIL; - } -#ifdef VERBOSE - std::cout<< "Signal "<< signalindex << " flag set to" << retval << std::endl; - if (ret==FAIL) { - std::cout<< "Set signal flag failed " << std::endl; - } -#endif - return retval; - - - - - - -} - - - - -int slsDetector::setReadOutFlags(readOutFlags flag) { - - - int fnum=F_SET_READOUT_FLAGS; - //readOutFlags retval; - int retval; - char mess[MAX_STR_LENGTH]=""; - int ret=OK; - - //#ifdef VERBOSE - std::cout<< "Setting readout flags to "<< hex << flag << dec << std::endl; - //#endif - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&flag,sizeof(flag)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(COULD_NOT_SET_READOUT_FLAGS)); - } else { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - thisDetector->roFlags=(readOutFlags)retval; - if (thisDetector->myDetectorType==JUNGFRAUCTB) { - - int nn=getTotalNumberOfChannels(); - cout << "Total number of channels is " << nn << endl; - //thisDetector->dataBytes=getTotalNumberOfChannels()* - //thisDetector->dynamicRange/8*thisDetector->timerValue[SAMPLES_JCTB]; - } - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } else { - if (flag!=GET_READOUT_FLAGS) - thisDetector->roFlags=flag; - } - - // std::cout<< "***ZMQ: " << hex<< flag << std::endl; - - if (flag & (PEDESTAL | NEWPEDESTAL | NEWFLAT | FLAT | FRAME)) { - - std::cout<< "***frameMode: " << std::endl; - string header=getNetworkParameter(ADDITIONAL_JSON_HEADER); - - std::cout<< "Old json header: " << header << std::endl; - //must be in the format '\"label1\":\"value1\",\"label2\":\"value2\"' etc." - // - size_t pos0; - pos0=header.find(",\"frameMode\""); - if (pos0==std::string::npos) { - pos0=header.find("\"frameMode\""); - } - if (pos0!=std::string::npos) { - size_t pos1=header.find_first_of(",",pos0+1); - // if (pos1!=std::string::npos) - if (flag!=GET_READOUT_FLAGS) { - cout << dec<< pos0 << " " << pos1 << endl; - std::cout<< "Replacing frame Mode: " << header.substr(pos0,pos1-pos0) << std::endl; - header.erase(pos0,pos1-pos0); - } - else if (header.substr(pos0,pos1+pos0)=="\"frameMode\":\"pedestal\"") - retval|=PEDESTAL; - else if (header.substr(pos0,pos1+pos0)=="\"frameMode\":\"newPedestal\"") - retval|=NEWPEDESTAL; - else if (header.substr(pos0,pos1+pos0)=="\"frameMode\":\"flatfield\"") - retval|=FLAT; - else if (header.substr(pos0,pos1+pos0)=="\"frameMode\":\"newFlatfield\"") - retval|=NEWFLAT; - else - retval|=FRAME; - - - } - char h[1000]; - switch (flag) { - case PEDESTAL: - retval|=PEDESTAL; - strcpy(h,"\"frameMode\":\"pedestal\""); - break; - case NEWPEDESTAL: - retval|=NEWPEDESTAL; - strcpy(h,"\"frameMode\":\"newPedestal\""); - break; - case FLAT: - retval|=FLAT; - strcpy(h,"\"frameMode\":\"flatfield\""); - break; - case NEWFLAT: - retval|=NEWFLAT; - strcpy(h,"\"frameMode\":\"newFlatfield\""); - break; - default: - retval|=FRAME; - strcpy(h,"\"frameMode\":\"frame\""); - } - if (flag!=GET_READOUT_FLAGS) { - if (header.length()>0) { - if (header.at(0)==',') - header.erase(0,1); - if (header.length()>0) - header.append(","); - } - header.append(h); - setReceiverOnline(ONLINE_FLAG); - setNetworkParameter(ADDITIONAL_JSON_HEADER, header); - } - std::cout<< "New json header: " << header << std::endl; - /***** END FOR ZMQ HEADER */ - ret=OK; - // retval=flag; - - } - - if (flag & (COUNTING | INTERPOLATING | ANALOG)) { - - std::cout<< "***detectorMode: " << std::endl; - - string header=getNetworkParameter(ADDITIONAL_JSON_HEADER); - - std::cout<< "Old json header: " << header << std::endl; - //must be in the format '\"label1\":\"value1\",\"label2\":\"value2\"' etc." - // - size_t pos0; - pos0=header.find(",\"detectorMode\""); - if (pos0==std::string::npos) { - pos0=header.find("\"detectorMode\""); - } - if (pos0!=std::string::npos) { - size_t pos1=header.find_first_of(",",pos0+1); - // if (pos1!=std::string::npos) - if (flag!=GET_READOUT_FLAGS) { - cout << dec<< pos0 << " " << pos1 << endl; - std::cout<< "Replacing detector Mode: " << header.substr(pos0,pos1-pos0) << std::endl; - header.erase(pos0,pos1-pos0); - } - else if (header.substr(pos0,pos1+pos0)=="\"detectorMode\":\"counting\"") - retval|=COUNTING; - else if (header.substr(pos0,pos1+pos0)=="\"detectorMode\":\"interpolating\"") - retval|=INTERPOLATING; - else - retval|=ANALOG; - } - char h[1000]; - switch (flag) { - case COUNTING: - strcpy(h,"\"detectorMode\":\"counting\""); - retval|=COUNTING; - break; - case INTERPOLATING: - retval|=INTERPOLATING; - strcpy(h,"\"detectorMode\":\"interpolating\""); - break; - default: - retval|=ANALOG; - strcpy(h,"\"detectorMode\":\"analog\""); - } - if (flag!=GET_READOUT_FLAGS) { - if (header.length()>0) { - if (header.at(0)==',') - header.erase(0,1); - if (header.length()>0) - header.append(","); - } - header.append(h); - setReceiverOnline(ONLINE_FLAG); - setNetworkParameter(ADDITIONAL_JSON_HEADER, header); - /***** END FOR ZMQ HEADER */ - // retval=flag; - } - std::cout<< "New json header: " << header << std::endl; - ret=OK; - } - - - if (ret==OK) { - - // thisDetector->roFlags=flag; - thisDetector->roFlags=(readOutFlags)retval; - } - - std::cout<< retval << std::endl; -#ifdef VERBOSE - std::cout<< "Readout flag set to "<< retval << std::endl; -#endif - return thisDetector->roFlags; -} - - -uint32_t slsDetector::writeRegister(uint32_t addr, uint32_t val) { - - uint32_t retval = 0; - int fnum=F_WRITE_REGISTER; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - uint32_t arg[2]; - arg[0]=addr; - arg[1]=val; - -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Writing to register "<< hex<onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(arg,sizeof(arg)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } -#ifdef VERBOSE - std::cout<< "Register returned "<< retval << std::endl; -#endif - if (ret==FAIL) { - std::cout<< "Write to register failed " << std::endl; - setErrorMask((getErrorMask())|(REGISER_WRITE_READ)); - } - - return retval; -} - - - -uint32_t slsDetector::readRegister(uint32_t addr) { - - uint32_t retval = 0; - int fnum=F_READ_REGISTER; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - uint32_t arg; - arg=addr; - - -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Reading register "<< hex<onlineFlag==ONLINE_FLAG) { - // if (connectControl() == OK){ - if (stopSocket) { - if (connectStop() == OK) { - stopSocket->SendDataOnly(&fnum,sizeof(fnum)); - stopSocket->SendDataOnly(&arg,sizeof(arg)); - stopSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) - stopSocket->ReceiveDataOnly(&retval,sizeof(retval)); - else { - stopSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectStop(); - } - } - } -#ifdef VERBOSE - std::cout<< "Register returned "<< retval << std::endl; -#endif - if (ret==FAIL) { - std::cout<< "Read register failed " << std::endl; - setErrorMask((getErrorMask())|(REGISER_WRITE_READ)); - } - return retval; - -} - - - - -uint32_t slsDetector::setBit(uint32_t addr, int n) { - if (n<0 || n>31) { - std::cout << "Bit number out of Range" << std:: endl; - setErrorMask((getErrorMask())|(REGISER_WRITE_READ)); - } - - // normal bit range - //TODO! (Erik) Check for errors! cannot use value since reg is 32bits - else { - uint32_t val = readRegister(addr); - writeRegister(addr,val | 1<31) { - std::cout << "Bit number out of Range" << std:: endl; - setErrorMask((getErrorMask())|(REGISER_WRITE_READ)); - } - - // normal bit range - else { - uint32_t val = readRegister(addr); - writeRegister(addr,val & ~(1<myDetectorType == EIGER) { - setReceiverUDPPort2(i); - return getReceiverUDPPort2(); - } else { - setReceiverUDPPort(i); - return getReceiverUDPPort(); - } - case DETECTOR_TXN_DELAY_LEFT: - case DETECTOR_TXN_DELAY_RIGHT: - case DETECTOR_TXN_DELAY_FRAME: - case FLOW_CONTROL_10G: - sscanf(value.c_str(),"%d",&i); - return setDetectorNetworkParameter(index, i); - case CLIENT_STREAMING_PORT: - return setClientStreamingPort(value); - case RECEIVER_STREAMING_PORT: - return setReceiverStreamingPort(value); - case CLIENT_STREAMING_SRC_IP: - return setClientStreamingIP(value); - case RECEIVER_STREAMING_SRC_IP: - return setReceiverStreamingIP(value); - case ADDITIONAL_JSON_HEADER: - return setAdditionalJsonHeader(value); - case RECEIVER_UDP_SCKT_BUF_SIZE: - sscanf(value.c_str(),"%d",&i); - setReceiverUDPSocketBufferSize(i); - return getReceiverUDPSocketBufferSize(); - - default: - return (char*)("unknown network parameter"); - } - -} - - - -string slsDetector::getNetworkParameter(networkParameter index) { - ostringstream ss;string s; - switch (index) { - case DETECTOR_MAC: - return getDetectorMAC(); - case DETECTOR_IP: - return getDetectorIP(); - case RECEIVER_HOSTNAME: - return getReceiver(); - case RECEIVER_UDP_IP: - return getReceiverUDPIP(); - case RECEIVER_UDP_MAC: - return getReceiverUDPMAC(); - case RECEIVER_UDP_PORT: - return getReceiverUDPPort(); - case RECEIVER_UDP_PORT2: - return getReceiverUDPPort2(); - case DETECTOR_TXN_DELAY_LEFT: - case DETECTOR_TXN_DELAY_RIGHT: - case DETECTOR_TXN_DELAY_FRAME: - case FLOW_CONTROL_10G: - return setDetectorNetworkParameter(index, -1); - case CLIENT_STREAMING_PORT: - return getClientStreamingPort(); - case RECEIVER_STREAMING_PORT: - return getReceiverStreamingPort(); - case CLIENT_STREAMING_SRC_IP: - return getClientStreamingIP(); - case RECEIVER_STREAMING_SRC_IP: - return getReceiverStreamingIP(); - case ADDITIONAL_JSON_HEADER: - return getAdditionalJsonHeader(); - case RECEIVER_UDP_SCKT_BUF_SIZE: - return getReceiverUDPSocketBufferSize(); - case RECEIVER_REAL_UDP_SCKT_BUF_SIZE: - return getReceiverRealUDPSocketBufferSize(); - - default: - return (char*)("unknown network parameter"); - } - -} - - - -string slsDetector::getDetectorMAC() { - return string(thisDetector->detectorMAC); -} - -string slsDetector::getDetectorIP() { - return string(thisDetector->detectorIP); -} - -string slsDetector::getReceiver() { - return string(thisDetector->receiver_hostname); -} - -string slsDetector::getReceiverUDPIP() { - return string(thisDetector->receiverUDPIP); -} - -string slsDetector::getReceiverUDPMAC() { - return string(thisDetector->receiverUDPMAC); -} -string slsDetector::getReceiverUDPPort() { - ostringstream ss; ss << thisDetector->receiverUDPPort; string s = ss.str(); - return s; -} -string slsDetector::getReceiverUDPPort2() { - ostringstream ss; ss << thisDetector->receiverUDPPort2; string s = ss.str(); - return s; -} -string slsDetector::getClientStreamingPort() { - ostringstream ss; ss << thisDetector->zmqport; string s = ss.str(); - return s; -} -string slsDetector::getReceiverStreamingPort() { - ostringstream ss; ss << thisDetector->receiver_zmqport; string s = ss.str(); - return s; -} -string slsDetector::getClientStreamingIP() { - return string(thisDetector->zmqip); -} -string slsDetector::getReceiverStreamingIP() { - return string(thisDetector->receiver_zmqip); -} -string slsDetector::getAdditionalJsonHeader() { - return string(thisDetector->receiver_additionalJsonHeader); -} -string slsDetector::getReceiverUDPSocketBufferSize() { - return setReceiverUDPSocketBufferSize(); -} - -string slsDetector::getReceiverRealUDPSocketBufferSize() { - - int fnum=F_RECEIVER_REAL_UDP_SOCK_BUF_SIZE; - int ret = FAIL; - int retval = -1; - - if(thisDetector->receiverOnlineFlag == ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Getting real UDP Socket Buffer size to receiver " << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->getInt(fnum,retval); - disconnectData(); - } - if(ret==FAIL) { - setErrorMask((getErrorMask())|(COULDNOT_SET_NETWORK_PARAMETER)); - printf("Warning: Could not get real socket buffer size\n"); - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - ostringstream ss; - ss << retval; - string s = ss.str(); - return s; -} - - -string slsDetector::setDetectorMAC(string detectorMAC) { - if(detectorMAC.length()==17){ - if((detectorMAC[2]==':')&&(detectorMAC[5]==':')&&(detectorMAC[8]==':')&& - (detectorMAC[11]==':')&&(detectorMAC[14]==':')){ - strcpy(thisDetector->detectorMAC,detectorMAC.c_str()); - if(!strcmp(thisDetector->receiver_hostname,"none")) -#ifdef VERBOSE - std::cout << "Warning: Receiver hostname not set yet." << endl; -#else - ; -#endif - else if(setUDPConnection()==FAIL) - std::cout<< "Warning: UDP connection set up failed" << std::endl; - }else{ - setErrorMask((getErrorMask())|(COULDNOT_SET_NETWORK_PARAMETER)); - std::cout << "Warning: server MAC Address should be in xx:xx:xx:xx:xx:xx " - "format" << endl; - } - } - else{ - setErrorMask((getErrorMask())|(COULDNOT_SET_NETWORK_PARAMETER)); - std::cout << "Warning: server MAC Address should be in xx:xx:xx:xx:xx:xx " - "format" << std::endl; - } - - return string(thisDetector->detectorMAC); -} - - - -string slsDetector::setDetectorIP(string detectorIP) { - struct sockaddr_in sa; - //taking function arguments into consideration - if(detectorIP.length()){ - if(detectorIP.length()<16){ - int result = inet_pton(AF_INET, detectorIP.c_str(), &(sa.sin_addr)); - if(result!=0){ - strcpy(thisDetector->detectorIP,detectorIP.c_str()); - if(!strcmp(thisDetector->receiver_hostname,"none")) -#ifdef VERBOSE - std::cout << "Warning: Receiver hostname not set yet." << endl; -#else - ; -#endif - else if(setUDPConnection()==FAIL) - std::cout<< "Warning: UDP connection set up failed" << std::endl; - }else{ - setErrorMask((getErrorMask())|(COULDNOT_SET_NETWORK_PARAMETER)); - std::cout << "Warning: Detector IP Address should be VALID and in " - "xxx.xxx.xxx.xxx format" << std::endl; - } - } - } - return string(thisDetector->detectorIP); -} - - - -string slsDetector::setReceiver(string receiverIP) { - - if(receiverIP == "none") { - memset(thisDetector->receiver_hostname, 0, MAX_STR_LENGTH); - strcpy(thisDetector->receiver_hostname,"none"); - thisDetector->receiverOnlineFlag = OFFLINE_FLAG; - return string(thisDetector->receiver_hostname); - } - - if(getRunStatus()==RUNNING){ - cprintf(RED,"Acquisition already running, Stopping it.\n"); - stopAcquisition(); - } - updateDetector(); - - strcpy(thisDetector->receiver_hostname,receiverIP.c_str()); - - if(setReceiverOnline(ONLINE_FLAG)==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Setting up receiver with" << endl; - std::cout << "detector type:" << slsDetectorBase::getDetectorType( - thisDetector->myDetectorType) << endl; - std::cout << "detector id:" << detId << endl; - std::cout << "detector hostname:" << thisDetector->hostname << endl; - std::cout << "file path:" << fileIO::getFilePath() << endl; - std::cout << "file name:" << fileIO::getFileName() << endl; - std::cout << "file index:" << fileIO::getFileIndex() << endl; - std::cout << "file format:" << fileIO::getFileFormat() << endl; - std::cout << "r_framesperfile:" << thisDetector->receiver_framesPerFile << endl; - std::cout << "r_discardpolicy:" << thisDetector->receiver_frameDiscardMode << endl; - std::cout << "r_padding:" << thisDetector->receiver_framePadding << endl; - pthread_mutex_lock(&ms); - std::cout << "write enable:" << multiDet->enableWriteToFileMask() << endl; - std::cout << "overwrite enable:" << multiDet->enableOverwriteMask() << endl; - pthread_mutex_unlock(&ms); - std::cout << "frame index needed:" << ((thisDetector->timerValue[FRAME_NUMBER] - *thisDetector->timerValue[CYCLES_NUMBER])>1) << endl; - std::cout << "frame period:" << thisDetector->timerValue[FRAME_PERIOD] << endl; - std::cout << "frame number:" << thisDetector->timerValue[FRAME_NUMBER] << endl; - std::cout << "sub exp time:" << thisDetector->timerValue[SUBFRAME_ACQUISITION_TIME] - << endl; - std::cout << "sub dead time:" << thisDetector->timerValue[SUBFRAME_DEADTIME] << endl; - std::cout << "dynamic range:" << thisDetector->dynamicRange << endl; - std::cout << "flippeddatax:" << thisDetector->flippedData[X] << endl; - if (thisDetector->myDetectorType == EIGER) { - std::cout << "activated: " << thisDetector->activated << endl; - std::cout << "receiver deactivated padding: " << thisDetector->receiver_deactivatedPaddingEnable << endl; - } - std::cout << "silent Mode:" << thisDetector->receiver_silentMode << endl; - std::cout << "10GbE:" << thisDetector->tenGigaEnable << endl; - std::cout << "Gap pixels: " << thisDetector->gappixels << endl; - std::cout << "rx streaming source ip:" << thisDetector->receiver_zmqip << endl; - std::cout << "rx additional json header:" << thisDetector->receiver_additionalJsonHeader << endl; - std::cout << "enable gap pixels:" << thisDetector->gappixels << endl; - std::cout << "rx streaming port:" << thisDetector->receiver_zmqport << endl; - std::cout << "r_readfreq:" << thisDetector->receiver_read_freq << endl; - std::cout << "rx_datastream:" << enableDataStreamingFromReceiver(-1) << endl << endl; - -#endif - if(setDetectorType()!= GENERIC){ - sendMultiDetectorSize(); - setDetectorId(); - setDetectorHostname(); - setUDPConnection(); - //setReceiverUDPSocketBufferSize(atoi(getReceiverUDPSocketBufferSize().c_str())); - - setFilePath(fileIO::getFilePath()); - setFileName(fileIO::getFileName()); - setFileIndex(fileIO::getFileIndex()); - setFileFormat(fileIO::getFileFormat()); - setReceiverFramesPerFile(thisDetector->receiver_framesPerFile); - setReceiverFramesDiscardPolicy(thisDetector->receiver_frameDiscardMode); - setReceiverPartialFramesPadding(thisDetector->receiver_framePadding); - pthread_mutex_lock(&ms); - int imask = multiDet->enableWriteToFileMask(); - pthread_mutex_unlock(&ms); - enableWriteToFile(imask); - pthread_mutex_lock(&ms); - imask = multiDet->enableOverwriteMask(); - pthread_mutex_unlock(&ms); - overwriteFile(imask); - setTimer(FRAME_PERIOD,thisDetector->timerValue[FRAME_PERIOD]); - setTimer(FRAME_NUMBER,thisDetector->timerValue[FRAME_NUMBER]); - setTimer(ACQUISITION_TIME,thisDetector->timerValue[ACQUISITION_TIME]); - if(thisDetector->myDetectorType == EIGER) { - setTimer(SUBFRAME_ACQUISITION_TIME, - thisDetector->timerValue[SUBFRAME_ACQUISITION_TIME]); - setTimer(SUBFRAME_DEADTIME,thisDetector->timerValue[SUBFRAME_DEADTIME]); - } - if(thisDetector->myDetectorType == JUNGFRAUCTB) - setTimer(SAMPLES_JCTB,thisDetector->timerValue[SAMPLES_JCTB]); - setDynamicRange(thisDetector->dynamicRange); - if(thisDetector->myDetectorType == EIGER){ - setFlippedData(X,-1); - activate(-1); - setDeactivatedRxrPaddingMode(thisDetector->receiver_deactivatedPaddingEnable); - } - setReceiverSilentMode(thisDetector->receiver_silentMode); - - if(thisDetector->myDetectorType == EIGER) - enableTenGigabitEthernet(thisDetector->tenGigaEnable); - - enableGapPixels(thisDetector->gappixels); - - // data streaming - setReadReceiverFrequency(thisDetector->receiver_read_freq); - setReceiverStreamingPort(getReceiverStreamingPort()); - setReceiverStreamingIP(getReceiverStreamingIP()); - setAdditionalJsonHeader(getAdditionalJsonHeader()); - enableDataStreamingFromReceiver(enableDataStreamingFromReceiver(-1)); - - if(thisDetector->myDetectorType == GOTTHARD) - sendROI(-1, NULL); - } - } - - return string(thisDetector->receiver_hostname); -} - - - - -string slsDetector::setReceiverUDPIP(string udpip) { - struct sockaddr_in sa; - //taking function arguments into consideration - if(udpip.length()){ - if(udpip.length()<16){ - int result = inet_pton(AF_INET, udpip.c_str(), &(sa.sin_addr)); - if(result==0){ - setErrorMask((getErrorMask())|(COULDNOT_SET_NETWORK_PARAMETER)); - std::cout << "Warning: Receiver UDP IP Address should be VALID " - "and in xxx.xxx.xxx.xxx format" << std::endl; - }else{ - strcpy(thisDetector->receiverUDPIP,udpip.c_str()); - if(!strcmp(thisDetector->receiver_hostname,"none")) { -#ifdef VERBOSE - std::cout << "Warning: Receiver hostname not set yet." << endl; -#else - ; -#endif - } - else if(setUDPConnection()==FAIL){ - std::cout<< "Warning: UDP connection set up failed" << std::endl; - } - } - } - } - return string(thisDetector->receiverUDPIP); -} - - - - -string slsDetector::setReceiverUDPMAC(string udpmac) { - if(udpmac.length()!=17){ - setErrorMask((getErrorMask())|(COULDNOT_SET_NETWORK_PARAMETER)); - std::cout << "Warning: receiver udp mac address should be in xx:xx:xx:xx:xx:xx " - "format" << std::endl; - } - else{ - if((udpmac[2]==':')&&(udpmac[5]==':')&&(udpmac[8]==':')&& - (udpmac[11]==':')&&(udpmac[14]==':')){ - strcpy(thisDetector->receiverUDPMAC,udpmac.c_str()); - if(!strcmp(thisDetector->receiver_hostname,"none")) { -#ifdef VERBOSE - std::cout << "Warning: Receiver hostname not set yet." << endl; -#else - ; -#endif - } - /* else if(setUDPConnection()==FAIL){ commented out to be replaced by user - * defined udpmac - std::cout<< "Warning: UDP connection set up failed" << std::endl; - }*/ - }else{ - setErrorMask((getErrorMask())|(COULDNOT_SET_NETWORK_PARAMETER)); - std::cout << "Warning: receiver udp mac address should be in xx:xx:xx:xx:xx:xx " - "format" << std::endl; - } - } - - - return string(thisDetector->receiverUDPMAC); -} - - - -int slsDetector::setReceiverUDPPort(int udpport) { - thisDetector->receiverUDPPort = udpport; - if(!strcmp(thisDetector->receiver_hostname,"none")) -#ifdef VERBOSE - std::cout << "Warning: Receiver hostname not set yet." << endl; -#else - ; -#endif - else if(setUDPConnection()==FAIL){ - std::cout<< "Warning: UDP connection set up failed" << std::endl; - } - return thisDetector->receiverUDPPort; -} - -int slsDetector::setReceiverUDPPort2(int udpport) { - thisDetector->receiverUDPPort2 = udpport; - if(!strcmp(thisDetector->receiver_hostname,"none")) -#ifdef VERBOSE - std::cout << "Warning: Receiver hostname not set yet." << endl; -#else - ; -#endif - else if(setUDPConnection()==FAIL){ - std::cout<< "Warning: UDP connection set up failed" << std::endl; - } - return thisDetector->receiverUDPPort2; -} - - -string slsDetector::setClientStreamingPort(string port) { - int defaultport = 0; - int numsockets = (thisDetector->myDetectorType == EIGER) ? 2:1; - int arg = 0; - - //multi command, calculate individual ports - size_t found = port.find("multi"); - if(found != string::npos) { - port.erase(found,5); - sscanf(port.c_str(),"%d",&defaultport); - arg = defaultport + (detId * numsockets); - } - else - sscanf(port.c_str(),"%d",&arg); - thisDetector->zmqport = arg; - - return getClientStreamingPort(); -} - - - - -string slsDetector::setReceiverStreamingPort(string port) { - int defaultport = 0; - int numsockets = (thisDetector->myDetectorType == EIGER) ? 2:1; - int arg = 0; - - //multi command, calculate individual ports - size_t found = port.find("multi"); - if(found != string::npos) { - port.erase(found,5); - sscanf(port.c_str(),"%d",&defaultport); - arg = defaultport + (detId * numsockets); - } - else - sscanf(port.c_str(),"%d",&arg); - - thisDetector->receiver_zmqport = arg; - - // send to receiver - int fnum=F_SET_RECEIVER_STREAMING_PORT; - int ret = FAIL; - int retval=-1; - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending receiver streaming port to receiver " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if (ret==FAIL) { - setErrorMask((getErrorMask())|(COULDNOT_SET_NETWORK_PARAMETER)); - std::cout << "Warning: Could not set receiver zmq port" << std::endl; - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - return getReceiverStreamingPort(); -} - -string slsDetector::setClientStreamingIP(string sourceIP) { - - struct addrinfo *result; - // on failure to convert to a valid ip - if (dataSocket->ConvertHostnameToInternetAddress(sourceIP.c_str(), &result)) { - std::cout << "Warning: Could not convert zmqip into a valid IP" << sourceIP - << std::endl; - setErrorMask((getErrorMask())|(COULDNOT_SET_NETWORK_PARAMETER)); - return getClientStreamingIP(); - } - // on success put IP as string into arg - else { - memset(thisDetector->zmqip, 0, MAX_STR_LENGTH); - dataSocket->ConvertInternetAddresstoIpString(result, thisDetector->zmqip, - MAX_STR_LENGTH); - } - - return getClientStreamingIP(); -} - - -string slsDetector::setReceiverStreamingIP(string sourceIP) { - - int fnum=F_RECEIVER_STREAMING_SRC_IP; - int ret = FAIL; - char arg[MAX_STR_LENGTH]; - memset(arg,0,sizeof(arg)); - char retval[MAX_STR_LENGTH]; - memset(retval,0, sizeof(retval)); - - // if empty, give rx_hostname - if (sourceIP.empty()) { - if(!strcmp(thisDetector->receiver_hostname,"none")) { - std::cout << "Receiver hostname not set yet. Cannot create rx_zmqip " - "from none\n" << endl; - setErrorMask((getErrorMask())|(COULDNOT_SET_NETWORK_PARAMETER)); - return getReceiverStreamingIP(); - } - sourceIP.assign(thisDetector->receiver_hostname); - } - - // verify the ip - { - struct addrinfo *result; - // on failure to convert to a valid ip - if (dataSocket->ConvertHostnameToInternetAddress(sourceIP.c_str(), &result)) { - std::cout << "Warning: Could not convert rx_zmqip into a valid IP" << - sourceIP << std::endl; - setErrorMask((getErrorMask())|(COULDNOT_SET_NETWORK_PARAMETER)); - return getReceiverStreamingIP(); - } - // on success put IP as string into arg - else { - dataSocket->ConvertInternetAddresstoIpString(result, arg, MAX_STR_LENGTH); - } - } - - // set it anyway, else it is lost - memset(thisDetector->receiver_zmqip, 0, MAX_STR_LENGTH); - strcpy(thisDetector->receiver_zmqip, arg); - - - // if zmqip is empty, update it - if (! strlen(thisDetector->zmqip)) - strcpy(thisDetector->zmqip, arg); - - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending receiver streaming source ip to receiver " << arg << - std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendString(fnum,retval,arg); - disconnectData(); - } - if(ret==FAIL) { - setErrorMask((getErrorMask())|(COULDNOT_SET_NETWORK_PARAMETER)); - std::cout << "Warning: Could not set rx_zmqip" << std::endl; - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - return getReceiverStreamingIP(); -} - - - -string slsDetector::setAdditionalJsonHeader(string jsonheader) { - - int fnum=F_ADDITIONAL_JSON_HEADER; - int ret = FAIL; - char arg[MAX_STR_LENGTH]; - memset(arg,0,sizeof(arg)); - char retval[MAX_STR_LENGTH]; - memset(retval,0, sizeof(retval)); - - strcpy(arg, jsonheader.c_str()); - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ - //#ifdef VERBOSE - // std::cout << "* Sending additional json header " << arg << std::endl; - //#endif - if (connectData() == OK){ - - // std::cout << "** Sending additional json header " << arg << std::endl; - ret=thisReceiver->sendString(fnum,retval,arg); - disconnectData(); - } - if(ret==FAIL) { - setErrorMask((getErrorMask())|(COULDNOT_SET_NETWORK_PARAMETER)); - std::cout << "Warning: Could not set additional json header" << std::endl; - } else - strcpy(thisDetector->receiver_additionalJsonHeader, retval); - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - return getAdditionalJsonHeader(); -} - - -string slsDetector::setReceiverUDPSocketBufferSize(int udpsockbufsize) { - - int fnum=F_RECEIVER_UDP_SOCK_BUF_SIZE; - int ret = FAIL; - int retval = -1; - int arg = udpsockbufsize; - - if(thisDetector->receiverOnlineFlag == ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending UDP Socket Buffer size to receiver " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if(ret==FAIL) { - setErrorMask((getErrorMask())|(COULDNOT_SET_NETWORK_PARAMETER)); - printf("Warning: Could not set udp socket buffer size\n"); - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - ostringstream ss; - ss << retval; - string s = ss.str(); - return s; -} - - - - - -string slsDetector::setDetectorNetworkParameter(networkParameter index, int delay) { - int fnum = F_SET_NETWORK_PARAMETER; - int ret = FAIL; - int retval = -1; - char mess[MAX_STR_LENGTH]=""; - -#ifdef VERBOSE - std::cout<< "Setting Transmission delay of mode "<< index << " to " << delay << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&index,sizeof(index)); - controlSocket->SendDataOnly(&delay,sizeof(delay)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(DETECTOR_NETWORK_PARAMETER)); - } else - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } -#ifdef VERBOSE - std::cout<< "Speed set to "<< retval << std::endl; -#endif - - ostringstream ss; - ss << retval; - string s = ss.str(); - return s; -} - - -int slsDetector::setUDPConnection() { - - int ret = FAIL; - int fnum = F_SETUP_RECEIVER_UDP; - char args[3][MAX_STR_LENGTH]; - memset(args,0,sizeof(args)); - char retval[MAX_STR_LENGTH]; - memset(retval,0,sizeof(retval)); - - //called before set up - if(!strcmp(thisDetector->receiver_hostname,"none")){ -#ifdef VERBOSE - std::cout << "Warning: Receiver hostname not set yet." << endl; -#endif - return FAIL; - } - - //if no udp ip given, use hostname - if(!strcmp(thisDetector->receiverUDPIP,"none")){ - //hostname is an ip address - if(strchr(thisDetector->receiver_hostname,'.')!=NULL) - strcpy(thisDetector->receiverUDPIP,thisDetector->receiver_hostname); - //if hostname not ip, convert it to ip - else{ - struct addrinfo *result; - if (!dataSocket->ConvertHostnameToInternetAddress( - thisDetector->receiver_hostname, &result)) { - // on success - memset(thisDetector->receiverUDPIP, 0, MAX_STR_LENGTH); - // on failure, back to none - if (dataSocket->ConvertInternetAddresstoIpString(result, - thisDetector->receiverUDPIP, MAX_STR_LENGTH)) { - strcpy(thisDetector->receiverUDPIP, "none"); - } - } - } - } - - - //copy arguments to args[][] - strcpy(args[0],thisDetector->receiverUDPIP); - sprintf(args[1],"%d",thisDetector->receiverUDPPort); - sprintf(args[2],"%d",thisDetector->receiverUDPPort2); -#ifdef VERBOSE - std::cout << "Receiver udp ip address: " << thisDetector->receiverUDPIP << std::endl; - std::cout << "Receiver udp port: " << thisDetector->receiverUDPPort << std::endl; - std::cout << "Receiver udp port2: " << thisDetector->receiverUDPPort2 << std::endl; -#endif - - //set up receiver for UDP Connection and get receivermac address - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Setting up UDP Connection for Receiver " << args[0] << "\t" << args[1] << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendUDPDetails(fnum,retval,args); - disconnectData(); - } - if(ret!=FAIL){ - strcpy(thisDetector->receiverUDPMAC,retval); - -#ifdef VERBOSE - std::cout << "Receiver mac address: " << thisDetector->receiverUDPMAC << std::endl; -#endif - if(ret==FORCE_UPDATE) - updateReceiver(); - - //configure detector with udp details, -100 is so it doesnt overwrite - //the previous value - if(configureMAC()==FAIL){ - setReceiverOnline(OFFLINE_FLAG); - std::cout << "could not configure mac" << endl; - } - } - }else { - ret=FAIL; - setErrorMask((getErrorMask())|(COULD_NOT_CONFIGURE_MAC)); - } -#ifdef VERBOSE - printReceiverConfiguration(); -#endif - return ret; -} - - - -int slsDetector::digitalTest( digitalTestMode mode, int imod) { - - - int retval; - int fnum=F_DIGITAL_TEST; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Getting id of "<< mode << std::endl; -#endif - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&mode,sizeof(mode)); - if ((mode==CHIP_TEST)|| (mode==DIGITAL_BIT_TEST)) - controlSocket->SendDataOnly(&imod,sizeof(imod)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } else { - ret=FAIL; - } -#ifdef VERBOSE - std::cout<< "Id "<< mode <<" is " << retval << std::endl; -#endif - if (ret==FAIL) { - std::cout<< "Get id failed " << std::endl; - return ret; - } else - return retval; -} - - - -int slsDetector::executeTrimming(trimMode mode, int par1, int par2, int imod) { - - int fnum= F_EXECUTE_TRIMMING; - int retval=FAIL; - char mess[MAX_STR_LENGTH]=""; - int ret=OK; - int arg[3]; - arg[0]=imod; - arg[1]=par1; - arg[2]=par2; - - -#ifdef VERBOSE - std::cout<< "Trimming module " << imod << " with mode "<< mode << " parameters " - << par1 << " " << par2 << std::endl; -#endif - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); -#ifdef VERBOSE - std::cout<< "sending mode bytes= "<< controlSocket->SendDataOnly( - &mode,sizeof(mode)) << std::endl; -#endif - controlSocket->SendDataOnly(&mode,sizeof(mode)); - controlSocket->SendDataOnly(arg,sizeof(arg)); - - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } else { -#ifdef VERBOSE - std::cout<< "Detector trimmed "<< ret << std::endl; -#endif - /* - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - thisDetector->roFlags=retval; - */ - retval=ret; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - return retval; - -} - - - -int slsDetector::loadImageToDetector(imageType index,string const fname) { - - int ret=FAIL; - short int arg[thisDetector->nChans*thisDetector->nChips*thisDetector->nMods]; - -#ifdef VERBOSE - std::cout<< std::endl<< "Loading "; - if(!index) - std::cout<<"Dark"; - else - std::cout<<"Gain"; - std::cout<<" image from file " << fname << std::endl; -#endif - - if(readDataFile(fname,arg)){ - ret = sendImageToDetector(index,arg); - return ret; - } - std::cout<< "Could not open file "<< fname << std::endl; - return ret; -} - - -int slsDetector::sendImageToDetector(imageType index,short int imageVals[]) { - - int ret=FAIL; - int retval; - int fnum=F_LOAD_IMAGE; - char mess[MAX_STR_LENGTH]=""; - -#ifdef VERBOSE - std::cout<<"Sending image to detector " <onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&index,sizeof(index)); - controlSocket->SendDataOnly(imageVals,thisDetector->dataBytes); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - return ret; -} - - - -int slsDetector::writeCounterBlockFile(string const fname,int startACQ) { - - int ret=FAIL; - short int counterVals[thisDetector->nChans*thisDetector->nChips*thisDetector->nMods]; - -#ifdef VERBOSE - std::cout<< std::endl<< "Reading Counter to \""<onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&startACQ,sizeof(startACQ)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) - controlSocket->ReceiveDataOnly(arg,thisDetector->dataBytes); - else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - return ret; -} - - - - -int slsDetector::resetCounterBlock(int startACQ) { - - int ret=FAIL; - int fnum=F_RESET_COUNTER_BLOCK; - char mess[MAX_STR_LENGTH]=""; - -#ifdef VERBOSE - std::cout<< std::endl<< "Resetting Counter"; - if(startACQ==1) - std::cout<<" and Restarting Acquisition"; - std::cout<onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&startACQ,sizeof(startACQ)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL){ - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - return ret; -} - - - - -int slsDetector::setCounterBit(int i) { - int fnum=F_SET_COUNTER_BIT; - int ret = FAIL; - int retval=-1; - char mess[MAX_STR_LENGTH]=""; - - if(thisDetector->onlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - if(i ==-1) - std::cout<< "Getting counter bit from detector" << endl; - else if(i==0) - std::cout<< "Resetting counter bit in detector " << endl; - else - std::cout<< "Setting counter bit in detector " << endl; -#endif - if (connectControl() == OK){ - - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&i,sizeof(i)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL){ - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Receiver returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(COULD_NOT_SET_COUNTER_BIT)); - } - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - - } - } - return retval; -} - - - - -int slsDetector::setROI(int n,ROI roiLimits[], int imod) { - int ret = FAIL; - //sort ascending order - int temp; - - /***** NEW PART FOR ZMQ HEADER */ - //std::cout<< "******* ROI" << std::endl; - - // char header[1000]; - string header=getNetworkParameter(ADDITIONAL_JSON_HEADER); - - std::cout<< "Old json header: " << header << std::endl; - //must be in the format '\"label1\":\"value1\",\"label2\":\"value2\"' etc." - // - size_t pos0; - pos0=header.find(",\"roi\""); - if (pos0==std::string::npos) { - pos0=header.find("\"roi\""); - } - if (pos0!=std::string::npos) { - // remove old roi - // std::cout<< header.substr(0,pos) << std::endl; - // size_t pos0=header.find_last_of(",",0,pos); - // if (pos0==std::string::npos) { - // pos0=pos; - // } else - // std::cout<< header.substr(pos0) << std::endl; - size_t pos1=header.find_first_of("]",pos0+1); - // std::cout << pos0 << " " << pos1 << std::endl; - std::cout<< "Replacing old ROI: " << header.substr(pos0,pos1-pos0+1) << std::endl; - // if (pos1!=std::string::npos) - header.erase(pos0,pos1-pos0+1); - // else - // header.erase(pos0); - } - if (header.length()>0) { - if (header.at(0)==',') - header.erase(0,1); - if (header.length()>0) - header.append(","); - } - // std::cout<< "Left: " << header << std::endl; - char h[1000]; - if (n) { - sprintf(h,"\"roi\":[%d, %d, %d, %d]",roiLimits[0].xmin, roiLimits[0].xmax, roiLimits[0].ymin, roiLimits[0].ymax); - // std::cout<< "new ROI: " << h << std::endl; - } else { - sprintf(h,"\"roi\":[%d, %d, %d, %d]",-1, -1, -1, -1); - } - header.append(h); - std::cout<< "New json header: " << header << std::endl; - setReceiverOnline(ONLINE_FLAG); - setNetworkParameter(ADDITIONAL_JSON_HEADER, header); - /***** END FOR ZMQ HEADER */ - ret=OK; - - if(thisDetector->myDetectorType==JUNGFRAUCTB) { - - thisDetector->nROI = n; - thisDetector->roiLimits[0].xmin=roiLimits[0].xmin; - thisDetector->roiLimits[0].xmax=roiLimits[0].xmax; - thisDetector->roiLimits[0].ymin=roiLimits[0].ymin; - thisDetector->roiLimits[0].ymax=roiLimits[0].ymax; - // std::cout << "** " << thisDetector->nROI << endl; - getTotalNumberOfChannels(); - // std::cout << "*** " << thisDetector->nROI << endl; - return ret; - } - // if(thisDetector->myDetectorType==JUNGFRAUCTB) - for(int i=0;imyDetectorType==JUNGFRAUCTB) getTotalNumberOfChannels(); - return ret; -} - - -slsDetectorDefs::ROI* slsDetector::getROI(int &n, int imod) { - if(thisDetector->myDetectorType==JUNGFRAUCTB) { - - - int xmin, xmax, ymin, ymax; - - string header=getNetworkParameter(ADDITIONAL_JSON_HEADER); - - - std::cout<< "Json header: " << header << std::endl; - - //must be in the format '\"label1\":\"value1\",\"label2\":\"value2\"' etc." - // - size_t pos0; - pos0=header.find("\"roi\""); - if (pos0!=std::string::npos) { - sscanf(header.substr(pos0).c_str(),"\"roi\":[%d, %d, %d, %d]", &xmin, &xmax, &ymin, &ymax); - if (xmin<0 && xmax<0 && ymin<0 && ymax<0) - thisDetector->nROI=0; - else { - thisDetector->nROI=1; - thisDetector->roiLimits[0].xmin=xmin; - thisDetector->roiLimits[0].xmax=xmax; - thisDetector->roiLimits[0].ymin=ymin; - thisDetector->roiLimits[0].ymax=ymax; - } - } else { - thisDetector->nROI=0; - } - - // cout << thisDetector->nROI << endl; - getTotalNumberOfChannels(); - } else { - sendROI(-1,NULL); - n=thisDetector->nROI; - } - return thisDetector->roiLimits; -} - -int slsDetector::getNRoi(){ - return thisDetector->nROI; -} - - -int slsDetector::sendROI(int n,ROI roiLimits[]) { - int ret=FAIL; - int fnum=F_SET_ROI; - char mess[MAX_STR_LENGTH]=""; - int arg = n; - int retvalsize=0; - ROI retval[MAX_ROIS]; - int nrec=-1; - if (roiLimits==NULL) - roiLimits=thisDetector->roiLimits; - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&arg,sizeof(arg)); - if(arg==-1){; -#ifdef VERBOSE - cout << "Getting ROI from detector" << endl; -#endif - }else{ -#ifdef VERBOSE - cout << "Sending ROI of size " << arg << " to detector" << endl; -#endif - controlSocket->SendDataOnly(roiLimits,arg*sizeof(ROI)); - } - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - - if (ret!=FAIL){ - controlSocket->ReceiveDataOnly(&retvalsize,sizeof(retvalsize)); - nrec = controlSocket->ReceiveDataOnly(retval,retvalsize*sizeof(ROI)); - if(nrec!=(retvalsize*(int)sizeof(ROI))){ - ret=FAIL; - std::cout << " wrong size received: received " << nrec << - "but expected " << retvalsize*sizeof(ROI) << endl; - } - }else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - //update client - if(ret==FAIL){ - setErrorMask((getErrorMask())|(COULDNOT_SET_ROI)); - } else { - for(int i=0;iroiLimits[i]=retval[i]; - thisDetector->nROI = retvalsize; - } - -#ifdef VERBOSE - for(int j=0;jnROI;++j) - cout<<"ROI [" <myDetectorType == GOTTHARD && n != -1) { - configureMAC(); - } - - // update roi in receiver - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ - int fnum=F_RECEIVER_SET_ROI; -#ifdef VERBOSE - std::cout << "Sending ROI to receiver " << thisDetector->nROI << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendROI(fnum, thisDetector->nROI, thisDetector->roiLimits); - disconnectData(); - } - if(ret==FAIL) - setErrorMask((getErrorMask())|(COULDNOT_SET_ROI)); - } - - - return ret; -} - - - - -int slsDetector::writeAdcRegister(int addr, int val) { - - int retval=-1; - int fnum=F_WRITE_ADC_REG; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - - uint32_t arg[2]; - arg[0]=addr; - arg[1]=val; - - -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Writing to adc register "<< hex<onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(arg,sizeof(arg)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } -#ifdef VERBOSE - std::cout<< "ADC Register returned "<< retval << std::endl; -#endif - if (ret==FAIL) { - std::cout<< "Write ADC to register failed " << std::endl; - setErrorMask((getErrorMask())|(REGISER_WRITE_READ)); - } - return retval; - -} - - -int slsDetector::activate(int const enable) { - int fnum = F_ACTIVATE; - int fnum2 = F_RECEIVER_ACTIVATE; - int retval = -1; - int arg = enable; - char mess[MAX_STR_LENGTH]=""; - int ret = FAIL; - - if(thisDetector->myDetectorType != EIGER){ - std::cout<< "Not implemented for this detector" << std::endl; - setErrorMask((getErrorMask())|(DETECTOR_ACTIVATE)); - return -1; - } - -#ifdef VERBOSE - if(!enable) - std::cout<< "Deactivating Detector" << std::endl; - else if(enable == -1) - std::cout<< "Getting Detector activate mode" << std::endl; - else - std::cout<< "Activating Detector" << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&arg,sizeof(arg)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(DETECTOR_ACTIVATE)); - } else { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - thisDetector->activated = retval; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } -#ifdef VERBOSE - if(retval==1) - std::cout << "Detector Activated" << std::endl; - else if(retval==0) - std::cout << "Detector Deactivated" << std::endl; - else - std::cout << "Detector Activation unknown:" << retval << std::endl; -#endif - - if(ret!=FAIL){ - int arg = thisDetector->activated; - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Activating/Deactivating Receiver: " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum2,retval,arg); - disconnectData(); - } - if(ret==FAIL) - setErrorMask((getErrorMask())|(RECEIVER_ACTIVATE)); - } - } -#ifdef VERBOSE - if(retval==1) - std::cout << "Receiver Activated" << std::endl; - else if(retval==0) - std::cout << "Receiver Deactivated" << std::endl; - else - std::cout << "Receiver Activation unknown:" << retval << std::endl; -#endif - - - return thisDetector->activated; - -} - - - -int slsDetector::setDeactivatedRxrPaddingMode(int padding) { - int fnum = F_RECEIVER_DEACTIVATED_PADDING_ENABLE; - int retval = -1; - int arg = padding; - int ret = OK; - - if(thisDetector->myDetectorType != EIGER){ - std::cout<< "Not implemented for this detector" << std::endl; - setErrorMask((getErrorMask())|(RECEIVER_ACTIVATE)); - return -1; - } - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Deactivated Receiver Padding Enable: " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if(ret==FAIL) - setErrorMask((getErrorMask())|(RECEIVER_ACTIVATE)); - else - thisDetector->receiver_deactivatedPaddingEnable = retval; - } - - return thisDetector->receiver_deactivatedPaddingEnable; -} - - - - -int slsDetector::getFlippedData(dimension d) { - return thisDetector->flippedData[d]; -} - - - -int slsDetector::setFlippedData(dimension d, int value) { - int retval=-1; - int fnum=F_SET_FLIPPED_DATA_RECEIVER; - int ret=FAIL; - int args[2]={X,-1}; - - - if(thisDetector->myDetectorType!= EIGER){ - std::cout << "Flipped Data is not implemented in this detector" << std::endl; - setErrorMask((getErrorMask())|(RECEIVER_FLIPPED_DATA_NOT_SET)); - return -1; - } - -#ifdef VERBOSE - std::cout << std::endl; - std::cout << "Setting/Getting flipped data across axis " << d <<" with value " - << value << std::endl; -#endif - if(value > -1){ - thisDetector->flippedData[d] = value; - args[1] = value; - }else - args[1] = thisDetector->flippedData[d]; - - args[0] = d; - - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG) { - if (connectData() == OK){ - ret=thisReceiver->sendIntArray(fnum,retval,args); - - disconnectData(); - } - - if((args[1] != retval && args[1]>=0) || (ret==FAIL)){ - ret = FAIL; - setErrorMask((getErrorMask())|(RECEIVER_FLIPPED_DATA_NOT_SET)); - } - - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - - return thisDetector->flippedData[d]; -} - - - -int slsDetector::setAllTrimbits(int val, int imod) { - int fnum=F_SET_ALL_TRIMBITS; - int retval = FAIL; - char mess[MAX_STR_LENGTH]=""; - int ret=OK; - -#ifdef VERBOSE - std::cout<< "Setting all trimbits to "<< val << std::endl; -#endif - if (getDetectorsType() == MYTHEN) { - if (val>=0) { - setChannel((val<<((int)TRIMBIT_OFF))|((int)COMPARATOR_ENABLE)); // trimbit scan - } - return val; - } else { - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&val,sizeof(val)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(ALLTIMBITS_NOT_SET)); - } else { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - } - -#ifdef VERBOSE - std::cout<< "All trimbits were set to "<< retval << std::endl; -#endif - return retval; -} - - - -int slsDetector::enableGapPixels(int val) { - - if(val > 0 && thisDetector->myDetectorType!= EIGER) - val = -1; - - if (val >= 0) { - val=(val>0)?1:0; - - // send to receiver - int ret=OK; - int retval=-1; - int fnum=F_ENABLE_GAPPIXELS_IN_RECEIVER; - int arg=val; - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG) { - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if((arg != retval) || (ret==FAIL)){ - ret = FAIL; - setErrorMask((getErrorMask())|(RECEIVER_ENABLE_GAPPIXELS_NOT_SET)); - } - - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - - // update client - if (ret == OK) { - thisDetector->gappixels = val; - thisDetector->dataBytesInclGapPixels = 0; - - if (thisDetector->dynamicRange != 4) { - thisDetector->dataBytesInclGapPixels = - (thisDetector->nMod[X] * thisDetector->nChip[X] * - thisDetector->nChan[X] + thisDetector->gappixels * - thisDetector->nGappixels[X]) * - (thisDetector->nMod[Y] * thisDetector->nChip[Y] * - thisDetector->nChan[Y] + thisDetector->gappixels * - thisDetector->nGappixels[Y]) * - thisDetector->dynamicRange/8; - // set data bytes for other detector ( for future use) - if(thisDetector->myDetectorType==JUNGFRAUCTB) - getTotalNumberOfChannels(); - else if(thisDetector->myDetectorType==MYTHEN){ - if (thisDetector->dynamicRange==24 || - thisDetector->timerValue[PROBES_NUMBER]>0) { - thisDetector->dataBytesInclGapPixels = - (thisDetector->nMod[X] * thisDetector->nChip[X] * - thisDetector->nChan[X] + thisDetector->gappixels * - thisDetector->nGappixels[X]) * - (thisDetector->nMod[Y] * thisDetector->nChip[Y] * - thisDetector->nChan[Y] + thisDetector->gappixels * - thisDetector->nGappixels[Y]) * - 4; - } - } - } - } - } - - return thisDetector->gappixels; -} - - - -int slsDetector::setTrimEn(int nen, int *en) { - if (en) { - for (int ien=0; ientrimEnergies[ien]=en[ien]; - thisDetector->nTrimEn=nen; - } - return (thisDetector->nTrimEn); -} - - -int slsDetector::getTrimEn(int *en) { - if (en) { - for (int ien=0; iennTrimEn; ien++) - en[ien]=thisDetector->trimEnergies[ien]; - } - return (thisDetector->nTrimEn); -} - - - - -int slsDetector::pulsePixel(int n,int x,int y) { - int ret=FAIL; - int fnum=F_PULSE_PIXEL; - char mess[MAX_STR_LENGTH]=""; - int arg[3]; - arg[0] = n; arg[1] = x; arg[2] = y; - -#ifdef VERBOSE - std::cout<< std::endl<< "Pulsing Pixel " << n << " number of times at (" << - x << "," << "y)" << endl << endl; -#endif - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(arg,sizeof(arg)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL){ - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(COULD_NOT_PULSE_PIXEL)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - return ret; -} - - -int slsDetector::pulsePixelNMove(int n,int x,int y) { - int ret=FAIL; - int fnum=F_PULSE_PIXEL_AND_MOVE; - char mess[MAX_STR_LENGTH]=""; - int arg[3]; - arg[0] = n; arg[1] = x; arg[2] = y; - -#ifdef VERBOSE - std::cout<< std::endl<< "Pulsing Pixel " << n << " number of times and move " - "by deltax:" << x << " deltay:" << y << endl << endl; -#endif - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(arg,sizeof(arg)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL){ - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(COULD_NOT_PULSE_PIXEL_NMOVE)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - return ret; -} - - - -int slsDetector::pulseChip(int n) { - int ret=FAIL; - int fnum=F_PULSE_CHIP; - char mess[MAX_STR_LENGTH]=""; - - -#ifdef VERBOSE - std::cout<< std::endl<< "Pulsing Pixel " << n << " number of times" << endl << endl; -#endif - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&n,sizeof(n)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL){ - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(COULD_NOT_PULSE_CHIP)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - return ret; -} - - - - -int slsDetector::setThresholdTemperature(int val, int imod) { - - int retval = -1; - int fnum = F_THRESHOLD_TEMP; - int ret = FAIL; - char mess[MAX_STR_LENGTH] = ""; - - int arg[2]; - arg[0]=val; - arg[1]=imod; - - -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Setting/Getting Threshold Temperature to "<< val << " of module " - << imod << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectStop() == OK){ - stopSocket->SendDataOnly(&fnum,sizeof(fnum)); - stopSocket->SendDataOnly(arg,sizeof(arg)); - stopSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - stopSocket->ReceiveDataOnly(&retval,sizeof(retval)); -#ifdef VERBOSE -std::cout<< "Threshold Temperature returned "<< retval << std::endl; -#endif - } else { - stopSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(TEMPERATURE_CONTROL)); - } - disconnectStop(); - } - } - - return retval; -} - - - -int slsDetector::setTemperatureControl(int val, int imod) { - - int retval = -1; - int fnum = F_TEMP_CONTROL; - int ret = FAIL; - char mess[MAX_STR_LENGTH] = ""; - - int arg[2]; - arg[0]=val; - arg[1]=imod; - - -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Setting/Getting Threshold Temperature to "<< val << " of module " - << imod << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectStop() == OK){ - stopSocket->SendDataOnly(&fnum,sizeof(fnum)); - stopSocket->SendDataOnly(arg,sizeof(arg)); - stopSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - stopSocket->ReceiveDataOnly(&retval,sizeof(retval)); -#ifdef VERBOSE -std::cout<< "Threshold Temperature returned "<< retval << std::endl; -#endif - } else { - stopSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(TEMPERATURE_CONTROL)); - } - disconnectStop(); - } - } - - return retval; -} - - - - -int slsDetector::setTemperatureEvent(int val, int imod) { - - int retval = -1; - int fnum = F_TEMP_EVENT; - int ret = FAIL; - char mess[MAX_STR_LENGTH] = ""; - - int arg[2]; - arg[0]=val; - arg[1]=imod; - - -#ifdef VERBOSE - std::cout<< std::endl; - std::cout<< "Setting/Getting Threshold Temperature to "<< val << " of module " - << imod << std::endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectStop() == OK){ - stopSocket->SendDataOnly(&fnum,sizeof(fnum)); - stopSocket->SendDataOnly(arg,sizeof(arg)); - stopSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - stopSocket->ReceiveDataOnly(&retval,sizeof(retval)); -#ifdef VERBOSE -std::cout<< "Threshold Temperature returned "<< retval << std::endl; -#endif - } else { - stopSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(TEMPERATURE_CONTROL)); - } - disconnectStop(); - } - } - - return retval; -} - - - -int slsDetector::setStoragecellStart(int pos) { - int ret=FAIL; - int fnum=F_STORAGE_CELL_START; - char mess[MAX_STR_LENGTH]; - memset(mess, 0, MAX_STR_LENGTH); - int retval=-1; - -#ifdef VERBOSE - std::cout<< "Sending storage cell start index " << pos << endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&pos,sizeof(pos)); - //check opening error - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(STORAGE_CELL_START)); - }else - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - return retval; -} - - - -int slsDetector::programFPGA(string fname) { - int ret=FAIL; - int fnum=F_PROGRAM_FPGA; - char mess[MAX_STR_LENGTH]=""; - size_t filesize=0; - char* fpgasrc = NULL; - - if(thisDetector->myDetectorType != JUNGFRAU && - thisDetector->myDetectorType != JUNGFRAUCTB){ - std::cout << "Not implemented for this detector" << std::endl; - return FAIL; - } - - - //check if it exists - struct stat st; - if(stat(fname.c_str(),&st)){ - std::cout << "Programming file does not exist" << endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - return FAIL; - } - - // open src - FILE* src = fopen(fname.c_str(),"rb"); - if (src == NULL) { - std::cout << "Could not open source file for programming: " << fname << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - return FAIL; - } - - // create temp destination file - char destfname[] = "/tmp/Jungfrau_MCB.XXXXXX"; - int dst = mkstemp(destfname); // create temporary file and open it in r/w - if (dst == -1) { - std::cout << "Could not create destination file in /tmp for programming: " - << destfname << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - return FAIL; - } - - // convert src to dst rawbin -#ifdef VERBOSE - std::cout << "Converting " << fname << " to " << destfname << std::endl; -#endif - int filepos,x,y,i; - // Remove header (0...11C) - for (filepos=0; filepos < 0x11C; ++filepos) - fgetc(src); - // Write 0x80 times 0xFF (0...7F) - { - char c = 0xFF; - for (filepos=0; filepos < 0x80; ++filepos) - write(dst, &c, 1); - } - // Swap bits and write to file - for (filepos=0x80; filepos < 0x1000000; ++filepos) { - x = fgetc(src); - if (x < 0) break; - y=0; - for (i=0; i < 8; ++i) - y=y| ( (( x & (1<> i) << (7-i) ); // This swaps the bits - write(dst, &y, 1); - } - if (filepos < 0x1000000){ - std::cout << "Could not convert programming file. EOF before end of flash" - << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - return FAIL; - } - if(fclose(src)){ - std::cout << "Could not close source file" << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - return FAIL; - } - if(close(dst)){ - std::cout << "Could not close destination file" << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - return FAIL; - } -#ifdef VERBOSE - std::cout << "File has been converted to " << destfname << std::endl; -#endif - - //loading dst file to memory - FILE* fp = fopen(destfname,"r"); - if(fp == NULL){ - std::cout << "Could not open rawbin file" << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - return FAIL; - } - if(fseek(fp,0,SEEK_END)){ - std::cout << "Seek error in rawbin file" << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - return FAIL; - } - filesize = ftell(fp); - if(filesize <= 0){ - std::cout << "Could not get length of rawbin file" << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - return FAIL; - } - rewind(fp); - fpgasrc = (char*)malloc(filesize+1); - if(fpgasrc == NULL){ - std::cout << "Could not allocate size of program" << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - return FAIL; - } - if(fread(fpgasrc, sizeof(char), filesize, fp) != filesize){ - std::cout << "Could not read rawbin file" << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - return FAIL; - } - - if(fclose(fp)){ - std::cout << "Could not close destination file after converting" << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - return FAIL; - } - unlink(destfname); // delete temporary file -#ifdef VERBOSE - std::cout << "Successfully loaded the rawbin file to program memory" << std::endl; -#endif - - - // send program from memory to detector -#ifdef VERBOSE - std::cout<< "Sending programming binary to detector " << endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&filesize,sizeof(filesize)); - //check opening error - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - filesize = 0; - } - - - //erasing flash - if(ret!=FAIL){ - std::cout<< "This can take awhile. Please be patient..." << endl; - printf("Erasing Flash:%d%%\r",0); - std::cout << flush; - //erasing takes 65 seconds, printing here (otherwise need threads - //in server-unnecessary) - int count = 66; - while(count>0){ - usleep(1 * 1000 * 1000); - --count; - printf("Erasing Flash:%d%%\r",(int) (((double)(65-count)/65)*100)); - std::cout << flush; - } - std::cout< 0)){ - - unitprogramsize = MAX_FPGAPROGRAMSIZE; //2mb - if(unitprogramsize > filesize) //less than 2mb - unitprogramsize = filesize; -#ifdef VERBOSE - std::cout << "unitprogramsize:" << unitprogramsize << "\t filesize:" - << filesize << std::endl; -#endif - controlSocket->SendDataOnly(fpgasrc+currentPointer,unitprogramsize); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - filesize-=unitprogramsize; - currentPointer+=unitprogramsize; - - //print progress - printf("Writing to Flash:%d%%\r", - (int) (((double)(totalsize-filesize)/totalsize)*100)); - std::cout << flush; - }else{ - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - } - } - std::cout<ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - } - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - - - //remapping stop server - if ((ret == FAIL) && - (strstr(mess,"not implemented") == NULL) && - (strstr(mess,"locked") == NULL) && - (strstr(mess,"-update") == NULL)) { - fnum=F_RESET_FPGA; - int stopret; - if (connectStop() == OK){ - stopSocket->SendDataOnly(&fnum,sizeof(fnum)); - stopSocket->ReceiveDataOnly(&stopret,sizeof(stopret)); - if (stopret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(PROGRAMMING_ERROR)); - } - disconnectControl(); - } - } - } - if (ret != FAIL) { - printf("You can now restart the detector servers in normal mode.\n"); - } - - //free resources - if(fpgasrc != NULL) - free(fpgasrc); - - return ret; -} - - -int slsDetector::resetFPGA() { - int ret=FAIL; - int fnum=F_RESET_FPGA; - char mess[MAX_STR_LENGTH]=""; - - if(thisDetector->myDetectorType != JUNGFRAU){ - std::cout << "Not implemented for this detector" << std::endl; - return FAIL; - } -#ifdef VERBOSE - std::cout<< "Sending reset to FPGA " << endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - // control server - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(RESET_ERROR)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - return ret; - -} - - - -int slsDetector::powerChip(int ival) { - int ret=FAIL; - int fnum=F_POWER_CHIP; - char mess[MAX_STR_LENGTH]=""; - int retval=-1; - - if(thisDetector->myDetectorType != JUNGFRAU && - thisDetector->myDetectorType != JUNGFRAUCTB ){ - std::cout << "Not implemented for this detector" << std::endl; - return FAIL; - } -#ifdef VERBOSE - std::cout<< "Sending power on/off/get to the chip " << endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&ival,sizeof(ival)); - //check opening error - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(POWER_CHIP)); - }else - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - return retval; - -} - - -int slsDetector::setAutoComparatorDisableMode(int ival) { - int ret=FAIL; - int fnum=F_AUTO_COMP_DISABLE; - char mess[MAX_STR_LENGTH]=""; - int retval=-1; - - if(thisDetector->myDetectorType != JUNGFRAU){ - std::cout << "Not implemented for this detector" << std::endl; - return FAIL; - } -#ifdef VERBOSE - std::cout<< "Enabling/disabling Auto comp disable mode " << endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&ival,sizeof(ival)); - //check opening error - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(AUTO_COMP_DISABLE)); - }else - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - return retval; - -} - - - -int slsDetector::getChanRegs(double* retval,bool fromDetector) { - int n=getTotalNumberOfChannels(); - if(fromDetector){ - for(int im=0;imnChans*thisDetector->nChips]; - int chiregs[thisDetector->nChips]; - dacs_t das[thisDetector->nDacs], ads[thisDetector->nAdcs]; - int mmin=imod, mmax=imod+1; - int ret=FAIL; - - if (imod==-1) { - mmin=0; - mmax=thisDetector->nModsMax; - } - - - - for (int im=mmin; imnChans; - myModule.nchip=thisDetector->nChips; - myModule.ndac=thisDetector->nDacs; - myModule.nadc=thisDetector->nAdcs; - - myModule.reg=reg; - if (detectorModules) { - myModule.gain=(detectorModules+im)->gain; - myModule.offset=(detectorModules+im)->offset; - myModule.serialnumber=(detectorModules+im)->serialnumber; - } else { - myModule.gain=-1; - myModule.offset=-1; - myModule.serialnumber=-1; - } - - - for (int i=0; inAdcs; ++i) - ads[i]=-1; - - if (chanregs) - myModule.chanregs=chanregs+im*thisDetector->nChips*thisDetector->nChans; - else { - for (int i=0; inChans*thisDetector->nChips; ++i) - charegs[i]=-1; - myModule.chanregs=charegs; - } - if (chipregs) - myModule.chipregs=chanregs+im*thisDetector->nChips; - else { - for (int ichip=0; ichipnChips; ++ichip) - chiregs[ichip]=-1; - myModule.chipregs=chiregs; - } - if (dacs) - myModule.dacs=dacs+im*thisDetector->nDacs; - else { - for (int i=0; inDacs; ++i) - das[i]=-1; - myModule.dacs=das; - } - if (adcs) - myModule.adcs=adcs+im*thisDetector->nAdcs; - else { - for (int i=0; inAdcs; ++i) - ads[i]=-1; - myModule.adcs=ads; - } - ret=setModule(myModule,-1,-1,-1,0,0); - } - return ret; - - -} - -int slsDetector::setModule(sls_detector_module module, int iodelay, int tau, - int e_eV, int* gainval, int* offsetval, int tb) { - - int fnum=F_SET_MODULE; - int retval=-1; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - - int imod=module.module; - - -#ifdef VERBOSE - std::cout << "slsDetector set module " << std::endl; -#endif - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - //to exclude trimbits - if(!tb) { - module.nchan=0; - module.nchip=0; - } - sendModule(&module); - - //not included in module - if(gainval && (thisDetector->nGain)) - controlSocket->SendDataOnly(gainval,sizeof(int)*thisDetector->nGain); - if(offsetval && (thisDetector->nOffset)) - controlSocket->SendDataOnly(offsetval,sizeof(int)*thisDetector->nOffset); - if(thisDetector->myDetectorType == EIGER) { - controlSocket->SendDataOnly(&iodelay,sizeof(iodelay)); - controlSocket->SendDataOnly(&tau,sizeof(tau)); - controlSocket->SendDataOnly(&e_eV,sizeof(e_eV)); - } - - - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - if(strstr(mess,"default tau")!=NULL) - setErrorMask((getErrorMask())|(RATE_CORRECTION_NO_TAU_PROVIDED)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - - if (ret!=FAIL) { - if (detectorModules) { - if (imod>=0 && imodnMod[X]*thisDetector->nMod[Y]) { - if(tb) { - (detectorModules+imod)->nchan=module.nchan; - (detectorModules+imod)->nchip=module.nchip; - } - (detectorModules+imod)->ndac=module.ndac; - (detectorModules+imod)->nadc=module.nadc; - if(tb) { - thisDetector->nChips=module.nchip; - thisDetector->nChans=module.nchan/module.nchip; - } - thisDetector->nDacs=module.ndac; - thisDetector->nAdcs=module.nadc; - - if(thisDetector->myDetectorType != JUNGFRAU){ - if(tb) { - for (int ichip=0; ichipnChips; ++ichip) { - if (chipregs) - chipregs[ichip+thisDetector->nChips*imod]= - module.chipregs[ichip]; - - if (chanregs) { - for (int i=0; inChans; ++i) { - chanregs[i+ichip* - thisDetector->nChans+ - thisDetector->nChips*thisDetector->nChans* - imod]=module.chanregs[ichip*thisDetector->nChans+i]; - } - } - } - } - if (adcs) { - for (int i=0; inAdcs; ++i) - adcs[i+imod*thisDetector->nAdcs]=module.adcs[i]; - } - } - - if (dacs) { - for (int i=0; inDacs; ++i) - dacs[i+imod*thisDetector->nDacs]=module.dacs[i]; - } - - (detectorModules+imod)->gain=module.gain; - (detectorModules+imod)->offset=module.offset; - (detectorModules+imod)->serialnumber=module.serialnumber; - (detectorModules+imod)->reg=module.reg; - } - } - - if ((thisDetector->nGain) && (gainval) && (gain)) { - for (int i=0; inGain; ++i) - gain[i+imod*thisDetector->nGain]=gainval[i]; - } - - if ((thisDetector->nOffset) && (offsetval) && (offset)) { - for (int i=0; inOffset; ++i) - offset[i+imod*thisDetector->nOffset]=offsetval[i]; - } - - if (e_eV != -1) - thisDetector->currentThresholdEV = e_eV; - - } - -#ifdef VERBOSE - std::cout<< "Module register returned "<< retval << std::endl; -#endif - - return retval; -} - - - - - -slsDetectorDefs::sls_detector_module *slsDetector::getModule(int imod) { - -#ifdef VERBOSE - std::cout << "slsDetector get module " << std::endl; -#endif - - int fnum=F_GET_MODULE; - sls_detector_module *myMod=createModule(); - - int* gainval=0, *offsetval=0; - if(thisDetector->nGain) - gainval=new int[thisDetector->nGain]; - if(thisDetector->nOffset) - offsetval=new int[thisDetector->nOffset]; - - //char *ptr, *goff=(char*)thisDetector; - - // int chanreg[thisDetector->nChans*thisDetector->nChips]; - //int chipreg[thisDetector->nChips]; - //double dac[thisDetector->nDacs], adc[thisDetector->nAdcs]; - - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - // int n; - -#ifdef VERBOSE - std::cout<< "getting module " << imod << std::endl; -#endif - - myMod->module=imod; - // myMod.nchan=thisDetector->nChans*thisDetector->nChips; - //myMod.chanregs=chanreg; - //myMod.nchip=thisDetector->nChips; - //myMod.chipregs=chipreg; - //myMod.ndac=thisDetector->nDacs; - //myMod.dacs=dac; - //myMod.ndac=thisDetector->nAdcs; - //myMod.dacs=adc; - - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&imod,sizeof(imod)); - - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - receiveModule(myMod); - - //extra gain and offset - eiger - if(thisDetector->nGain) - controlSocket->ReceiveDataOnly(gainval,sizeof(int)*thisDetector->nGain); - if(thisDetector->nOffset) - controlSocket->ReceiveDataOnly(offsetval,sizeof(int)*thisDetector->nOffset); - } else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - - if (ret!=FAIL) { - if (detectorModules) { - if (imod>=0 && imodnMod[X]*thisDetector->nMod[Y]) { - (detectorModules+imod)->nchan=myMod->nchan; - (detectorModules+imod)->nchip=myMod->nchip; - (detectorModules+imod)->ndac=myMod->ndac; - (detectorModules+imod)->nadc=myMod->nadc; - thisDetector->nChips=myMod->nchip; - thisDetector->nChans=myMod->nchan/myMod->nchip; - thisDetector->nDacs=myMod->ndac; - thisDetector->nAdcs=myMod->nadc; - - if(thisDetector->myDetectorType != JUNGFRAU){ - for (int ichip=0; ichipnChips; ++ichip) { - if (chipregs) - chipregs[ichip+thisDetector->nChips*imod]= - myMod->chipregs[ichip]; - - if (chanregs) { - for (int i=0; inChans; ++i) { - chanregs[i+ichip*thisDetector->nChans+ - thisDetector->nChips*thisDetector->nChans*imod]= - myMod->chanregs[ichip*thisDetector->nChans+i]; - } - } - } - - if (adcs) { - for (int i=0; inAdcs; ++i) - adcs[i+imod*thisDetector->nAdcs]=myMod->adcs[i]; - } - } - - if (dacs) { - for (int i=0; inDacs; ++i) { - dacs[i+imod*thisDetector->nDacs]=myMod->dacs[i]; - //cprintf(BLUE,"dac%d:%d\n",i, myMod->dacs[i]); - } - } - (detectorModules+imod)->gain=myMod->gain; - (detectorModules+imod)->offset=myMod->offset; - (detectorModules+imod)->serialnumber=myMod->serialnumber; - (detectorModules+imod)->reg=myMod->reg; - } - } - - if ((thisDetector->nGain) && (gainval) && (gain)) { - for (int i=0; inGain; ++i) - gain[i+imod*thisDetector->nGain]=gainval[i]; - } - - if ((thisDetector->nOffset) && (offsetval) && (offset)) { - for (int i=0; inOffset; ++i) - offset[i+imod*thisDetector->nOffset]=offsetval[i]; - } - - } else { - deleteModule(myMod); - myMod=NULL; - } - - if(gainval) delete[]gainval; - if(offsetval) delete[]offsetval; - - return myMod; -} - - - - -int slsDetector::setChannel(int64_t reg, int ichan, int ichip, int imod) { - sls_detector_channel myChan; -#ifdef VERBOSE - std::cout<< "Setting channel "<< ichan << " " << ichip << " " << imod << - " to " << reg << std::endl; -#endif - //int mmin=imod, mmax=imod+1, chimin=ichip, chimax=ichip+1, chamin=ichan, - //chamax=ichan+1; - - int ret; - - /* if (imod==-1) { - mmin=0; - mmax=thisDetector->nModsMax; - } - - if (ichip==-1) { - chimin=0; - chimax=thisDetector->nChips; - } - - if (ichan==-1) { - chamin=0; - chamax=thisDetector->nChans; - }*/ - - // for (int im=mmin; imonlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - sendChannel(&chan); - - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - } else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - - if (ret!=FAIL) { - if (chanregs) { - - int mmin=imod, mmax=imod+1, chimin=ichip, chimax=ichip+1, chamin=ichan, - chamax=ichan+1; - - if (imod==-1) { - mmin=0; - mmax=thisDetector->nModsMax; - } - - if (ichip==-1) { - chimin=0; - chimax=thisDetector->nChips; - } - - if (ichan==-1) { - chamin=0; - chamax=thisDetector->nChans; - } - - - - - - - for (int im=mmin; imnChans* - thisDetector->nChips+ichi*thisDetector->nChips+icha)=retval; - - } - } - } - - } - } -#ifdef VERBOSE - std::cout<< "Channel register returned "<< retval << std::endl; -#endif - return retval; - -} - - - - - -slsDetectorDefs::sls_detector_channel slsDetector::getChannel(int ichan, int ichip, - int imod) { - - - int fnum=F_GET_CHANNEL; - sls_detector_channel myChan; - int arg[3]; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - arg[0]=ichan; - arg[1]=ichip; - arg[2]=imod; - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(arg,sizeof(arg)); - - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - receiveChannel(&myChan); - } else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - - if (ret!=FAIL) { - if (chanregs) { - *(chanregs+imod*thisDetector->nChans*thisDetector->nChips+ichip* - thisDetector->nChips+ichan)=myChan.reg; - } - } - -#ifdef VERBOSE - std::cout<< "Returned channel "<< ichan << " " << ichip << " " << imod << " " - << myChan.reg << std::endl; -#endif - return myChan; -} - - - -int slsDetector::setChip(int reg, int ichip, int imod) { - sls_detector_chip myChip; - -#ifdef VERBOSE - std::cout<< "Setting chip "<< ichip << " " << imod << " to " << reg << std::endl; -#endif - - - int chregs[thisDetector->nChans]; - int mmin=imod, mmax=imod+1, chimin=ichip, chimax=ichip+1; - int ret=FAIL; - if (imod==-1) { - mmin=0; - mmax=thisDetector->nModsMax; - } - - if (ichip==-1) { - chimin=0; - chimax=thisDetector->nChips; - } - - myChip.nchan=thisDetector->nChans; - myChip.reg=reg; - for (int im=mmin; imnChans+im* - thisDetector->nChans*thisDetector->nChips); - else { - for (int i=0; inChans; ++i) - chregs[i]=-1; - myChip.chanregs=chregs; - } - ret=setChip(myChip); - } - } - return ret; -} - -int slsDetector::setChip(sls_detector_chip chip) { - - int fnum=F_SET_CHIP; - int retval = FAIL; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - - int ichi=chip.chip; - int im=chip.module; - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - sendChip(&chip); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - } else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - - if (ret!=FAIL) { - if (chipregs) - *(chipregs+ichi+im*thisDetector->nChips)=retval; - } - -#ifdef VERBOSE - std::cout<< "Chip register returned "<< retval << std::endl; -#endif - return retval; -} - - -slsDetectorDefs::sls_detector_chip slsDetector::getChip(int ichip, int imod) { - - int fnum=F_GET_CHIP; - sls_detector_chip myChip; - int chanreg[thisDetector->nChans]; - - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - - - myChip.chip=ichip; - myChip.module=imod; - myChip.nchan=thisDetector->nChans; - myChip.chanregs=chanreg; - - int arg[2]; - arg[0]=ichip; - arg[1]=imod; - - - - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(arg,sizeof(arg)); - - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - receiveChip(&myChip); - } else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - - if (ret!=FAIL) { - if (chipregs) - *(chipregs+ichip+imod*thisDetector->nChips)=myChip.reg; - if (chanregs) { - for (int ichan=0; ichannChans; ++ichan) - *(chanregs+imod*thisDetector->nChans*thisDetector->nChips+ichip* - thisDetector->nChans+ichan)=*((myChip.chanregs)+ichan); - } - } -#ifdef VERBOSE - std::cout<< "Returned chip "<< ichip << " " << imod << " " << myChip.reg << std::endl; -#endif - - return myChip; -} - - - -int slsDetector::getMoveFlag(int imod) { - if (moveFlag) - return *moveFlag; - else return 1; -} - - -int slsDetector::fillModuleMask(int *mM) { - if (mM) - for (int i=0; ionlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&frames,sizeof(frames)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - return retval; -} - - - -int slsDetector::setRateCorrection(double t) { - - if (getDetectorsType() == EIGER){ - int fnum=F_SET_RATE_CORRECT; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - int64_t arg = t; - -#ifdef VERBOSE - std::cout<< "Setting Rate Correction to " << arg << endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&arg,sizeof(arg)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL) { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - if(strstr(mess,"default tau")!=NULL) - setErrorMask((getErrorMask())|(RATE_CORRECTION_NO_TAU_PROVIDED)); - if(strstr(mess,"32")!=NULL) - setErrorMask((getErrorMask())|(RATE_CORRECTION_NOT_32or16BIT)); - else - setErrorMask((getErrorMask())|(COULD_NOT_SET_RATE_CORRECTION)); - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - return ret; //only success/fail - } - - - //mythen - double tdead[]=defaultTDead; - if (t==0) { -#ifdef VERBOSE - std::cout<< "unsetting rate correction" << std::endl; -#endif - thisDetector->correctionMask&=~(1<correctionMask|=(1<0) - thisDetector->tDead=t; - else { - if (thisDetector->currentSettings<3 && thisDetector->currentSettings>-1) - thisDetector->tDead=tdead[thisDetector->currentSettings]; - else - thisDetector->tDead=0; - } -#ifdef VERBOSE - std::cout<< "Setting rate correction with dead time "<< thisDetector->tDead - << std::endl; -#endif - } - return thisDetector->correctionMask&(1<myDetectorType == EIGER){ - t = getRateCorrectionTau(); - return t; - } - - if (thisDetector->correctionMask&(1<tDead << std::endl; -#endif - t=thisDetector->tDead; - return 1; - } else - t=0; -#ifdef VERBOSE - std::cout<< "Rate correction is disabled " << std::endl; -#endif - return 0; -}; - -double slsDetector::getRateCorrectionTau() { - - if(thisDetector->myDetectorType == EIGER){ - int fnum=F_GET_RATE_CORRECT; - int ret=FAIL; - char mess[MAX_STR_LENGTH]=""; - int64_t retval = -1; -#ifdef VERBOSE - std::cout<< "Setting Rate Correction to " << arg << endl; -#endif - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - return double(retval); - } - - - //mythen only - if (thisDetector->correctionMask&(1<tDead << std::endl; -#endif - return thisDetector->tDead; - //return 1; - } else -#ifdef VERBOSE - std::cout<< "Rate correction is disabled " << std::endl; -#endif - return 0; -} - - -int slsDetector::getRateCorrection() { - - if (thisDetector->myDetectorType == EIGER){ - double t = getRateCorrectionTau(); - return (int)t; - } - - if (thisDetector->correctionMask&(1<tDead; - double t=thisDetector->timerValue[ACQUISITION_TIME]; - // double data; - double e; - if (thisDetector->correctionMask&(1<nMod[X]*thisDetector->nMod[Y]* - thisDetector->nChans*thisDetector->nChips; ++ichan) { - - if (errin==NULL) { - e=sqrt(datain[ichan]); - } else - e=errin[ichan]; - - postProcessingFuncs::rateCorrect(datain[ichan], e, dataout[ichan], - errout[ichan], tau, t); - } - } - - return 0; -} - - - -int slsDetector::setFlatFieldCorrection(string fname) { - double data[thisDetector->nModMax[X]*thisDetector->nModMax[Y]* - thisDetector->nChans*thisDetector->nChips]; - int im=0; - int nch; - thisDetector->nBadFF=0; - - char ffffname[MAX_STR_LENGTH*2]; - if (fname=="default") { - fname=string(thisDetector->flatFieldFile); - } - - if (fname=="") { -#ifdef VERBOSE - std::cout<< "disabling flat field correction" << std::endl; -#endif - thisDetector->correctionMask&=~(1<flatFieldDir,fname.c_str()); - nch=readDataFile(string(ffffname),data); - if (nch>0) { - - //???? bad ff chans? - int nm=getNMods(); - int chpm[nm]; - int mMask[nm]; - for (int i=0; i=0) { - strcpy(thisDetector->flatFieldFile,fname.c_str()); - - - thisDetector->correctionMask|=(1<correctionMask&(1<nMod[Y]*thisDetector->nMod[X]* - thisDetector->nChans*thisDetector->nChips; ++ichan) { - // #ifdef VERBOSE - // std::cout<< ichan << " "<< corr[ichan] << std::endl; - // #endif - ffcoefficients[ichan]=corr[ichan]; - if (ecorr!=NULL) - fferrors[ichan]=ecorr[ichan]; - else - fferrors[ichan]=1; - - cout << ichan << " " << ffcoefficients[ichan] << endl; - } - thisDetector->correctionMask|=(1<correctionMask&=~(1<correctionMask)& - (1<correctionMask&(1<correctionMask&(1<nMod[X]*thisDetector->nMod[Y]* - thisDetector->nChans*thisDetector->nChips; ++ichan) { - corr[ichan]=ffcoefficients[ichan]; - if (ecorr) { - //ecorr[ichan]=ffcoefficients[ichan]/fferrors[ichan]; - ecorr[ichan]=fferrors[ichan]; - } - } - } - return 1; - } else { -#ifdef VERBOSE - std::cout<< "Flat field correction is disabled" << std::endl; -#endif - if (corr) - for (int ichan=0; ichannMod[X]*thisDetector->nMod[Y]* - thisDetector->nChans*thisDetector->nChips; ++ichan) { - corr[ichan]=1; - if (ecorr) - ecorr[ichan]=0; - } - return 0; - } - -} - - - -int slsDetector::flatFieldCorrect(double* datain, double *errin, double* dataout, - double *errout) { -#ifdef VERBOSE - std::cout<< "Flat field correcting data" << std::endl; -#endif - double e, eo; - if (thisDetector->correctionMask & (1<nMod[X]*thisDetector->nChans* - thisDetector->nChips; ++ichan) { - if (errin==NULL) { - e=0; - } else { - e=errin[ichan]; - } - postProcessingFuncs::flatFieldCorrect(datain[ichan],e,dataout[ichan], - eo,ffcoefficients[ichan],fferrors[ichan]); - if (errout) - errout[ichan]=eo; - } - } - return 0; - -} - - - - -int slsDetector::setBadChannelCorrection(string fname) { - - // int nbadmod; - int ret=0; - //int badchanlist[MAX_BADCHANS]; - //int off; - - string fn=fname; - - if (fname=="default") - fname=string(badChanFile); - - if (nBadChans && badChansList) - ret=setBadChannelCorrection(fname, *nBadChans, badChansList); - - if (ret) { - *correctionMask|=(1<0) { - thisDetector->correctionMask|=(1<nBadChans=0; - for (int ich=0 ;ich=0 && chs[ich]badChansList[ich]=chs[ich]; - ++thisDetector->nBadChans; - } - } - } else - thisDetector->correctionMask&=~(1<0) { - thisDetector->nBadFF=nch; - for (int ich=0 ;ichbadFFList[ich]=chs[ich]; - } - } - } -#ifdef VERBOSE - cout << "badchans flag is "<< (thisDetector->correctionMask& - (1<< DISCARD_BAD_CHANNELS)) << endl; -#endif - // fillBadChannelMask(); - if (thisDetector->correctionMask&(1<< DISCARD_BAD_CHANNELS)) { - return thisDetector->nBadChans+thisDetector->nBadFF; - } else - return 0; - -} - - -int slsDetector::getBadChannelCorrection(int *bad) { - int ichan; - if (thisDetector->correctionMask&(1<< DISCARD_BAD_CHANNELS)) { - if (bad) { - for (ichan=0; ichannBadChans; ++ichan) - bad[ichan]=thisDetector->badChansList[ichan]; - for (int ich=0; ichnBadFF; ++ich) - bad[ichan+ich]=thisDetector->badFFList[ich]; - } - return thisDetector->nBadChans+thisDetector->nBadFF; - } else - return 0; -} - - -int slsDetector::readAngularConversionFile(string fname) { - - return readAngularConversion(fname,thisDetector->nModsMax, thisDetector->angOff); - -} - -int slsDetector::readAngularConversion(ifstream& ifs) { - - return readAngularConversion(ifs,thisDetector->nModsMax, thisDetector->angOff); - -} - - -int slsDetector:: writeAngularConversion(string fname) { - - return writeAngularConversion(fname, thisDetector->nMods, thisDetector->angOff); - -} - - -int slsDetector:: writeAngularConversion(ofstream &ofs) { - - return writeAngularConversion(ofs, thisDetector->nMods, thisDetector->angOff); - -} - -int slsDetector::getAngularConversion(int &direction, angleConversionConstant *angconv) { - direction=thisDetector->angDirection; - if (angconv) { - for (int imod=0; imodnMods; ++imod) { - (angconv+imod)->center=thisDetector->angOff[imod].center; - (angconv+imod)->r_conversion=thisDetector->angOff[imod].r_conversion; - (angconv+imod)->offset=thisDetector->angOff[imod].offset; - (angconv+imod)->ecenter=thisDetector->angOff[imod].ecenter; - (angconv+imod)->er_conversion=thisDetector->angOff[imod].er_conversion; - (angconv+imod)->eoffset=thisDetector->angOff[imod].eoffset; - } - } - if (thisDetector->correctionMask&(1<< ANGULAR_CONVERSION)) { - return 1; - } else { - return 0; - } -} - - - -angleConversionConstant* slsDetector::getAngularConversionPointer(int imod) { - return &thisDetector->angOff[imod]; -} - - -int slsDetector::printReceiverConfiguration() { - - std::cout << "Detector IP:\t\t" << getNetworkParameter(DETECTOR_IP) << std::endl; - std::cout << "Detector MAC:\t\t" << getNetworkParameter(DETECTOR_MAC) << std::endl; - - std::cout << "Receiver Hostname:\t" << getNetworkParameter(RECEIVER_HOSTNAME) << std::endl; - std::cout << "Receiver UDP IP:\t" << getNetworkParameter(RECEIVER_UDP_IP) << std::endl; - std::cout << "Receiver UDP MAC:\t" << getNetworkParameter(RECEIVER_UDP_MAC) << std::endl; - std::cout << "Receiver UDP Port:\t" << getNetworkParameter(RECEIVER_UDP_PORT) << std::endl; - - if(thisDetector->myDetectorType == EIGER) - std::cout << "Receiver UDP Port2:\t" << getNetworkParameter(RECEIVER_UDP_PORT2) - << std::endl; - std::cout << std::endl; - - return OK; -} - - - - - -int slsDetector::setReceiverOnline(int off) { - if (off!=GET_ONLINE_FLAG) { - // no receiver - if(!strcmp(thisDetector->receiver_hostname,"none")) - thisDetector->receiverOnlineFlag = OFFLINE_FLAG; - else - thisDetector->receiverOnlineFlag = off; - // check receiver online - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG){ - setReceiverTCPSocket(); - // error in connecting - if(thisDetector->receiverOnlineFlag==OFFLINE_FLAG){ - std::cout << "cannot connect to receiver" << endl; - setErrorMask((getErrorMask())|(CANNOT_CONNECT_TO_RECEIVER)); - } - } - - } - return thisDetector->receiverOnlineFlag; -} - - - -string slsDetector::checkReceiverOnline() { - string retval = ""; - //if it doesnt exits, create data socket - if(!dataSocket){ - //this already sets the online/offline flag - setReceiverTCPSocket(); - if(thisDetector->receiverOnlineFlag==OFFLINE_FLAG) - return string(thisDetector->receiver_hostname); - else - return string(""); - } - //still cannot connect to socket, dataSocket=0 - if(dataSocket){ - if (connectData() == FAIL) { - dataSocket->SetTimeOut(5); - thisDetector->receiverOnlineFlag=OFFLINE_FLAG; - delete dataSocket; - dataSocket=0; -#ifdef VERBOSE - std::cout<< "receiver offline!" << std::endl; -#endif - return string(thisDetector->receiver_hostname); - } else { - thisDetector->receiverOnlineFlag=ONLINE_FLAG; - dataSocket->SetTimeOut(100); - disconnectData(); -#ifdef VERBOSE - std::cout<< "receiver online!" << std::endl; -#endif - return string(""); - } - } - return retval; -} - - - - - -int slsDetector::setReceiverTCPSocket(string const name, int const receiver_port) { - - char thisName[MAX_STR_LENGTH]; - int thisRP; - int retval=OK; - - //if receiver ip given - if (strcmp(name.c_str(),"")!=0) { -#ifdef VERBOSE - std::cout<< "setting receiver" << std::endl; -#endif - strcpy(thisName,name.c_str()); - strcpy(thisDetector->receiver_hostname,thisName); - if (dataSocket){ - delete dataSocket; - dataSocket=0; - } - } else - strcpy(thisName,thisDetector->receiver_hostname); - - //if receiverTCPPort given - if (receiver_port>0) { -#ifdef VERBOSE - std::cout<< "setting data port" << std::endl; -#endif - thisRP=receiver_port; - thisDetector->receiverTCPPort=thisRP; - if (dataSocket){ - delete dataSocket; - dataSocket=0; - } - } else - thisRP=thisDetector->receiverTCPPort; - - //create data socket - if (!dataSocket) { - try { - dataSocket = new MySocketTCP(thisName, thisRP); -#ifdef VERYVERBOSE - std::cout<< "Data socket connected " << - thisName << " " << thisRP << std::endl; -#endif - } catch(...) { -#ifdef VERBOSE - std::cout<< "Could not connect Data socket " << - thisName << " " << thisRP << std::endl; -#endif - dataSocket = 0; - retval = FAIL; - } - } - - - //check if it connects - if (retval!=FAIL) { - checkReceiverOnline(); - thisReceiver->setSocket(dataSocket); - // check for version compatibility - switch (thisDetector->myDetectorType) { - case EIGER: - case JUNGFRAU: - case GOTTHARD: - if (thisDetector->receiverAPIVersion == 0){ - if (checkVersionCompatibility(DATA_PORT) == FAIL) - thisDetector->receiverOnlineFlag=OFFLINE_FLAG; - } - break; - default: - break; - } - - } else { - thisDetector->receiverOnlineFlag=OFFLINE_FLAG; -#ifdef VERBOSE - std::cout<< "offline!" << std::endl; -#endif - } - return retval; -} - - - -int slsDetector::lockReceiver(int lock) { - int fnum=F_LOCK_RECEIVER; - int ret = FAIL; - int retval=-1; - int arg=lock; - - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Locking or Unlocking Receiver " << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - return retval; -} - - - - - - -string slsDetector::getReceiverLastClientIP() { - int fnum=F_GET_LAST_RECEIVER_CLIENT_IP; - int ret = FAIL; - char retval[INET_ADDRSTRLEN]=""; - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Geting Last Client IP connected to Receiver " << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->getLastClientIP(fnum,retval); - disconnectData(); - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - return string(retval); -} - - -int slsDetector::exitReceiver() { - - int retval = FAIL; - int fnum=F_EXIT_RECEIVER; - - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG) { - if (dataSocket) { - dataSocket->Connect(); - dataSocket->SendDataOnly(&fnum,sizeof(fnum)); - dataSocket->ReceiveDataOnly(&retval,sizeof(retval)); - disconnectData(); - } - } - if (retval!=OK) { - std::cout<< std::endl; - std::cout<< "Shutting down the receiver" << std::endl; - std::cout<< std::endl; - } - return retval; - -} - - -int slsDetector::updateReceiverNoWait() { - - int n = 0,ind; - char path[MAX_STR_LENGTH]; - char lastClientIP[INET_ADDRSTRLEN]; - - n += dataSocket->ReceiveDataOnly(lastClientIP,sizeof(lastClientIP)); -#ifdef VERBOSE - cout << "Updating receiver last modified by " << lastClientIP << std::endl; -#endif - - // filepath - n += dataSocket->ReceiveDataOnly(path,MAX_STR_LENGTH); - pthread_mutex_lock(&ms); - fileIO::setFilePath(path); - pthread_mutex_unlock(&ms); - - // filename - n += dataSocket->ReceiveDataOnly(path,MAX_STR_LENGTH); - pthread_mutex_lock(&ms); - fileIO::setFileName(path); - pthread_mutex_unlock(&ms); - - // index - n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); - pthread_mutex_lock(&ms); - fileIO::setFileIndex(ind); - pthread_mutex_unlock(&ms); - - //file format - n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); - pthread_mutex_lock(&ms); - fileIO::setFileFormat(ind); - pthread_mutex_unlock(&ms); - - // frames per file - n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); - thisDetector->receiver_framesPerFile = ind; - - // frame discard policy - n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); - thisDetector->receiver_frameDiscardMode = (frameDiscardPolicy)ind; - - // frame padding - n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); - thisDetector->receiver_framePadding = ind; - - // file write enable - n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); - pthread_mutex_lock(&ms); - multiDet->enableWriteToFileMask(ind); - pthread_mutex_unlock(&ms); - - // file overwrite enable - n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); - pthread_mutex_lock(&ms); - multiDet->enableOverwriteMask(ind); - pthread_mutex_unlock(&ms); - - // gap pixels - n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); - thisDetector->gappixels = ind; - - // receiver read frequency - n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); - thisDetector->receiver_read_freq = ind; - - // receiver streaming port - n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); - thisDetector->receiver_zmqport = ind; - - // streaming source ip - n += dataSocket->ReceiveDataOnly(path,MAX_STR_LENGTH); - strcpy(thisDetector->receiver_zmqip, path); - - // additional json header - n += dataSocket->ReceiveDataOnly(path,MAX_STR_LENGTH); - strcpy(thisDetector->receiver_additionalJsonHeader, path); - - // receiver streaming enable - n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); - thisDetector->receiver_upstream = ind; - - // activate - n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); - thisDetector->activated = ind; - - // deactivated padding enable - n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); - thisDetector->receiver_deactivatedPaddingEnable = ind; - - // silent mode - n += dataSocket->ReceiveDataOnly(&ind,sizeof(ind)); - thisDetector->receiver_silentMode = ind; - - if (!n) printf("n: %d\n", n); - - return OK; - -} - - - - - -int slsDetector::updateReceiver() { - int fnum=F_UPDATE_RECEIVER_CLIENT; - int ret=OK; - char mess[MAX_STR_LENGTH]=""; - - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG) { - if (connectData() == OK){ - dataSocket->SendDataOnly(&fnum,sizeof(fnum)); - dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) { - dataSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Receiver returned error: " << mess << std::endl; - } - else - updateReceiverNoWait(); - - //if ret is force update, do not update now as client is updating - //receiver currently - disconnectData(); - } - } - - return ret; -} - - - -void slsDetector::sendMultiDetectorSize() { - int fnum=F_SEND_RECEIVER_MULTIDETSIZE; - int ret = FAIL; - int retval = -1; - int arg[2]; - - pthread_mutex_lock(&ms); - multiDet->getNumberOfDetectors(arg[0],arg[1]); - pthread_mutex_unlock(&ms); - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending multi detector size to Receiver (" << arg[0] << "," - << arg[1] << ")" << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendIntArray(fnum,retval,arg); - disconnectData(); - } - if(ret==FAIL){ - std::cout << "Could not set position Id" << std::endl; - setErrorMask((getErrorMask())|(RECEIVER_MULTI_DET_SIZE_NOT_SET)); - } - } -} - - -void slsDetector::setDetectorId() { - int fnum=F_SEND_RECEIVER_DETPOSID; - int ret = FAIL; - int retval = -1; - int arg = detId; - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending detector pos id to Receiver " << detId << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if((ret==FAIL) || (retval != arg)){ - std::cout << "Could not set position Id" << std::endl; - setErrorMask((getErrorMask())|(RECEIVER_DET_POSID_NOT_SET)); - } - } -} - - -void slsDetector::setDetectorHostname() { - int fnum=F_SEND_RECEIVER_DETHOSTNAME; - int ret = FAIL; - char retval[MAX_STR_LENGTH]=""; - - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending detector hostname to Receiver " << - thisDetector->hostname << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendString(fnum,retval,thisDetector->hostname); - disconnectData(); - } - if((ret==FAIL) || (strcmp(retval,thisDetector->hostname))) - setErrorMask((getErrorMask())|(RECEIVER_DET_HOSTNAME_NOT_SET)); - } -} - - -string slsDetector::getFilePath() { - return setFilePath(); -} - - - - - -string slsDetector::setFilePath(string s) { - int fnum = F_SET_RECEIVER_FILE_PATH; - int ret = FAIL; - char arg[MAX_STR_LENGTH]=""; - char retval[MAX_STR_LENGTH] = ""; - struct stat st; - - if(thisDetector->receiverOnlineFlag==OFFLINE_FLAG){ - if(!s.empty()){ - if(stat(s.c_str(),&st)){ - std::cout << "path does not exist" << endl; - setErrorMask((getErrorMask())|(FILE_PATH_DOES_NOT_EXIST)); - }else{ - pthread_mutex_lock(&ms); - fileIO::setFilePath(s); - pthread_mutex_unlock(&ms); - } - } - } - - else{ - strcpy(arg,s.c_str()); -#ifdef VERBOSE - std::cout << "Sending file path to receiver " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendString(fnum,retval,arg); - disconnectData(); - } - if(ret!=FAIL){ - pthread_mutex_lock(&ms); - fileIO::setFilePath(string(retval)); - pthread_mutex_unlock(&ms); - } - else if(!s.empty()){ - std::cout << "file path does not exist" << endl; - setErrorMask((getErrorMask())|(FILE_PATH_DOES_NOT_EXIST)); - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - pthread_mutex_lock(&ms); - s = fileIO::getFilePath(); - pthread_mutex_unlock(&ms); - - return s; -} - - -string slsDetector::getFileName() { - return setFileName(); -} - -string slsDetector::setFileName(string s) { - int fnum=F_SET_RECEIVER_FILE_NAME; - int ret = FAIL; - char arg[MAX_STR_LENGTH]=""; - char retval[MAX_STR_LENGTH]=""; - string sretval=""; - - /*if(!s.empty()){ - pthread_mutex_lock(&ms); - fileIO::setFileName(s); - s=multiDet->createReceiverFilePrefix(); - pthread_mutex_unlock(&ms); - }*/ - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ - strcpy(arg,s.c_str()); -#ifdef VERBOSE - std::cout << "Sending file name to receiver " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendString(fnum,retval,arg); - disconnectData(); - } - if(ret!=FAIL){ -#ifdef VERBOSE - std::cout << "Complete file prefix from receiver: " << retval << std::endl; -#endif - /* - pthread_mutex_lock(&ms); - fileIO::setFileName(multiDet->getNameFromReceiverFilePrefix(string(retval))); - pthread_mutex_unlock(&ms); - */ - sretval = fileIO::getNameFromReceiverFilePrefix(string(retval)); - } - - if(ret==FORCE_UPDATE) - updateReceiver(); - return sretval; - - } else { - if(!s.empty()){ - pthread_mutex_lock(&ms); - fileIO::setFileName(s); - pthread_mutex_unlock(&ms); - } - pthread_mutex_lock(&ms); - s = fileIO::getFileName(); - pthread_mutex_unlock(&ms); - - return s; - - } - -} - - -int slsDetector::setReceiverFramesPerFile(int f) { - int fnum = F_SET_RECEIVER_FRAMES_PER_FILE; - int ret = FAIL; - int retval = -1; - int arg = f; - - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending frames per file to receiver " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if(ret==FAIL) - setErrorMask((getErrorMask())|(RECEIVER_PARAMETER_NOT_SET)); - else if(ret!=FAIL && retval > -1){ - thisDetector->receiver_framesPerFile = retval; - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - return thisDetector->receiver_framesPerFile; -} - - -slsReceiverDefs::frameDiscardPolicy slsDetector::setReceiverFramesDiscardPolicy(frameDiscardPolicy f) { - int fnum = F_RECEIVER_DISCARD_POLICY; - int ret = FAIL; - int retval = -1; - int arg = f; - - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending frames discard policy to receiver " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if(ret==FAIL) - setErrorMask((getErrorMask())|(RECEIVER_PARAMETER_NOT_SET)); - else if(ret!=FAIL && retval > -1){ - thisDetector->receiver_frameDiscardMode = (frameDiscardPolicy)retval; - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - return thisDetector->receiver_frameDiscardMode; -} - -int slsDetector::setReceiverPartialFramesPadding(int f) { - int fnum = F_RECEIVER_PADDING_ENABLE; - int ret = FAIL; - int retval = -1; - int arg = f; - - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending partial frames enable to receiver " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if(ret==FAIL) - setErrorMask((getErrorMask())|(RECEIVER_PARAMETER_NOT_SET)); - else if(ret!=FAIL && retval > -1){ - thisDetector->receiver_framePadding = (bool)retval; - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - return thisDetector->receiver_framePadding; -} - -slsReceiverDefs::fileFormat slsDetector::setFileFormat(fileFormat f) { - int fnum=F_SET_RECEIVER_FILE_FORMAT; - int ret = FAIL; - int arg = -1; - int retval = -1; - - - - if(thisDetector->receiverOnlineFlag==OFFLINE_FLAG){ - if(f>=0){ - pthread_mutex_lock(&ms); - fileIO::setFileFormat(f); - pthread_mutex_unlock(&ms); - } - } - - else{ - arg = (int)f; -#ifdef VERBOSE - std::cout << "Sending file format to receiver " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if(ret == FAIL) - setErrorMask((getErrorMask())|(RECEIVER_FILE_FORMAT)); - else{ - pthread_mutex_lock(&ms); - fileIO::setFileFormat(retval); - pthread_mutex_unlock(&ms); - if(ret==FORCE_UPDATE) - updateReceiver(); - } - } - - return fileIO::getFileFormat(); -} - - - -slsReceiverDefs::fileFormat slsDetector::getFileFormat() { - return setFileFormat(); -} - -int slsDetector::getFileIndex() { - return setFileIndex(); -} - -int slsDetector::setFileIndex(int i) { - int fnum=F_SET_RECEIVER_FILE_INDEX; - int ret = FAIL; - int retval=-1; - int arg = i; - - - if(thisDetector->receiverOnlineFlag==OFFLINE_FLAG){ - if(i>=0){ - pthread_mutex_lock(&ms); - fileIO::setFileIndex(i); - pthread_mutex_unlock(&ms); - } - } - - else{ -#ifdef VERBOSE - std::cout << "Sending file index to receiver " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if(ret!=FAIL){ - pthread_mutex_lock(&ms); - fileIO::setFileIndex(retval); - pthread_mutex_unlock(&ms); - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - return fileIO::getFileIndex(); -} - - - - - -int slsDetector::startReceiver() { - int fnum=F_START_RECEIVER; - int ret = FAIL; - char mess[MAX_STR_LENGTH] = ""; - - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG) { -#ifdef VERBOSE - std::cout << "Starting Receiver " << std::endl; -#endif - - if (connectData() == OK){ - ret=thisReceiver->executeFunction(fnum,mess); - disconnectData(); - } - if(ret==FORCE_UPDATE) - ret=updateReceiver(); - else if (ret == FAIL){ - if(strstr(mess,"UDP")!=NULL) - setErrorMask((getErrorMask())|(COULDNOT_CREATE_UDP_SOCKET)); - else if(strstr(mess,"file")!=NULL) - setErrorMask((getErrorMask())|(COULDNOT_CREATE_FILE)); - else - setErrorMask((getErrorMask())|(COULDNOT_START_RECEIVER)); - } - } - - return ret; -} - - - - -int slsDetector::stopReceiver() { - int fnum=F_STOP_RECEIVER; - int ret = FAIL; - char mess[MAX_STR_LENGTH] = ""; - - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG) { -#ifdef VERBOSE - std::cout << "Stopping Receiver " << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->executeFunction(fnum,mess); - disconnectData(); - } - if(ret==FORCE_UPDATE) - ret=updateReceiver(); - else if (ret == FAIL) - setErrorMask((getErrorMask())|(COULDNOT_STOP_RECEIVER)); - } - - return ret; -} - - - - -slsDetectorDefs::runStatus slsDetector::startReceiverReadout() { - int fnum=F_START_RECEIVER_READOUT; - int ret = FAIL; - int retval=-1; - runStatus s=ERROR; - - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG) { -#ifdef VERBOSE - std::cout << "Starting Receiver Readout" << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->getInt(fnum,retval); - disconnectData(); - } - if(retval!=-1) - s=(runStatus)retval; - if(ret==FORCE_UPDATE) - ret=updateReceiver(); - } - - return s; -} - - - - - -slsDetectorDefs::runStatus slsDetector::getReceiverStatus() { - int fnum=F_GET_RECEIVER_STATUS; - int ret = FAIL; - int retval=-1; - runStatus s=ERROR; - - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG) { -#ifdef VERBOSE - std::cout << "Getting Receiver Status" << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->getInt(fnum,retval); - disconnectData(); - } - if(retval!=-1) - s=(runStatus)retval; - if(ret==FORCE_UPDATE) - ret=updateReceiver(); - } - - return s; -} - - - - -int slsDetector::getFramesCaughtByReceiver() { - int fnum=F_GET_RECEIVER_FRAMES_CAUGHT; - int ret = FAIL; - int retval=-1; - - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG) { -#ifdef VERBOSE - std::cout << "Getting Frames Caught by Receiver " << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->getInt(fnum,retval); - disconnectData(); - } - if(ret==FORCE_UPDATE) - ret=updateReceiver(); - } - - return retval; -} - - - -int slsDetector::getFramesCaughtByAnyReceiver() { - return getFramesCaughtByReceiver(); -} - - - -int slsDetector::getReceiverCurrentFrameIndex() { - int fnum=F_GET_RECEIVER_FRAME_INDEX; - int ret = FAIL; - int retval=-1; - - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG) { -#ifdef VERBOSE - std::cout << "Getting Current Frame Index of Receiver " << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->getInt(fnum,retval); - disconnectData(); - } - if(ret==FORCE_UPDATE) - ret=updateReceiver(); - } - - return retval; -} - - - - -int slsDetector::resetFramesCaught() { - int fnum=F_RESET_RECEIVER_FRAMES_CAUGHT; - int ret = FAIL; - char mess[MAX_STR_LENGTH] = ""; - - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG) { -#ifdef VERBOSE - std::cout << "Reset Frames Caught by Receiver" << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->executeFunction(fnum,mess); - disconnectData(); - } - if(ret==FORCE_UPDATE) - ret=updateReceiver(); - } - - return ret; -} - - - - - - - - - - -int slsDetector::enableWriteToFile(int enable) { - int fnum=F_ENABLE_RECEIVER_FILE_WRITE; - int ret = FAIL; - int retval=-1; - int arg = enable; - - - if(thisDetector->receiverOnlineFlag==OFFLINE_FLAG){ - if(enable>=0){ - pthread_mutex_lock(&ms); - multiDet->enableWriteToFileMask(enable); - pthread_mutex_unlock(&ms); - } - } - - else if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending enable file write to receiver " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if(ret!=FAIL){ - pthread_mutex_lock(&ms); - multiDet->enableWriteToFileMask(retval); - pthread_mutex_unlock(&ms); - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - pthread_mutex_lock(&ms); - retval = multiDet->enableWriteToFileMask(); - pthread_mutex_unlock(&ms); - - return retval; -} - - - - -int slsDetector::overwriteFile(int enable) { - int fnum=F_ENABLE_RECEIVER_OVERWRITE; - int ret = FAIL; - int retval=-1; - int arg = enable; - - - if(thisDetector->receiverOnlineFlag==OFFLINE_FLAG){ - if(enable>=0){ - pthread_mutex_lock(&ms); - multiDet->enableOverwriteMask(enable); - pthread_mutex_unlock(&ms); - } - } - - else if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending enable file write to receiver " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if(ret!=FAIL){ - pthread_mutex_lock(&ms); - multiDet->enableOverwriteMask(retval); - pthread_mutex_unlock(&ms); - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - pthread_mutex_lock(&ms); - retval = multiDet->enableOverwriteMask(); - pthread_mutex_unlock(&ms); - - return retval; -} - - - - - - - - - - - - - -int slsDetector::setReadReceiverFrequency(int freq) { - - if (freq >= 0) { - thisDetector->receiver_read_freq = freq; - - int fnum=F_READ_RECEIVER_FREQUENCY; - int ret = FAIL; - int retval=-1; - int arg = freq; - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending read frequency to receiver " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if((ret == FAIL) || (retval != freq)) { - cout << "could not set receiver read frequency to " << freq - <<" Returned:" << retval << endl; - setErrorMask((getErrorMask())|(RECEIVER_READ_FREQUENCY)); - } - - if(ret==FORCE_UPDATE) - updateReceiver(); - } - } - - return thisDetector->receiver_read_freq; -} - - - -int slsDetector::setReceiverReadTimer(int time_in_ms) { - int fnum=F_READ_RECEIVER_TIMER; - int ret = FAIL; - int arg = time_in_ms; - int retval = -1; - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Sending read timer to receiver " << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if(ret==FORCE_UPDATE) - updateReceiver(); - } - - if ((time_in_ms > 0) && (retval != time_in_ms)){ - cout << "could not set receiver read timer to " << time_in_ms - <<" Returned:" << retval << endl; - setErrorMask((getErrorMask())|(RECEIVER_READ_TIMER)); - } - return retval; -} - - -int slsDetector::enableDataStreamingToClient(int enable) { - cprintf(RED,"ERROR: Must be called from the multi Detector level\n"); - return 0; -} - - - - - -int slsDetector::enableDataStreamingFromReceiver(int enable) { - - if (enable >= 0) { - int fnum=F_STREAM_DATA_FROM_RECEIVER; - int ret = FAIL; - int retval=-1; - int arg = enable; - - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "***************Sending Data Streaming in Receiver " - << arg << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,arg); - disconnectData(); - } - if(ret==FAIL) { - retval = -1; - cout << "could not set data streaming in receiver to " << - enable <<" Returned:" << retval << endl; - setErrorMask((getErrorMask())|(DATA_STREAMING)); - } else { - thisDetector->receiver_upstream = retval; - if(ret==FORCE_UPDATE) - updateReceiver(); - } - } - } - - return thisDetector->receiver_upstream; -} - - - -int slsDetector::enableReceiverCompression(int i) { - int fnum=F_ENABLE_RECEIVER_COMPRESSION; - int ret = FAIL; - int retval=-1; - - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - std::cout << "Getting/Enabling/Disabling Receiver Compression with argument " - << i << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,i); - disconnectData(); - } - if(ret==FAIL) - setErrorMask((getErrorMask())|(COULDNOT_ENABLE_COMPRESSION)); - } - return retval; -} - - - - - - -int slsDetector::enableTenGigabitEthernet(int i) { - int ret=FAIL; - int retval = -1; - int fnum=F_ENABLE_TEN_GIGA,fnum2 = F_ENABLE_RECEIVER_TEN_GIGA; - char mess[MAX_STR_LENGTH]=""; - -#ifdef VERBOSE - std::cout<< std::endl<< "Enabling / Disabling 10Gbe" << endl; -#endif - - if (thisDetector->onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&i,sizeof(i)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==FAIL){ - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - setErrorMask((getErrorMask())|(DETECTOR_TEN_GIGA)); - } - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - - if(ret!=FAIL){ - //must also configuremac - if((i != -1)&&(retval == i)) - if(configureMAC() != FAIL){ - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ - ret = FAIL; - retval=-1; -#ifdef VERBOSE - std::cout << "Enabling / Disabling 10Gbe in receiver: " - << i << std::endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum2,retval,i); - disconnectData(); - } - if(ret==FAIL) - setErrorMask((getErrorMask())|(RECEIVER_TEN_GIGA)); - } - } - } - - if(ret != FAIL) - thisDetector->tenGigaEnable=retval; - return retval; -} - - - - -int slsDetector::setReceiverFifoDepth(int i) { - int fnum=F_SET_RECEIVER_FIFO_DEPTH; - int ret = FAIL; - int retval=-1; - - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - if(i ==-1) - std::cout<< "Getting Receiver Fifo Depth" << endl; - else - std::cout<< "Setting Receiver Fifo Depth to " << i << endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,i); - disconnectData(); - } - if(ret==FAIL) - setErrorMask((getErrorMask())|(COULD_NOT_SET_FIFO_DEPTH)); - } - return retval; -} - - - -int slsDetector::setReceiverSilentMode(int i) { - int fnum=F_SET_RECEIVER_SILENT_MODE; - int ret = FAIL; - int retval=-1; - - - if(thisDetector->receiverOnlineFlag==ONLINE_FLAG){ -#ifdef VERBOSE - if(i ==-1) - std::cout<< "Getting Receiver Silent Mode" << endl; - else - std::cout<< "Setting Receiver Silent Mode to " << i << endl; -#endif - if (connectData() == OK){ - ret=thisReceiver->sendInt(fnum,retval,i); - disconnectData(); - } - if(ret==FAIL) - setErrorMask((getErrorMask())|(RECEIVER_PARAMETER_NOT_SET)); - else - thisDetector->receiver_silentMode = retval; - } - return thisDetector->receiver_silentMode; -} - - - - -int slsDetector::restreamStopFromReceiver() { - int fnum=F_RESTREAM_STOP_FROM_RECEIVER; - int ret = FAIL; - char mess[MAX_STR_LENGTH] = ""; - - if (thisDetector->receiverOnlineFlag==ONLINE_FLAG) { -#ifdef VERBOSE - std::cout << "To Restream stop dummy from Receiver via zmq" << std::endl; -#endif - - if (connectData() == OK){ - ret=thisReceiver->executeFunction(fnum,mess); - disconnectData(); - } - if(ret==FORCE_UPDATE) - ret=updateReceiver(); - else if (ret == FAIL) { - setErrorMask((getErrorMask())|(RESTREAM_STOP_FROM_RECEIVER)); - std::cout << " Could not restream stop dummy packet from receiver" << endl; - } - } - - return ret; -} - - - - -int slsDetector::setCTBPattern(string fname) { - - uint64_t word; - - int addr=0; - - FILE *fd=fopen(fname.c_str(),"r"); - if (fd) { - while (fread(&word, sizeof(word), 1,fd)) { - setCTBWord(addr,word); - // cout << hex << addr << " " << word << dec << endl; - ++addr; - } - - fclose(fd); - } else - return -1; - - - - - - return addr; - - -} - - -uint64_t slsDetector::setCTBWord(int addr,uint64_t word) { - - //uint64_t ret; - - int ret=FAIL; - uint64_t retval=-1; - int fnum=F_SET_CTB_PATTERN; - int mode=0; //sets word - - char mess[MAX_STR_LENGTH]=""; - -#ifdef VERBOSE - std::cout<<"Setting CTB word" <onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&mode,sizeof(mode)); - controlSocket->SendDataOnly(&addr,sizeof(addr)); - controlSocket->SendDataOnly(&word,sizeof(word)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - return retval; - - -} - - -int slsDetector::setCTBPatLoops(int level,int &start, int &stop, int &n) { - - - int retval[3], args[4]; - - args[0]=level; - args[1]=start; - args[2]=stop; - args[3]=n; - - - int ret=FAIL; - int fnum=F_SET_CTB_PATTERN; - int mode=1; //sets loop - - char mess[MAX_STR_LENGTH]=""; - -#ifdef VERBOSE - std::cout<<"Setting CTB word" <onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&mode,sizeof(mode)); - controlSocket->SendDataOnly(&args,sizeof(args)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - start=retval[0]; - stop=retval[1]; - n=retval[2]; - } else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - return ret; - - -} - - -int slsDetector::setCTBPatWaitAddr(int level, int addr) { - - - - - int retval=-1; - - - int ret=FAIL; - int fnum=F_SET_CTB_PATTERN; - int mode=2; //sets loop - - char mess[MAX_STR_LENGTH]=""; - -#ifdef VERBOSE - std::cout<<"Setting CTB word" <onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&mode,sizeof(mode)); - controlSocket->SendDataOnly(&level,sizeof(level)); - controlSocket->SendDataOnly(&addr,sizeof(addr)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - } else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - return retval; - - - -} - - -int slsDetector::setCTBPatWaitTime(int level, uint64_t t) { - - - uint64_t retval=-1; - - int ret=FAIL; - // uint64_t retval=-1; - int fnum=F_SET_CTB_PATTERN; - int mode=3; //sets loop - - char mess[MAX_STR_LENGTH]=""; - -#ifdef VERBOSE - std::cout<<"Setting CTB word" <onlineFlag==ONLINE_FLAG) { - if (connectControl() == OK){ - controlSocket->SendDataOnly(&fnum,sizeof(fnum)); - controlSocket->SendDataOnly(&mode,sizeof(mode)); - controlSocket->SendDataOnly(&level,sizeof(level)); - controlSocket->SendDataOnly(&t,sizeof(t)); - controlSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret!=FAIL) { - controlSocket->ReceiveDataOnly(&retval,sizeof(retval)); - } else { - controlSocket->ReceiveDataOnly(mess,sizeof(mess)); - std::cout<< "Detector returned error: " << mess << std::endl; - } - disconnectControl(); - if (ret==FORCE_UPDATE) - updateDetector(); - } - } - - return retval; - - -} - - - diff --git a/slsDetectorSoftware/slsDetector/slsDetector.h b/slsDetectorSoftware/slsDetector/slsDetector.h deleted file mode 100644 index 7e8e1e80d..000000000 --- a/slsDetectorSoftware/slsDetector/slsDetector.h +++ /dev/null @@ -1,2495 +0,0 @@ -#ifndef SLS_DETECTOR_H -#define SLS_DETECTOR_H - -/** - * - * @short complete detector functionalities for a single module detector. - * The slsDetector class takes care of the communication with the - * detector and all kind actions related with a single detector controller - * @author Anna Bergamaschi - */ - -#include "slsDetectorUtils.h" -#include "energyConversion.h" -#include "angleConversionConstant.h" -#include "MySocketTCP.h" -#include "angleConversionConstant.h" - -class multiSlsDetector; -class SharedMemory; -class receiverInterface; - -#define SLS_SHMVERSION 0x180629 -#define NMODMAXX 24 -#define NMODMAXY 24 -#define NCHIPSMAX 10 -#define NCHANSMAX 65536 -#define NDACSMAX 16 -/** - * parameter list that has to be initialized depending on the detector type - */ -typedef struct detParameterList { - int nModMaxX; - int nModMaxY; - int nChanX; - int nChanY; - int nChipX; - int nChipY; - int nDacs; - int nAdcs; - int nGain; - int nOffset; - int dynamicRange; - int moveFlag; - int nGappixelsX; - int nGappixelsY; -} detParameterList; - - -class slsDetector : public slsDetectorUtils, public energyConversion { - -private: - /** - * @short structure allocated in shared memory to store detector settings for IPC and cache - */ - typedef struct sharedSlsDetector { - - /* FIXED PATTERN FOR STATIC FUNCTIONS. DO NOT CHANGE, ONLY APPEND ------*/ - - /** shared memory version */ - int shmversion; - - /** online flag - is set if the detector is connected, unset if socket - * connection is not possible */ - int onlineFlag; - - /** stopped flag - is set if an acquisition error occurs or the detector - * is stopped manually. Is reset to 0 at the start of the acquisition */ - int stoppedFlag; - - /** is the hostname (or IP address) of the detector. needs to be set - * before starting the communication */ - char hostname[MAX_STR_LENGTH]; - - /** END OF FIXED PATTERN -----------------------------------------------*/ - - - - - /** Detector offset in the X & Y direction in the multi detector structure */ - int offset[2]; - - /** is the port used for control functions */ - int controlPort; - - /** is the port used to stop the acquisition */ - int stopPort; - - /** detector type \ see :: detectorType*/ - detectorType myDetectorType; - - /** path of the trimbits/settings files */ - char settingsDir[MAX_STR_LENGTH]; - - /** path of the calibration files */ - char calDir[MAX_STR_LENGTH]; - - /** number of energies at which the detector has been trimmed */ - int nTrimEn; - - /** list of the energies at which the detector has been trimmed */ - int trimEnergies[MAX_TRIMEN]; - - /** indicator for the acquisition progress - set to 0 at the beginning - * of the acquisition and incremented when each frame is processed */ - int progressIndex; - - /** total number of frames to be acquired */ - int totalProgress; - - /** path of the output files */ - char filePath[MAX_STR_LENGTH]; - - /** number of installed modules of the detector (x and y directions) */ - int nMod[2]; - - /** number of modules ( nMod[X]*nMod[Y]) \see nMod */ - int nMods; - - /** maximum number of modules of the detector (x and y directions) */ - int nModMax[2]; - - /** maximum number of modules (nModMax[X]*nModMax[Y]) \see nModMax */ - int nModsMax; - - /** number of channels per chip */ - int nChans; - - /** number of channels per chip in one direction */ - int nChan[2]; - - /** number of chips per module*/ - int nChips; - - /** number of chips per module in one direction */ - int nChip[2]; - - /** number of dacs per module*/ - int nDacs; - - /** number of adcs per module */ - int nAdcs; - - /** number of extra gain values*/ - int nGain; - - /** number of extra offset values */ - int nOffset; - - /** dynamic range of the detector data */ - int dynamicRange; - - /** size of the data that are transfered from the detector */ - int dataBytes; - - /** corrections to be applied to the data \see ::correctionFlags */ - int correctionMask; - - /** threaded processing flag - * (i.e. if data are processed in a separate thread) */ - int threadedProcessing; - - /** dead time (in ns) for rate corrections */ - double tDead; - - /** directory where the flat field files are stored */ - char flatFieldDir[MAX_STR_LENGTH]; - - /** file used for flat field corrections */ - char flatFieldFile[MAX_STR_LENGTH]; - - /** number of bad channels from bad channel list */ - int nBadChans; - - /** file with the bad channels */ - char badChanFile[MAX_STR_LENGTH]; - - /** list of bad channels */ - int badChansList[MAX_BADCHANS]; - - /** number of bad channels from flat field - * i.e. channels which read 0 in the flat field file */ - int nBadFF; - - /** list of bad channels from flat field - * i.e. channels which read 0 in the flat field file */ - int badFFList[MAX_BADCHANS]; - - /** file with the angular conversion factors */ - char angConvFile[MAX_STR_LENGTH]; - - /** array of angular conversion constants for each module - * \see ::angleConversionConstant */ - angleConversionConstant angOff[MAXMODS]; - - /** angular direction (1 if it corresponds to the encoder direction - * i.e. channel 0 is 0, maxchan is positive high angle, 0 otherwise */ - int angDirection; - - /** beamline fine offset (of the order of mdeg, - * might be adjusted for each measurements) */ - double fineOffset; - - /** beamline offset (might be a few degrees beacuse of encoder offset - - * normally it is kept fixed for a long period of time) */ - double globalOffset; - - /** number of positions at which the detector should acquire */ - int numberOfPositions; - - /** list of encoder positions at which the detector should acquire */ - double detPositions[MAXPOS]; - - /** bin size for data merging */ - double binSize; - - /** add encoder value flag (i.e. wether the detector is - * moving - 1 - or stationary - 0) */ - int moveFlag; - - /** number of rois defined */ - int nROI; - - /** list of rois */ - ROI roiLimits[MAX_ROIS]; - - /** readout flags */ - readOutFlags roFlags; - - /** name root of the output files */ - char settingsFile[MAX_STR_LENGTH]; - - /** detector settings (standard, fast, etc.) */ - detectorSettings currentSettings; - - /** detector threshold (eV) */ - int currentThresholdEV; - - /** timer values */ - int64_t timerValue[MAX_TIMERS]; - - /** action mask */ - int actionMask; - - /** action script */ - mystring actionScript[MAX_ACTIONS]; - - /** action parameter */ - mystring actionParameter[MAX_ACTIONS]; - - /** scan mode */ - int scanMode[MAX_SCAN_LEVELS]; - - /** scan script */ - mystring scanScript[MAX_SCAN_LEVELS]; - - /** scan parameter */ - mystring scanParameter[MAX_SCAN_LEVELS]; - - /** n scan steps */ - int nScanSteps[MAX_SCAN_LEVELS]; - - /** scan steps */ - mysteps scanSteps[MAX_SCAN_LEVELS]; - - /** scan precision */ - int scanPrecision[MAX_SCAN_LEVELS]; - - /** memory offsets for the flat field coefficients */ - int ffoff; - - /** memory offsets for the flat filed coefficient errors */ - int fferroff; - - /** memory offsets for the module structures */ - int modoff; - - /** memory offsets for the dac arrays */ - int dacoff; - - /** memory offsets for the adc arrays */ - int adcoff; - - /** memory offsets for the chip register arrays */ - int chipoff; - - /** memory offsets for the channel register arrays -trimbits*/ - int chanoff; - - /** memory offsets for the gain register arrays */ - int gainoff; - - /** memory offsets for the offset register arrays -trimbits*/ - int offsetoff; - - /** ip address/hostname of the receiver for client control via TCP */ - char receiver_hostname[MAX_STR_LENGTH]; - - /** is the TCP port used to communicate between client and the receiver */ - int receiverTCPPort; - - /** is the UDP port used to send data from detector to receiver */ - int receiverUDPPort; - - /** is the port used to communicate between second half module of - * Eiger detector and the receiver*/ - int receiverUDPPort2; - - /** ip address of the receiver for the detector to send packets to**/ - char receiverUDPIP[MAX_STR_LENGTH]; - - /** mac address of receiver for the detector to send packets to **/ - char receiverUDPMAC[MAX_STR_LENGTH]; - - /** mac address of the detector **/ - char detectorMAC[MAX_STR_LENGTH]; - - /** ip address of the detector **/ - char detectorIP[MAX_STR_LENGTH]; - - /** online flag - is set if the receiver is connected, - * unset if socket connection is not possible */ - int receiverOnlineFlag; - - /** 10 Gbe enable*/ - int tenGigaEnable; - - /** flipped data across x or y axis */ - int flippedData[2]; - - /** tcp port from gui/different process to receiver (only data) */ - int zmqport; - - /** tcp port from receiver to gui/different process (only data) */ - int receiver_zmqport; - - /** data streaming (up stream) enable in receiver */ - bool receiver_upstream; - - /* Receiver read frequency */ - int receiver_read_freq; - - /** zmq tcp src ip address in client (only data) **/ - char zmqip[MAX_STR_LENGTH]; - - /** zmq tcp src ip address in receiver (only data) **/ - char receiver_zmqip[MAX_STR_LENGTH]; - - /** gap pixels enable */ - int gappixels; - - /** gap pixels in each direction */ - int nGappixels[2]; - - /** data bytes including gap pixels */ - int dataBytesInclGapPixels; - - /** additional json header */ - char receiver_additionalJsonHeader[MAX_STR_LENGTH]; - - /** frames per file in receiver */ - int receiver_framesPerFile; - - /** detector control server software API version */ - int64_t detectorControlAPIVersion; - - /** detector stop server software API version */ - int64_t detectorStopAPIVersion; - - /** receiver server software API version */ - int64_t receiverAPIVersion; - - /** receiver frames discard policy */ - frameDiscardPolicy receiver_frameDiscardMode; - - /** receiver partial frames padding enable */ - bool receiver_framePadding; - - /** activated receiver */ - bool activated; - - /** padding enable in deactivated receiver */ - bool receiver_deactivatedPaddingEnable; - - /** silent receiver */ - bool receiver_silentMode; - - } sharedSlsDetector; - - - - - -public: - - using slsDetectorUtils::getDetectorType; - using postProcessing::flatFieldCorrect; - using postProcessing::rateCorrect; - using postProcessing::setBadChannelCorrection; - using angularConversion::readAngularConversion; - using angularConversion::writeAngularConversion; - using slsDetectorUtils::getAngularConversion; - - //FIXME: all pos or id arguments needed only for same multi signature - - /** - * Constructor called when creating new shared memory - * @param type detector type - * @param multiId multi detector shared memory id - * @param id sls detector id (position in detectors list) - * @param verify true to verify if shared memory version matches existing one - * @param m multiSlsDetector reference - */ - slsDetector(detectorType type, int multiId = 0, int id = 0, bool verify = true, multiSlsDetector* m = NULL); - - /** - * Constructor called when opening existing shared memory - * @param multiId multi detector shared memory id - * @param id sls detector id (position in detectors list) - * @param verify true to verify if shared memory version matches existing one - * @param m multiSlsDetector reference - */ - slsDetector(int multiId = 0, int id = 0, bool verify = true, multiSlsDetector* m = NULL); - - /** - * Destructor - */ - virtual ~slsDetector(); - - /** - * returns false. Used when reference is slsDetectorUtils and to determine - * if command can be implemented as slsDetector/multiSlsDetector object/ - */ - bool isMultiSlsDetectorClass(); - - /** - * Decode data from the detector converting them to an array of doubles, - * one for each channel (Mythen only) - * @param datain data from the detector - * @param nn size of datain array - * @param fdata double array of decoded data - * @returns pointer to a double array with a data per channel - */ - double* decodeData(int *datain, int &nn, double *fdata=NULL); - - /** - * Clears error mask and also the bit in parent det multi error mask - * @returns error mask - */ - int64_t clearAllErrorMask(); - - /** - * Set acquiring flag in shared memory - * @param b acquiring flag - */ - void setAcquiringFlag(bool b=false); - - /** - * Get acquiring flag from shared memory - * @returns acquiring flag - */ - bool getAcquiringFlag(); - - /** - * Check if acquiring flag is set, set error if set - * @returns FAIL if not ready, OK if ready - */ - bool isAcquireReady(); - - /** - * Check version compatibility with detector/receiver software - * (if hostname/rx_hostname has been set/ sockets created) - * @param p port type control port or receiver port - * @returns FAIL for incompatibility, OK for compatibility - */ - int checkVersionCompatibility(portType t); - - /** - * Get ID or version numbers - * @param mode version type - * @param imod module number in entire module list (gets decoded) (-1 for all) - * @returns Id or version number of that type - */ - int64_t getId(idMode mode, int imod=0); - - /** - * Free shared memory without creating objects - * If this is called, must take care to update - * multiSlsDetectors thisMultiDetector->numberofDetectors - * avoiding creating the constructor classes and mapping - * @param multiId multi detector Id - * @param slsId slsDetectorId or position of slsDetector in detectors list - */ - static void freeSharedMemory(int multiId, int slsId); - - /** - * Free shared memory and delete shared memory structure - * occupied by the sharedSlsDetector structure - * Is only safe to call if one deletes the slsDetector object afterward - * and frees multi shared memory/updates thisMultiDetector->numberOfDetectors - */ - void freeSharedMemory(); - - /** - * Get user details of shared memory - * Should only be called from multi detector level - * @returns string with user details - */ - std::string getUserDetails(); - - /** - * Sets the hostname of all sls detectors in shared memory - * Connects to them to set up online flag - * @param name hostname - */ - void setHostname(const char *name); - - /** - * Gets the hostname of detector - * @param pos insignificant - * @returns hostname - */ - std::string getHostname(int pos = -1); - - /** - * Appends detectors to the end of the list in shared memory - * Connects to them to set up online flag - * Should only be called from multi detector level - * @param name concatenated hostname of the sls detectors to be appended to the list - */ - void addMultipleDetectors(const char* name); - - /** - * Connect to the control port - * @returns OK, FAIL or undefined - */ - int connectControl(); - - /** - * Disconnect the control port - */ - void disconnectControl(); - - /** - * Connect to the data port - * @returns OK, FAIL or undefined - */ - int connectData(); - - /** - * Disconnect the data port - */ - void disconnectData(); - - /** - * Connect to the stop port - * @returns OK, FAIL or undefined - */ - int connectStop(); - - /** - * Disconnect the stop port - */ - void disconnectStop(); - - /** - * Get detector type by connecting to the detector without creating an object - * @param name hostname of detector - * @param cport TCP control port - * @returns detector tpe or GENERIC if failed - */ - static detectorType getDetectorType(const char *name, int cport=DEFAULT_PORTNO); - - /** - * Gets detector type from detector and set it in receiver - * @param type the detector type - * @returns detector type in receiver - */ - int setDetectorType(detectorType type=GET_DETECTOR_TYPE); - - /** - * Gets detector type (string) from detector and set it in receiver - * @param type string of detector type - * @returns detector type in receiver - */ - int setDetectorType(std::string stype); - - /** - * Get Detector type from shared memory variable - * @param pos insignificant - * @returns detector type from shared memory variable - */ - detectorType getDetectorsType(int pos = -1); - - /** - * Gets string version of detector type from shared memory variable - * @param pos insignificant - * @returns string version of detector type from shared memory variable - */ - std::string sgetDetectorsType(int pos=-1); - - /** - * Just to overload getDetectorType from users - * Gets string version of detector type from shared memory variable - * @returns gets string version of detector type from shared memory variable - */ - std::string getDetectorType(); - - /** - * Returns number of modules from shared memory (Mythen) - * Other detectors, it is 1 - * @returns number of modules - */ - int getNMods(); - - /** - * Returns number of modules in dimension d from shared memory (Mythen) - * Other detectors, it is 1 - * @param d dimension d - * @returns number of modules in dimension d - */ - int getNMod(dimension d); - - /** - * Returns maximum number of modules from shared memory (Mythen) - * Other detectors, it is 1 - * @returns maximum number of modules - */ - int getMaxMods(); - - /** - * Returns maximum number of modules in dimension d from shared memory (Mythen) - * Other detectors, it is 1 - * @param d dimension d - * @returns maximum number of modules in dimension d - */ - int getNMaxMod(dimension d); - - /** - * Returns maximum number of modules in dimension d (Mythen) - * from the detector directly. - * Other detectors, it is 1 - * @param d dimension d - * @returns maximum number of modules in dimension d - */ - int getMaxNumberOfModules(dimension d=X); // - - /** - * Sets/Gets the number of modules in dimension d (Mythen) - * from the detector directly. - * Other detectors, it is 1 - * @param i the number of modules to set to (-1 gets) - * @param d dimension d - * @returns the number of modules in dimension d - */ - int setNumberOfModules(int n=GET_FLAG, dimension d=X); - - /** - * returns the number of channels per that module - * from shared memory (Mythen) - * @param imod insignificant - * @returns number of channels per module - */ - int getChansPerMod(int imod=0); - - /** - * returns the number of channels per that module in dimension d - * from shared memory (Mythen) - * @param d dimension d - * @param imod insignificant - * @returns number of channels per module in dimension d - */ - int getChansPerMod( dimension d,int imod=0); - - /** - * Returns the total number of channels from shared memory - * @returns the total number of channels - */ - int getTotalNumberOfChannels(); - - /** - * Returns the total number of channels in dimension d from shared memory - * @param d dimension d - * @returns the total number of channels in dimension d - */ - int getTotalNumberOfChannels(dimension d); - - /** - * Returns the total number of channels of in dimension d including gap pixels - * from shared memory - * @param d dimension d - * @returns the total number of channels including gap pixels in dimension d - * including gap pixels - */ - int getTotalNumberOfChannelsInclGapPixels(dimension d); - - /** - * Returns the maximum number of channels from shared memory (Mythen) - * @returns the maximum number of channels - */ - int getMaxNumberOfChannels(); - - /** - * Returns the maximum number of channels in dimension d from shared memory (Mythen) - * @param d dimension d - * @returns the maximum number of channels in dimension d - */ - int getMaxNumberOfChannels(dimension d); - - /** - * Returns the maximum number of channels in dimension d from shared memory (Mythen) - * @param d dimension d - * @returns the maximum number of channels in dimension d - */ - int getMaxNumberOfChannelsInclGapPixels(dimension d); - - /** - * returns the number of channels per chip from shared memory (Mythen) - * @returns number of channels per chip - */ - int getNChans(); - - /** - * returns the number of channels per chip in dimension d from shared memory (Mythen) - * @param d dimension d - * @returns number of channels per chip in dimension d - */ - int getNChans(dimension d); - - /** - * returns the number of chips per module from shared memory (Mythen) - * @returns number of chips per module - */ - int getNChips(); - - /** - * returns the number of chips per module in dimension d from shared memory (Mythen) - * @param d dimension d - * @returns number of chips per module in dimension d - */ - int getNChips(dimension d); - - /** - * Get Detector offset from shared memory in dimension d - * @param d dimension d - * @returns offset in dimension d - */ - int getDetectorOffset(dimension d); - - /** - * Set Detector offset in shared memory in dimension d - * @param d dimension d - * @param off offset for detector - */ - void setDetectorOffset(dimension d, int off); - - /** - * Checks if the detector is online and sets the online flag - * @param online if GET_ONLINE_FLAG, only returns shared memory online flag, - * else sets the detector in online/offline state - * if OFFLINE_FLAG, (i.e. no communication to the detector - using only local structure - no data acquisition possible!); - * if ONLINE_FLAG, detector in online state (i.e. communication to the detector updating the local structure) - * @returns online/offline status - */ - int setOnline(int const online=GET_ONLINE_FLAG); - - /** - * Checks if each of the detector is online/offline - * @returns empty string if it is online - * else returns hostnameif it is offline - */ - std::string checkOnline(); - - /** - * Configure the TCP socket communciation and initializes the socket instances - * @param name hostname, empty if current hostname - * @param control_port TCP port for control commands, -1 if current is used - * @param stop_port TCP port for data commands, -1 if current is used - * @returns OK or FAIL - * \sa sharedSlsDetector - */ - int setTCPSocket(std::string const name="", int const control_port=-1, int const stop_port=-1); - - - /** - * Set/Gets TCP Port of detector or receiver - * @param t port type - * @param p port number (-1 gets) - * @returns port number - */ - int setPort(portType type, int num=-1); - - /** - * Returns the detector TCP control port \sa sharedSlsDetector - * @returns the detector TCP control port - */ - int getControlPort(); - - /** - * Returns the detector TCP stop port \sa sharedSlsDetector - * @returns the detector TCP stop port - */ - int getStopPort(); - - /** - * Returns the receiver TCP port \sa sharedSlsDetector - * @returns the receiver TCP port - */ - int getReceiverPort(); - - /** - * Lock server for this client IP - * @param p 0 to unlock, 1 to lock (-1 gets) - * @returns 1 for locked or 0 for unlocked - */ - int lockServer(int lock=-1); - - /** - * Get last client IP saved on detector server - * @returns last client IP saved on detector server - */ - std::string getLastClientIP(); - - /** - * Exit detector server - * @returns OK or FAIL - */ - int exitServer(); - - /** - * Executes a system command on the detector server - * e.g. mount an nfs disk, reboot and returns answer etc. - * @param cmd command to be executed - * @param answer is the answer from the detector - * @returns OK or FAIL - */ - int execCommand(std::string cmd, std::string answer); - - /** - * Updates some of the shared memory receiving the data from the detector - * @returns OK - */ - int updateDetectorNoWait(); - - /** - * Updates soem of the shared memory receiving the data from the detector - * calls updateDetectorNoWait - * @returns OK or FAIL or FORCE_RET - */ - int updateDetector(); - - /** - * Load configuration from a configuration File - * calls readConfigurationFile and gives it the stream - * @param fname configuration file name - * @return OK or FAIL - */ - int readConfigurationFile(std::string const fname); - - /** - * Load configuration from a stream - * @param infile stream - * @return OK or FAIL - */ - int readConfigurationFile(std::ifstream &infile); - - /** - * Write current configuration to a file - * calls writeConfigurationFile giving it a stream to write to - * @param fname configuration file name - * @returns OK or FAIL - */ - int writeConfigurationFile(std::string const fname); - - /** - * Write current configuration to a stream - * @param outfile outstream - * @param id detector id - * @returns OK or FAIL - */ - int writeConfigurationFile(std::ofstream &outfile, int id=-1); - - /** - * Returns the trimfile or settings file name (Useless??) - * @returns the trimfile or settings file name - */ - std::string getSettingsFile(); - - /** - * Writes a trim/settings file for module number imod, - * the values will be read from the current detector structure - * @param fname name of the file to be written - * @param imod module number - * @param iodelay io delay (detector specific) - * @param tau tau (detector specific) - * @returns OK or FAIL if the file could not be written - * \sa ::sls_detector_module sharedSlsDetector mythenDetector::writeSettingsFile(string, int) - */ - using energyConversion::writeSettingsFile; - int writeSettingsFile(std::string fname, int imod, int iodelay, int tau); - - /** - * Get detector settings - * @param imod module number (-1 all) - * @returns current settings - */ - detectorSettings getSettings(int imod=-1); - - /** - * Load detector settings from the settings file picked from the trimdir/settingsdir - * Eiger only stores in shared memory ( a get will overwrite this) - * For Eiger, one must use threshold - * Gotthard, Propix, Jungfrau and Moench only sends the settings enum to the detector - * @param isettings settings - * @param imod module number (-1 all) - * @returns current settings - */ - detectorSettings setSettings(detectorSettings isettings, int imod=-1); - - /** - * Send detector settings only (set only for Jungfrau, Gotthard, Moench, get for all) - * Only the settings enum is sent to the detector, where it will - * initialize al the dacs already hard coded in the detector server - * @param isettings settings - * @param imod module number (-1 all) - * @returns current settings - */ - detectorSettings sendSettingsOnly(detectorSettings isettings, int imod=-1); - - /** - * Get threshold energy (Mythen and Eiger) - * @param imod module number (-1 all) - * @returns current threshold value for imod in ev (-1 failed) - */ - int getThresholdEnergy(int imod=-1); - - - /** - * Set threshold energy (Mythen and Eiger) - * For Eiger, calls setThresholdEneryAndSettings - * @param e_eV threshold in eV - * @param imod module number (-1 all) - * @param isettings ev. change settings - * @param tb 1 to include trimbits, 0 to exclude - * @returns current threshold value for imod in ev (-1 failed) - */ - int setThresholdEnergy(int e_eV, int imod=-1, detectorSettings isettings=GET_SETTINGS, int tb=1); - - /** - * Set threshold energy and settings (Eiger only) - * @param e_eV threshold in eV - * @param isettings ev. change settings - * @param tb 1 to include trimbits, 0 to exclude - * @returns OK if successful, else FAIL - */ - int setThresholdEnergyAndSettings(int e_eV, detectorSettings isettings, int tb=1); - - /** - * Returns the detector trimbit/settings directory \sa sharedSlsDetector - * @returns the trimbit/settings directory - */ - std::string getSettingsDir(); - - /** - * Sets the detector trimbit/settings directory \sa sharedSlsDetector - * @param s trimbits/settings directory - * @returns the trimbit/settings directory - */ - std::string setSettingsDir(std::string s); - - /** - * Returns the calibration files directory \sa sharedSlsDetector (Mythen) - * @returns the calibration files directory - */ - std::string getCalDir(); - - /** - * Sets the calibration files directory \sa sharedSlsDetector (Mythen) - * @param s the calibration files directory - * @returns the calibration files directory - */ - std::string setCalDir(std::string s); - - /** - * Loads the modules settings/trimbits reading from a specific file - * file name extension is automatically generated. - * @param fname specific settings/trimbits file - * @param imod module index of the entire list, - * from which will be calculated the detector index and the module index (-1 for all) - * returns OK or FAIL - */ - int loadSettingsFile(std::string fname, int imod=-1); - - /** - * Saves the modules settings/trimbits to a specific file - * file name extension is automatically generated. - * @param fname specific settings/trimbits file - * @param imod module number (-1 for all) - * returns OK or FAIL - */ - int saveSettingsFile(std::string fname, int imod=-1); - - /** - * Loads the modules calibration data reading from a specific file (Mythen) - * file name extension is automatically generated. - * @param fname specific calibration file - * @param imod module number (-1 for all) - * returns OK or FAIL - */ - int loadCalibrationFile(std::string fname, int imod=-1); - - /** - * Saves the modules calibration data to a specific file (Mythen) - * file name extension is automatically generated. - * @param fname specific calibration file - * @param imod module number (-1 for all) - * returns OK or FAIL - */ - int saveCalibrationFile(std::string fname, int imod=-1); - - /** - * Sets/gets the detector in position i as master of the structure (Mythen) - * (e.g. it gates the other detectors and therefore must be started as last. - * Assumes that signal 0 is gate in, signal 1 is trigger in, signal 2 is gate out - * @param i position of master (-1 gets, -2 unset) - * @return master's position (-1 none) - */ - masterFlags setMaster(masterFlags flag); - - /** - * Sets/gets the synchronization mode of the various detector (Mythen) - * @param sync syncronization mode - * @returns current syncronization mode - */ - synchronizationMode setSynchronization(synchronizationMode sync=GET_SYNCHRONIZATION_MODE); - - /** - * Calcualtes the total number of steps of the acquisition - * Called when number of frames, number of cycles, number of positions and scan steps change - * @returns the total number of steps of the acquisition - */ - int setTotalProgress(); - - /** - * Returns the current progress in % - * @returns the current progress in % - */ - double getCurrentProgress(); - - /** - * Get run status of the detector - * @returns the status of the detector - */ - runStatus getRunStatus(); - - /** - * Prepares detector for acquisition (Eiger and Gotthard) - * For Gotthard, it sets the detector data transmission mode (CPU or receiver) - * @returns OK or FAIL - */ - int prepareAcquisition(); - - /** - * Cleans up after acquisition (Gotthard only) - * For Gotthard, it sets the detector data transmission to default (via CPU) - * @returns OK or FAIL - */ - int cleanupAcquisition(); - - /** - * Start detector acquisition (Non blocking) - * @returns OK or FAIL if even one does not start properly - */ - int startAcquisition(); - - /** - * Stop detector acquisition - * @returns OK or FAIL - */ - int stopAcquisition(); - - /** - * Give an internal software trigger to the detector (Eiger only) - * @return OK or FAIL - */ - int sendSoftwareTrigger(); - - /** - * Start readout (without exposure or interrupting exposure) (Mythen) - * @returns OK or FAIL - */ - int startReadOut(); - - /** - * Start detector acquisition and read all data (Blocking until end of acquisition) - * (Mythen, puts all data into a data queue. Others, data at receiver via udp packets) - * @returns pointer to the front of the data queue (return significant only for Mythen) - * \sa startAndReadAllNoWait getDataFromDetector dataQueue - */ - int* startAndReadAll(); - - /** - * Start detector acquisition and call read out, but not reading (data for Mythen, - * and status for other detectors) from the socket. - * (startAndReadAll calls this and getDataFromDetector. Client is not blocking, - * but server is blocked until getDataFromDetector is called. so not recommended - * for users) - * @returns OK or FAIL - */ - int startAndReadAllNoWait(); - - /** - * Reads from the detector socket (data frame for Mythen and status for other - * detectors) - * @returns pointer to the data or NULL. If NULL disconnects the socket - * (return significant only for Mythen) - * Other detectors return NULL - * \sa getDataFromDetector - */ - int* getDataFromDetector(int *retval=NULL); - - /** - * Requests and receives a single data frame from the detector - * (Mythen: and puts it in the data queue) - * @returns pointer to the data or NULL. (return Mythen significant) - * Other detectors return NULL - * \sa getDataFromDetector - */ - int* readFrame(); - - /** - * Receives all data from the detector - * (Mythen: and puts them in a data queue) - * @returns pointer to the front of the queue or NULL (return Mythen significant) - * Other detectors return NULL - * \sa getDataFromDetector dataQueue - */ - int* readAll(); - - /** - * Requests detector for all data, calls readAll afterwards - * (Mythen: and puts them in a data queue) - * @returns pointer to the front of the queue or NULL (return Mythen significant) - * Other detectors return NULL - * \sa getDataFromDetector dataQueue - */ - int readAllNoWait(); - - /** - * Configures in detector the destination for UDP packets (Not Mythen) - * @returns OK or FAIL - */ - int configureMAC(); - - /** - * Set/get timer value (not all implemented for all detectors) - * @param index timer index - * @param t time in ns or number of...(e.g. frames, gates, probes) - * \param imod module number (pointless in slsDetector) - * @returns timer set value in ns or number of...(e.g. frames, gates, probes) - */ - int64_t setTimer(timerIndex index, int64_t t=-1, int imod = -1); - - /** - * Set/get timer value left in acquisition (not all implemented for all detectors) - * @param index timer index - * @param t time in ns or number of...(e.g. frames, gates, probes) - * @param imod module number - * @returns timer set value in ns or number of...(e.g. frames, gates, probes) - */ - int64_t getTimeLeft(timerIndex index, int imod = -1); - - /** - * Set speed - * @param sp speed type (clkdivider option for Jungfrau and Eiger, others for Mythen/Gotthard) - * @param value (clkdivider 0,1,2 for full, half and quarter speed). Other values check manual - * @returns value of speed set - */ - int setSpeed(speedVariable sp, int value=-1); - - /** - * Set/get dynamic range and updates the number of dataBytes - * (Eiger: If i is 32, also sets clkdivider to 2, if 16, sets clkdivider to 1) - * @param i dynamic range (-1 get) - * @returns current dynamic range - * \sa sharedSlsDetector - */ - int setDynamicRange(int n=-1); - - /** - * Recalculated number of data bytes - * @returns tota number of data bytes - */ - int getDataBytes(); - - /** - * Recalculated number of data bytes including gap pixels - * @returns tota number of data bytes including gap pixels - */ - int getDataBytesInclGapPixels(); - - /** - * Set/get dacs value - * @param val value (in V) - * @param index DAC index - * @param mV 0 in dac units or 1 in mV - * @param imod module number (if -1 all modules) - * @returns current DAC value - */ - dacs_t setDAC(dacs_t val, dacIndex index , int mV, int imod=-1); - - /** - * Get adc value - * @param index adc(DAC) index - * @param imod module number (if -1 all modules) - * @returns current adc value (temperature for eiger and jungfrau in millidegrees) - */ - dacs_t getADC(dacIndex index, int imod=0); - - /** - * Set/get timing mode - * @param pol timing mode (-1 gets) - * @returns current timing mode - */ - externalCommunicationMode setExternalCommunicationMode(externalCommunicationMode pol=GET_EXTERNAL_COMMUNICATION_MODE); - - /** - * Set/get external signal flags (to specify triggerinrising edge etc) (Gotthard, Mythen) - * @param pol external signal flag (-1 gets) - * @param signalindex singal index (0 - 3) - * @returns current timing mode - */ - externalSignalFlag setExternalSignalFlags(externalSignalFlag pol=GET_EXTERNAL_SIGNAL_FLAG , int signalindex=0); - - /** - * Set/get readout flags (Eiger, Mythen) - * @param flag readout flag (Eiger options: parallel, nonparallel, safe etc.) (-1 gets) - * @returns readout flag - */ - int setReadOutFlags(readOutFlags flag=GET_READOUT_FLAGS); - - /** - * Write in a register. For Advanced users - * @param addr address of register - * @param val value to write into register - * @returns value read after writing - */ - uint32_t writeRegister(uint32_t addr, uint32_t val); - - /** - * Read from a register. For Advanced users - * @param addr address of register - * @returns value read from register - */ - uint32_t readRegister(uint32_t addr); - - /** - * Set bit in a register. For Advanced users - * @param addr address of register - * @param n nth bit - * @returns value read from register - */ - uint32_t setBit(uint32_t addr, int n); - - /** - * Clear bit in a register. For Advanced users - * @param addr address of register - * @param n nth bit - * @returns value read from register - */ - uint32_t clearBit(uint32_t addr, int n); - - /** - * Set network parameter - * @param p network parameter type - * @param s network parameter value - * @returns network parameter value set (from getNetworkParameter) - */ - std::string setNetworkParameter(networkParameter index, std::string value); - - /** - * Get network parameter - * @param p network parameter type - * @returns network parameter value set (from getNetworkParameter) - */ - std::string getNetworkParameter(networkParameter index); - - /** - * Returns the detector MAC address\sa sharedSlsDetector - * @returns the detector MAC address - */ - std::string getDetectorMAC(); - - /** - * Returns the detector IP address\sa sharedSlsDetector - * @returns the detector IP address - */ - std::string getDetectorIP(); - - /** - * Returns the receiver IP address\sa sharedSlsDetector - * @returns the receiver IP address - */ - std::string getReceiver(); - - /** - * Returns the receiver UDP IP address\sa sharedSlsDetector - * @returns the receiver UDP IP address - */ - std::string getReceiverUDPIP(); - - /** - * Returns the receiver UDP MAC address\sa sharedSlsDetector - * @returns the receiver UDP MAC address - */ - std::string getReceiverUDPMAC(); - - /** - * Returns the receiver UDP port\sa sharedSlsDetector - * @returns the receiver UDP port - */ - std::string getReceiverUDPPort(); - - /** - * Returns the receiver UDP port 2 of same interface\sa sharedSlsDetector - * @returns the receiver UDP port 2 of same interface - */ - std::string getReceiverUDPPort2(); - - /** - * Returns the client zmq port \sa sharedSlsDetector - * @returns the client zmq port - */ - std::string getClientStreamingPort(); - - /** - * Returns the receiver zmq port \sa sharedSlsDetector - * @returns the receiver zmq port - */ - std::string getReceiverStreamingPort(); - - /** - * Returns the client zmq ip \sa sharedSlsDetector - * @returns the client zmq ip, returns "none" if default setting and no custom ip set - */ - std::string getClientStreamingIP(); - - /** - * Returns the receiver zmq ip \sa sharedSlsDetector - * @returns the receiver zmq ip, returns "none" if default setting and no custom ip set - */ - std::string getReceiverStreamingIP(); - - /** - * Validates the format of the detector MAC address and sets it \sa sharedSlsDetector - * @param detectorMAC detector MAC address - * @returns the detector MAC address - */ - std::string setDetectorMAC(std::string detectorMAC); - - /** - * Validates the format of the detector IP address and sets it \sa sharedSlsDetector - * @param detectorIP detector IP address - * @returns the detector IP address - */ - std::string setDetectorIP(std::string detectorIP); - - /** - * Validates and sets the receiver. - * Also updates the receiver with all the shared memory parameters significant for the receiver - * Also configures the detector to the receiver as UDP destination - * @param receiver receiver hostname or IP address - * @returns the receiver IP address from shared memory - */ - std::string setReceiver(std::string receiver); - - /** - * Validates the format of the receiver UDP IP address and sets it \sa sharedSlsDetector - * @param udpip receiver UDP IP address - * @returns the receiver UDP IP address - */ - std::string setReceiverUDPIP(std::string udpip); - - /** - * Validates the format of the receiver UDP MAC address and sets it \sa sharedSlsDetector - * @param udpmac receiver UDP MAC address - * @returns the receiver UDP MAC address - */ - std::string setReceiverUDPMAC(std::string udpmac); - - /** - * Sets the receiver UDP port\sa sharedSlsDetector - * @param udpport receiver UDP port - * @returns the receiver UDP port - */ - int setReceiverUDPPort(int udpport); - - /** - * Sets the receiver UDP port 2\sa sharedSlsDetector - * @param udpport receiver UDP port 2 - * @returns the receiver UDP port 2 - */ - int setReceiverUDPPort2(int udpport); - - /** - * Sets the client zmq port\sa sharedSlsDetector - * @param port client zmq port (includes "multi" at the end if it should - * calculate individual ports) - * @returns the client zmq port - */ - std::string setClientStreamingPort(std::string port); - - /** - * Sets the receiver zmq port\sa sharedSlsDetector - * @param port receiver zmq port (includes "multi" at the end if it should - * calculate individual ports) - * @returns the receiver zmq port - */ - std::string setReceiverStreamingPort(std::string port); - - /** - * Sets the client zmq ip\sa sharedSlsDetector - * @param sourceIP client zmq ip - * @returns the client zmq ip, returns "none" if default setting and no custom ip set - */ - std::string setClientStreamingIP(std::string sourceIP); - - /** - * Sets the receiver zmq ip\sa sharedSlsDetector - * @param sourceIP receiver zmq ip. If empty, uses rx_hostname - * @returns the receiver zmq ip, returns "none" if default setting and no custom ip set - */ - std::string setReceiverStreamingIP(std::string sourceIP); - - /** - * Execute a digital test (Gotthard, Mythen) - * @param mode testmode type - * @param imod module index (-1 for all) - * @returns result of test - */ - int digitalTest(digitalTestMode mode, int imod=0); - - /** - * Execute trimming (Mythen) - * @param mode trimming mode type - * @param par1 parameter 1 - * @param par2 parameter 2 - * @param imod module index (-1 for all) - * @returns result of trimming - */ - int executeTrimming(trimMode mode, int par1, int par2, int imod=-1); - - /** - * Load dark or gain image to detector (Gotthard) - * @param index image type, 0 for dark image and 1 for gain image - * @param fname file name from which to load image - * @returns OK or FAIL - */ - int loadImageToDetector(imageType index,std::string const fname); - - /** - * Called from loadImageToDetector to send the image to detector - * @param index image type, 0 for dark image and 1 for gain image - * @param imageVals image - * @returns OK or FAIL - */ - int sendImageToDetector(imageType index,short int imageVals[]); - - /** - * Writes the counter memory block from the detector (Gotthard) - * @param fname file name to load data from - * @param startACQ is 1 to start acquisition after reading counter - * @returns OK or FAIL - */ - int writeCounterBlockFile(std::string const fname,int startACQ=0); - - /** - * Gets counter memory block in detector (Gotthard) - * @param arg counter memory block from detector - * @param startACQ 1 to start acquisition afterwards, else 0 - * @returns OK or FAIL - */ - int getCounterBlock(short int arg[],int startACQ=0); - - /** - * Resets counter in detector - * @param startACQ is 1 to start acquisition after resetting counter - * @returns OK or FAIL - */ - int resetCounterBlock(int startACQ=0); - - /** - * Set/get counter bit in detector (Gotthard) - * @param i is -1 to get, 0 to reset and any other value to set the counter bit - * @returns the counter bit in detector - */ - int setCounterBit(int i = -1); - - /** - * Set ROI (Gotthard) - * At the moment only one set allowed - * @param n number of rois - * @param roiLimits array of roi - * @param imod module number (ignored) - * @returns OK or FAIL - */ - int setROI(int n=-1,ROI roiLimits[]=NULL, int imod = -1); - - /** - * Get ROI from each detector and convert it to the multi detector scale (Gotthard) - * @param n number of rois - * @param imod module number (ignored) - * @returns pointer to array of ROI structure - */ - ROI* getROI(int &n, int imod = -1); - - /** - * Returns number of rois - * @returns number of ROIs - */ - int getNRoi(); - - /** - * Send ROI to the detector after calculating - * from setROI - * @param n number of ROIs (-1 to get) - * @param roiLimits ROI - * @returns OK or FAIL - */ - int sendROI(int n=-1,ROI roiLimits[]=NULL); - - /** - * Write to ADC register (Gotthard, Jungfrau, ChipTestBoard). For expert users - * @param addr address of adc register - * @param val value - * @returns return value (mostly -1 as it can't read adc register) - */ - int writeAdcRegister(int addr, int val); - - /** - * Activates/Deactivates the detector (Eiger only) - * @param enable active (1) or inactive (0), -1 gets - * @returns 0 (inactive) or 1 (active)for activate mode - */ - int activate(int const enable=-1); - - /** - * Set deactivated Receiver padding mode (Eiger only) - * @param padding padding option for deactivated receiver. Can be 1 (padding), 0 (no padding), -1 (gets) - * @returns 1 (padding), 0 (no padding), -1 (inconsistent values) for padding option - */ - int setDeactivatedRxrPaddingMode(int padding=-1); - - /** - * Returns the enable if data will be flipped across x or y axis (Eiger) - * @param d axis across which data is flipped - * @returns 1 for flipped, else 0 - */ - int getFlippedData(dimension d=X); - - /** - * Sets the enable which determines if - * data will be flipped across x or y axis (Eiger) - * @param d axis across which data is flipped - * @param value 0 or 1 to reset/set or -1 to get value - * @returns enable flipped data across x or y axis - */ - int setFlippedData(dimension d=X, int value=-1); - - /** - * Sets all the trimbits to a particular value (Eiger) - * @param val trimbit value - * @param imod module number, -1 means all modules - * @returns OK or FAIL - */ - int setAllTrimbits(int val, int imod=-1); - - /** - * Enable gap pixels, only for Eiger and for 8,16 and 32 bit mode. (Eiger) - * 4 bit mode gap pixels only in gui call back - * @param val 1 sets, 0 unsets, -1 gets - * @returns gap pixel enable or -1 for error - */ - int enableGapPixels(int val=-1); - - /** - * Sets the number of trim energies and their value (Eiger) - * \sa sharedSlsDetector - * @param nen number of energies - * @param en array of energies - * @returns number of trim energies - */ - int setTrimEn(int nen, int *en=NULL); - - /** - * Returns the number of trim energies and their value (Eiger) - * \sa sharedSlsDetector - * @param en array of energies - * @returns number of trim energies - */ - int getTrimEn(int *en=NULL); - - /** - * Pulse Pixel (Eiger) - * @param n is number of times to pulse - * @param x is x coordinate - * @param y is y coordinate - * @returns OK or FAIL - */ - int pulsePixel(int n=0,int x=0,int y=0); - - /** - * Pulse Pixel and move by a relative value (Eiger) - * @param n is number of times to pulse - * @param x is relative x value - * @param y is relative y value - * @returns OK or FAIL - */ - int pulsePixelNMove(int n=0,int x=0,int y=0); - - /** - * Pulse Chip (Eiger) - * @param n is number of times to pulse - * @returns OK or FAIL - */ - int pulseChip(int n=0); - - /** - * Set/gets threshold temperature (Jungfrau) - * @param val value in millidegrees, -1 gets - * @param imod module number, -1 is all - * @returns threshold temperature in millidegrees - */ - int setThresholdTemperature(int val=-1, int imod=-1); - - /** - * Enables/disables temperature control (Jungfrau) - * @param val value, -1 gets - * @param imod module number, -1 is all - * @returns temperature control enable - */ - int setTemperatureControl(int val=-1, int imod=-1); - - /** - * Resets/ gets over-temperature event (Jungfrau) - * @param val value, -1 gets - * @param imod module number, -1 is all - * @returns over-temperature event - */ - int setTemperatureEvent(int val=-1, int imod=-1); - - /** - * Set storage cell that stores first acquisition of the series (Jungfrau) - * @param value storage cell index. Value can be 0 to 15. (-1 gets) - * @returns the storage cell that stores the first acquisition of the series - */ - int setStoragecellStart(int pos=-1); - - /** - * Programs FPGA with pof file (Jungfrau) - * @param fname file name - * @returns OK or FAIL - */ - int programFPGA(std::string fname); - - /** - * Resets FPGA (Jungfrau) - * @returns OK or FAIL - */ - int resetFPGA(); - - /** - * Power on/off Chip (Jungfrau) - * @param ival on is 1, off is 0, -1 to get - * @returns OK or FAIL - */ - int powerChip(int ival= -1); - - /** - * Automatic comparator disable (Jungfrau) - * @param ival on is 1, off is 0, -1 to get - * @returns OK or FAIL - */ - int setAutoComparatorDisableMode(int ival= -1); - - - /** - * Returns the trimbits from the detector's shared memmory (Mythen, Eiger) - * @param retval is the array with the trimbits - * @param fromDetector is true if the trimbits shared memory have to be - * uploaded from detector - * @returns total number of channels for the detector - */ - int getChanRegs(double* retval,bool fromDetector); - - /** - * Configure module (who calls this?) - * @param imod module number (-1 all) - * @returns current register value - * \sa ::sls_detector_module - */ - int setModule(int reg, int imod=-1); - - /** - * Configure Module (Mythen, Eiger) - * Called for loading trimbits and settings settings to the detector - * @param module module to be set - must contain correct module number and - * also channel and chip registers - * @param iodelay iodelay (detector specific) - * @param tau tau (detector specific) - * @param e_eV threashold in eV (detector specific) - * @param gainval pointer to extra gain values - * @param offsetval pointer to extra offset values - * @param tb 1 to include trimbits, 0 to exclude (used for eiger) - * @returns current register value - * \sa ::sls_detector_module - */ - int setModule(sls_detector_module module, int iodelay, int tau, int e_eV, - int* gainval=0, int* offsetval=0, int tb=1); - - - /** - * Get module structure from detector (all detectors) - * @param imod module number - * @returns pointer to module structure (which has been created and must then be deleted) - */ - sls_detector_module *getModule(int imod); - - /** - * Configure channel (Mythen) - * @param reg channel register - * @param ichan channel number (-1 all) - * @param ichip chip number (-1 all) - * @param imod module number (-1 all) - * @returns current register value - * \sa ::sls_detector_channel - */ - int setChannel(int64_t reg, int ichan=-1, int ichip=-1, int imod=-1); - - /** - * Configure channel (Mythen) - * @param chan channel to be set - - * must contain correct channel, module and chip number - * @returns current register value - */ - int setChannel(sls_detector_channel chan); - - /** - * Get channel (Mythen) - * @param ichan channel number - * @param ichip chip number - * @param imod module number - * @returns current channel structure for channel - */ - sls_detector_channel getChannel(int ichan, int ichip, int imod); - - /** - * Configure chip (Mythen) - * @param reg chip register - * @param ichip chip number (-1 all) - * @param imod module number (-1 all) - * @returns current register value - * \sa ::sls_detector_chip - */ - int setChip(int reg, int ichip=-1, int imod=-1); - - /** - * Configure chip (Mythen) - * @param chip chip to be set - * must contain correct module and chip number and also channel registers - * @returns current register value - * \sa ::sls_detector_chip - */ - int setChip(sls_detector_chip chip); - - /** - * Get chip (Mythen) - * @param ichip chip number - * @param imod module number - * @returns current chip structure for channel - * \bug probably does not return corretly! - */ - sls_detector_chip getChip(int ichip, int imod); - - /** - * Get Move Flag (Mythen) - * @param imod module number (-1 all) - * @param istep step index - * @returns move flag - */ - int getMoveFlag(int imod); - - /** - * Fill Module mask for flat field corrections (Mythen) - * @param mM array - * @returns number of modules - */ - int fillModuleMask(int *mM); - - /** - * Calibrate Pedestal (ChipTestBoard) - * Starts acquisition, calibrates pedestal and writes to fpga - * @param frames number of frames - * @returns number of frames - */ - int calibratePedestal(int frames = 0); - - /** - * Set Rate correction (Mythen, Eiger) - * @param t dead time in ns - if 0 disable correction, - * if >0 set dead time to t, if < 0 set deadtime to default dead time - * for current settings - * @returns 0 if rate correction disabled, >0 otherwise - */ - int setRateCorrection(double t=0); - - /** - * Get rate correction (Mythen, Eiger) - * @param t reference for dead time - * @returns 0 if rate correction disabled, > 0 otherwise - */ - int getRateCorrection(double &t); - - /** - * Get rate correction tau (Mythen, Eiger) - * @returns 0 if rate correction disabled, otherwise the tau used for the correction - */ - double getRateCorrectionTau(); - - /** - * Get rate correction (Mythen, Eiger) - * @returns 0 if rate correction disabled, > 0 otherwise - */ - int getRateCorrection(); - - /** - * Rate correct data (Mythen) - * @param datain data array - * @param errin error array on data (if NULL will default to sqrt(datain) - * @param dataout array of corrected data - * @param errout error on corrected data (if not NULL) - * @returns 0 - */ - int rateCorrect(double* datain, double *errin, double* dataout, double *errout); - - /** - * Set flat field corrections (Mythen) - * @param fname name of the flat field file (or "" if disable) - * @returns 0 if disable (or file could not be read), >0 otherwise - */ - int setFlatFieldCorrection(std::string fname=""); - - /** - * Set flat field corrections (Mythen) - * @param corr if !=NULL the flat field corrections will be filled with - * corr (NULL usets ff corrections) - * @param ecorr if !=NULL the flat field correction errors will be filled - * with ecorr (1 otherwise) - * @returns 0 if ff correction disabled, >0 otherwise - */ - int setFlatFieldCorrection(double *corr, double *ecorr=NULL); - - /** - * Get flat field corrections (Mythen) - * @param corr if !=NULL will be filled with the correction coefficients - * @param ecorr if !=NULL will be filled with the correction coefficients errors - * @returns 0 if ff correction disabled, >0 otherwise - */ - int getFlatFieldCorrection(double *corr=NULL, double *ecorr=NULL); - - /** - * Flat field correct data (Mythen) - * @param datain data array - * @param errin error array on data (if NULL will default to sqrt(datain) - * @param dataout array of corrected data - * @param errout error on corrected data (if not NULL) - * @returns 0 - */ - int flatFieldCorrect(double* datain, double *errin, double* dataout, double *errout); - - /** - * Set bad channels correction (Mythen) - * @param fname file with bad channel list ("" disable) - * @returns 0 if bad channel disabled, >0 otherwise - */ - int setBadChannelCorrection(std::string fname=""); - - /** - * Set bad channels correction (Mythen) - * @param nch number of bad channels - * @param chs array of channels - * @param ff 0 if normal bad channels, 1 if ff bad channels - * @returns 0 if bad channel disabled, >0 otherwise - */ - int setBadChannelCorrection(int nch, int *chs, int ff=0); - - /** - * Get bad channels correction (Mythen) - * @param bad pointer to array that if bad!=NULL will be filled with the - * bad channel list - * @returns 0 if bad channel disabled or no bad channels, >0 otherwise - */ - int getBadChannelCorrection(int *bad=NULL); - - /** - * Reads an angular conversion file (Mythen, Gotthard) - * \sa angleConversionConstant mythenDetector::readAngularConversion - * @param fname file to be read - * @returns 0 if angular conversion disabled, >0 otherwise - */ - int readAngularConversionFile(std::string fname=""); - - /** - * Reads an angular conversion file (Mythen, Gotthard) - * \sa angleConversionConstant mythenDetector::readAngularConversion - * @param ifs input stream - * @returns 0 if angular conversion disabled, >0 otherwise - */ - int readAngularConversion(std::ifstream& ifs); - - /** - * Writes an angular conversion file (Mythen, Gotthard) - * \sa angleConversionConstant mythenDetector::writeAngularConversion - * @param fname file to be written - * @returns 0 if angular conversion disabled, >0 otherwise - */ - int writeAngularConversion(std::string fname=""); - - /** - * Writes an angular conversion file (Mythen, Gotthard) - * \sa angleConversionConstant mythenDetector::writeAngularConversion - * @param ofs output stream - * @returns 0 if angular conversion disabled, >0 otherwise - */ - int writeAngularConversion(std::ofstream &ofs); - - /** - * Get angular conversion (Mythen, Gotthard) - * \sa angleConversionConstant mythenDetector::getAngularConversion - * @param direction reference to diffractometer - * @param angconv array that will be filled with the angular conversion constants - * @returns 0 if angular conversion disabled, >0 otherwise - */ - int getAngularConversion(int &direction, angleConversionConstant *angconv=NULL) ; - - /** - * Return angular conversion pointer (Mythen, Gotthard) - * @param imod module number - * @returns angular conversion pointer - */ - angleConversionConstant *getAngularConversionPointer(int imod=0); - - /** - * Prints receiver configuration - * @returns OK or FAIL - */ - int printReceiverConfiguration(); - - /** - * Checks if receiver is online and set flag - * Also initializes the data socekt - * @param online 1 to set online, 0 to set offline, -1 gets - * @returns online, offline (from shared memory) - */ - int setReceiverOnline(int const online=GET_ONLINE_FLAG); - - /** - * Checks if the receiver is really online - * @returns empty string if online, else returns receiver hostname - */ - std::string checkReceiverOnline(); - - /** - * Configure the socket communication and initializes the socket instances - * @param name receiver ip - if "" the current receiver hostname is used - * @param receiver_port port for receiving data - if -1 the current is used - * @returns OK is connection succeded, FAIL otherwise - * \sa sharedSlsDetector - */ - int setReceiverTCPSocket(std::string const name="", int const receiver_port=-1); - - /** - * Locks/Unlocks the connection to the receiver - * @param lock sets (1), usets (0), gets (-1) the lock - * @returns lock status of the receiver - */ - int lockReceiver(int lock=-1); - - /** - * Returns the IP of the last client connecting to the receiver - * @returns the IP of the last client connecting to the receiver - */ - std::string getReceiverLastClientIP(); - - /** - * Exits the receiver TCP server - * @retutns OK or FAIL - */ - int exitReceiver(); - - /** - updates the shared memory receiving the data from the detector (without asking and closing the connection - /returns OK - */ - int updateReceiverNoWait(); - - /** - * Updates the shared memory receiving the data from the detector - * @returns OK or FAIL - */ - int updateReceiver(); - - /** - * Send the multi detector size to the detector - */ - void sendMultiDetectorSize(); - - /** - * Send the detector pos id to the receiver - * for various file naming conventions for multi detectors in receiver - */ - void setDetectorId(); - - /** - * Send the detector host name to the receiver - * for various handshaking required with the detector - */ - void setDetectorHostname(); - - /** - * Returns output file directory - * @returns output file directory - */ - std::string getFilePath(); - - /** - * Sets up the file directory - * @param s file directory - * @returns file dir - */ - std::string setFilePath(std::string s=""); - - /** - * Returns file name prefix - * @returns file name prefix - */ - std::string getFileName(); - - /** - * Sets up the file name prefix - * @param s file name prefix - * @returns file name prefix - */ - std::string setFileName(std::string s=""); - - /** - * Sets the max frames per file in receiver - * @param f max frames per file - * @returns max frames per file in receiver - */ - int setReceiverFramesPerFile(int f = -1); - - /** - * Sets the frames discard policy in receiver - * @param f frames discard policy - * @returns frames discard policy set in receiver - */ - frameDiscardPolicy setReceiverFramesDiscardPolicy(frameDiscardPolicy f = GET_FRAME_DISCARD_POLICY); - - /** - * Sets the partial frames padding enable in receiver - * @param f partial frames padding enable - * @returns partial frames padding enable in receiver - */ - int setReceiverPartialFramesPadding(int f = -1); - - /** - * Returns file format - * @returns file name - */ - fileFormat getFileFormat(); - - /** - * Sets up the file format - * @param f file format - * @returns file format - */ - fileFormat setFileFormat(fileFormat f=GET_FILE_FORMAT); - - /** - * Returns file index - * @returns file index - */ - int getFileIndex(); - - /** - * Sets up the file index - * @param i file index - * @returns file index - */ - int setFileIndex(int i=-1); - - /** - * Receiver starts listening to packets - * @returns OK or FAIL - */ - int startReceiver(); - - /** - * Stops the listening mode of receiver - * @returns OK or FAIL - */ - int stopReceiver(); - - /** - * Sets the receiver to start any readout remaining in the fifo and - * change status to transmitting (Mythen) - * The status changes to run_finished when fifo is empty - */ - runStatus startReceiverReadout(); - - /** - * Gets the status of the listening mode of receiver - * @returns status - */ - runStatus getReceiverStatus(); - - /** - * Gets the number of frames caught by receiver - * @returns number of frames caught by receiver - */ - int getFramesCaughtByReceiver(); - - /** - * Gets the number of frames caught by any one receiver (to avoid using threadpool) - * @returns number of frames caught by any one receiver (master receiver if exists) - */ - int getFramesCaughtByAnyReceiver(); - - /** - * Gets the current frame index of receiver - * @returns current frame index of receiver - */ - int getReceiverCurrentFrameIndex(); - - /** - * Resets framescaught in receiver - * Use this when using startAcquisition instead of acquire - * @returns OK or FAIL - */ - int resetFramesCaught(); - - /** - * Sets/Gets receiver file write enable - * @param enable 1 or 0 to set/reset file write enable - * @returns file write enable - */ - int enableWriteToFile(int enable=-1); - - /** - * Sets/Gets file overwrite enable - * @param enable 1 or 0 to set/reset file overwrite enable - * @returns file overwrite enable - */ - int overwriteFile(int enable=-1); - - /** - * Sets the read receiver frequency - * if data required from receiver randomly readRxrFrequency=0, - * else every nth frame to be sent to gui/callback - * @param freq is the receiver read frequency. Value 0 is 200 ms timer (other - * frames not sent), 1 is every frame, 2 is every second frame etc. - * @returns read receiver frequency - */ - int setReadReceiverFrequency(int freq=-1); - - /** - * Sets the read receiver timer - * if data required from receiver randomly readRxrFrequency=0, - * then the timer between each data stream is set with time_in_ms - * @param time_in_ms timer between frames - * @returns read receiver timer - */ - int setReceiverReadTimer(int time_in_ms=500); - - /** - * Enable data streaming to client - * @param enable 0 to disable, 1 to enable, -1 to get the value - * @returns data streaming to client enable - */ - int enableDataStreamingToClient(int enable=-1); - - /** - * Enable or disable streaming data from receiver to client - * @param enable 0 to disable 1 to enable -1 to only get the value - * @returns data streaming from receiver enable - */ - int enableDataStreamingFromReceiver(int enable=-1); - - /** - * Enable/disable or get data compression in receiver - * @param i is -1 to get, 0 to disable and 1 to enable - * @returns data compression in receiver - */ - int enableReceiverCompression(int i = -1); - - /** - * Enable/disable or 10Gbe - * @param i is -1 to get, 0 to disable and 1 to enable - * @returns if 10Gbe is enabled - */ - int enableTenGigabitEthernet(int i = -1); - - /** - * Set/get receiver fifo depth - * @param i is -1 to get, any other value to set the fifo deph - * @returns the receiver fifo depth - */ - int setReceiverFifoDepth(int i = -1); - - /** - * Set/get receiver silent mode - * @param i is -1 to get, 0 unsets silent mode, 1 sets silent mode - * @returns the receiver silent mode enable - */ - int setReceiverSilentMode(int i = -1); - - /** - * If data streaming in receiver is enabled, - * restream the stop dummy packet from receiver - * Used usually for Moench, - * in case it is lost in network due to high data rate - * @returns OK if success else FAIL - */ - int restreamStopFromReceiver(); - - /** - * Opens pattern file and sends pattern to CTB - * @param fname pattern file to open - * @returns OK/FAIL - */ - int setCTBPattern(std::string fname); - - /** - * Writes a pattern word to the CTB - * @param addr address of the word, -1 is I/O control register, -2 is clk control register - * @param word 64bit word to be written, -1 gets - * @returns actual value - */ - uint64_t setCTBWord(int addr,uint64_t word=-1); - - /** - * Sets the pattern or loop limits in the CTB - * @param level -1 complete pattern, 0,1,2, loop level - * @param start start address if >=0 - * @param stop stop address if >=0 - * @param n number of loops (if level >=0) - * @returns OK/FAIL - */ - int setCTBPatLoops(int level,int &start, int &stop, int &n); - - /** - * Sets the wait address in the CTB - * @param level 0,1,2, wait level - * @param addr wait address, -1 gets - * @returns actual value - */ - int setCTBPatWaitAddr(int level, int addr=-1); - - /** - * Sets the wait time in the CTB - * @param level 0,1,2, wait level - * @param t wait time, -1 gets - * @returns actual value - */ - int setCTBPatWaitTime(int level, uint64_t t=-1); - -private: - - /** - * Get Detector Type from Shared Memory (opening shm without verifying size) - * @param multiId multi detector Id - * @param verify true to verify if shm size matches existing one - * @returns detector type - */ - detectorType getDetectorTypeFromShm(int multiId, bool verify = true); - - /** - * Initialize shared memory - * @param created true if shared memory must be created, else false to open - * @param type type of detector - * @param multiId multi detector Id - * @param verify true to verify if shm size matches existing one - * @returns true if the shared memory was created now - */ - void initSharedMemory(bool created, detectorType type, int multiId, bool verify = true); - - /** - * Sets detector parameters depending detector type - * @param type detector type - * @param list structure of parameters to initialize depending on detector type - */ - void setDetectorSpecificParameters(detectorType type, detParameterList& list); - - /** - * Calculate shared memory size based on detector type - * @param type type of detector - * @returns size of shared memory of sharedSlsDetector structure - */ - int calculateSharedMemorySize(detectorType type); - - /** - * Initialize detector structure to defaults - * Called when new shared memory is created - * @param type type of detector - */ - void initializeDetectorStructure(detectorType type); - - /** - * Initialize class members (and from parent classes) - * Also connect member pointers to detector structure pointers - * Called when shared memory created/existed - */ - void initializeMembers(); - - /** - * Initialize detector structure - * Called when new shared memory created - * Initializes the member pointers to defaults as well - */ - void initializeDetectorStructurePointers(); - - /** - * Allocates the memory for a sls_detector_module structure and initializes it - * Uses current detector type - * @returns myMod the pointer to the allocate dmemory location - */ - sls_detector_module* createModule(); - - /** - * Allocates the memory for a sls_detector_module structure and initializes it - * Has detector type - * @param type detector type - * @returns myMod the pointer to the allocate dmemory location - */ - sls_detector_module* createModule(detectorType type); - - /** - * Frees the memory for a sls_detector_module structure - * @param myMod the pointer to the memory to be freed - */ - void deleteModule(sls_detector_module *myMod); - - /** - * Send a sls_detector_channel structure over socket - * @param myChan channel structure to send - * @returns number of bytes sent to the detector - */ - int sendChannel(sls_detector_channel* myChan); - - /** - * Send a sls_detector_chip structure over socket - * @param myChip chip structure to send - * @returns number of bytes sent to the detector - */ - int sendChip(sls_detector_chip* myChip); - - /** - * Send a sls_detector_module structure over socket - * @param myMod module structure to send - * @returns number of bytes sent to the detector - */ - int sendModule(sls_detector_module* myMod); - - /** - * Receive a sls_detector_channel structure over socket - * @param myChan channel structure to receive - * @returns number of bytes received from the detector - */ - int receiveChannel(sls_detector_channel* myChan); - - /** - * Receive a sls_detector_chip structure over socket - * @param myChip chip structure to receive - * @returns number of bytes received from the detector - */ - int receiveChip(sls_detector_chip* myChip); - - /** - * Receive a sls_detector_module structure over socket - * @param myMod module structure to receive - * @returns number of bytes received from the detector - */ - int receiveModule(sls_detector_module* myMod); - - /** - * Returns the additional json header \sa sharedSlsDetector - * @returns the additional json header, returns "none" if default setting and no custom ip set - */ - std::string getAdditionalJsonHeader(); - - /** - * Returns the receiver UDP socket buffer size\sa sharedSlsDetector - * @returns the receiver UDP socket buffer size - */ - std::string getReceiverUDPSocketBufferSize() ; - - /** - * Returns the receiver real UDP socket buffer size\sa sharedSlsDetector - * @returns the receiver real UDP socket buffer size - */ - std::string getReceiverRealUDPSocketBufferSize(); - - /** - * Sets the additional json header\sa sharedSlsDetector - * @param jsonheader additional json header - * @returns additional json header, returns "none" if default setting and no custom ip set - */ - std::string setAdditionalJsonHeader(std::string jsonheader); - - /** - * Sets the receiver UDP socket buffer size - * @param udpsockbufsize additional json header - * @returns receiver udp socket buffer size - */ - std::string setReceiverUDPSocketBufferSize(int udpsockbufsize=-1); - - /** - * Sets the transmission delay for left, right or entire frame - * (Eiger, Jungfrau(only entire frame)) - * @param index type of delay - * @param delay delay - * @returns transmission delay - */ - std::string setDetectorNetworkParameter(networkParameter index, int delay); - - - /** - * Get MAC from the receiver using udpip and - * set up UDP connection in detector - * @returns Ok or FAIL - */ - int setUDPConnection(); - - /** slsDetector Id or position in the detectors list */ - int detId; - - /** Shared Memory object */ - SharedMemory* sharedMemory; - - /** Shared memory structure */ - sharedSlsDetector *thisDetector; - - /** multiSlsDetector referece */ - multiSlsDetector *multiDet; - - receiverInterface *thisReceiver; - - /** socket for control commands */ - MySocketTCP *controlSocket; - - /** socket for emergency stop */ - MySocketTCP *stopSocket; - - /** socket for data acquisition */ - MySocketTCP *dataSocket; - - /** pointer to flat field coefficients in shared memory */ - double *ffcoefficients; - - /** pointer to flat field coefficient errors in shared memory */ - double *fferrors; - - /** pointer to detector module structures in shared memory */ - sls_detector_module *detectorModules; - - /** pointer to dac valuse in shared memory */ - dacs_t *dacs; - - /** pointer to adc valuse in shared memory */ - dacs_t *adcs; - - /** pointer to chip registers in shared memory */ - int *chipregs; - - /** pointer to channal registers in shared memory */ - int *chanregs; - - /** pointer to gain values in shared memory */ - int *gain; - - /** pointer to offset values in shared memory */ - int *offset; -}; - -#endif diff --git a/slsDetectorSoftware/slsDetector/slsDetectorActions.cpp b/slsDetectorSoftware/slsDetector/slsDetectorActions.cpp deleted file mode 100644 index 6e8eaf632..000000000 --- a/slsDetectorSoftware/slsDetector/slsDetectorActions.cpp +++ /dev/null @@ -1,507 +0,0 @@ -#include "slsDetectorActions.h" -#include -#include -#include -using namespace std; - - - /** - set action - \param iaction can be enum {startScript, scriptBefore, headerBefore, headerAfter,scriptAfter, stopScript, MAX_ACTIONS} - \param fname for script ("" disable but leaves script unchanged, "none" disables and overwrites) - \returns 0 if action disabled, >0 otherwise - */ -int slsDetectorActions::setAction(int iaction, string fname, string par) { - - int am; - - - if (iaction>=0 && iaction=0 && iaction=0 && iaction=0 && iaction=0 && iaction0 otherwise - */ -int slsDetectorActions::setScan(int iscan, string script, int nvalues, double *values, string par, int precision) { - if (iscan>=0 && iscan=0) { - // cout << "nvalues " << nvalues << endl; - if (nvalues==0) - scanMode[iscan]=noScan; - else { - nScanSteps[iscan]=nvalues; - if (nvalues>MAX_SCAN_STEPS) - nScanSteps[iscan]=MAX_SCAN_STEPS; - } - } - - if (values && scanMode[iscan]>0 ) { - for (int iv=0; iv=0) - scanPrecision[iscan]=precision; - - if (scanMode[iscan]>0){ - *actionMask |= 1<< (iscan+MAX_ACTIONS); - } else { - *actionMask &= ~(1 << (iscan+MAX_ACTIONS)); - } - - - - setTotalProgress(); - - return scanMode[iscan]; - } else - return -1; - -} - -int slsDetectorActions::setScanScript(int iscan, string script) { - if (iscan>=0 && iscan0){ - *actionMask |= (1 << (iscan+MAX_ACTIONS)); - } else { - *actionMask &= ~(1 << (iscan+MAX_ACTIONS)); - } - - setTotalProgress(); - -#ifdef VERBOSE - cout << "Action mask is " << hex << actionMask << dec << endl; -#endif - return scanMode[iscan]; - } else - return -1; -} - - - -int slsDetectorActions::setScanParameter(int iscan, string par) { - - - if (iscan>=0 && iscan=0 && iscan=0) - scanPrecision[iscan]=precision; - return scanMode[iscan]; - } else - return -1; - -} - -int slsDetectorActions::setScanSteps(int iscan, int nvalues, double *values) { - - if (iscan>=0 && iscan=0) { - if (nvalues==0) - scanMode[iscan]=noScan; - else { - nScanSteps[iscan]=nvalues; - if (nvalues>MAX_SCAN_STEPS) - nScanSteps[iscan]=MAX_SCAN_STEPS; - } - } - - if (values) { - for (int iv=0; iv0){ - *actionMask |= (1 << (iscan+MAX_ACTIONS)); - } else { - *actionMask &= ~(1 << (iscan+MAX_ACTIONS)); - } - -#ifdef VERBOSE - cout << "Action mask is " << hex << actionMask << dec << endl; -#endif - setTotalProgress(); - - - - - return scanMode[iscan]; - - - } else - return -1; - - - - -} - - - - /** - returns scan script - \param iscan can be (0,1) - \returns scan script - */ -string slsDetectorActions::getScanScript(int iscan){ - if (iscan>=0 && iscan=0 && iscan=0 && iscan=0 && iscan=0 && iscanMAX_SCAN_LEVELS) - return -1; - - currentScanVariable[level]=getScanStep(level,istep); - currentScanIndex[level]=istep; - - switch(scanMode[level]) { - case energyScan: - setThresholdEnergy((int)currentScanVariable[level]); //energy scan - break; - case thresholdScan: - setDAC((dacs_t)currentScanVariable[level],THRESHOLD,0); // threshold scan - break; - case dacScan: - setDAC((dacs_t)currentScanVariable[level],(slsDetectorDefs::dacIndex)atoi(getScanParameter(level).c_str()),0); - break; - case trimbitsScan: - trimbit=(int)currentScanVariable[level]; - if(getDetectorsType() == EIGER) - setAllTrimbits(trimbit); - else - setChannel((trimbit<<((int)TRIMBIT_OFF))|((int)COMPARATOR_ENABLE)); // trimbit scan - break; - case positionScan: - //check if channels are connected! - moveDetector(currentScanVariable[level]); - break; - case noScan: - currentScanVariable[level]=0; - break; - case scriptScan: - //Custom scan script level 1. The arguments are passed as nrun=n fn=filename var=v par=p" - sprintf(cmd,"%s nrun=%d fn=%s var=%f par=%s",getScanScript(level).c_str(),getFileIndex(),createFileName().c_str(),currentScanVariable[level],getScanParameter(level).c_str()); -#ifdef VERBOSE - cout << "Executing scan script "<< level << " " << cmd << endl; -#endif - system(cmd); - break; - default: - cout << "Scan mode unknown "<< level << " " < -#include - - -// - -/** - -@short class implementing the script and scan utilities of the detectors - - -*/ - -class slsDetectorActions : public virtual slsDetectorBase -// : public virtual postProcessing -{ - public : - - enum {noScan, energyScan, thresholdScan, trimbitsScan, positionScan, scriptScan, dacScan }; - - - /** default constructor */ - slsDetectorActions(){}; - - /** virtual destructor */ - virtual ~slsDetectorActions(){}; - - /** - set action - \param iaction can be enum {startScript, scriptBefore, headerBefore, headerAfter,scriptAfter, stopScript, MAX_ACTIONS} - \param fname for script ("" disable) - \param par for script - \returns 0 if action disabled, >0 otherwise - */ - int setAction(int iaction,std::string fname="",std::string par=""); - - /** - set action script - \param iaction can be enum {startScript, scriptBefore, headerBefore, headerAfter,scriptAfter, stopScript, MAX_ACTIONS} - \param fname for script ("" disable) - \returns 0 if action disabled, >0 otherwise - */ - int setActionScript(int iaction, std::string fname=""); - - - /** - set action - \param iaction can be enum {startScript, scriptBefore, headerBefore, headerAfter,scriptAfter, stopScript, MAX_ACTIONS} - \param par for script - \returns 0 if action disabled, >0 otherwise - */ - int setActionParameter(int iaction, std::string par=""); - - - /** - returns action script - \param iaction can be enum {startScript, scriptBefore, headerBefore, headerAfter,scriptAfter, stopScript} - \returns action script - */ - std::string getActionScript(int iaction); - - /** - returns action parameter - \param iaction can be enum {startScript, scriptBefore, headerBefore, headerAfter,scriptAfter, stopScript} - \returns action parameter - */ - std::string getActionParameter(int iaction); - - /** - returns action mode - \param iaction can be enum {startScript, scriptBefore, headerBefore, headerAfter,scriptAfter, stopScript} - \returns action mode - */ - int getActionMode(int iaction); - - /** - set scan - \param index of the scan (0,1) - \param script fname for script ("" disables, "none" disables and overwrites current, "threshold" threshold scan, "trimbits", trimbits scan) - \param nvalues number of steps (0 disables, -1 leaves current value) - \param values pointer to steps (if NULL leaves current values) - \param par parameter for the scan script ("" leaves unchanged) - \param precision to write the scan varaible in the scan name (-1 unchanged) - \returns 0 is scan disabled, >0 otherwise - */ - int setScan(int index, std::string script="", int nvalues=-1, double *values=NULL, std::string par="", int precision=-1); - - /** set scan script - \param index of the scan (0,1) - \param script fname for script ("" disables, "none" disables and overwrites current, "threshold" threshold scan, "trimbits", trimbits scan) - \returns 0 is scan disabled, >0 otherwise - */ - int setScanScript(int index, std::string script=""); - /** set scan script parameter - \param index of the scan (0,1) - \param script parameter for scan - \returns 0 is scan disabled, >0 otherwise - */ - int setScanParameter(int index, std::string par=""); - /** set scan script parameter - \param index of the scan (0,1) - \param precision scan varaible precision to be printed in file name - \returns 0 is scan disabled, >0 otherwise - */ - int setScanPrecision(int index, int precision=-1); - - - /** set scan steps - \param index of the scan (0,1) - \param nvalues number of steps - \param values pointer to array of values - \returns 0 is scan disabled, >0 otherwise - */ - int setScanSteps(int index, int nvalues=-1, double *values=NULL); - - /** get scan step - \param index of the scan (0,1) - \param istep step number - \returns value of the scan variable - */ - double getScanStep(int index, int istep){if (index=0 && istep>=0 && istep=0) {startIndex=i; lastIndex=startIndex; nowIndex=startIndex;};return startIndex;}; - int setLastIndex(int i=-1){if (i>=0 && i>lastIndex) lastIndex=i; return lastIndex;}; - - - virtual double moveDetector(double)=0; - virtual double getDetectorPosition()=0; - - - - protected: - - - int executeScan(int level, int istep); - int executeAction(int level); - - - - /** action mask */ - int *actionMask; - /** array of action scripts */ - mystring *actionScript; - /** array of actionparameters */ - mystring *actionParameter; - - /** pointer to number of steps [2] */ - int *nScanSteps; - /** pointer to arrays of step values [2] */ - mysteps *scanSteps; - /** pointer to array of scan mode [2] */ - int *scanMode; - - /** POINTER TO ARRAY OF SCAN PRECISION [2] */ - int *scanPrecision; - - /** pointer to array of scan scripts [2] */ - mystring *scanScript; - - /** pointer to array of scan parameters [2] */ - mystring *scanParameter; - - - - - - - /** - current scan variable of the detector - */ - double currentScanVariable[MAX_SCAN_LEVELS]; - - /** - current scan variable index of the detector - */ - int currentScanIndex[MAX_SCAN_LEVELS]; - - - - - private: - int startIndex; - int lastIndex; - int nowIndex; - std::string fName; - - - - - - -}; -#endif diff --git a/slsDetectorSoftware/slsDetector/slsDetectorBase.h b/slsDetectorSoftware/slsDetector/slsDetectorBase.h deleted file mode 100644 index 3344aa0ec..000000000 --- a/slsDetectorSoftware/slsDetector/slsDetectorBase.h +++ /dev/null @@ -1,958 +0,0 @@ - -#ifndef SLS_DETECTOR_BASE_H -#define SLS_DETECTOR_BASE_H -/** - \mainpage Common C++ library for SLS detectors data acquisition - * - * \section intro_sec Introduction - - * \subsection mot_sec Motivation - Although the SLS detectors group delvelops several types of detectors (1/2D, counting/integrating etc.) it is common interest of the group to use a common platfor for data acquisition - \subsection arch_sec System Architecture - The architecture of the acquisitions system is intended as follows: - \li A socket server running on the detector (or more than one in some special cases) - \li C++ classes common to all detectors for client-server communication. These can be supplied to users as libraries and embedded also in acquisition systems which are not developed by the SLS - \li the possibility of using a Qt-based graphical user interface (with eventually root analisys capabilities) - \li the possibility of running all commands from command line. In order to ensure a fast operation of this so called "text client" the detector parameters should not be re-initialized everytime. For this reason a shared memory block is allocated where the main detector flags and parameters are stored - \li a Root library for data postprocessing and detector calibration (energy, angle). - - \section howto_sec How to use it - - The detectors can be simply operated by using the provided GUi or command line executable.
- In case you need to embed the detector control e.g in the beamline control software, compile these classes using -
- make package -
- and link the shared library created to your software slsDetectorSoftware/bin/libSlsDetector.so -
- The software can also be installed (with super-user rights)
- make install -
-
- Most methods of interest for the user are implemented in the ::slsDetectorBase interface class, but the classes to be implemented in the main program are either ::slsDetector (for single controller detectors) or ::multiSlsDetector (for multiple controllers, but can work also for single controllers). - - @author Anna Bergamaschi - @version 0.1alpha - -*/ - - - -/** - * - * - * - * @author Anna Bergamaschi - * @version 0.1alpha - */ - - -#include "sls_detector_defs.h" -#include "sls_receiver_defs.h" -#include "slsDetectorUsers.h" -#include "error_defs.h" - -#include - -/** - -@libdoc The slsDetectorBase contains also a set of purely virtual functions useful for the implementation of the derived classes - - -* @short This is the base class for all detector functionalities - -*/ - -//public virtual slsDetectorUsers, -class slsDetectorBase : public virtual slsDetectorDefs, public virtual errorDefs { - - public: - - /** default constructor */ - slsDetectorBase(){}; - - - /** virtual destructor */ - virtual ~slsDetectorBase(){}; - - /** returns the detector type - \param pos position in the multi detector structure (is -1 returns type of detector with id -1) - \returns type - */ - virtual detectorType getDetectorsType(int pos=-1)=0; - - std::string getDetectorDeveloper(){return std::string("PSI");}; - // protected: - - /** - set angular conversion - \param fname file with angular conversion constants ("" disable) - \returns 0 if angular conversion disabled, >0 otherwise - */ - virtual int setAngularConversionFile(std::string fname="")=0; - - - /** - pure virtual function - returns the angular conversion file - */ - virtual std::string getAngularConversionFile()=0; - - - - /** - set action - \param iaction can be enum {startScript, scriptBefore, headerBefore, headerAfter,scriptAfter, stopScript, MAX_ACTIONS} - \param fname for script ("" disable) - \returns 0 if action disabled, >0 otherwise - */ - virtual int setActionScript(int iaction, std::string fname="")=0; - - /** - set action - \param iaction can be enum {startScript, scriptBefore, headerBefore, headerAfter,scriptAfter, stopScript, MAX_ACTIONS} - \param par for script ("" disable) - \returns 0 if action disabled, >0 otherwise - */ - virtual int setActionParameter(int iaction, std::string par="")=0; - - /** - returns action script - \param iaction can be enum {startScript, scriptBefore, headerBefore, headerAfter,scriptAfter, stopScript} - \returns action script - */ - virtual std::string getActionScript(int iaction)=0; - - /** - returns action parameter - \param iaction can be enum {startScript, scriptBefore, headerBefore, headerAfter,scriptAfter, stopScript} - \returns action parameter - */ - virtual std::string getActionParameter(int iaction)=0; - - /** - set scan script - \param index is the scan index (0 or 1) - \param script fname for script ("" disable, "none" disables and overwrites current, "threshold" makes threshold scan, "trimbits" make trimbits scan, "energy" makes energy scan) - \returns 0 if scan disabled, >0 otherwise - */ - virtual int setScanScript(int index, std::string script="")=0; - - /** - set scan script parameter - \param index is the scan index (0 or 1) - \param spar parameter to be passed to the scan script with syntax par=spar - \returns 0 if scan disabled, >0 otherwise - */ - virtual int setScanParameter(int index, std::string spar="")=0; - - - /** set scan precision - \param index is the scan index (0 or 1) - \param precision number of decimals to use for the scan variable in the file name - \returns 0 if scan disabled, >0 otherwise */ - virtual int setScanPrecision(int index, int precision=-1)=0; - - /** - set scan steps (passed to the scan script as var=step) - \param index is the scan index (0 or 1) - \param nvalues is the number of steps - \param values array of steps - \returns 0 if scan disabled, >0 otherwise*/ - - virtual int setScanSteps(int index, int nvalues=-1, double *values=NULL)=0; - - /** - get scan script - \param index is the scan index (0 or 1) - \returns "none" if disables, "threshold" threshold scan, "trimbits" trimbits scan, "energy" energy scan or scan script name - */ - virtual std::string getScanScript(int index)=0; - - /** - get scan script - \param index is the scan index (0 or 1) - \returns scan script parameter - */ - virtual std::string getScanParameter(int index)=0; - - /** - get scan precision - \param index is the scan index (0 or 1) - \returns precision i.e. number of decimals to use for the scan variable in the file name - */ - virtual int getScanPrecision(int index)=0; - - /** - get scan steps - \param index is the scan index (0 or 1) - \param values pointer to array of values (must be allocated in advance) - \returns number of steps - */ - virtual int getScanSteps(int index, double *values=NULL)=0; - - - /** - Writes the configuration file -- will contain all the informations needed for the configuration (e.g. for a PSI detector caldir, settingsdir, angconv, badchannels etc.) - \param fname file name - \returns OK or FAIL - */ - virtual int writeConfigurationFile(std::string const fname)=0; - - - /** - Loads dark image or gain image to the detector - \param index can be DARK_IMAGE or GAIN_IMAGE - \param fname file name to load data from - \returns OK or FAIL - */ - virtual int loadImageToDetector(imageType index,std::string const fname)=0; - - /** - \returns number of positions - */ - virtual int getNumberOfPositions()=0;// {return 0;}; - - /** - \returns action mask - */ - virtual int getActionMask()=0;// {return 0;}; - /** - \param index scan level index - \returns current scan variable - */ - virtual double getCurrentScanVariable(int index)=0;// {return 0;}; - - /** - \returns current position index - */ - virtual int getCurrentPositionIndex()=0;// {return 0;}; - - /** - \returns total number of channels - */ - virtual int getTotalNumberOfChannels()=0; - - /** - \returns total number of channels for each dimension - */ - virtual int getTotalNumberOfChannels(dimension d)=0; - - /** generates file name without extension */ - virtual std::string createFileName()=0; - - - virtual void incrementProgress()=0; - virtual void setCurrentProgress(int i=0)=0; - virtual double getCurrentProgress()=0; - virtual void incrementFileIndex()=0; - virtual int setTotalProgress()=0; - - - virtual double* decodeData(int *datain, int &nn, double *fdata=NULL)=0; - - - virtual std::string getCurrentFileName()=0; - - - virtual int getFileIndexFromFileName(std::string fname)=0; - - virtual int getIndicesFromFileName(std::string fname,int &index)=0; - - virtual double *convertAngles()=0; - /** - set rate correction - \param t dead time in ns - if 0 disable correction, if >0 set dead time to t, if <0 set deadtime to default dead time for current settings - \returns 0 if rate correction disabled, >0 otherwise - */ - virtual int setRateCorrection(double t=0)=0; - - /** - get rate correction - \param t reference for dead time - \returns 0 if rate correction disabled, >0 otherwise - */ - virtual int getRateCorrection(double &t)=0; - - /** - get rate correction - \returns 0 if rate correction disabled, >0 otherwise - */ - virtual int getRateCorrection()=0; - - virtual int setFlatFieldCorrection(std::string fname="")=0; - - int setFlatFieldCorrectionFile(std::string fname=""){return setFlatFieldCorrection(fname);}; - - /** - set/get dynamic range - \param i dynamic range (-1 get) - \returns current dynamic range - */ - virtual int setDynamicRange(int i=-1)=0; - // int setBitDepth(int i=-1){return setDynamicRange(i);}; - - /** - set/get the size of the detector - \param i number of modules - \param d dimension - \returns current number of modules in direction d - */ - virtual int setNumberOfModules(int i=-1, dimension d=X)=0; - - // int setDetectorSize(int x0=-1, int y0=-1, int nx=-1, int ny=-1){return setNumberOfModules(nx/getChansPerMod(0),X);}; - - // int getDetectorSize(int &x0, int &y0, int &nx, int &ny){x0=0; nx=setNumberOfModules(-1,X)*getChansPerMod(0); return nx;}; - - virtual int getMaxNumberOfModules(dimension d=X)=0; // - // int getMaximumDetectorSize(int &nx, int &ny){nx=getMaxNumberOfModules(X)*getChansPerMod(0); ny=1; return nx;}; - - - /** Locks/Unlocks the connection to the server - /param lock sets (1), usets (0), gets (-1) the lock - /returns lock status of the server - */ - virtual int lockServer(int i=-1)=0; - - - - /** performs a complete acquisition including scansand data processing - moves the detector to next position
- starts and reads the detector
- reads the IC (if required)
- reads the encoder (iof required for angualr conversion)
- processes the data (flat field, rate, angular conversion and merging ::processData()) - \param delflag 0 leaves the data in the final data queue (default is 1) - \returns OK or FAIL depending on if it already started - */ - virtual int acquire(int delflag=1)=0; - - int startMeasurement(){acquire(0); return OK;}; - - /** - asks and receives a data frame from the detector, writes it to disk and processes the data - \returns pointer to the data or NULL (unused!!!). - */ - virtual int* readFrame()=0; - - - /** - get detector ids/versions for module=0 - \param mode which id/version has to be read - \param imod module number for module serial number - \returns id - */ - virtual int64_t getId(idMode mode, int imod=0)=0; - int64_t getModuleFirmwareVersion(int imod=-1){return getId(MODULE_FIRMWARE_VERSION,imod);}; - int64_t getModuleSerialNumber(int imod=-1){return getId(MODULE_SERIAL_NUMBER,imod);}; - int64_t getDetectorFirmwareVersion(int imod=-1){return getId(DETECTOR_FIRMWARE_VERSION,imod);}; - int64_t getDetectorSerialNumber(int imod=-1){return getId(DETECTOR_SERIAL_NUMBER,imod);}; - int64_t getDetectorSoftwareVersion(int imod=-1){return getId(DETECTOR_SOFTWARE_VERSION,imod);}; - int64_t getThisSoftwareVersion(){return getId(THIS_SOFTWARE_VERSION,-1);}; - - /** - start detector acquisition - \returns OK/FAIL - */ - virtual int startAcquisition()=0; - /** - stop detector acquisition - \returns OK/FAIL - */ - virtual int stopAcquisition()=0; - int stopMeasurement(){return stopAcquisition();}; - virtual int getChansPerMod(int imod=0)=0; - - /** - set/get timer value - \param index timer index - \param t time in ns or number of...(e.g. frames, gates, probes) - \param imod module number - \returns timer set value in ns or number of...(e.g. frames, gates, probes) - */ - virtual int64_t setTimer(timerIndex index, int64_t t=-1, int imod = -1)=0; - int64_t setExposureTime(int64_t t=-1, int imod = -1){return setTimer(ACQUISITION_TIME,t,imod);}; - int64_t setSubFrameExposureTime(int64_t t=-1, int imod = -1){return setTimer(SUBFRAME_ACQUISITION_TIME,t,imod);}; - int64_t setSubFrameDeadTime(int64_t t=-1, int imod = -1){return setTimer(SUBFRAME_DEADTIME,t,imod);}; - int64_t setExposurePeriod(int64_t t=-1, int imod = -1){return setTimer(FRAME_PERIOD,t,imod);}; - int64_t setDelayAfterTrigger(int64_t t=-1, int imod = -1){return setTimer(DELAY_AFTER_TRIGGER,t,imod);}; - int64_t setNumberOfGates(int64_t t=-1, int imod = -1){return setTimer(GATES_NUMBER,t,imod);}; - int64_t setNumberOfFrames(int64_t t=-1, int imod = -1){return setTimer(FRAME_NUMBER,t,imod);}; - int64_t setNumberOfCycles(int64_t t=-1, int imod = -1){return setTimer(CYCLES_NUMBER,t,imod);}; - - - /** sets/gets the value of important readout speed parameters - \param sp is the parameter to be set/get - \param value is the value to be set, if -1 get value - \returns current value for the specified parameter - \sa speedVariable - */ - virtual int setSpeed(speedVariable sp, int value=-1)=0; - int setClockDivider(int s=-1){return setSpeed(CLOCK_DIVIDER,s);}; - - /** - set/get readout flags - \param flag readout flag to be set - \returns current flag - */ - virtual int setReadOutFlags(readOutFlags flag=GET_READOUT_FLAGS)=0; - void setParallelMode(int value){ \ - if(value>=0){ \ - switch(value){ \ - case 0: setReadOutFlags(NONPARALLEL);break; \ - case 1: setReadOutFlags(PARALLEL);break; \ - default: setReadOutFlags(SAFE);break; \ - } \ - } \ - }; - - void setOverflowMode(int value){ \ - if(value>=0){ \ - switch(value){ \ - case 1: setReadOutFlags(SHOW_OVERFLOW);break; \ - case 0: setReadOutFlags(NOOVERFLOW);break; \ - } \ - } \ - }; - - /** - get readout mode of detector (eiger specific) - \returns 0 for nonparallel, 1 for parallel, 2 for safe - */ - int getParallelMode(){ \ - int ret = setReadOutFlags(); \ - if (ret&NONPARALLEL) return 0; \ - if (ret&PARALLEL) return 1; \ - if (ret&SAFE) return 2; \ - return -1; \ - } - - - /** - get readout overflow mode of detector (eiger specific) - \returns 1 for show overflow, 0 for do not show overflow - */ - int getOverflowMode(){ \ - int ret = setReadOutFlags(); \ - if (ret&SHOW_OVERFLOW) return 1; \ - if (ret&NOOVERFLOW) return 0; \ - return -1; \ - } \ - - /** - set/ get high voltage - \param val high voltage (>0 sets, 0 unsets, -1 gets) - \returns high voltage - */ - int setHighVoltage(int val){return setDAC(val, HV_NEW, 0, -1);} \ - - /** - set dacs value - \param val value - \param index DAC index - \param mV 0 in dac units or 1 in mV - \param imod module number (if -1 alla modules) - \returns current DAC value - */ - virtual dacs_t setDAC(dacs_t val, dacIndex index , int mV, int imod=-1)=0; - int setDACValue(int val, int index , int imod=-1) { return (int)setDAC((dacs_t)val,(dacIndex)index,0,imod);}; - - - /** - gets ADC value - \param index ADC index - \param imod module number - \returns current ADC value - */ - virtual dacs_t getADC(dacIndex index, int imod=-1)=0; - int getADCValue(int index, int imod=-1){return (int)getADC((dacIndex)index, imod);}; - /////////////////////////////////////////////////////////////////////////////////////////// - /** - @short get run status - \returns status mask - */ - virtual runStatus getRunStatus()=0; - int getDetectorStatus() {return (int)getRunStatus();}; - - - /** @short sets the onlineFlag - \param online can be: -1 returns wether the detector is in online (1) or offline (0) state; 0 detector in offline state; 1 detector in online state - \returns 0 (offline) or 1 (online) - */ - virtual int setOnline(int const online=-1)=0; - - /** - * Activates/Deactivates the detector (Eiger only) - * @param enable active (1) or inactive (0), -1 gets - * @returns 0 (inactive) or 1 (active)for activate mode - */ - virtual int activate(int const enable=-1)=0; - - /** - * Set deactivated Receiver padding mode (Eiger only) - * @param padding padding option for deactivated receiver. Can be 1 (padding), 0 (no padding), -1 (gets) - * @returns 1 (padding), 0 (no padding), -1 (inconsistent values) for padding option - */ - virtual int setDeactivatedRxrPaddingMode(int padding=-1)=0; - - /** - @short set detector settings - \param isettings settings index (-1 gets) - \returns current settings - */ - virtual detectorSettings setSettings(detectorSettings isettings, int imod=-1)=0; - int setSettings(int isettings){return (int)setSettings((detectorSettings)isettings,-1);}; - - virtual detectorSettings getSettings(int imod=-1)=0; - /** - get threshold energy - \param imod module number (-1 all) - \returns current threshold value for imod in ev (-1 failed) - */ - virtual int getThresholdEnergy(int imod)=0; - int getThresholdEnergy(){return getThresholdEnergy(-1);}; - - /** - set/get the external communication mode - - obsolete \sa setExternalSignalFlags - \param pol value to be set \sa externalCommunicationMode - \returns current external communication mode - */ - virtual externalCommunicationMode setExternalCommunicationMode(externalCommunicationMode pol=GET_EXTERNAL_COMMUNICATION_MODE)=0; - int setTimingMode(int i=-1){return slsDetectorUsers::getTimingMode( externalCommunicationType( setExternalCommunicationMode(externalCommunicationType( slsDetectorUsers::getTimingMode(i) ) ) ) );}; - - virtual int setThresholdEnergy(int e_eV, int imod, detectorSettings isettings=GET_SETTINGS, int tb=1)=0; - int setThresholdEnergy(int e_eV){return setThresholdEnergy(e_eV,-1);}; - int setThresholdEnergy(int e_ev, int tb, int isettings, int id){return setThresholdEnergy(e_ev, id, (detectorSettings)isettings, tb);} - - - /** - Prints receiver configuration - \returns OK or FAIL - */ - virtual int printReceiverConfiguration()=0; - - /** - Reads the configuration file fname - \param fname file name - \returns OK or FAIL - */ - virtual int readConfigurationFile(std::string const fname)=0; - - virtual int dumpDetectorSetup(std::string const fname, int level)=0; - int dumpDetectorSetup(std::string const fname){return dumpDetectorSetup(fname,0);}; - virtual int retrieveDetectorSetup(std::string const fname, int level)=0; - int retrieveDetectorSetup(std::string const fname){return retrieveDetectorSetup(fname,0);}; - /** - @short - \returns the default output file index - */ - virtual int getFileIndex()=0; - - /** - @short sets the default output file index - \param i file index - \returns the default output file index - */ - virtual int setFileIndex(int i)=0; - - - //receiver - /** - calls setReceiverTCPSocket if online and sets the flag - */ - virtual int setReceiverOnline(int const online=GET_ONLINE_FLAG)=0; - - /** Starts the listening mode of receiver - \returns OK or FAIL - */ - virtual int startReceiver()=0; - - /** Stops the listening mode of receiver - \returns OK or FAIL - */ - virtual int stopReceiver()=0; - - /** gets the status of the listening mode of receiver - \returns status - */ - virtual runStatus getReceiverStatus()=0; - - /** gets the number of frames caught by receiver - \returns number of frames caught by receiver - */ - virtual int getFramesCaughtByReceiver()=0; - - /** gets the number of frames caught by any one receiver (to avoid using threadpool) - \returns number of frames caught by any one receiver (master receiver if exists) - */ - virtual int getFramesCaughtByAnyReceiver()=0; - - /** - \returns current frame index of receiver - */ - virtual int getReceiverCurrentFrameIndex()=0; - - /** Locks/Unlocks the connection to the receiver - /param lock sets (1), usets (0), gets (-1) the lock - /returns lock status of the receiver - */ - virtual int lockReceiver(int lock=-1)=0; - - - /** Reads frames from receiver through a constant socket - */ -virtual void readFrameFromReceiver()=0; - - -/** - * Enable data streaming to client - * @param enable 0 to disable, 1 to enable, -1 to get the value - * @returns data streaming to client enable - */ -virtual int enableDataStreamingToClient(int enable=-1)=0; - -/** Enable or disable streaming data from receiver to client - * @param enable 0 to disable 1 to enable -1 to only get the value - * @returns data streaming from receiver enable -*/ -virtual int enableDataStreamingFromReceiver(int enable=-1)=0; - - /** Sets the read receiver frequency - if data required from receiver randomly readRxrFrequency=0, - else every nth frame to be sent to gui - @param freq is the receiver read frequency - /returns read receiver frequency - */ - virtual int setReadReceiverFrequency(int freq=-1)=0; - - /** Sets the receiver to start any readout remaining in the fifo and - * change status to transmitting. - * The status changes to run_finished when fifo is empty - */ - virtual runStatus startReceiverReadout()=0; - - - /** returns detector type std::string from detector type index - \param t std::string can be Mythen, Pilatus, Eiger, Gotthard, Agipd, Unknown - \returns MYTHEN, PILATUS, EIGER, GOTTHARD, AGIPD, MÖNCH, GENERIC - */ - static std::string getDetectorType(detectorType t){\ - switch (t) {\ - case MYTHEN: return std::string("Mythen"); \ - case PILATUS: return std::string("Pilatus"); \ - case EIGER: return std::string("Eiger"); \ - case GOTTHARD: return std::string("Gotthard"); \ - case AGIPD: return std::string("Agipd"); \ - case MOENCH: return std::string("Moench"); \ - case JUNGFRAU: return std::string("Jungfrau"); \ - case JUNGFRAUCTB: return std::string("JungfrauCTB"); \ - case PROPIX: return std::string("Propix"); \ - default: return std::string("Unknown"); \ - }}; - - /** returns detector type index from detector type std::string - \param type can be MYTHEN, PILATUS, EIGER, GOTTHARD, AGIPD, GENERIC - \returns Mythen, Pilatus, Eiger, Gotthard, Agipd, Mönch, Unknown - */ - static detectorType getDetectorType(std::string const type){\ - if (type=="Mythen") return MYTHEN;\ - if (type=="Pilatus") return PILATUS; \ - if (type=="Eiger") return EIGER; \ - if (type=="Gotthard") return GOTTHARD; \ - if (type=="Agipd") return AGIPD; \ - if (type=="Moench") return MOENCH; \ - if (type=="Jungfrau") return JUNGFRAU; \ - if (type=="JungfrauCTB") return JUNGFRAUCTB; \ - if (type=="Propix") return PROPIX; \ - return GENERIC;}; - - - - /** returns synchronization type index from std::string - \param type can be none, gating, trigger, complementary - \returns ONE, MASTER_GATES, MASTER_TRIGGERS, SLAVE_STARTS_WHEN_MASTER_STOPS - */ - static synchronizationMode getSyncType(std::string const type){\ - if (type=="none") return NO_SYNCHRONIZATION;\ - if (type=="gating") return MASTER_GATES;\ - if (type=="trigger") return MASTER_TRIGGERS; \ - if (type=="complementary") return SLAVE_STARTS_WHEN_MASTER_STOPS; \ - return GET_SYNCHRONIZATION_MODE; \ - }; - - /** returns synchronization type std::string from index - \param s can be NONE, MASTER_GATES, MASTER_TRIGGERS, SLAVE_STARTS_WHEN_MASTER_STOPS - \returns none, gating, trigger, complementary, unknown - */ - static std::string getSyncType(synchronizationMode s ){\ - switch(s) { \ - case NO_SYNCHRONIZATION: return std::string("none"); \ - case MASTER_GATES: return std::string("gating"); \ - case MASTER_TRIGGERS: return std::string("trigger"); \ - case SLAVE_STARTS_WHEN_MASTER_STOPS: return std::string("complementary"); \ - default: return std::string("unknown"); \ - }}; - - - - /** returns std::string from external signal type index - \param f can be SIGNAL_OFF, GATE_IN_ACTIVE_HIGH, GATE_IN_ACTIVE_LOW, TRIGGER_IN_RISING_EDGE, TRIGGER_IN_FALLING_EDGE, RO_TRIGGER_IN_RISING_EDGE, RO_TRIGGER_IN_FALLING_EDGE, GATE_OUT_ACTIVE_HIGH, GATE_OUT_ACTIVE_LOW, =TRIGGER_OUT_RISING_EDGE, TRIGGER_OUT_FALLING_EDGE, RO_TRIGGER_OUT_RISING_EDGE, RO_TRIGGER_OUT_FALLING_EDGE, OUTPUT_LOW, OUTPUT_HIGH, MASTER_SLAVE_SYNCHRONIZATION, GET_EXTERNAL_SIGNAL_FLAG - \returns std::string off, gate_in_active_high, gate_in_active_low, trigger_in_rising_edge, trigger_in_falling_edge, ro_trigger_in_rising_edge, ro_trigger_in_falling_edge, gate_out_active_high, gate_out_active_low, trigger_out_rising_edge, trigger_out_falling_edge, ro_trigger_out_rising_edge, ro_trigger_out_falling_edge, gnd, vcc, sync, unknown - */ - static std::string externalSignalType(externalSignalFlag f){\ - switch(f) { \ - case SIGNAL_OFF: return std::string( "off"); \ - case GATE_IN_ACTIVE_HIGH: return std::string( "gate_in_active_high"); \ - case GATE_IN_ACTIVE_LOW: return std::string( "gate_in_active_low"); \ - case TRIGGER_IN_RISING_EDGE: return std::string( "trigger_in_rising_edge"); \ - case TRIGGER_IN_FALLING_EDGE: return std::string( "trigger_in_falling_edge"); \ - case RO_TRIGGER_IN_RISING_EDGE: return std::string( "ro_trigger_in_rising_edge"); \ - case RO_TRIGGER_IN_FALLING_EDGE: return std::string( "ro_trigger_in_falling_edge"); \ - case GATE_OUT_ACTIVE_HIGH: return std::string( "gate_out_active_high"); \ - case GATE_OUT_ACTIVE_LOW: return std::string( "gate_out_active_low"); \ - case TRIGGER_OUT_RISING_EDGE: return std::string( "trigger_out_rising_edge"); \ - case TRIGGER_OUT_FALLING_EDGE: return std::string( "trigger_out_falling_edge"); \ - case RO_TRIGGER_OUT_RISING_EDGE: return std::string( "ro_trigger_out_rising_edge"); \ - case RO_TRIGGER_OUT_FALLING_EDGE: return std::string( "ro_trigger_out_falling_edge"); \ - case MASTER_SLAVE_SYNCHRONIZATION: return std::string("sync"); \ - case OUTPUT_LOW: return std::string("gnd"); \ - case OUTPUT_HIGH: return std::string("vcc"); \ - default: return std::string( "unknown"); \ - } }; - - - - - /** returns external signal type index from std::string - \param sval off, gate_in_active_high, gate_in_active_low, trigger_in_rising_edge, trigger_in_falling_edge, ro_trigger_in_rising_edge, ro_trigger_in_falling_edge, gate_out_active_high, gate_out_active_low, trigger_out_rising_edge, trigger_out_falling_edge, ro_trigger_out_rising_edge, ro_trigger_out_falling_edge, gnd, vcc, sync, unknown - \returns can be SIGNAL_OFF, GATE_IN_ACTIVE_HIGH, GATE_IN_ACTIVE_LOW, TRIGGER_IN_RISING_EDGE, TRIGGER_IN_FALLING_EDGE, RO_TRIGGER_IN_RISING_EDGE, RO_TRIGGER_IN_FALLING_EDGE, GATE_OUT_ACTIVE_HIGH, GATE_OUT_ACTIVE_LOW, TRIGGER_OUT_RISING_EDGE, TRIGGER_OUT_FALLING_EDGE, RO_TRIGGER_OUT_RISING_EDGE, RO_TRIGGER_OUT_FALLING_EDGE, OUTPUT_LOW, OUTPUT_HIGH, MASTER_SLAVE_SYNCHRONIZATION, GET_EXTERNAL_SIGNAL_FLAG (if unknown) - */ - - static externalSignalFlag externalSignalType(std::string sval){\ - if (sval=="off") return SIGNAL_OFF;\ - if (sval=="gate_in_active_high") return GATE_IN_ACTIVE_HIGH; \ - if (sval=="gate_in_active_low") return GATE_IN_ACTIVE_LOW;\ - if (sval=="trigger_in_rising_edge") return TRIGGER_IN_RISING_EDGE;\ - if (sval=="trigger_in_falling_edge") return TRIGGER_IN_FALLING_EDGE;\ - if (sval=="ro_trigger_in_rising_edge") return RO_TRIGGER_IN_RISING_EDGE;\ - if (sval=="ro_trigger_in_falling_edge") return RO_TRIGGER_IN_FALLING_EDGE;\ - if (sval=="gate_out_active_high") return GATE_OUT_ACTIVE_HIGH;\ - if (sval=="gate_out_active_low") return GATE_OUT_ACTIVE_LOW;\ - if (sval=="trigger_out_rising_edge") return TRIGGER_OUT_RISING_EDGE;\ - if (sval=="trigger_out_falling_edge") return TRIGGER_OUT_FALLING_EDGE;\ - if (sval=="ro_trigger_out_rising_edge") return RO_TRIGGER_OUT_RISING_EDGE;\ - if (sval=="ro_trigger_out_falling_edge") return RO_TRIGGER_OUT_FALLING_EDGE;\ - if (sval=="sync") return MASTER_SLAVE_SYNCHRONIZATION;\ - if (sval=="gnd") return OUTPUT_LOW;\ - if (sval=="vcc") return OUTPUT_HIGH;\ - return GET_EXTERNAL_SIGNAL_FLAG ;}; - - /** returns detector settings std::string from index - \param s can be STANDARD, FAST, HIGHGAIN, DYNAMICGAIN, LOWGAIN, MEDIUMGAIN, VERYHIGHGAIN, LOWNOISE, - DYNAMICHG0, FIXGAIN1, FIXGAIN2, FORCESWITCHG1, FORCESWITCHG2, GET_SETTINGS - \returns standard, fast, highgain, dynamicgain, lowgain, mediumgain, veryhighgain, lownoise, - dynamichg0, fixgain1, fixgain2, forceswitchg1, forceswitchg2, verylowgain, undefined - */ - static std::string getDetectorSettings(detectorSettings s){\ - switch(s) { \ - case STANDARD: return std::string("standard"); \ - case FAST: return std::string("fast"); \ - case HIGHGAIN: return std::string("highgain"); \ - case DYNAMICGAIN: return std::string("dynamicgain"); \ - case LOWGAIN: return std::string("lowgain"); \ - case MEDIUMGAIN: return std::string("mediumgain"); \ - case VERYHIGHGAIN: return std::string("veryhighgain"); \ - case LOWNOISE: return std::string("lownoise"); \ - case DYNAMICHG0: return std::string("dynamichg0"); \ - case FIXGAIN1: return std::string("fixgain1"); \ - case FIXGAIN2: return std::string("fixgain2"); \ - case FORCESWITCHG1: return std::string("forceswitchg1");\ - case FORCESWITCHG2: return std::string("forceswitchg2");\ - case VERYLOWGAIN: return std::string("verylowgain");\ - default: return std::string("undefined"); \ - }}; - - /** returns detector settings std::string from index - \param s can be standard, fast, highgain, dynamicgain, lowgain, mediumgain, veryhighgain, lownoise, - dynamichg0, fixgain1, fixgain2, forceswitchg1, forceswitchg2, undefined - \returns setting index STANDARD, FAST, HIGHGAIN, DYNAMICGAIN, LOWGAIN, MEDIUMGAIN, VERYHIGHGAIN,LOWNOISE, - DYNAMICHG0, FIXGAIN1, FIXGAIN2, FORCESWITCHG1, FORCESWITCHG2, VERYLOWGAIN, GET_SETTINGS - */ - - static detectorSettings getDetectorSettings(std::string s){ \ - if (s=="standard") return STANDARD; \ - if (s=="fast") return FAST; \ - if (s=="highgain") return HIGHGAIN; \ - if (s=="dynamicgain") return DYNAMICGAIN; \ - if (s=="lowgain") return LOWGAIN; \ - if (s=="mediumgain") return MEDIUMGAIN; \ - if (s=="veryhighgain") return VERYHIGHGAIN; \ - if (s=="lownoise") return LOWNOISE; \ - if (s=="dynamichg0") return DYNAMICHG0; \ - if (s=="fixgain1") return FIXGAIN1; \ - if (s=="fixgain2") return FIXGAIN2; \ - if (s=="forceswitchg1") return FORCESWITCHG1; \ - if (s=="forceswitchg2") return FORCESWITCHG2; \ - if (s=="verylowgain") return VERYLOWGAIN; \ - return GET_SETTINGS; \ - }; - - - /** - returns external communication mode std::string from index - \param f can be AUTO_TIMING, TRIGGER_EXPOSURE, TRIGGER_READOUT, GATE_FIX_NUMBER, GATE_WITH_START_TRIGGER, BURST_TRIGGER, GET_EXTERNAL_COMMUNICATION_MODE - \returns auto, trigger, ro_trigger, gating, triggered_gating, unknown - */ - - static std::string externalCommunicationType(externalCommunicationMode f){ \ - switch(f) { \ - case AUTO_TIMING: return std::string( "auto"); \ - case TRIGGER_EXPOSURE: return std::string("trigger"); \ - case TRIGGER_READOUT: return std::string("ro_trigger"); \ - case GATE_FIX_NUMBER: return std::string("gating"); \ - case GATE_WITH_START_TRIGGER: return std::string("triggered_gating"); \ - case BURST_TRIGGER: return std::string("burst_trigger"); \ - default: return std::string( "unknown"); \ - } }; - - - - /** - returns external communication mode index from std::string - \param sval can be auto, trigger, ro_trigger, gating, triggered_gating - \returns AUTO_TIMING, TRIGGER_EXPOSURE, TRIGGER_READOUT, GATE_FIX_NUMBER, GATE_WITH_START_TRIGGER, BURST_TRIGGER, GET_EXTERNAL_COMMUNICATION_MODE - */ - - static externalCommunicationMode externalCommunicationType(std::string sval){\ - if (sval=="auto") return AUTO_TIMING;\ - if (sval=="trigger") return TRIGGER_EXPOSURE; \ - if (sval=="ro_trigger") return TRIGGER_READOUT;\ - if (sval=="gating") return GATE_FIX_NUMBER;\ - if (sval=="triggered_gating") return GATE_WITH_START_TRIGGER;\ - if (sval=="burst_trigger") return BURST_TRIGGER;\ - return GET_EXTERNAL_COMMUNICATION_MODE; \ - }; - - /** returns std::string from run status index - \param s can be ERROR, WAITING, RUNNING, TRANSMITTING, RUN_FINISHED - \returns std::string error, waiting, running, data, finished - */ - static std::string runStatusType(runStatus s){\ - switch (s) { \ - case ERROR: return std::string("error"); \ - case WAITING: return std::string("waiting"); \ - case RUNNING: return std::string("running");\ - case TRANSMITTING: return std::string("data"); \ - case RUN_FINISHED: return std::string("finished"); \ - case STOPPED: return std::string("stopped"); \ - default: return std::string("idle"); \ - }}; - - /** returns std::string from file format index - \param s can be RAW, HDF5 - \returns std::string raw, hdf5 - */ - static std::string fileFormats(fileFormat f){\ - switch (f) { \ - case BINARY: return std::string("binary"); \ - case ASCII: return std::string("ascii"); \ - case HDF5: return std::string("hdf5"); \ - default: return std::string("unknown"); \ - }}; - - /** returns std::string from timer index - \param s can be FRAME_NUMBER,ACQUISITION_TIME,FRAME_PERIOD, DELAY_AFTER_TRIGGER,GATES_NUMBER,PROBES_NUMBER, CYCLES_NUMBER, ACTUAL_TIME,MEASUREMENT_TIME, PROGRESS,MEASUREMENTS_NUMBER,FRAMES_FROM_START,FRAMES_FROM_START_PG,SAMPLES_JCTB,SUBFRAME_ACQUISITION_TIME,STORAGE_CELL_NUMBER, SUBFRAME_DEADTIME - \returns std::string frame_number,acquisition_time,frame_period, delay_after_trigger,gates_number,probes_number, cycles_number, actual_time,measurement_time, progress,measurements_number,frames_from_start,frames_from_start_pg,samples_jctb,subframe_acquisition_time,storage_cell_number, SUBFRAME_DEADTIME - */ - static std::string getTimerType(timerIndex t){ \ - switch (t) { \ - case FRAME_NUMBER: return std::string("frame_number"); \ - case ACQUISITION_TIME: return std::string("acquisition_time"); \ - case FRAME_PERIOD: return std::string("frame_period"); \ - case DELAY_AFTER_TRIGGER: return std::string("delay_after_trigger"); \ - case GATES_NUMBER: return std::string("gates_number"); \ - case PROBES_NUMBER: return std::string("probes_number"); \ - case CYCLES_NUMBER: return std::string("cycles_number"); \ - case ACTUAL_TIME: return std::string("actual_time"); \ - case MEASUREMENT_TIME: return std::string("measurement_time"); \ - case PROGRESS: return std::string("progress"); \ - case MEASUREMENTS_NUMBER: return std::string("measurements_number"); \ - case FRAMES_FROM_START: return std::string("frames_from_start"); \ - case FRAMES_FROM_START_PG: return std::string("frames_from_start_pg"); \ - case SAMPLES_JCTB: return std::string("samples_jctb"); \ - case SUBFRAME_ACQUISITION_TIME: return std::string("subframe_acquisition_time"); \ - case SUBFRAME_DEADTIME: return std::string("subframe_deadtime"); \ - case STORAGE_CELL_NUMBER: return std::string("storage_cell_number"); \ - default: return std::string("unknown"); \ - }}; - - - /** - @short returns adc index from std::string - \param s can be temp_fpga, temp_fpgaext, temp_10ge, temp_dcdc, temp_sodl, temp_sodr, temp_fpgafl, temp_fpgafr - \returns TEMPERATURE_FPGA, TEMPERATURE_FPGAEXT, TEMPERATURE_10GE, TEMPERATURE_DCDC, TEMPERATURE_SODL, - TEMPERATURE_SODR, TEMPERATURE_FPGA2, TEMPERATURE_FPGA3, -1 when unknown mode - */ - static int getADCIndex(std::string s){ \ - if (s=="temp_fpga") return TEMPERATURE_FPGA; \ - if (s=="temp_fpgaext") return TEMPERATURE_FPGAEXT; \ - if (s=="temp_10ge") return TEMPERATURE_10GE; \ - if (s=="temp_dcdc") return TEMPERATURE_DCDC; \ - if (s=="temp_sodl") return TEMPERATURE_SODL; \ - if (s=="temp_sodr") return TEMPERATURE_SODR; \ - if (s=="temp_fpgafl") return TEMPERATURE_FPGA2; \ - if (s=="temp_fpgafr") return TEMPERATURE_FPGA3; \ - return -1; \ - }; \ - - - /** - @short returns dac index from std::string - \param s can be vcmp_ll, vcmp_lr, vcmp_rl, vcmp_rr, vthreshold, vrf, vrs, vtr, vcall, vcp - \returns E_Vcmp_ll, E_Vcmp_lr, E_Vcmp_rl, E_Vcmp_rr, THRESHOLD, E_Vrf, E_Vrs, E_Vtr, E_cal, E_Vcp , -1 when unknown mode - */ - static int getDACIndex(std::string s){ \ - if (s=="vcmp_ll") return E_Vcmp_ll; \ - if (s=="vcmp_lr") return E_Vcmp_lr; \ - if (s=="vcmp_rl") return E_Vcmp_rl; \ - if (s=="vcmp_rr") return E_Vcmp_rr; \ - if (s=="vthreshold") return THRESHOLD; \ - if (s=="vrf") return E_Vrf; \ - if (s=="vrs") return E_Vrs; \ - if (s=="vtr") return E_Vtr; \ - if (s=="vcall") return E_cal; \ - if (s=="vcp") return E_Vcp; \ - return -1; \ - }; \ - - /** - @short returns receiver frame discard policy from std::string - \param s can be nodiscard, discardempty, discardpartial - \returns NO_DISCARD, DISCARD_EMPTY_FRAMES, DISCARD_PARTIAL_FRAMES, GET_FRAME_DISCARD_POLICY when unknown mode - */ - static frameDiscardPolicy getReceiverFrameDiscardPolicy(std::string s){ \ - if (s=="nodiscard") return NO_DISCARD; \ - if (s=="discardempty") return DISCARD_EMPTY_FRAMES; \ - if (s=="discardpartial") return DISCARD_PARTIAL_FRAMES; \ - return GET_FRAME_DISCARD_POLICY; \ - }; \ - - /** returns std::string from frame discard policy - \param f can be NO_DISCARD, DISCARD_EMPTY_FRAMES, DISCARD_PARTIAL_FRAMES - \returns std::string nodiscard, discardempty, discardpartial, unknown - */ - static std::string getReceiverFrameDiscardPolicy(frameDiscardPolicy f){ \ - switch (f) { \ - case NO_DISCARD: return std::string("nodiscard"); \ - case DISCARD_EMPTY_FRAMES: return std::string("discardempty"); \ - case DISCARD_PARTIAL_FRAMES: return std::string("discardpartial"); \ - default: return std::string("unknown"); \ - }}; \ - - -}; - - -#endif diff --git a/slsDetectorSoftware/slsDetector/slsDetectorCommand.cpp b/slsDetectorSoftware/slsDetector/slsDetectorCommand.cpp deleted file mode 100644 index 5f831190a..000000000 --- a/slsDetectorSoftware/slsDetector/slsDetectorCommand.cpp +++ /dev/null @@ -1,7155 +0,0 @@ -#include "slsDetectorCommand.h" - -#include -#include -#include -#include - -#include -using namespace std; - -/*! \mainpage Introduction - -This program is intended to control the SLS detectors via command line interface. -This is the only way to access all possible functionality of the detectors, however it is often recommendable to avoid changing the most advanced settings, rather leaving the task to configuration files, as when using the GUI or the API provided. - -The command line interface consists in four main functions: - -- \b sls_detector_acquire to acquire data from the detector -- \b sls_detector_put to set detector parameters -- \b sls_detector_get to retrieve detector parameters -- \b sls_detector_help to get help concerning the text commands -Additionally the program slsReceiver should be started on the machine expected to receive the data from the detector. - - -If you need control a single detector, the use of the command line interface does not need any additional arguments. - -For commands addressing a single controller of your detector, the command cmd should be called with the index i of the controller: - - -sls_detector_clnt i:cmd - - -where \b sls_detector_clnt is the text client (put, get, acquire, help). - -In case more than one detector is configured on the control PC, the command cmd should be called with their respective index j: - - -sls_detector_clnt j-cmd - - -where \b sls_detector_clnt is the text client (put, get, acquire, help). - -To address a specific controller i of detector j use: - -sls_detector_clnt j-i:cmd - - -To use different shared memory segements for different detectors on the same -client pc, one can use environment variable SLSDETNAME set to any string to -different strings to make the shared memory segments unique. One can then use -the same multi detector id for both detectors as they have a different shared memory names. - -For additional questions concerning the indexing of the detector, please refer to the SLS Detectors FAQ documentation. - -The commands are sudivided into different pages depending on their functionalities: - - \ref acquisition "Acquisition": commands to start/stop the acquisition and retrieve data - - \ref config "Configuration": commands to configure the detector - - \ref timing "Timing": commands to configure the detector timing - - \ref data "Data postprocessing": commands to process the data - mainly for MYTHEN except for rate corrections. - - \ref settings "Settings": commands to define detector settings/threshold. - - \ref output "Output": commands to define output file destination and format - - \ref actions "Actions": commands to define scripts to be executed during the acquisition flow - - \ref network "Network": commands to setup the network between client, detector and receiver - - \ref receiver "Receiver": commands to configure the receiver - - \ref ctb "Chiptest board": commands specific for the new chiptest board as pattern generator - - \ref test "Developer": commands to be used only for software debugging. Avoid using them! - - */ - -slsDetectorCommand::slsDetectorCommand(slsDetectorUtils *det) { - - myDet=det; - - int i=0; - - cmd=string("none"); - - /*! \page test Developer - Commands to be used only for software debugging. Avoid using them! - - \b test returns an error - */ - - descrToFuncMap[i].m_pFuncName="test"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdUnderDevelopment; - ++i; - - /*! \page test - - help Returns a list of possible commands. - */ - descrToFuncMap[i].m_pFuncName="help";//OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdHelp; - ++i; - - /*! \page test - - exitserver Shuts down all the detector servers. Don't use it!!!! - */ - descrToFuncMap[i].m_pFuncName="exitserver";//OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdExitServer; - ++i; - - /*! \page test - - exitreceiver Shuts down all the receivers. Don't use it!!!! - */ - descrToFuncMap[i].m_pFuncName="exitreceiver";//OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdExitServer; - ++i; - - /*! \page test - - flippeddatay [i] enables/disables data being flipped across y axis. 1 enables, 0 disables. Not implemented. - */ - descrToFuncMap[i].m_pFuncName="flippeddatay"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDetectorSize; - ++i; - - /* digital test and debugging */ - - /*! \page test - - digitest [i] will perform test which will plot the unique channel identifier, instead of data. Only get! - */ - descrToFuncMap[i].m_pFuncName="digitest"; // /* find command! */ - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDigiTest; - ++i; - - /*! \page test - - bustest performs test of the bus interface between FPGA and embedded Linux system. Can last up to a few minutes. Cannot set! Used for Mythen only. Only get! - */ - descrToFuncMap[i].m_pFuncName="bustest"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDigiTest; - ++i; - - /*! \page test - - digibittest:[i] performs digital test of the module i. Returns 0 if succeeded, otherwise error mask. Only put! - */ - descrToFuncMap[i].m_pFuncName="digibittest"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDigiTest; - ++i; - - /*! \page test - - reg [addr] [val] ??? writes to an register \c addr with \c value in hexadecimal format. - */ - descrToFuncMap[i].m_pFuncName="reg"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdRegister; - ++i; - - /*! \page test - - adcreg [addr] [val] ??? writes to an adc register \c addr with \c value in hexadecimal format. Only put! - */ - descrToFuncMap[i].m_pFuncName="adcreg"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdRegister; - ++i; - - /*! \page test - - setbit ??? Only put! - */ - descrToFuncMap[i].m_pFuncName="setbit"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdRegister; - ++i; - - /*! \page test - - clearbit ??? Only put! - */ - descrToFuncMap[i].m_pFuncName="clearbit"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdRegister; - ++i; - - /*! \page test - - getbit ??? Only get! - */ - descrToFuncMap[i].m_pFuncName="getbit"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdRegister; - ++i; - - /*! \page test - - r_compression [i] sets/gets compression in receiver. 1 sets, 0 unsets. Not implemented. - */ - descrToFuncMap[i].m_pFuncName="r_compression"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdReceiver; - ++i; - - - - /* Acquisition and status commands */ - /*! \page acquisition Acquition commands - Commands to control the acquisition - */ - /*! \page acquisition - - \b acquire blocking acquisition (like calling sls_detector_acquire). Starts receiver and detector, writes and processes the data, stops detector. Only get! - \c Returns (string)\c "acquire unsuccessful" if fails, else "" for MYTHEN, \c "Acquired (int)" for others, where int is number of frames caught. - */ - descrToFuncMap[i].m_pFuncName="acquire"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAcquire; - ++i; - - /*! \page acquisition - - busy i sets/gets acquiring flag. \c 1 the acquisition is active, \c 0 otherwise. Acquire command will set this flag to 1 at the beginning and to 0 at the end. Use this to clear flag if acquisition terminated unexpectedly. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="busy"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdStatus; - ++i; - - /*! \page acquisition - - status [s] starts or stops acquisition in detector in non blocking mode. When using stop acquisition and if acquisition is done, it will restream the stop packet from receiver (if data streaming in receiver is on). Eiger can also provide an internal software trigger. \c s: [\c start, \c stop, \c trigger(EIGER only)]. \c Returns the detector status: [\c running, \c error, \c transmitting, \c finished, \c waiting, \c idle]. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="status"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdStatus; - ++i; - - /*! \page acquisition - - \b data gets all data from the detector (if any) processes them and writes them to file according to the preferences already setup (MYTHEN only). Only get! - */ - descrToFuncMap[i].m_pFuncName="data"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdData; - ++i; - - /*! \page acquisition - - \b frame gets a single frame from the detector (if any) processes it and writes it to file according to the preferences already setup (MYTHEN only). Only get! - */ - descrToFuncMap[i].m_pFuncName="frame"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdFrame; - ++i; - - /*! \page acquisition - - readctr Reads the counters from the detector memory (analog detector returning values translated into number of photons - only GOTTHARD). Cannot put. - */ - descrToFuncMap[i].m_pFuncName="readctr"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdCounter; - ++i; - - /*! \page acquisition - - resetctr i Resets counter in detector, restarts acquisition if i=1(analog detector returning values translated into number of photons - only GOTTHARD). Cannot put. - */ - descrToFuncMap[i].m_pFuncName="resetctr"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdCounter; - ++i; - - /*! \page acquisition - - resmat i sets/resets counter bit in detector.gets the counter bit in detector ???? - */ - descrToFuncMap[i].m_pFuncName="resmat"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdCounter; - ++i; - - - - /*! \page config Configuration commands - Commands to configure the detector. these commands are often left to the configuration file. - - \ref configstructure "Data Structure": commands to configure detector data structure - - \ref configstatus "Status": commands to configure detector status - - \ref configsize "Data Size": commands to configure detector data size - - \ref configflags "Flags": commands to configure detector flags - - \ref configchip "Chip": commands to configure chip of the detector - - \ref configversions "Versions": commands to check version of each subsytem - - \ref configspeed "Speed": commands to configure speed of detector - - \ref configsettings "Detector Parameters": commands to configure/retrieve configuration of detector - */ - /*! \page timing Timing commands - Commands to setup the timing - */ - /* Detector structure configuration and debugging commands */ - /*! \page config - \section configstructure Data Structure - commands to configure detector data structure - */ - - /*! \page config - - \b free Free shared memory on the control PC - */ - descrToFuncMap[i].m_pFuncName="free";//OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdFree; - ++i; - - /*! \page config - - hostname \c put frees shared memory and sets the hostname (or IP adress). Only allowed at multi detector level. \c Returns the list of the hostnames of the multi-detector structure. \c (string) - */ - descrToFuncMap[i].m_pFuncName="hostname"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdHostname; - ++i; - - /*! \page config - - \b add appends a hostname (or IP address) at the end of the multi-detector structure. Only allowed at multi detector level. Cannot get. \c Returns the current list of detector hostnames. \c (string) - */ - descrToFuncMap[i].m_pFuncName="add";//OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdHostname; - ++i; - - /*! \page config - - replace \c Sets the hostname (or IP adress) for a single detector. Only allowed at single detector level. Cannot get. \c Returns the hostnames for that detector \c (string) - */ - descrToFuncMap[i].m_pFuncName="replace"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdHostname; - ++i; - - /*! \page config - - user \c Returns user details from shared memory. Only allowed at multi detector level. Cannot put. \c (string) - */ - descrToFuncMap[i].m_pFuncName="user"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdUser; - ++i; - - /*! \page config - - master i \c put sets the position of the master of the acquisition (-1 if none). Returns the position of the master of the detector structure (-1 if none). - */ - descrToFuncMap[i].m_pFuncName="master"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdMaster; - ++i; - - /*! \page config - - sync Sets/gets the synchronization mode of the detectors in the multi-detector structure. Can be: \c none, \c gating, \c trigger, \c complementary. Mainly used by MYTHEN/GOTTHARD. - */ - descrToFuncMap[i].m_pFuncName="sync"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSync; - ++i; - - /*! \page config - \section configstatus Status - commands to configure detector status - */ - - /*! \page config - - online [i] sets the detector in online (1) or offline (0) mode. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="online"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdOnline; - ++i; - - /*! \page config - - checkonline returns the hostnames of all detectors without connecting to them. \c Returns (string) "All online" or "[list of offline hostnames] : Not online". - */ - descrToFuncMap[i].m_pFuncName="checkonline"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdOnline; - ++i; - /*! \page config - - activate [b] [p] Activates/Deactivates the detector. \c b is 1 for activate, 0 for deactivate. Deactivated detector does not send data. \c p is optional and can be padding (default) or nonpadding for receivers for deactivated detectors. Used for EIGER only. \c Returns \c (int) (string) - */ - descrToFuncMap[i].m_pFuncName="activate"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdOnline; - ++i; - - - /* detector and data size */ - /*! \page config - \section configsize Data Size - commands to configure detector data size - */ - - /*! \page config - - nmod [i] sets/gets the number of modules of the detector. Used for MYTHEN only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="nmod"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDetectorSize; - ++i; - - /*! \page config - - maxmod Gets the maximum number of modules of the detector. Used for MYTHEN only. Cannot put! \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="maxmod"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDetectorSize; - ++i; - - /*! \page config - - dr [i] sets/gets the dynamic range of detector. Mythen [4,8,16,24]. Eiger [4,8,16,32]. Others cannot put! \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="dr"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDetectorSize; - ++i; - - /*! \page config - - roi [i] [xmin] [xmax] [ymin] [ymax] sets region of interest of the detector, where i is number of rois;i=0 to clear rois. Used for GOTTHARD only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="roi"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDetectorSize; - ++i; - - /*! \page config - - detsizechan [xmax] [ymax] sets the maximum number of channels in each dimension for complete detector set; -1 is no limit. Use for multi-detector system as first command in config file. \c Returns \c ("int int") - */ - descrToFuncMap[i].m_pFuncName="detsizechan"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDetectorSize; - ++i; - - /*! \page config - - roimask [i] ?? \c Returns \c (int) in hexadecimal - */ - descrToFuncMap[i].m_pFuncName="roimask"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDetectorSize; - ++i; - - /*! \page config - - flippeddatax [i] enables/disables data being flipped across x axis. 1 enables, 0 disables. Used for EIGER only. 1 for bottom half-module, 0 for top-half module. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="flippeddatax"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDetectorSize; - ++i; - - /*! \page config - - tengiga [i] enables/disables 10GbE in system (detector & receiver). 1 enabled 10GbE, 0 enables 1GbE. Used in EIGER only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="tengiga"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdReceiver; - ++i; - - /*! \page config - - gappixels [i] enables/disables gap pixels in system (detector & receiver). 1 sets, 0 unsets. Used in EIGER only and only in multi detector level command. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="gappixels"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDetectorSize; - ++i; - - - - /* flags */ - /*! \page config - \section configflags Flags - commands to configure detector flags - */ - - /*! \page config - - flags [flag] sets/gets the readout flags to mode. Options: none, storeinram, tot, continous, parallel, nonparallel, safe, digital, analog_digital, overflow, nooverflow, unknown. Used for MYTHEN and EIGER only. \c Returns \c (string). put takes one string and \c returns concatenation of all active flags separated by spaces. - */ - descrToFuncMap[i].m_pFuncName="flags"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAdvanced; - ++i; - - /*! \page config - - extsig:[i] [flag] sets/gets the mode of the external signal i. Options: \c off, \c gate_in_active_high, \c gate_in_active_low, \c trigger_in_rising_edge, \c trigger_in_falling_edge, - \c ro_trigger_in_rising_edge, \c ro_trigger_in_falling_edge, \c gate_out_active_high, \c gate_out_active_low, \c trigger_out_rising_edge, \c trigger_out_falling_edge, \c ro_trigger_out_rising_edge, - \c ro_trigger_out_falling_edge. \n Used in MYTHEN, GOTTHARD, PROPIX only. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="extsig"; /* find command! */ - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAdvanced; - ++i; - - - /* fpga */ - - - /*! \page config - - programfpga [file] programs the FPGA with file f (with .pof extension). Used for JUNGFRAU, MOENCH only. Only put! \c Returns \c ("successful", "unsuccessful") - */ - descrToFuncMap[i].m_pFuncName="programfpga"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAdvanced; - ++i; - - /*! \page config - - resetfpga [f] resets FPGA, where f can be any value. Used for JUNGFRAU only. Only put! \c Returns \c ("successful", "unsuccessful") - */ - descrToFuncMap[i].m_pFuncName="resetfpga"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAdvanced; - ++i; - - - /* chip */ - /*! \page config - \section configchip Chip - commands to configure chip of the detector - */ - - /*! \page config - - powerchip [i] Powers on/off the chip. 1 powers on, 0 powers off. Can also get the power status. Used for JUNGFRAU only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="powerchip"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAdvanced; - ++i; - - /*! \page config - - led [i] sets/gets the led status. 1 on, 0 off. Used for MOENCH only ?? \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="led"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAdvanced; - ++i; - - /*! \page config - - auto_comp_disable i Currently not implemented. this mode disables the on-chip gain switching comparator automatically after 93.75% of exposure time (only for longer than 100us). 1 enables mode, 0 disables mode. By default, mode is disabled (comparator is enabled throughout). (JUNGFRAU only). \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="auto_comp_disable"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAdvanced; - ++i; - - /*! \page config - - pulse [n] [x] [y] pulses pixel at coordinates (x,y) n number of times. Used in EIGER only. Only put! \c Returns \c ("successful", "unsuccessful") - */ - descrToFuncMap[i].m_pFuncName="pulse"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPulse; - ++i; - - /*! \page config - - pulsenmove [n] [x] [y] pulses pixel n number of times and moves relatively by x value (x axis) and y value(y axis). Used in EIGER only. Only put! \c Returns \c ("successful", "unsuccessful") - */ - descrToFuncMap[i].m_pFuncName="pulsenmove"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPulse; - ++i; - - /*! \page config - - pulsechip [n]pulses chip n number of times, while n=-1 will reset it to normal mode. Used in EIGER only. Only put! \c Returns \c ("successful", "unsuccessful") - */ - descrToFuncMap[i].m_pFuncName="pulsechip"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPulse; - ++i; - - - - - /* versions/ serial numbers getId */ - /*! \page config - \section configversions Versions - Commands to check versions of each subsystem - */ - - /*! \page config - - checkdetversion Checks the version compatibility with detector server (if hostname is in shared memory). Only get! Only for Eiger, Jungfrau & Gotthard. \c Returns \c ("compatible", "incompatible") - */ - descrToFuncMap[i].m_pFuncName="checkdetversion"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSN; - ++i; - - - /*! \page config - - checkrecversion Checks the version compatibility with receiver server (if rx_hostname is in shared memory). Only get! Only for Eiger, Jungfrau & Gotthard. \c Returns \c ("compatible", "incompatible") - */ - descrToFuncMap[i].m_pFuncName="checkrecversion"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSN; - ++i; - - - /*! \page config - - moduleversion:[i] Gets the firmware version of module i. Used for MYTHEN only. Only get! \c Returns \c (long int) in hexadecimal or "undefined module number" - */ - descrToFuncMap[i].m_pFuncName="moduleversion"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSN; - ++i; - - /*! \page config - - detectornumber Gets the serial number or MAC of detector. Only get! \c Returns \c (long int) in hexadecimal - */ - descrToFuncMap[i].m_pFuncName="detectornumber"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSN; - ++i; - - /*! \page config - - modulenumber:[i] Gets the serial number of module i. Used for MYTHEN only. Only get! \c Returns \c (long int) in hexadecimal or "undefined module number" - */ - descrToFuncMap[i].m_pFuncName="modulenumber"; /* find command! */ - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSN; - ++i; - - /*! \page config - - detectorversion Gets the firmware version of detector. Only get! \c Returns \c (long int) in hexadecimal - */ - descrToFuncMap[i].m_pFuncName="detectorversion"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSN; - ++i; - - /*! \page config - - softwareversion Gets the software version of detector server. Only get! \c Returns \c (long int) in hexadecimal - */ - descrToFuncMap[i].m_pFuncName="softwareversion"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSN; - ++i; - - /*! \page config - - thisversion Gets the software version of this client software. Only get! \c Returns \c (long int) in hexadecimal - */ - descrToFuncMap[i].m_pFuncName="thisversion"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSN; - ++i; - - /*! \page config - - receiverversion Gets the software version of receiver. Only get! \c Returns \c (long int) in hexadecimal - */ - descrToFuncMap[i].m_pFuncName="receiverversion"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSN; - ++i; - - /* r/w timers */ - - - /*! \page timing - - timing [mode] sets/gets synchronization mode of the detector. Mode: auto, trigger, ro_trigger, gating, triggered_gating (string) - */ - descrToFuncMap[i].m_pFuncName="timing"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTiming; - ++i; - - - /*! \page timing - - exptime [i] sets/gets exposure time in s. \c Returns \c (double with 9 decimal digits) - */ - descrToFuncMap[i].m_pFuncName="exptime"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimer; - ++i; - - /*! \page timing - - subexptime [i] sets/gets sub exposure time in s. Used in EIGER only in 32 bit mode. \c Returns \c (double with 9 decimal digits) - */ - descrToFuncMap[i].m_pFuncName="subexptime"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimer; - ++i; - - /*! \page timing - - period [i] sets/gets frame period in s. \c Returns \c (double with 9 decimal digits) - */ - descrToFuncMap[i].m_pFuncName="period"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimer; - ++i; - - /*! \page timing - - subdeadtime [i] sets/gets sub frame dead time in s. Subperiod is set in the detector = subexptime + subdeadtime. This value is normally a constant in the config file. Used in EIGER only in 32 bit mode. \c Returns \c (double with 9 decimal digits) - */ - descrToFuncMap[i].m_pFuncName="subdeadtime"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimer; - ++i; - - /*! \page timing - - delay [i] sets/gets delay in s. Used in MYTHEN, GOTTHARD only. \c Returns \c (double with 9 decimal digits) - */ - descrToFuncMap[i].m_pFuncName="delay"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimer; - ++i; - - /*! \page timing - - gates [i] sets/gets number of gates. Used in MYTHEN, GOTTHARD only. \c Returns \c (long long int) - */ - descrToFuncMap[i].m_pFuncName="gates"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimer; - ++i; - - /*! \page timing - - frames [i] sets/gets number of frames. If \c timing is not \c auto, then it is the number of frames per cycle/trigger. \c Returns \c (long long int) - */ - descrToFuncMap[i].m_pFuncName="frames"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimer; - ++i; - - /*! \page timing - - cycles [i] sets/gets number of triggers. Timing mode should be set appropriately. \c Returns \c (long long int) - */ - descrToFuncMap[i].m_pFuncName="cycles"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimer; - ++i; - - /*! \page timing - - probes [i] sets/gets number of probes to accumulate. When setting, max 3! cycles should be set to 1, frames to the number of pump-probe events. Used in MYTHEN only. \c Returns \c (long long int) - */ - descrToFuncMap[i].m_pFuncName="probes"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimer; - ++i; - - /*! \page timing - - measurements [i] sets/gets number of measurements. \c Returns \c (long long int) - */ - descrToFuncMap[i].m_pFuncName="measurements"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimer; - ++i; - - /*! \page timing - - samples [i] sets/gets number of samples expected from the jctb. Used in CHIP TEST BOARD only. \c Returns \c (long long int) - */ - descrToFuncMap[i].m_pFuncName="samples"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimer; - ++i; - - /*! \page timing - - storagecells [i] sets/gets number of additional storage cells per acquisition. For very advanced users only! For JUNGFRAU only. Range: 0-15. The #images = #frames * #cycles * (#storagecells +1). \c Returns \c (long long int) - */ - descrToFuncMap[i].m_pFuncName="storagecells"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimer; - ++i; - - /*! \page timing - - storagecell_start [i] sets/gets the storage cell that stores the first acquisition of the series. Default is 15(0xf).. For very advanced users only! For JUNGFRAU only. Range: 0-15. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="storagecell_start"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimer; - ++i; - - /* read only timers */ - - /*! \page timing - - exptimel gets exposure time left. Used in MYTHEN, GOTTHARD only. Only get! \c Returns \c (double with 9 decimal digits) - */ - descrToFuncMap[i].m_pFuncName="exptimel"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimeLeft; - ++i; - - /*! \page timing - - periodl gets frame period left. Used in MYTHEN, GOTTHARD only. Only get! \c Returns \c (double with 9 decimal digits) - */ - descrToFuncMap[i].m_pFuncName="periodl"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimeLeft; - ++i; - - /*! \page timing - - delayl gets delay left. Used in MYTHEN, GOTTHARD only. Only get! \c Returns \c (double with 9 decimal digits) - */ - descrToFuncMap[i].m_pFuncName="delayl"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimeLeft; - ++i; - - /*! \page timing - - gatesl gets number of gates left. Used in MYTHEN, GOTTHARD only. Only get! \c Returns \c (double with 9 decimal digits) - */ - descrToFuncMap[i].m_pFuncName="gatesl"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimeLeft; - ++i; - - /*! \page config - - framesl gets number of frames left. Used in MYTHEN, GOTTHARD only. Only get! \c Returns \c (double with 9 decimal digits) - */ - descrToFuncMap[i].m_pFuncName="framesl"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimeLeft; - ++i; - - /*! \page timing - - cyclesl gets number of cylces left. Used in MYTHEN, GOTTHARD only. Only get! \c Returns \c (double with 9 decimal digits) - */ - descrToFuncMap[i].m_pFuncName="cyclesl"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimeLeft; - ++i; - - /*! \page timing - - probesl gets number of probes left. Used in MYTHEN, GOTTHARD only. Only get! \c Returns \c (double with 9 decimal digits) - */ - descrToFuncMap[i].m_pFuncName="probesl"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimeLeft; - ++i; - - // descrToFuncMap[i].m_pFuncName="progress"; - // descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimer; - // ++i; - - /*! \page timing - - now Actual time of the detector. Only get! - */ - descrToFuncMap[i].m_pFuncName="now"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimeLeft; - ++i; - - /*! \page timing - - timestamp Last frame timestamp for MYTHEN. Only get! - */ - descrToFuncMap[i].m_pFuncName="timestamp"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimeLeft; - ++i; - - /*! \page timing - - nframes ??? Only get! - */ - descrToFuncMap[i].m_pFuncName="nframes"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimeLeft; - ++i; - - /*! \page timing - - measuredperiod gets the measured frame period (time between last frame and the previous one) in s. For Eiger only. Makes sense only for acquisitions of more than 1 frame. \c Returns \c (double with 9 decimal digits) - */ - descrToFuncMap[i].m_pFuncName="measuredperiod"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimeLeft; - ++i; - - /*! \page timing - - measuredsubperiod gets the measured subframe period (time between last subframe and the previous one) in s. For Eiger only and in 32 bit mode. \c Returns \c (double with 9 decimal digits) - */ - descrToFuncMap[i].m_pFuncName="measuredsubperiod"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTimeLeft; - ++i; - - /* speed */ - /*! \page config - \section configspeed Speed - commands to configure speed of detector - */ - - /*! \page config - - clkdivider [i] sets/gets the readout clock divider. EIGER, JUNGFRAU [0(fast speed), 1(half speed), 2(quarter speed)]. Jungfrau, full speed is not implemented and overwrites adcphase to recommended default. MYTHEN[???]. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="clkdivider"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSpeed; - ++i; - - /*! \page config - - setlength [i] sets/gets length of set/reset signals (in clock cycles). Used in MYTHEN only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="setlength"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSpeed; - ++i; - - /*! \page config - - waitstates [i] sets/gets waitstates of the bus interface (in clock cycles). Used in MYTHEN only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="waitstates"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSpeed; - ++i; - - /*! \page config - - totdivider [i] sets/gets clock divider in tot mode. Used in MYTHEN only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="totdivider"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSpeed; - ++i; - - /*! \page config - - totdutycycle [i] sets/gets duty cycle of the tot clock. Used in MYTHEN only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="totdutycycle"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSpeed; - ++i; - - /*! \page config - - phasestep [i] Only put for gotthard. Moves the phase of the ADC clock.\c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="phasestep"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSpeed; - ++i; - - /*! \page config - - oversampling [i] Sets/gets the number of adcsamples per clock. For the new chiptestboard.\c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="oversampling"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSpeed; - ++i; - - /*! \page config - - adcclk [i] sets/gets the ADC clock frequency in MHz. For the new chiptestboard!\c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="adcclk"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSpeed; - ++i; - - /*! \page config - - adcphase [i] Sets/gets phase of the sampling clock. For JUNGFRAU, setting speed (clkdivider) overwrites adcphase to its default recommended value. (Not for EIGER) \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="adcphase"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSpeed; - ++i; - - /*! \page config - - adcpipeline [i] Sets/gets the pipeline of the ADC. For the new chiptestbaord!\c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="adcpipeline"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSpeed; - ++i; - - /*! \page config - - dbitclk [i] Sets/gets the clock frequency of the latching of the digital bits in MHz. For the new chiptestboard!\c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="dbitclk"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSpeed; - ++i; - - /*! \page config - - dbitphase [i] Sets/gets the phase of the clock for latching of the digital bits. For the new chiptestboard!?\c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="dbitphase"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSpeed; - ++i; - - /*! \page config - - dbitpipeline [i] Sets/gets the pipeline of the latching of the digital bits. For the new chiptestbaord!\c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="dbitpipeline"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSpeed; - ++i; - - - /* settings dump/retrieve */ - /*! \page config - \section configsettings Detector Parameters - commands to configure/retrieve configuration of detector - */ - - /*! \page config - - config [fname] sets/saves detector/receiver to configuration contained in fname. Same as executing sls_detector_put for every line. Normally a one time operation. \c Returns \c (string) fname - */ - descrToFuncMap[i].m_pFuncName="config"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdConfiguration; - ++i; - - /* settings dump/retrieve */ - /*! \page config - - rx_printconfig prints the receiver configuration. Only get! \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="rx_printconfig"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdConfiguration; - ++i; - - /*! \page config - - parameters [fname] sets/saves detector parameters contained in fname. Normally once per different measurement. \c Returns \c (string) fname - */ - descrToFuncMap[i].m_pFuncName="parameters"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdConfiguration; - ++i; - - /*! \page config - - setup [fname] sets/saves detector complete setup contained in fname (extensions automatically generated), including trimfiles, ff coefficients etc. \c Returns \c (string) fname - */ - descrToFuncMap[i].m_pFuncName="setup"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdConfiguration; - ++i; - - - - - /* data processing commands */ - - /*! \page data Data processing commands - Commands to setup the data processing (mainly MYTHEN related) - */ - /*! \page data - - flatfield [fn] \c put sets flatfield file to \c fn (relative to \c ffdir). \get returns the flatfield file name relative to \c ffdir (string). If \fn is specified, it writes the flat field correction factors and errors to \c fn. \c Returns \c (string) fn - \c none disables flat field corrections. - */ - descrToFuncMap[i].m_pFuncName="flatfield"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdFlatField; - ++i; - - /*! \page data - - ffdir [d] Sets/gets the directory in which the flat field file is located. \c Returns \c (string) ffdir - */ - descrToFuncMap[i].m_pFuncName="ffdir"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdFlatField; - ++i; - - /*! \page data - - ratecorr [ns] Returns the dead time used for rate correections in ns (int). \c put sets the deadtime correction constant in ns, -1 will set it to default tau of settings (0 unset). \c Returns \c (double with 9 decimal digit precision) - */ - descrToFuncMap[i].m_pFuncName="ratecorr"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdRateCorr; - ++i; - - /*! \page data - - badchannels [fn] \c put sets the badchannels file to \c fn . \get returns the bad channels file name. If \fn is specified, it writes the badchannels to \c fn. \c none disables badchannel corrections. - */ - descrToFuncMap[i].m_pFuncName="badchannels"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdBadChannels; - ++i; - - /*! \page data - - angconv [fn] \c put sets the angular conversion file to \c fn . \get returns the angular conversion file name. If \fn is specified, it writes the angular conversion factors to \c fn. \c none disables angular corrections. - */ - descrToFuncMap[i].m_pFuncName="angconv"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAngConv; - ++i; - - /*! \page data - - globaloff [f] Sets/gets the beamline angular global offset (float). - */ - descrToFuncMap[i].m_pFuncName="globaloff"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAngConv; - ++i; - - /*! \page data - - fineoff [f] Sets/gets the angular fine offset of the measurement (float). - */ - //2017/08/15 - descrToFuncMap[i].m_pFuncName="fineoff"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAngConv; - ++i; - - /*! \page data - - binsize [f] Sets/gets the bin size used for the angular conversion (float). - */ - descrToFuncMap[i].m_pFuncName="binsize" ;// - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAngConv; - ++i; - - /*! \page data - - angdir [i] Sets/gets the angular direction. 1 means increasing channels number as increasing angle, -1 increasing channel number decreasing angle. - */ - descrToFuncMap[i].m_pFuncName="angdir" ;// - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAngConv; - ++i; - - /*! \page data - - moveflag [i] Sets/gets the flag for physically moving the detector during the acquisition of several positions. 1 sets (moves), 0 unsets. - */ - descrToFuncMap[i].m_pFuncName="moveflag" ;// - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAngConv; - ++i; - - /*! \page data - - samplex [f] Sets/gets the sample displacement in th direction parallel to the beam in um. Unused! - */ - descrToFuncMap[i].m_pFuncName="samplex" ;// - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAngConv; - ++i; - - /*! \page data - - sampley [f] Sets/gets the sample displacement in th direction orthogonal to the beam in um. Unused! - */ - descrToFuncMap[i].m_pFuncName="sampley" ;// - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdAngConv; - ++i; - - /*! \page data - - threaded [i] Sets/gets the data processing threaded flag. 1 is threaded, 0 unthreaded. - */ - descrToFuncMap[i].m_pFuncName="threaded"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdThreaded; - ++i; - - /*! \page data - - darkimage fn Loads the dark image to the detector from file fn (pedestal image). Cannot get. - */ - descrToFuncMap[i].m_pFuncName="darkimage"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdImage; - ++i; - - /*! \page data - - gainimage fn Loads the gain image to the detector from file fn (gain map for translation into number of photons of an analog detector). Cannot get. - */ - descrToFuncMap[i].m_pFuncName="gainimage"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdImage; - ++i; - - /*! \page data - - gainimage fn Loads the gain image to the detector from file fn (gain map for translation into number of photons of an analog detector). Cannot get. - */ - descrToFuncMap[i].m_pFuncName="flatimage"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdImage; - ++i; - - - - - /*! \page settings Detector settings commands - Commands to setup the settings of the detector - - \ref settingsdir "Settings, trim & cal Directories": commands to setup settings/trim/cal directories - - \ref settingssett "Settings and Threshold": commands to configure settings and threshold of detector - - \ref settingsdacs "DACs": commands to configure DACs of detector - - \ref settingsadcs "ADCs": commands to readout ADCs of detector - - \ref settingstmp "Temp Control": commands to monitor and handle temperature overshoot (only JUNGFRAU) - */ - - /* trim/cal directories */ - /*! \page settings - \section settingsdir Settings, trim & cal Directories - commands to setup settings/trim/cal directories - */ - /*! \page settings - - settingsdir [dir] Sets/gets the directory where the settings files are located. \c Returns \c (string) dir - */ - descrToFuncMap[i].m_pFuncName="settingsdir"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSettingsDir; - ++i; - /*! \page settings - - trimdir [dir] obsolete \c settingsdir. \c Returns \c (string) dir - */ - descrToFuncMap[i].m_pFuncName="trimdir"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSettingsDir; - ++i; - - /*! \page settings - - caldir [dir] Sets/gets the directory where the calibration files are located. \c Returns \c (string) dir - */ - descrToFuncMap[i].m_pFuncName="caldir"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdCalDir; - ++i; - - /*! \page settings - - trimen [n e0 e1...e(n-1)] Sets/gets the number of energies n at which the detector has default trim file and their values in eV (int). \c Returns \c (int int...) n e0 e1...e(n-1) - */ - descrToFuncMap[i].m_pFuncName="trimen"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTrimEn; - ++i; - - /* settings, threshold */ - /*! \page settings - \section settingssett Settings and Threshold - commands to configure settings and threshold of detector - */ - - /*! \page settings - - settings [s] sets/gets the settings of the detector. Options: \c standard, \c fast, \c highgain, \c dynamicgain, \c lowgain, \c mediumgain, \c veryhighgain, - \c lownoise, \c dynamichg0, \c fixgain1, \c fixgain2, \c forceswitchg1, \c forceswitchg2. - \n In Eiger, only sets in client shared memory. Use \c threshold or \c thresholdnotb to pass to detector. Gets from detector. \c Returns \c (string) s - */ - descrToFuncMap[i].m_pFuncName="settings"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSettings; - ++i; - - /*! \page settings - - threshold [eV] [sett] sets/gets the detector threshold in eV. sett is optional and if provided also sets the settings. Use this for Eiger instead of \c settings. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="threshold"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSettings; - ++i; - - /*! \page settings - - thresholdnotb [eV] [sett] sets/gets the detector threshold in eV without loading trimbits. sett is optional and if provided also sets the settings. Use this for Eiger instead of \c settings. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="thresholdnotb"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSettings; - ++i; - - /*! \page settings - - trimbits [fname] loads/stores the trimbits to/from the detector. If no extension is specified, the serial number of each module will be attached. \c Returns \c (string) fname - */ - descrToFuncMap[i].m_pFuncName="trimbits"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSettings; - ++i; - - /*! \page settings - - trim:[mode] [fname] trims the detector according to mode and saves resulting trimbits to file. Mode: noise, beam, improve, fix. Used in MYTHEN only. Only put! \c Returns \c ("done") - */ - descrToFuncMap[i].m_pFuncName="trim"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSettings; - ++i; - - /*! \page settings - - trimval [i] sets all trimbits to i. Used in EIGER only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="trimval"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSettings; - ++i; - - /*! \page settings - - pedestal [i] starts acquisition for i frames, calculates pedestal and writes back to fpga. Used in GOTTHARD only. Only put! \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="pedestal"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdSettings; - ++i; - - - - /* pots */ - /*! \page settings - \section settingsdacs DACs - commands to configure DACs of detector - */ - /*! \page settings - - emin [i] Sets/gets detector minimum energy threshold for the CTB (soft setting) - */ - descrToFuncMap[i].m_pFuncName="emin"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - emax [i] Sets/gets detector maximum energy threshold for the CTB (soft setting) - */ - descrToFuncMap[i].m_pFuncName="emax"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - /*! \page settings - - vthreshold [i] [mv] Sets/gets detector threshold voltage for single photon counters. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vthreshold"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vcalibration [i] [mv] Sets/gets the voltage of the calibration pulses. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vcalibration"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vtrimbit [i] [mv] Sets/gets the voltage to set the width of the trimbits. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vtrimbit"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vpreamp [i] [mv] Sets/gets the voltage to define the preamplifier feedback resistance. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vpreamp"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vhaper1 [i] [mv] Sets/gets the voltage to define the feedback resistance of the first shaper. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vshaper1"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vshaper2 [i] [mv] Sets/gets the voltage to define the feedback resistance of the second shaper. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vshaper2"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vhighvoltage [i] Sets/gets the high voltage to the sensor in V. \c Returns \c (int ["mV"]). - */ - descrToFuncMap[i].m_pFuncName="vhighvoltage"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vapower [i] Sets/gets the analog power supply for the old chiptest board in DAC units. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vapower"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vddpower [i] Sets/gets the digital power supply for the old chiptest board in DAC units. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vddpower"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vshpower [i] Sets/gets the comparator power supply for the old chiptest board in DAC units. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vshpower"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - viopower [i] Sets/gets the power supply of the FPGA I/Os for the old chiptest board in DAC units. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="viopower"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vrefds [i] [mv] Sets/gets vrefds. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vref_ds"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vcascn_pb [i] [mv] Sets/gets vcascn_pb. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vcascn_pb"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vcasc_pb [i] [mv] Sets/gets vcasc_pb. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vcascp_pb"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vout_cm [i] [mv] Sets/gets vout_cm. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vout_cm"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vcasc_out [i] [mv] Sets/gets vcasc_out. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vcasc_out"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vin_com [i] [mv] Sets/gets vin_com. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vin_cm"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vref_comp [i] [mv] Sets/gets vref_comp. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vref_comp"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - ib_test_c [i] [mv] Sets/gets ib_test_c. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="ib_test_c"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - dac[0..7] [i] [mv] Sets/gets dac[0..7] for MOENCH02. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="dac0"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="dac1"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="dac2"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="dac3"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="dac4"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="dac5"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="dac6"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="dac7"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vsvp [i] [mv] Sets/gets vsvp. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vsvp"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vsvn [i] [mv] Sets/gets vsvn. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vsvn"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vtr [i] [mv] Sets/gets vtr. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vtr"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vrf [i] [mv] Sets/gets vrf. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vrf"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vrs [i] [mv] Sets/gets vrs. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vrs"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vtgstv [i] [mv] Sets/gets vtgstv. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vtgstv"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vcmp_ll [i] [mv] Sets/gets vcmp_ll. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vcmp_ll"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vcmp_lr [i] [mv] Sets/gets vcmp_lr. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vcmp_lr"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vcal_l [i] [mv] Sets/gets vcal_l. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vcall"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vcomp_rl [i] [mv] Sets/gets vcomp_rl. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vcmp_rl"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vcomp_rr [i] [mv] Sets/gets vcomp_rr. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vcmp_rr"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - rxb_rb [i] [mv] Sets/gets rxb_rb. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="rxb_rb"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - rxb_lb [i] [mv] Sets/gets rxb_lb. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="rxb_lb"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vcp [i] [mv] Sets/gets vcp. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vcp"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vcn [i] [mv] Sets/gets vcn. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vcn"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - vis [i] [mv] Sets/gets vis. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="vis"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - iodelay [i] [mv] Sets/gets iodelay. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="iodelay"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - - /*! \page settings - - dac:j [i] [mv] Sets/gets value for DAC number j for the new chiptestboard. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="dac"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - - - /*! \page settings - - adcvpp [i] Sets/gets the Vpp of the ADC 0 -> 1V ; 1 -> 1.14V ; 2 -> 1.33V ; 3 -> 1.6V ; 4 -> 2V . \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="adcvpp"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - - /*! \page settings - - v_a [i] mv Sets/gets value for Va on the new chiptest board. Must be in mV. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="v_a"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - v_b [i] mv Sets/gets value for Vb on the new chiptest board. Must be in mV. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="v_b"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - v_c [i] mv Sets/gets value for Vc on the new chiptest board. Must be in mV. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="v_c"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - v_d [i] mv Sets/gets value for Vd on the new chiptest board. Must be in mV. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="v_d"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - v_io [i] mv Sets/gets value for Vio on the new chiptest board. Must be in mV. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="v_io"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - - /*! \page settings - - v_chip [i] mv Sets/gets value for Vchip on the new chiptest board. Must be in mV. \c Returns \c (int ["mV"]). Normally don't use it! - */ - descrToFuncMap[i].m_pFuncName="v_chip"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - v_limit [i] mv Sets/gets a soft limit for the power supplies and the DACs on the new chiptest board. Must be in mV. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="v_limit"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - - - /* MYTHEN 3.01 - all values are in DACu */ - - - descrToFuncMap[i].m_pFuncName="vIpre"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="VcdSh"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - Vth1 Sets/gets first detector threshold voltage for Mythen 3.01. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="Vth1"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - Vth1 Sets/gets second detector threshold voltage for Mythen 3.01. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="Vth2"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - /*! \page settings - - Vth1 Sets/gets third detector threshold voltage for Mythen 3.01. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) - */ - descrToFuncMap[i].m_pFuncName="Vth3"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="VPL"; // baseline for analog pulsing - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="Vtrim"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="vIbias"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="vIinSh"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="cas"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="casSh"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="vIbiasSh"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="vIcin"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - descrToFuncMap[i].m_pFuncName="vIpreOut"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDAC; - ++i; - - - /* r/w timers */ - /*! \page settings - \section settingsadcs ADCs - commands to readout ADCs of detector - */ - - /*! \page settings - - temp_adc Gets the ADC temperature. \c Returns \c EIGER,JUNGFRAU(double"°C") Others \c (int"°C") - */ - descrToFuncMap[i].m_pFuncName="temp_adc"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - temp_fpga Gets the FPGA temperature. \c Returns \c EIGER,JUNGFRAU(double"°C") Others \c (int"°C") - */ - descrToFuncMap[i].m_pFuncName="temp_fpga"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - temp_fpgaext Gets the external FPGA temperature. Used in EIGER only. \c Returns \c EIGER(double"°C") - */ - descrToFuncMap[i].m_pFuncName="temp_fpgaext"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - temp_10ge Gets the 10Gbe temperature. Used in EIGER only. \c Returns \c EIGER(double"°C") - */ - descrToFuncMap[i].m_pFuncName="temp_10ge"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - temp_dcdc Gets the temperature of the DC/DC converter. Used in EIGER only. \c Returns \c EIGER(double"°C") - */ - descrToFuncMap[i].m_pFuncName="temp_dcdc"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - temp_sodl Gets the temperature of the left so-dimm memory . Used in EIGER only. \c Returns \c EIGER(double"°C") - */ - descrToFuncMap[i].m_pFuncName="temp_sodl"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - temp_sodr Gets the temperature of the right so-dimm memory. Used in EIGER only. \c Returns \c EIGER(double"°C") - */ - descrToFuncMap[i].m_pFuncName="temp_sodr"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - - /*! \page settings - - adc:j Gets the values of the slow ADC number j for the new chiptest board. \c Returns \c (int"°C") - */ - descrToFuncMap[i].m_pFuncName="adc"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - temp_fpgal Gets the temperature of the left frontend FPGA. Used in EIGER only. \c Returns \c EIGER(double"°C") - */ - descrToFuncMap[i].m_pFuncName="temp_fpgafl"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - temp_fpgar Gets the temperature of the right frontend FPGA. Used in EIGER only. \c Returns \c EIGER(double"°C") - */ - descrToFuncMap[i].m_pFuncName="temp_fpgafr"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - - /*! \page settings - - i_a Gets the current of the power supply a on the new chiptest board. \c Returns \c (int"mV") - */ - descrToFuncMap[i].m_pFuncName="i_a"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - i_b Gets the current of the power supply b on the new chiptest board \c Returns \c (int"mV") - */ - descrToFuncMap[i].m_pFuncName="i_b"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - i_c Gets the current of the power supply c on the new chiptest board \c Returns \c (int"mV") - */ - descrToFuncMap[i].m_pFuncName="i_c"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - i_d Gets the current of the power supply d on the new chiptest board \c Returns \c (int"mV") - */ - descrToFuncMap[i].m_pFuncName="i_d"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - i_io Gets the current of the power supply io on the new chiptest board \c Returns \c (int"mV") - */ - descrToFuncMap[i].m_pFuncName="i_io"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - vm_a Gets the measured voltage of the power supply a on the new chiptest board \c Returns \c (int"mV") - */ - descrToFuncMap[i].m_pFuncName="vm_a"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - vm_b Gets the measured voltage of the power supply b on the new chiptest board \c Returns \c (int"mV") - */ - descrToFuncMap[i].m_pFuncName="vm_b"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - vm_c Gets the measured voltage of the power supply c on the new chiptest board \c Returns \c (int"mV") - */ - descrToFuncMap[i].m_pFuncName="vm_c"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - vm_d Gets the measured voltage of the power supply d on the new chiptest board \c Returns \c (int"mV") - */ - descrToFuncMap[i].m_pFuncName="vm_d"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - /*! \page settings - - vm_io Gets the measured voltage of the power supply io on the new chiptest board \c Returns \c (int"mV") - */ - descrToFuncMap[i].m_pFuncName="vm_io"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdADC; - ++i; - - - /* temperature control */ - /*! \page settings - \section settingstmp Temp Control - commands to monitor and handle temperature overshoot (only JUNGFRAU) - */ - - /*! \page settings - - temp_threshold Sets/gets the threshold temperature. JUNGFRAU ONLY. \c Returns \c (double"°C") - */ - descrToFuncMap[i].m_pFuncName="temp_threshold"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTempControl; - ++i; - - /*! \page settings - - temp_control Enables/Disables the temperature control. 1 enables, 0 disables. JUNGFRAU ONLY. \c Returns \c int - */ - descrToFuncMap[i].m_pFuncName="temp_control"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTempControl; - ++i; - - /*! \page settings - - temp_event Resets/gets over-temperative event. Put only with option 0 to clear event. Gets 1 if temperature went over threshold and control is enabled, else 0. /Disables the temperature control. JUNGFRAU ONLY. \c Returns \c int - */ - descrToFuncMap[i].m_pFuncName="temp_event"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdTempControl; - ++i; - - - /* file name */ - - /*! \page output Output settings - Commands to setup the file destination and format - */ - - /*! \page output - - outdir [dir] Sets/gets the file output directory. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="outdir"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdOutDir; - ++i; - - /*! \page output - - fname [fn] Sets/gets the root of the output file name \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="fname"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdFileName; - ++i; - - /*! \page output - - index [i] Sets/gets the current file index. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="index"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdFileIndex; - ++i; - - /*! \page output - - enablefwrite [i] Enables/disables file writing. 1 enables, 0 disables. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="enablefwrite"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdEnablefwrite; - ++i; - - /*! \page output - - overwrite [i] enables(1) /disables(0) file overwriting. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="overwrite"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdOverwrite; - ++i; - - /*! \page output - - currentfname gets the filename for the data without index and extension. MYTHEN only. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="currentfname"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdFileName; - ++i; - - /*! \page output - - fileformat sets/gets the file format for data in receiver. Options: [ascii, binary, hdf5]. Ascii is not implemented in Receiver. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="fileformat"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdFileName; - ++i; - - - - /* Acquisition actions */ - - /*! \page actions Actions - Commands to define scripts to be executed during the acquisition flow - */ - - /*! \page actions - - positions [n [p0..pn-1]] sets/gets number of angular position and positions to be acquired.. \c Returns \c (int int..) n [p0..pn-1] - */ - descrToFuncMap[i].m_pFuncName="positions"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPositions; - ++i; - - /*! \page actions - - startscript [s] sets/gets the script to be executed at the beginning of the acquisition. \c none unsets. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="startscript"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScripts; - ++i; - - /*! \page actions - - startscriptpar [s] sets/gets a string to be passed as a parameter to the startscript. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="startscriptpar"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScripts; - ++i; - - /*! \page actions - - stopscript [s] sets/gets the script to be executed at the end of the acquisition. \c none unsets. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="stopscript"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScripts; - ++i; - - /*! \page actions - - stopscriptpar [s] sets/gets a string to be passed as a parameter to the stopscript. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="stopscriptpar"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScripts; - ++i; - - /*! \page actions - - scriptbefore [s] sets/gets the script to be executed before starting the detector every time in the acquisition. \c none unsets. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="scriptbefore"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScripts; - ++i; - - /*! \page actions - - scriptbeforepar [s] sets/gets a string to be passed as a parameter to the scriptbefore. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="scriptbeforepar"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScripts; - ++i; - - /*! \page actions - - scriptafter [s] sets/gets the script to be executed after the detector has finished every time in the acquisition. \c none unsets. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="scriptafter"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScripts; - ++i; - - /*! \page actions - - scriptafterpar [s] sets/gets a string to be passed as a parameter to the scriptafter. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="scriptafterpar"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScripts; - ++i; - - /*! \page actions - - headerafter [s] sets/gets the script to be executed for logging the detector parameters. \c none unsets. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="headerafter"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScripts; - ++i; - - /*! \page actions - - headerbefore [s] sets/gets the script to be executed for logging the detector parameters. \c none unsets. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="headerbefore"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScripts; - ++i; - - /*! \page actions - - headerbeforepar [s] sets/gets a string to be passed as a parameter to the headerbefore script. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="headerbeforepar"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScripts; - ++i; - - /*! \page actions - - headerafterpar [s] sets/gets a string to be passed as a parameter to the headerafter script. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="headerafterpar"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScripts; - ++i; - - /*! \page actions - - enacallog [i] enables/disables logging of the parameters necessary for the energy calibration. 1 sets, 0 unsets. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="encallog"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScripts; - ++i; - - /*! \page actions - - angcallog [i] enables/disables logging of the parameters necessary for the angular calibration. 1 sets, 0 unsets. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="angcallog"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScripts; - ++i; - - /*! \page actions - - scan0script [s] sets/gets the script to be executed for the scan 0 level. \c none unsets. - */ - descrToFuncMap[i].m_pFuncName="scan0script"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScans; - ++i; - - /*! \page actions - - scan0par [s] sets/gets a string to be passed as a parameter to the scan0script - */ - descrToFuncMap[i].m_pFuncName="scan0par"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScans; - ++i; - - /*! \page actions - - scan0prec [i] sets/gets number of digits to be used for the scan0 variable in the file name. - */ - descrToFuncMap[i].m_pFuncName="scan0prec"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScans; - ++i; - - /*! \page actions - - scan0steps [i [s0..sn-1]] sets/gets number of steps (int) of the scan0 level and their values (float). - */ - descrToFuncMap[i].m_pFuncName="scan0steps"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScans; - ++i; - - - /*! \page actions - - scan0range [smin smax sstep] sets scan0 min, max and step, returns the number of steps and their values as scan0steps. - */ - descrToFuncMap[i].m_pFuncName="scan0range"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScans; - ++i; - - /*! \page actions - - scan1script [s] sets/gets the script to be executed for the scan1 level. \c none unsets. - */ - descrToFuncMap[i].m_pFuncName="scan1script"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScans; - ++i; - - /*! \page actions - - scan1par [s] sets/gets a string to be passed as a parameter to the scan1script - */ - descrToFuncMap[i].m_pFuncName="scan1par"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScans; - ++i; - - /*! \page actions - - scan1prec [i] sets/gets number of digits to be used for the scan1 variable in the file name. - */ - descrToFuncMap[i].m_pFuncName="scan1prec"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScans; - ++i; - - /*! \page actions - - scan1steps [i [s0..sn-1]] sets/gets number of steps (int) of the scan1 level and their values (float). - */ - descrToFuncMap[i].m_pFuncName="scan1steps"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScans; - ++i; - - /*! \page actions - - scan1range [smin smax sstep] sets scan1 min, max and step, returns the number of steps and their values as scan1steps. - */ - descrToFuncMap[i].m_pFuncName="scan1range"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdScans; - ++i; - - - - - - /* communication configuration */ - - /*! \page network Network - Commands to setup the network between client, detector and receiver - - rx_hostname [s] sets/gets the receiver hostname or IP address, configures detector mac with all network parameters and updates receiver with acquisition parameters. Normally used for single detectors (Can be multi-detector). \c none disables. If used, use as last network command in configuring detector MAC. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="rx_hostname"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - /*! \page network - - rx_udpip [ip] sets/gets the ip address of the receiver UDP interface where the data from the detector will be streamed to. Normally used for single detectors (Can be multi-detector). Used if different from eth0. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="rx_udpip"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - - /*! \page network - - rx_udpmac [mac] sets/gets the mac address of the receiver UDP interface where the data from the detector will be streamed to. Normally used for single detectors (Can be multi-detector). \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="rx_udpmac"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - - /*! \page network - - rx_udpport [port] sets/gets the port of the receiver UDP interface where the data from the detector will be streamed to. Use single-detector command. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="rx_udpport"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - - /*! \page network - - rx_udpport2 [port] sets/gets the second port of the receiver UDP interface where the data from the second half of the detector will be streamed to. Use single-detector command. Used for EIGER only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="rx_udpport2"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - - /*! \page network - - rx_udpsocksize [size] sets/gets the UDP socket buffer size. Already trying to set by default to 100mb, 2gb for Jungfrau. Does not remember in client shared memory, so must be initialized each time after setting receiver hostname in config file.\c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="rx_udpsocksize"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - - /*! \page network - - rx_realudpsocksize [size] gets the actual UDP socket buffer size. Usually double the set udp socket buffer size due to kernel bookkeeping. Get only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="rx_realudpsocksize"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - - - /*! \page network - - detectormac [mac] sets/gets the mac address of the detector UDP interface from where the detector will stream data. Use single-detector command. Normally unused. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="detectormac"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - - /*! \page network - - detectorip [ip] sets/gets the ip address of the detector UDP interface from where the detector will stream data. Use single-detector command. Keep in same subnet as rx_udpip (if rx_udpip specified). \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="detectorip"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - - /*! \page network - - txndelay_left [delay] sets/gets the transmission delay of first packet in an image being streamed out from the detector's left UDP port. Use single-detector command. Used for EIGER only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="txndelay_left"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - - /*! \page network - - txndelay_right [delay] sets/gets the transmission delay of first packet in an image being streamed out from the detector's right UDP port. Use single-detector command. Used for EIGER only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="txndelay_right"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - - /*! \page network - - txndelay_frame [delay] sets/gets the transmission frame period of entire frame being streamed out from the detector for both ports. Use single-detector command. Used for EIGER only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="txndelay_frame"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - - /*! \page network - - flowcontrol_10g [delay] Enables/disables 10 GbE flow control. 1 enables, 0 disables. Used for EIGER only. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="flowcontrol_10g"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - - /*! \page network - - zmqport [port] sets/gets the 0MQ (TCP) port of the client to where final data is streamed to (eg. for GUI). The default already connects with rx_zmqport for the GUI. Use single-detector command to set individually or multi-detector command to calculate based on \c port for the rest. Must restart zmq client streaming in gui/external gui \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="zmqport"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - - /*! \page network - - rx_zmqport [port] sets/gets the 0MQ (TCP) port of the receiver from where data is streamed from (eg. to GUI or another process for further processing). Use single-detector command to set individually or multi-detector command to calculate based on \c port for the rest. put restarts streaming in receiver with new port. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="rx_zmqport"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - ++i; - - /*! \page network - - rx_datastream enables/disables data streaming from receiver. 1 enables 0MQ data stream from receiver (creates streamer threads), while 0 disables (destroys streamer threads). Switching to Gui enables data streaming in receiver and switching back to command line acquire will require disabling data streaming in receiver for fast applications \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="rx_datastream"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdDataStream; - ++i; - - /*! \page network - - zmqip [ip] sets/gets the 0MQ (TCP) ip of the client to where final data is streamed to (eg. for GUI). For Experts only! Default is ip of rx_hostname and works for GUI. This command to change from default can be used from command line when sockets are not already open as the command line is not aware/create the 0mq sockets in the client side. This is usually used to stream in from an external process. . If no custom ip, empty until first time connect to receiver. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="zmqip"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - i++; - - /*! \page network - - rx_zmqip [ip] sets/gets the 0MQ (TCP) ip of the receiver from where data is streamed from (eg. to GUI or another process for further processing). For Experts only! Default is ip of rx_hostname and works for GUI. This is usually used to stream out to an external process for further processing. . If no custom ip, empty until first time connect to receiver. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="rx_zmqip"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - i++; - - /*! \page network - - rx_jsonaddheader [t] sets/gets additional json header to be streamed out with the zmq from receiver. Default is empty. \c t must be in the format "\"label1\":\"value1\",\"label2\":\"value2\"" etc. Use only if it needs to be processed by an intermediate process. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="rx_jsonaddheader"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdNetworkParameter; - i++; - - /*! \page network - - configuremac [i] configures the MAC of the detector with these parameters: detectorip, detectormac, rx_udpip, rx_udpmac, rx_udpport, rx_udpport2 (if applicable). This command is already included in \c rx_hsotname. Only put!. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="configuremac"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdConfigureMac; - ++i; - - /*! \page network - - rx_tcpport [port] sets/gets the port of the client-receiver TCP interface. Use single-detector command. Is different for each detector if same \c rx_hostname used. Must be first command to communicate with receiver. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="rx_tcpport"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPort; - ++i; - - /*! \page network - - port [port] sets/gets the port of the client-detector control server TCP interface. Use single-detector command. Default value is 1952 for all detectors. Normally not changed. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="port"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPort; - ++i; - - /*! \page network - - stopport [port] sets/gets the port of the client-detector stop server TCP interface. Use single-detector command. Default value is 1953 for all detectors. Normally not changed. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="stopport"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPort; - ++i; - - - /*! \page network - - lock [i] Locks/Unlocks the detector to communicate with this client. 1 locks, 0 unlocks. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="lock"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdLock; - ++i; - - /*! \page network - - lastclient Gets the last client communicating with the detector. Cannot put!. \c Returns \c (string) - */ - descrToFuncMap[i].m_pFuncName="lastclient"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdLastClient; - ++i; - - - - - - - - - - - - - - - /* receiver functions */ - - /*! \page receiver Receiver commands - Commands to configure the receiver. Not used in MYTHEN. - */ - - /*! \page receiver - - receiver [s] starts/stops the receiver to listen to detector packets. Options: [ \c start, \c stop]. \c Returns \c (string) status of receiver[ \c idle, \c running]. - */ - descrToFuncMap[i].m_pFuncName="receiver"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdReceiver; - ++i; - - /*! \page receiver - - r_online [i] sets/gets the receiver in online/offline mode. 1 is online, 0 is offline. Get is from shared memory. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="r_online"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdOnline; - ++i; - - /*! \page receiver - - r_checkonline Checks the receiver if it is online/offline mode. Only get! \c Returns (string) "All online" or "[list of offline hostnames] : Not online". - */ - descrToFuncMap[i].m_pFuncName="r_checkonline"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdOnline; - ++i; - - - /*! \page receiver - - framescaught gets the number of frames caught by receiver. Average of all for multi-detector command. Only get! \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="framescaught"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdReceiver; - ++i; - - /*! \page receiver - - resetframescaught [i] resets the number of frames caught to 0. i can be any number. Use this if using status start, instead of acquire (this command is included). Only put! \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="resetframescaught"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdReceiver; - ++i; - - /*! \page receiver - - frameindex [i] gets the current frame index of receiver. Average of all for multi-detector command. Only get! \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="frameindex"; - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdReceiver; - ++i; - - /*! \page receiver - - r_lock [i] locks/unlocks the receiver to communicate with only this client. 1 locks, 0 unlocks. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="r_lock"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdLock; - ++i; - - /*! \page receiver - - r_lastclient gets the last client communicating with the receiver. Only get! \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="r_lastclient"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdLastClient; - ++i; - - /*! \page receiver - - r_readfreq [i] sets/gets the stream frequency of data from receiver to client. i > 0 is the nth frame being streamed. 0 sets frequency to a default timer (200ms). \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="r_readfreq"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdReceiver; - ++i; - - /*! \page receiver - - rx_fifodepth [i] sets/gets receiver fifo (between Listener and Writer Threads) depth to i number of frames. Can improve listener packet loss (loss due to packet processing time in Listener threads), not if limited by writing. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="rx_fifodepth"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdReceiver; - ++i; - - /*! \page receiver - - r_silent [i] sets/gets receiver in silent mode, ie. it will not print anything during real time acquisition. 1 sets, 0 unsets. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="r_silent"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdReceiver; - ++i; - - /*! \page receiver - - r_framesperfile [i] sets/gets the frames per file in receiver to i. 0 means infinite or all frames in a single file. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="r_framesperfile"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdReceiver; - ++i; - - /*! \page receiver - - r_discardpolicy sets/gets the frame discard policy in the receiver. nodiscard (default) - discards nothing, discardempty - discard only empty frames, discardpartial(fastest) - discards all partial frames. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="r_discardpolicy"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdReceiver; - ++i; - - /*! \page receiver - - r_padding sets/gets the frame padding in the receiver. 0 does not pad partial frames(fastest), 1 (default) pads partial frames. \c Returns \c (int) - */ - descrToFuncMap[i].m_pFuncName="r_padding"; //OK - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdReceiver; - ++i; - - /* pattern generator */ - - /*! \page ctb Chiptest board - Commands specific for the new chiptest board as pattern generator - */ - - /*! \page ctb - - adcinvert [mask] Sets/gets ADC inversion mask (8 digits hex format) - */ - descrToFuncMap[i].m_pFuncName="adcinvert"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - adcdisable [mask] Sets/gets ADC disable mask (8 digits hex format) - */ - descrToFuncMap[i].m_pFuncName="adcdisable"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - pattern fn loads binary pattern file fn - */ - descrToFuncMap[i].m_pFuncName="pattern"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patword addr [word] sets/gets 64 bit word at address addr of pattern memory. Both address and word in hex format. Advanced! - */ - descrToFuncMap[i].m_pFuncName="patword"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patioctrl [word] sets/gets 64 bit mask defining input (0) and output (1) signals. hex format. - */ - descrToFuncMap[i].m_pFuncName="patioctrl"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patclkctrl [word] sets/gets 64 bit mask defining if output signal is a clock and runs. hex format. Unused at the moment. - */ - descrToFuncMap[i].m_pFuncName="patclkctrl"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patlimits [addr1 addr2] sets/gets the start and stop limits of the pattern to be executed. hex format. Advanced! - */ - descrToFuncMap[i].m_pFuncName="patlimits"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patloop0 [addr1 addr2] sets/gets the start and stop limits of the level 0 loop. hex format. Advanced! - */ - descrToFuncMap[i].m_pFuncName="patloop0"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patnloop0 [n] sets/gets the number of cyclesof the level 0 loop (int). - */ - descrToFuncMap[i].m_pFuncName="patnloop0"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patwait0 [addr] sets/gets the address of the level 0 wait point. hex format. Advanced! - */ - descrToFuncMap[i].m_pFuncName="patwait0"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patwaittime0 [n] sets/gets the duration of the witing of the 0 waiting point in clock cycles (int). - */ - descrToFuncMap[i].m_pFuncName="patwaittime0"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patloop1 [addr1 addr2] sets/gets the start and stop limits of the level 1 loop. hex format. Advanced! - */ - descrToFuncMap[i].m_pFuncName="patloop1"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patnloop1 [n] sets/gets the number of cyclesof the level 1 loop (int). - */ - descrToFuncMap[i].m_pFuncName="patnloop1"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patwait1 [addr] sets/gets the address of the level 1 wait point. hex format. Advanced! - */ - descrToFuncMap[i].m_pFuncName="patwait1"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patwaittime1 [n] sets/gets the duration of the witing of the 1 waiting point in clock cycles (int). - */ - descrToFuncMap[i].m_pFuncName="patwaittime1"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patloop2 [addr1 addr2] sets/gets the start and stop limits of the level 2 loop. hex format. Advanced! - */ - descrToFuncMap[i].m_pFuncName="patloop2"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patnloop2 [n] sets/gets the number of cyclesof the level 2 loop (int). - */ - descrToFuncMap[i].m_pFuncName="patnloop2"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patwait2 [addr] sets/gets the address of the level 2 wait point. hex format. Advanced! - */ - descrToFuncMap[i].m_pFuncName="patwait2"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - patwaittime2 [n] sets/gets the duration of the waiting of the 2 waiting point in clock cycles (int). - */ - descrToFuncMap[i].m_pFuncName="patwaittime2"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - /*! \page ctb - - dut_clk [i] sets/gets the signal to be used as a clock for the digital data coming from the device under test. Advanced! - */ - descrToFuncMap[i].m_pFuncName="dut_clk"; // - descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdPattern; - ++i; - - - - numberOfCommands=i; - - // #ifdef VERBOSE - // cout << "Number of commands is " << numberOfCommands << endl; - // #endif -} - - - - - -//----------------------------------------------------------- - -/*! - */ - -//----------------------------------------------------------- - -string slsDetectorCommand::executeLine(int narg, char *args[], int action) { - - - - if (action==READOUT_ACTION) - return cmdAcquire(narg, args, action); - - - size_t s=string(args[0]).find(':'); - string key=string(args[0]).substr(0,s); // truncate at : - - if (action==PUT_ACTION && narg<1) - action=HELP_ACTION; - - - for(int i=0; igetNumberOfDetectors()) { - cprintf(RED, "Error: This shared memory has no detectors added. Aborting.\n"); - return string("acquire unsuccessful"); - } - myDet->setOnline(ONLINE_FLAG); - int r_online = myDet->setReceiverOnline(ONLINE_FLAG); - - if(myDet->acquire() == FAIL) - return string("acquire unsuccessful"); - if(r_online){ - char answer[100]; - sprintf(answer,"\nAcquired %d",myDet->getFramesCaughtByReceiver()); - return string(answer); - } - - return string(""); - -} - - - - -string slsDetectorCommand::helpAcquire(int narg, char *args[], int action){ - - - if (action==PUT_ACTION) - return string(""); - ostringstream os; - os << "Usage is "<< std::endl << "sls_detector_acquire id " << std::endl; - os << "where id is the id of the detector " << std::endl; - os << "the detector will be started, the data acquired, processed and written to file according to the preferences configured " << std::endl; - return os.str(); - -} - - -string slsDetectorCommand::cmdData(int narg, char *args[], int action) { - -#ifdef VERBOSE - cout << string("Executing command ")+string(args[0])+string(" ( ")+cmd+string(" )\n"); -#endif - int b; - if (action==PUT_ACTION) { - return string("cannot set"); - } else if (action==HELP_ACTION) { - return helpData(narg,args,HELP_ACTION); - } else { - b=myDet->setThreadedProcessing(-1); - myDet->setThreadedProcessing(0); - myDet->setOnline(ONLINE_FLAG); - myDet->setReceiverOnline(ONLINE_FLAG); - myDet->readAll(); - //processdata in receiver is useful only for gui purposes - if(myDet->setReceiverOnline()==OFFLINE_FLAG) - myDet->processData(1); - myDet->setThreadedProcessing(b); - return string(""); - } -} - - - -string slsDetectorCommand::helpData(int narg, char *args[], int action){ - - if (action==PUT_ACTION) - return string(""); - else - return string("data \t gets all data from the detector (if any) processes them and writes them to file according to the preferences already setup\n"); - -} - -string slsDetectorCommand::cmdFrame(int narg, char *args[], int action) { - - int b; -#ifdef VERBOSE - cout << string("Executing command ")+string(args[0])+string(" ( ")+cmd+string(" )\n"); -#endif - if (action==PUT_ACTION) { - return string("cannot set"); - } else if (action==HELP_ACTION) { - return helpFrame(narg,args,HELP_ACTION); - } else { - b=myDet->setThreadedProcessing(-1); - myDet->setThreadedProcessing(0); - myDet->setOnline(ONLINE_FLAG); - myDet->setReceiverOnline(ONLINE_FLAG); - myDet->readFrame(); - //processdata in receiver is useful only for gui purposes - if(myDet->setReceiverOnline()==OFFLINE_FLAG) - myDet->processData(1); - myDet->setThreadedProcessing(b); - return string("ok"); - } - -} - -string slsDetectorCommand::helpFrame(int narg, char *args[], int action) { - - if (action==PUT_ACTION) - return string(""); - return string("frame \t gets a single frame from the detector (if any) processes it and writes it to file according to the preferences already setup\n"); - -} - -string slsDetectorCommand::cmdStatus(int narg, char *args[], int action) { - -#ifdef VERBOSE - cout << string("Executing command ")+string(args[0])+string(" ( ")+cmd+string(" )\n"); -#endif - - if (action==HELP_ACTION) - return helpStatus(narg,args,action); - - if (cmd=="status") { - myDet->setOnline(ONLINE_FLAG); - if (action==PUT_ACTION) { - //myDet->setThreadedProcessing(0); - if (string(args[1])=="start") - myDet->startAcquisition(); - else if (string(args[1])=="stop") { - myDet->setReceiverOnline(ONLINE_FLAG);//restream stop - myDet->stopAcquisition(); - } - else if (string(args[1])=="trigger") { - myDet->sendSoftwareTrigger(); - } - else - return string("unknown action"); - } - runStatus s=myDet->getRunStatus(); - return myDet->runStatusType(s); - } - else if (cmd=="busy") { - if (action==PUT_ACTION) { - int i; - if(!sscanf(args[1],"%d",&i)) - return string("cannot parse busy mode"); - myDet->setAcquiringFlag(i); - } - char answer[100]; - sprintf(answer,"%d", myDet->getAcquiringFlag()); - return string(answer); - } - else return string("cannot scan command ")+string(cmd); - -} - - - -string slsDetectorCommand::helpStatus(int narg, char *args[], int action) { - - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) { - os << string("status \t gets the detector status - can be: running, error, transmitting, finished, waiting or idle\n"); - os << string("busy \t gets the status of acquire- can be: 0 or 1. 0 for idle, 1 for running\n"); - } - if (action==PUT_ACTION || action==HELP_ACTION) { - os << string("status \t controls the detector acquisition - can be start or stop or trigger(EIGER only). When using stop acquisition and if acquisition is done, it will restream the stop packet from receiver (if data streaming in receiver is on). Eiger can also provide an internal software trigger\n"); - os << string("busy i\t sets the status of acquire- can be: 0(idle) or 1(running).Command Acquire sets it to 1 at beignning of acquire and back to 0 at the end. Clear Flag for unexpected acquire terminations. \n"); - } - return os.str(); -} - - - -string slsDetectorCommand::cmdDataStream(int narg, char *args[], int action) { - -#ifdef VERBOSE - cout << string("Executing command ")+string(args[0])+string(" ( ")+cmd+string(" )\n"); -#endif - int ival=-1; - char ans[100]=""; - - myDet->setOnline(ONLINE_FLAG); - myDet->setReceiverOnline(ONLINE_FLAG); - - if (action==HELP_ACTION) - return helpDataStream(narg,args,HELP_ACTION); - - if (action==PUT_ACTION) { - if (!sscanf(args[1],"%d",&ival)) - return string ("cannot scan rx_datastream mode"); - myDet->enableDataStreamingFromReceiver(ival); - } - - sprintf(ans,"%d",myDet->enableDataStreamingFromReceiver()); - return string(ans); -} - - -string slsDetectorCommand::helpDataStream(int narg, char *args[], int action) { - - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) - os << string("rx_datastream \t enables/disables data streaming from receiver. 1 is 0MQ data stream from receiver enabled, while 0 is 0MQ disabled. -1 for inconsistency between multiple receivers. \n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("rx_datastream i\t enables/disables data streaming from receiver. i is 1 enables 0MQ data stream from receiver (creates streamer threads), while 0 disables (destroys streamer threads). \n"); - return os.str(); -} - - - -string slsDetectorCommand::cmdFree(int narg, char *args[], int action) { - -#ifdef VERBOSE - cout << string("Executing command ")+string(args[0])+string(" ( ")+cmd+string(" )\n"); -#endif - if (action==HELP_ACTION) { - return helpFree(narg,args,HELP_ACTION); - } - - return("Error: Should have been freed before creating constructor\n"); -} - - -string slsDetectorCommand::helpFree(int narg, char *args[], int action) { - return string("free \t frees the shared memory\n"); -} - - -string slsDetectorCommand::cmdHostname(int narg, char *args[], int action){ -#ifdef VERBOSE - cout << string("Executing command ")+string(args[0])+string(" ( ")+cmd+string(" )\n"); -#endif - - if (action==HELP_ACTION) { - return helpHostname(narg,args,HELP_ACTION); - } - if (action==GET_ACTION) { - if ((cmd == "add") || (cmd == "replace")) - return string("cannot get"); - } - - if (action==PUT_ACTION) { - if (((cmd == "add") || (cmd == "hostname")) && - (!myDet->isMultiSlsDetectorClass())) { - return string ("Wrong usage - setting hostname/add only from " - "multiDetector level"); - } - if ((cmd == "replace") && (myDet->isMultiSlsDetectorClass())) { - return string ("Wrong usage - replace only from " - "single detector level"); - } - char hostname[1000]; - strcpy(hostname,""); - // if each argument is a hostname - for (int id=1; id2) - strcat(hostname,"+"); - } - - if (cmd == "add") - myDet->addMultipleDetectors(hostname); - else - myDet->setHostname(hostname); - } - - return myDet->getHostname(); -} - - - -string slsDetectorCommand::helpHostname(int narg, char *args[], int action){ - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) { - os << string("hostname \t returns the hostname(s) of the multi detector structure.\n"); - os << string("add \t cannot get\n"); - os << string("replace \t cannot get\n"); - } - if (action==PUT_ACTION || action==HELP_ACTION) { - os << string("hostname name [name name]\t frees shared memory and " - "sets the hostname (or IP adress). Only allowed at multi detector level.\n"); - os << string ("add det [det det]\t appends a hostname (or IP address) at " - "the end of the multi-detector structure. Only allowed at multi detector level." - "Returns hostnames in the multi detector structure\n"); - os << string ("replace det \t Sets the hostname (or IP adress) for a " - "single detector. Only allowed at single detector level. " - "Returns the hostnames for that detector\n"); - } - return os.str(); -} - - -string slsDetectorCommand::cmdUser(int narg, char *args[], int action){ -#ifdef VERBOSE - cout << string("Executing command ")+string(args[0])+string(" ( ")+cmd+string(" )\n"); -#endif - - if (action==HELP_ACTION) { - return helpHostname(narg,args,HELP_ACTION); - } - if (action==PUT_ACTION) { - return string("cannot put"); - } - if (!myDet->isMultiSlsDetectorClass()) { - return string ("Wrong usage - getting user details only from " - "multiDetector level"); - } - return myDet->getUserDetails(); -} - - - -string slsDetectorCommand::helpUser(int narg, char *args[], int action){ - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) { - os << string("user \t returns user details from shared memory without updating shared memory. " - "Only allowed at multi detector level.\n"); - } - if (action==PUT_ACTION || action==HELP_ACTION) { - os << string("user \t cannot put\n"); - } - return os.str(); -} - - - -string slsDetectorCommand::cmdMaster(int narg, char *args[], int action){ -#ifdef VERBOSE - cout << string("Executing command ")+string(args[0])+string(" ( ")+cmd+string(" )\n"); - -#endif - - ostringstream os; - int ival; - - - if (action==HELP_ACTION) { - return helpMaster(narg,args,HELP_ACTION); - } - myDet->setOnline(ONLINE_FLAG); - if (action==PUT_ACTION) { - istringstream vvstr(args[1]); - vvstr >> ival; - if (vvstr.fail()) - return helpMaster(narg,args,HELP_ACTION); - myDet->setMaster(ival); - } - os << myDet->setMaster(); - return os.str(); - -} - - -string slsDetectorCommand::helpMaster(int narg, char *args[], int action){ - - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) - os << string("master \t gets the master of the detector structure (-1 if none)\n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("master pos \t sets position of the master of the detector structure (-1 if none) \n"); - return os.str(); - -} - -string slsDetectorCommand::cmdSync(int narg, char *args[], int action){ -#ifdef VERBOSE - cout << string("Executing command ")+string(args[0])+string(" ( ")+cmd+string(" )\n"); -#endif - - if (action==HELP_ACTION) { - return helpSync(narg,args,HELP_ACTION); - } - myDet->setOnline(ONLINE_FLAG); - if (action==PUT_ACTION) { - if (myDet->getSyncType(string(args[1]))==GET_SYNCHRONIZATION_MODE) return helpSync(narg,args, action); - myDet->setSynchronization(myDet->getSyncType(string(args[1]))); - } - return myDet->getSyncType(myDet->setSynchronization()); - -} -string slsDetectorCommand::helpSync(int narg, char *args[], int action){ - - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) - os << string("sync \t gets the synchronization mode of the structure\n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("sync mode \t sets synchronization mode of the structure. Cane be none, gating, trigger, complementary \n"); - return os.str(); -} - -string slsDetectorCommand::cmdHelp(int narg, char *args[], int action){ -#ifdef VERBOSE - cout << string("Executing command ")+string(args[0])+string(" ( ")+cmd+string(" )\n"); -#endif - - cout << narg << endl; - - if (narg>=1) - return helpLine(narg-1, args+1, action); - else - return helpLine(0, args, action); - - - -} - -string slsDetectorCommand::cmdExitServer(int narg, char *args[], int action){ -#ifdef VERBOSE - cout << string("Executing command ")+string(args[0])+string(" ( ")+cmd+string(" )\n"); -#endif - if (action==HELP_ACTION) { - return helpExitServer(narg, args, action); - } - - if (action==PUT_ACTION) { - if (cmd=="exitserver"){ - myDet->setOnline(ONLINE_FLAG); - if (myDet->exitServer()!=OK) - return string("Server shut down."); - else - return string("Error closing server\n"); - } - else if (cmd=="exitreceiver"){ - myDet->setReceiverOnline(ONLINE_FLAG); - if(myDet->exitReceiver()!=OK) - return string("Receiver shut down\n"); - else - return string("Error closing receiver\n"); - } - else return("cannot decode command\n"); - } else - return ("cannot get"); - -} - -string slsDetectorCommand::helpExitServer(int narg, char *args[], int action){ - ostringstream os; - os << string("exitserver \t shuts down all the detector servers. Don't use it!!!!\n"); - os << string("exitreceiver \t shuts down all the receiver servers.\n"); - return os.str(); -} - - -string slsDetectorCommand::cmdSettingsDir(int narg, char *args[], int action){ -#ifdef VERBOSE - cout << string("Executing command ")+string(args[0])+string(" ( ")+cmd+string(" )\n"); -#endif - if (action==HELP_ACTION) { - return helpSettingsDir(narg, args, action); - } - if (action==PUT_ACTION) { - myDet->setSettingsDir(string(args[1])); - } - if (myDet->getSettingsDir()=="") - return string("undefined"); - return myDet->getSettingsDir(); -} - - - -string slsDetectorCommand::helpSettingsDir(int narg, char *args[], int action){ - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) - os << string("settingsdir \t gets the directory where the settings files are located\n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("settingsdir dir \t sets the directory where the settings files are located\n"); - if (action==GET_ACTION || action==HELP_ACTION) - os << string("trimdir \t obsolete for settingsdir\n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("trimdir dir \t obsolete for settingsdir\n"); - return os.str(); -} - - - -string slsDetectorCommand::cmdCalDir(int narg, char *args[], int action){ - - if (action==HELP_ACTION) { - return helpCalDir(narg, args, action); - } - if (action==PUT_ACTION) { - myDet->setCalDir(string(args[1])); - } - if ( (myDet->getCalDir()).empty() ) - return string("undefined"); - return myDet->getCalDir(); -} - - - -string slsDetectorCommand::helpCalDir(int narg, char *args[], int action){ - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) - os << string("caldir \t gets the directory where the calibration files are located\n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("caldir dir \t sets the directory where the calibration files are located\n"); - return os.str(); -} - - - -string slsDetectorCommand::cmdTrimEn(int narg, char *args[], int action){ - int ival; - int ip; - - char answer[1000]; - - if (action==HELP_ACTION) return helpTrimEn(narg,args,action); - - if (action==PUT_ACTION) { - if (sscanf(args[1],"%d",&ival)) { - int pos[ival]; - for (ip=0; ipsetTrimEn(ip,pos); - } - } - int npos=myDet->getTrimEn(); - if (npos != -1) { - sprintf(answer,"%d",npos); - int opos[npos]; - npos = myDet->getTrimEn(opos); - if (npos != -1) { - for (int ip=0; ipsetReceiverOnline(ONLINE_FLAG); - if (action==HELP_ACTION) - return helpOutDir(narg, args, action); - - else if(action==PUT_ACTION) - myDet->setFilePath(string(args[1])); - - return string(myDet->getFilePath()); -} - - - -string slsDetectorCommand::helpOutDir(int narg, char *args[], int action){ - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) - os << string("outdir \t gets the directory where the output files will be written\n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("outdir dir \t sets the directory where the output files will be written\n"); - return os.str(); -} - - - - -string slsDetectorCommand::cmdFileName(int narg, char *args[], int action){ - myDet->setReceiverOnline(ONLINE_FLAG); - if (action==HELP_ACTION) - return helpFileName(narg, args, action); - if (cmd=="fname") { - if (action==PUT_ACTION) - myDet->setFileName(string(args[1])); - - return string(myDet->getFileName()); - } else if(cmd=="fileformat") { - if (action==PUT_ACTION){ - if (string(args[1])=="binary") - myDet->setFileFormat(BINARY); - else if (string(args[1])=="ascii") - myDet->setFileFormat(ASCII); - else if (string(args[1])=="hdf5") - myDet->setFileFormat(HDF5); - else return string("could not scan file format mode\n"); - } - return myDet->fileFormats(myDet->getFileFormat()); - } - return string(myDet->getCurrentFileName()); - -} - - - -string slsDetectorCommand::helpFileName(int narg, char *args[], int action){ - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION){ - os << string("fname \t gets the filename for the data without index and extension\n"); - os << string("fileformat \t gets the file format for data\n"); - } - if (action==PUT_ACTION || action==HELP_ACTION){ - os << string("fname s \t sets the filename for the data (index and extension will be automatically appended)\n"); - os << string("fileformat s \t sets the file format for the data (binary, ascii, hdf5)\n"); - } - return os.str(); -} - - - -string slsDetectorCommand::cmdEnablefwrite(int narg, char *args[], int action){ - - int i; - char ans[100]; - myDet->setReceiverOnline(ONLINE_FLAG); - if (action==HELP_ACTION) { - return helpEnablefwrite(narg, args, action); - } - if (action==PUT_ACTION) { - if (sscanf(args[1],"%d",&i)) - myDet->enableWriteToFile(i); - else - return string("could not decode enable file write"); - - - } - sprintf(ans,"%d",myDet->enableWriteToFile()); - return string(ans); -} - - - -string slsDetectorCommand::helpEnablefwrite(int narg, char *args[], int action){ - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) - os << string("enablefwrite \t When Enabled writes the data into the file\n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("enablefwrite i \t should be 1 or 0 or -1\n"); - return os.str(); -} - - -string slsDetectorCommand::cmdOverwrite(int narg, char *args[], int action){ - - int i; - char ans[100]; - myDet->setReceiverOnline(ONLINE_FLAG); - if (action==HELP_ACTION) { - return helpOverwrite(narg, args, action); - } - if (action==PUT_ACTION) { - if (sscanf(args[1],"%d",&i)) - myDet->overwriteFile(i); - else - return string("could not decode overwrite"); - - - } - sprintf(ans,"%d",myDet->overwriteFile()); - return string(ans); -} - - - -string slsDetectorCommand::helpOverwrite(int narg, char *args[], int action){ - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) - os << string("overwrite \t When Enabled overwrites files\n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("overwrite i \t should be 1 or 0 or -1\n"); - return os.str(); -} - - - -string slsDetectorCommand::cmdFileIndex(int narg, char *args[], int action){ - char ans[100]; - int i; - myDet->setReceiverOnline(ONLINE_FLAG); - if (action==HELP_ACTION) { - return helpFileName(narg, args, action); - } - else if (action==PUT_ACTION){ - if(!sscanf(args[1],"%d",&i)) - return string("cannot parse file index"); - myDet->setFileIndex(i); - } - - sprintf(ans,"%d", myDet->getFileIndex()); - return string(ans); -} - - - -string slsDetectorCommand::helpFileIndex(int narg, char *args[], int action){ - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) - os << string("index \t gets the file index for the next the data file\n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("index i \t sets the fileindex for the next data file\n"); - return os.str(); -} - - -string slsDetectorCommand::cmdFlatField(int narg, char *args[], int action){ - - if (action==HELP_ACTION) { - return helpFlatField(narg, args, action); - } - string sval; - - if (string(args[0])==string("ffdir")) { - if (action==PUT_ACTION) { - sval=string(args[1]); - if (sval=="none") - sval=""; - myDet->setFlatFieldCorrectionDir(sval); - } - return string(myDet->getFlatFieldCorrectionDir()); - - } else if (string(args[0])==string("flatfield")) { - - if (action==PUT_ACTION) { - sval=string(args[1]); - if (sval=="none") - sval=""; - myDet->setFlatFieldCorrection(sval); - return string(myDet->getFlatFieldCorrectionFile()); - - } else {// if (action==GET_ACTION) { - if (narg>1) - sval=string(args[1]); - else - sval="none"; - // cout << myDet->getMaxNumberOfChannels() << endl; - double corr[ myDet->getMaxNumberOfChannels()], ecorr[myDet->getMaxNumberOfChannels()]; - if (myDet->getFlatFieldCorrection(corr,ecorr)) { - if (sval!="none") { - myDet->writeDataFile(sval,corr,ecorr,NULL,'i'); - return sval; - } - return string(myDet->getFlatFieldCorrectionFile()); - } else { - return string("none"); - } - } - } - return string("could not decode flat field action ")+cmd; - -} - - -string slsDetectorCommand::helpFlatField(int narg, char *args[], int action){ - - int t=0; - ostringstream os; - if (string(args[0])==string("ffdir")) { - t=1; - } else if (string(args[0])==string("flatfield")) { - t=2; - } - if (t!=1) { - - if (action==GET_ACTION || action==HELP_ACTION) { - os << string("flatfield [fn]\t gets the flat field file name. the coorection values and errors can be dumped to fn if specified. \n"); - } if (action==PUT_ACTION || action==HELP_ACTION) - os << string("flatfield s \t sets the flat field file name\n"); - } - if (t!=2) { - - if (action==GET_ACTION || action==HELP_ACTION) - os << string("ffdir \t gets the path for the flat field files \n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("ffdir s \t sets the path for flat field files\n"); - } - return os.str(); - -} - - - - - -string slsDetectorCommand::cmdRateCorr(int narg, char *args[], int action){ - - if (action==HELP_ACTION) { - return helpRateCorr(narg, args, action); - } - double fval; - char answer[1000]; - - myDet->setOnline(ONLINE_FLAG); - - if (action==PUT_ACTION) { - sscanf(args[1],"%lf",&fval); - myDet->setRateCorrection(fval); - } - double t; - if (myDet->getRateCorrection(t)) { - sprintf(answer,"%0.9f",t); - } else { - sprintf(answer,"%0.9f",0.); - } - return string(answer); -} - - -string slsDetectorCommand::helpRateCorr(int narg, char *args[], int action){ - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) - os << string("ratecorr \t returns the dead time used for rate correections in ns \n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("ratecorr ns \t sets the deadtime correction constant in ns, -1 in Eiger will set it to default tau of settings\n"); - return os.str(); - -} - - - - -string slsDetectorCommand::cmdBadChannels(int narg, char *args[], int action){ - - string sval; - - if (action==HELP_ACTION) { - return helpBadChannels(narg, args, action); - } - if (action==PUT_ACTION) { - sval=string(args[1]); - if (sval=="none") - sval=""; - myDet->setBadChannelCorrection(sval); - } else if (action==GET_ACTION) { - if (narg>1) - sval=string(args[1]); - else - sval="none"; - int bch[myDet->getMaxNumberOfChannels()], nbch; - if ((nbch=myDet->getBadChannelCorrection(bch))) { - if (sval!="none") { - ofstream outfile; - outfile.open (sval.c_str(),ios_base::out); - if (outfile.is_open()) { - for (int ich=0; ichgetBadChannelCorrectionFile()); - -} - - -string slsDetectorCommand::helpBadChannels(int narg, char *args[], int action){ - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) - os << string("badchannels [fn]\t returns the badchannels file. Prints the list of bad channels in fn, if specified. \n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("badchannels \t sets the bad channels list\n"); - - return os.str(); -} - - - -string slsDetectorCommand::cmdAngConv(int narg, char *args[], int action){ - - if (action==HELP_ACTION) { - return helpAngConv(narg, args, action); - } - string sval; - char answer[1000]; - double fval; - angleConversionParameter c; - - if (string(args[0])==string("angconv")) { - if (action==PUT_ACTION) { - sval=string(args[1]); - - if (sval=="none") - sval=""; - - myDet->setAngularConversionFile(sval); - - return string(myDet->getAngularConversionFile()); - } else if (action==GET_ACTION) { - if (narg>1) - sval=string(args[1]); - else - sval="none"; - int dir; - if (myDet->getAngularConversion(dir)) { - if (sval!="none") { - myDet->writeAngularConversion(sval.c_str()); - return sval; - } - return string(myDet->getAngularConversionFile()); - } else { - return string("none"); - } - }else{ - return "unknown action"; - } - } else if (string(args[0])==string("globaloff")) { - c=GLOBAL_OFFSET; - } else if (string(args[0])==string("fineoff")) { - c=FINE_OFFSET; - } else if (string(args[0])==string("binsize")) { - c=BIN_SIZE; - } else if (string(args[0])==string("angdir")) { - c=ANGULAR_DIRECTION; - } else if (string(args[0])==string("moveflag")) { - c=MOVE_FLAG; - } else if (string(args[0])==string("samplex")) { - c=SAMPLE_X; - } else if (string(args[0])==string("sampley")) { - c=SAMPLE_Y; - }else{ - return string("could not decode angular conversion parameter ")+cmd; - } - - - if (action==PUT_ACTION) { - if (sscanf(args[1],"%lf",&fval)) - myDet->setAngularConversionParameter(c,fval); - } - sprintf(answer,"%f",myDet->getAngularConversionParameter(c)); - return string(answer); - - -} - - -string slsDetectorCommand::helpAngConv(int narg, char *args[], int action){ - - - int t=0xffff; - ostringstream os; - - if (string(args[0])==string("angconv")) { - t=1; - } else if (string(args[0])==string("globaloff")) { - t=2; - } else if (string(args[0])==string("fineoff")) { - t=4; - } else if (string(args[0])==string("binsize")) { - t=8; - } else if (string(args[0])==string("samplex")) { - t=16; - } else if (string(args[0])==string("sampley")) { - t=32; - } - if (t&1) { - if (action==GET_ACTION || action==HELP_ACTION) - os << string("angconv [fn]\t returns the constants used for angular conversion prints them to the file fn if specified \n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("angconv fn\t sets the angualr conversion constants (none unsets) \n"); - } if (t&2) { - if (action==GET_ACTION || action==HELP_ACTION) - os << string("globaloff\t returns the global offset used for angular conversion \n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("globaloff f\t sets the global offset used for the angular conversion \n"); - - - } if (t&4) { - if (action==GET_ACTION || action==HELP_ACTION) - os << string("fineoff\t returns the fine offset used for angular conversion \n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("fineoff f\t sets the fine offset used for the angular conversion \n"); - - - - } if (t&8) { - if (action==GET_ACTION || action==HELP_ACTION) - os << string("binsize\t returns the bin size used for the angular conversion \n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("binsize f\t sets the bin size used for the angular conversion \n"); - - } - if (t&16) { - if (action==GET_ACTION || action==HELP_ACTION) - os << string("samplex \t gets the sample displacement in th direction parallel to the beam \n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("samplex f\t sets the sample displacement in th direction parallel to the beam \n"); - } - if (t&32) { - if (action==GET_ACTION || action==HELP_ACTION) - os << string("sampley \t gets the sample displacement in the direction orthogonal to the beam \n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("sampley f\t sets the sample displacement in the direction orthogonal to the beam \n"); - } - - return os.str(); -} - - -string slsDetectorCommand::cmdThreaded(int narg, char *args[], int action){ - int ival; - char answer[1000]; - - if (action==HELP_ACTION) - return helpThreaded(narg,args,action); - - if (action==PUT_ACTION) { - if (sscanf(args[1],"%d",&ival)) - myDet->setThreadedProcessing(ival); - } - sprintf(answer,"%d",myDet->setThreadedProcessing()); - return string(answer); - -} - - -string slsDetectorCommand::helpThreaded(int narg, char *args[], int action){ - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) - os << string("threaded \t returns wether the data processing is threaded. \n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("threaded t \t sets the threading flag ( 1sets, 0 unsets).\n"); - - return os.str(); - -} - - -string slsDetectorCommand::cmdImage(int narg, char *args[], int action){ - string sval; - int retval = FAIL; - if (action==HELP_ACTION) - return helpImage(narg,args,HELP_ACTION); - else if (action==GET_ACTION) - return string("Cannot get"); - - sval=string(args[1]); - myDet->setOnline(ONLINE_FLAG); - - - if (string(args[0])==string("darkimage")) - retval=myDet->loadImageToDetector(DARK_IMAGE,sval); - else if (string(args[0])==string("gainimage")) - retval=myDet->loadImageToDetector(GAIN_IMAGE,sval); - - - if(retval==OK) - return string("Image loaded succesfully"); - else - return string("Image load failed"); -} - - -string slsDetectorCommand::helpImage(int narg, char *args[], int action){ - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION){ - os << "darkimage f \t loads the image to detector from file f"<< std::endl; - os << "gainimage f \t loads the image to detector from file f"<< std::endl; - } - if (action==GET_ACTION || action==HELP_ACTION){ - os << "darkimage \t Cannot get"<< std::endl; - os << "gainimage \t Cannot get"<< std::endl; - } - return os.str(); -} - - -string slsDetectorCommand::cmdCounter(int narg, char *args[], int action){ - int ival; - char answer[100]; - string sval; - int retval = FAIL; - if (action==HELP_ACTION) - return helpCounter(narg,args,HELP_ACTION); - else if (action==PUT_ACTION) - ival=atoi(args[1]); - - myDet->setOnline(ONLINE_FLAG); - - if (string(args[0])==string("readctr")){ - if (action==PUT_ACTION) - return string("Cannot put"); - else{ - if (narg<3) - return string("should specify I/O file"); - sval=string(args[2]); - retval=myDet->writeCounterBlockFile(sval,ival); - } - } - else if (string(args[0])==string("resetctr")){ - if (action==GET_ACTION) - return string("Cannot get"); - else - retval=myDet->resetCounterBlock(ival); - } - - else if (string(args[0])==string("resmat")){ - if (action==PUT_ACTION){ - if (!sscanf(args[1],"%d",&ival)) - return string("Could not scan resmat input ")+string(args[1]); - if(ival>=0) - sprintf(answer,"%d",myDet->setCounterBit(ival)); - }else - sprintf(answer,"%d",myDet->setCounterBit()); - return string(answer); - } - - if(retval==OK) - return string("Counter read/reset succesfully"); - else - return string("Counter read/reset failed"); -} - - -string slsDetectorCommand::helpCounter(int narg, char *args[], int action){ - ostringstream os; - os << std::endl; - if (action==PUT_ACTION || action==HELP_ACTION){ - os << "readctr \t Cannot put"<< std::endl; - os << "resetctr i \t resets counter in detector, restarts acquisition if i=1"<< std::endl; - os << "resmat i \t sets/resets counter bit in detector"<< std::endl; - } - if (action==GET_ACTION || action==HELP_ACTION){ - os << "readctr i fname\t reads counter in detector to file fname, restarts acquisition if i=1"<< std::endl; - os << "resetctr \t Cannot get"<< std::endl; - os << "resmat i \t gets the counter bit in detector"<< std::endl; - } - return os.str(); -} - - - - -string slsDetectorCommand::cmdPositions(int narg, char *args[], int action){ - int ival; - int ip; - - char answer[1000]; - - if (action==HELP_ACTION) return helpPositions(narg,args,action); - - if (action==PUT_ACTION) { - if (sscanf(args[1],"%d",&ival)) { - double pos[ival]; - for (ip=0; ipsetPositions(ip,pos); - } - } - int npos=myDet->getPositions(); - sprintf(answer,"%d",npos); - double opos[npos]; - myDet->getPositions(opos); - for (int ip=0; ipsetActionParameter(ia, args[1]); - } - return string(myDet->getActionParameter(ia)); - - } else { - - if (ia==enCalLog || ia==angCalLog) { - - - if (action==PUT_ACTION) { - - int arg=-1; - - - sscanf(args[1],"%d",&arg); - - if (arg==0) - myDet->setActionScript(ia,"none"); - else - myDet->setActionScript(ia,args[1]); - - } - - sprintf(answer,"%d",myDet->getActionMode(ia)); - return string(answer); - - } - - - if (action==PUT_ACTION) { - myDet->setActionScript(ia, args[1]); - } - return string(myDet->getActionScript(ia)); - - } - return string("could not decode command")+cmd; - - - - -} - -string slsDetectorCommand::helpScripts(int narg, char *args[], int action) { - - ostringstream os; - - if (narg>0) { - if ((string(args[0]).find("start")!=string::npos) || (string(args[0]).find("stop")!=string::npos) || (string(args[0]).find("scriptbefore")!=string::npos) || \ - (string(args[0]).find("scriptafter")!=string::npos) || (string(args[0]).find("headerafter")!=string::npos) || (string(args[0]).find("headerbefore")!=string::npos)) { - - - if (action==PUT_ACTION || action==HELP_ACTION) - os << args[0] << " script \t sets the script to execute for the corresponding action"<< std::endl; - if (action==GET_ACTION || action==HELP_ACTION) - os << args[0] << " \t returns the script to execute for the corresponding action"<< std::endl; - - } - - - if ((string(args[0]).find("encallog")!=string::npos) || (string(args[0]).find("angcallog")!=string::npos)) { - - - - if (action==PUT_ACTION || action==HELP_ACTION) - os << args[0] << " i \t enables (1) or disables (0) the logging for the calibration"<< std::endl; - if (action==GET_ACTION || action==HELP_ACTION) - os << args[0] << " \t returns the calibration log mode"<< std::endl; - } - } - return os.str(); - -} - -string slsDetectorCommand::cmdScans(int narg, char *args[], int action) { - - int is=-1, ival, ns=0; - char answer[MAX_SCAN_STEPS*10]; - double *values; - if (action==HELP_ACTION) - return helpScans(narg,args,action); - - - if (cmd.find("0")!=string::npos) is=0; - else if (cmd.find("1")!=string::npos) is=1; - else return string("cannot define scan level ")+cmd; - - if (cmd.find("par")!=string::npos) { - if (action==PUT_ACTION) { - myDet->setScanParameter(is, args[1]); - } - return myDet->getScanParameter(is); - } - if (cmd.find("script")!=string::npos) { - if (action==PUT_ACTION) { - myDet->setScanScript(is, args[1]); - } - return myDet->getScanScript(is); - } - if (cmd.find("prec")!=string::npos) { - if (action==PUT_ACTION) { - if (sscanf(args[1],"%d",&ival)) { - myDet->setScanPrecision(is, ival); - } else - return string("invalid precision ")+cmd; - } - sprintf(answer,"%d", myDet->getScanPrecision(is)); - return string(answer); - } - if (cmd.find("steps")!=string::npos) { - - if (action==PUT_ACTION) { - if (sscanf(args[1],"%d",&ival)) { - - if (ival>MAX_SCAN_STEPS) - return string("too many steps required!"); - - values=new double[ival]; - for (int i=0; i=(i+2)) { - if (sscanf(args[i+2],"%lf",values+i)) - ++ns; - else - break; - } else - break; - } - myDet->setScanSteps(is, ns, values); - delete [] values; - } else { - return string("invalid number of steps ")+string(args[1]); - } - } - ns=myDet->getScanSteps(is); - sprintf(answer,"%d ",ns); - if (ns>0) { - values=new double[ns]; - ns=myDet->getScanSteps(is, values); - int p=myDet->getScanPrecision(is); - char format[1000]; - sprintf(format, "%%s %%0.%df",p); - for (int i=0; iMAX_SCAN_STEPS) - return string("too many steps required!"); - - if (fmax>fmin) - if (fstep<0) - fstep=-1*fstep; - - if (fmax0) - fstep=-1*fstep; - - - values=new double[ns]; - for (int i=0; isetScanSteps(is, ns, values); - delete [] values; - } - - ns=myDet->getScanSteps(is); - values=new double[ns]; - ns=myDet->getScanSteps(is, values); - int p=myDet->getScanPrecision(is); - char format[1000]; - sprintf(format, "%%s %%0.%df",p); - sprintf(answer,"%d ",ns); - for (int i=0; isetOnline(ONLINE_FLAG); - myDet->setReceiverOnline(ONLINE_FLAG); - - if (cmd=="detectormac") { - t=DETECTOR_MAC; - } else if (cmd=="detectorip") { - t=DETECTOR_IP; - } else if (cmd=="rx_hostname") { - t=RECEIVER_HOSTNAME; - } else if (cmd=="rx_udpip") { - t=RECEIVER_UDP_IP; - } else if (cmd=="rx_udpmac") { - t=RECEIVER_UDP_MAC; - } else if (cmd=="rx_udpport") { - t=RECEIVER_UDP_PORT; - if (action==PUT_ACTION){ - if (!(sscanf(args[1],"%d",&i))) - return ("cannot parse argument") + string(args[1]); - } - } else if (cmd=="rx_udpport2") { - t=RECEIVER_UDP_PORT2; - if (action==PUT_ACTION){ - if (!(sscanf(args[1],"%d",&i))) - return ("cannot parse argument") + string(args[1]); - } - } else if (cmd=="rx_udpsocksize") { - t=RECEIVER_UDP_SCKT_BUF_SIZE; - if (action==PUT_ACTION){ - if (!(sscanf(args[1],"%d",&i))) - return ("cannot parse argument") + string(args[1]); - } - } else if (cmd=="rx_realudpsocksize") { - t=RECEIVER_REAL_UDP_SCKT_BUF_SIZE; - if (action==PUT_ACTION){ - return ("cannot put!"); - } - } else if (cmd=="txndelay_left") { - t=DETECTOR_TXN_DELAY_LEFT; - if (action==PUT_ACTION){ - if (!(sscanf(args[1],"%d",&i))) - return ("cannot parse argument") + string(args[1]); - } - } else if (cmd=="txndelay_right") { - t=DETECTOR_TXN_DELAY_RIGHT; - if (action==PUT_ACTION){ - if (!(sscanf(args[1],"%d",&i))) - return ("cannot parse argument") + string(args[1]); - } - } else if (cmd=="txndelay_frame") { - t=DETECTOR_TXN_DELAY_FRAME; - if (action==PUT_ACTION){ - if (!(sscanf(args[1],"%d",&i))) - return ("cannot parse argument") + string(args[1]); - } - } else if (cmd=="flowcontrol_10g") { - t=FLOW_CONTROL_10G; - if (action==PUT_ACTION){ - if (!(sscanf(args[1],"%d",&i))) - return ("cannot parse argument") + string(args[1]); - } - }else if (cmd=="zmqport") { - t=CLIENT_STREAMING_PORT; - if (action==PUT_ACTION){ - if (!(sscanf(args[1],"%d",&i))) - return ("cannot parse argument") + string(args[1]); - } - }else if (cmd=="rx_zmqport") { - t=RECEIVER_STREAMING_PORT; - if (action==PUT_ACTION){ - if (!(sscanf(args[1],"%d",&i))) - return ("cannot parse argument") + string(args[1]); - // if streaming, switch it off - prev_streaming = myDet->enableDataStreamingFromReceiver(); - if (prev_streaming) myDet->enableDataStreamingFromReceiver(0); - } - }else if (cmd=="zmqip") { - t=CLIENT_STREAMING_SRC_IP; - }else if (cmd=="rx_zmqip") { - t=RECEIVER_STREAMING_SRC_IP; - // if streaming, switch it off - prev_streaming = myDet->enableDataStreamingFromReceiver(); - if (prev_streaming) myDet->enableDataStreamingFromReceiver(0); - } else if (cmd=="rx_jsonaddheader") { - t=ADDITIONAL_JSON_HEADER; - } - else return ("unknown network parameter")+cmd; - if (action==PUT_ACTION) { - myDet->setNetworkParameter(t, args[1]); - // switch it back on, if it had been switched on - if (prev_streaming && (t == RECEIVER_STREAMING_PORT || t == RECEIVER_STREAMING_SRC_IP)) - myDet->enableDataStreamingFromReceiver(1); - - } - - return myDet->getNetworkParameter(t); -} - -string slsDetectorCommand::helpNetworkParameter(int narg, char *args[], int action) { - - - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "detectormac mac \n sets detector mac to mac"<< std::endl; - os << "detectorip ip \n sets detector ip to ip"<< std::endl; - os << "rx_hostname name \n sets receiver ip/hostname to name"<< std::endl; - os << "rx_udpip ip \n sets receiver udp ip to ip"<< std::endl; - os << "rx_udpmac mac \n sets receiver udp mac to mac"<< std::endl; - os << "rx_udpport port \n sets receiver udp port to port"<< std::endl; - os << "rx_udpport2 port \n sets receiver udp port to port. For Eiger, it is the second half module and for other detectors, same as rx_udpport"<< std::endl; - os << "txndelay_left port \n sets detector transmission delay of the left port"<< std::endl; - os << "txndelay_right port \n sets detector transmission delay of the right port"<< std::endl; - os << "txndelay_frame port \n sets detector transmission delay of the entire frame"<< std::endl; - os << "flowcontrol_10g port \n sets flow control for 10g for eiger"<< std::endl; - os << "zmqport port \n sets the 0MQ (TCP) port of the client to where final data is streamed to (eg. for GUI). The default already connects with rx_zmqport for the GUI. " - "Use single-detector command to set individually or multi-detector command to calculate based on port for the rest." - "Must restart streaming in client with new port from gui/external gui"<< std::endl; - os << "rx_zmqport port \n sets the 0MQ (TCP) port of the receiver from where data is streamed from (eg. to GUI or another process for further processing). " - "Use single-detector command to set individually or multi-detector command to calculate based on port for the rest." - "Restarts streaming in receiver with new port"<< std::endl; - os << "zmqip ip \n sets the 0MQ (TCP) ip of the client to where final data is streamed to (eg. for GUI). Default is ip of rx_hostname and works for GUI. " - "This is usually used to stream in from an external process." - "Must restart streaming in client with new port from gui/external gui. " << std::endl; - os << "rx_zmqip ip \n sets/gets the 0MQ (TCP) ip of the receiver from where data is streamed from (eg. to GUI or another process for further processing). " - "Default is ip of rx_hostname and works for GUI. This is usually used to stream out to an external process for further processing." - "restarts streaming in receiver with new port" << std::endl; - os << "rx_jsonaddheader [t]\n sets additional json header to be streamed " - "out with the zmq from receiver. Default is empty. t must be in the format '\"label1\":\"value1\",\"label2\":\"value2\"' etc." - "Use only if it needs to be processed by an intermediate process." << std::endl; - os << "rx_udpsocksize [t]\n sets the UDP socket buffer size. Different defaults for Jungfrau. " - "Does not remember in client shared memory, " - "so must be initialized each time after setting receiver " - "hostname in config file." << std::endl; - } - if (action==GET_ACTION || action==HELP_ACTION) { - os << "detectormac \n gets detector mac "<< std::endl; - os << "detectorip \n gets detector ip "<< std::endl; - os << "rx_hostname \n gets receiver ip "<< std::endl; - os << "rx_udpmac \n gets receiver udp mac "<< std::endl; - os << "rx_udpport \n gets receiver udp port "<< std::endl; - os << "rx_udpport2 \n gets receiver udp port. For Eiger, it is the second half module and for other detectors, same as rx_udpport"<< std::endl; - os << "txndelay_left \n gets detector transmission delay of the left port"<< std::endl; - os << "txndelay_right \n gets detector transmission delay of the right port"<< std::endl; - os << "txndelay_frame \n gets detector transmission delay of the entire frame"<< std::endl; - os << "flowcontrol_10g \n gets flow control for 10g for eiger"<< std::endl; - os << "zmqport \n gets the 0MQ (TCP) port of the client to where final data is streamed to"<< std::endl; - os << "rx_zmqport \n gets the 0MQ (TCP) port of the receiver from where data is streamed from"<< std::endl; - os << "zmqip \n gets the 0MQ (TCP) ip of the client to where final data is streamed to.If no custom ip, empty until first time connect to receiver" << std::endl; - os << "rx_zmqip \n gets/gets the 0MQ (TCP) ip of the receiver from where data is streamed from. If no custom ip, empty until first time connect to receiver" << std::endl; - os << "rx_jsonaddheader \n gets additional json header to be streamed " - "out with the zmq from receiver." << std::endl; - os << "rx_udpsocksize \n gets the UDP socket buffer size." << std::endl; - os << "rx_realudpsocksize \n gets the actual UDP socket buffer size. Usually double the set udp socket buffer size due to kernel bookkeeping." << std::endl; - - } - return os.str(); - - -} - -string slsDetectorCommand::cmdPort(int narg, char *args[], int action) { - - if (action==HELP_ACTION) - return helpPort(narg,args,action); - int val; //ret, - char ans[1000]; - portType index; - - if (action==PUT_ACTION) { - if (sscanf(args[1],"%d",&val)) - ; - else - return string("could not scan port number")+string(args[1]); - } - - if (cmd=="port") { - index=CONTROL_PORT; - } else if (cmd=="rx_tcpport") { - index=DATA_PORT; - } else if (cmd=="stopport") { - index=STOP_PORT; - } else - return string("unknown port type ")+cmd; - - myDet->setOnline(ONLINE_FLAG); - if (action==PUT_ACTION) - myDet->setPort(index,val); - - sprintf(ans,"%d",myDet->setPort(index)); - return string(ans); - -} - - - -string slsDetectorCommand::helpPort(int narg, char *args[], int action) { - - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "port i \n sets the communication control port"<< std::endl; - os << "rx_tcpport i \n sets the communication receiver port"<< std::endl; - os << "stopport i \n sets the communication stop port "<< std::endl; - - } - if (action==GET_ACTION || action==HELP_ACTION) { - os << "port \n gets the communication control port"<< std::endl; - os << "rx_tcpport \n gets the communication receiver port"<< std::endl; - os << "stopport \n gets the communication stop port "<< std::endl; - } - return os.str(); - - -} - - -string slsDetectorCommand::cmdLock(int narg, char *args[], int action) { - - if (action==HELP_ACTION) - return helpLock(narg,args,action); - - int val;//, ret; - char ans[1000]; - - if(cmd=="lock"){ - myDet->setOnline(ONLINE_FLAG); - if (action==PUT_ACTION) { - if (sscanf(args[1],"%d",&val)) - myDet->lockServer(val); - else - return string("could not lock status")+string(args[1]); - } - - sprintf(ans,"%d",myDet->lockServer()); - } - - - else if(cmd=="r_lock"){ - myDet->setReceiverOnline(ONLINE_FLAG); - if (action==PUT_ACTION) { - if (sscanf(args[1],"%d",&val)) - myDet->lockReceiver(val); - else - return string("could not decode lock status")+string(args[1]); - } - sprintf(ans,"%d",myDet->lockReceiver()); - } - - - else - return string("could not decode command"); - - return string(ans); -} - - - -string slsDetectorCommand::helpLock(int narg, char *args[], int action) { - - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "lock i \n locks (1) or unlocks (0) the detector to communicate to this client"<< std::endl; - os << "r_lock i \n locks (1) or unlocks (0) the receiver to communicate to this client"<< std::endl; - } - if (action==GET_ACTION || action==HELP_ACTION) { - os << "lock \n returns the detector lock status"<< std::endl; - os << "r_lock \n returns the receiver lock status"<< std::endl; - } - return os.str(); - - -} - - -string slsDetectorCommand::cmdLastClient(int narg, char *args[], int action) { - - if (action==HELP_ACTION) - return helpLastClient(narg,args,action); - - if (action==PUT_ACTION) - return string("cannot set"); - - - if(cmd=="lastclient"){ - myDet->setOnline(ONLINE_FLAG); - return myDet->getLastClientIP(); - } - - else if(cmd=="r_lastclient"){ - myDet->setReceiverOnline(ONLINE_FLAG); - return myDet->getReceiverLastClientIP(); - } - - return string("cannot decode command"); -} - -string slsDetectorCommand::helpLastClient(int narg, char *args[], int action) { - - - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) { - os << "lastclient \n returns the last client communicating with the detector"<< std::endl; - os << "r_lastclient \n returns the last client communicating with the receiver"<< std::endl; - } - return os.str(); - -} - - -string slsDetectorCommand::cmdOnline(int narg, char *args[], int action) { - - if (action==HELP_ACTION) { - return helpOnline(narg,args,action); - } - int ival; - char ans[1000]; - - if(cmd=="online"){ - if (action==PUT_ACTION) { - if (sscanf(args[1],"%d",&ival)) - myDet->setOnline(ival); - else - return string("Could not scan online mode ")+string(args[1]); - } - sprintf(ans,"%d",myDet->setOnline()); - } - else if(cmd=="checkonline"){ - if (action==PUT_ACTION) - return string("cannot set"); - strcpy(ans,myDet->checkOnline().c_str()); - if(!strlen(ans)) - strcpy(ans,"All online"); - else - strcat(ans," :Not online"); - } - else if(cmd=="activate"){ - myDet->setOnline(ONLINE_FLAG); - myDet->setReceiverOnline(ONLINE_FLAG); - if (action==PUT_ACTION) { - if (!sscanf(args[1],"%d",&ival)) - return string("Could not scan activate mode ")+string(args[1]); - myDet->activate(ival); - bool padding = true; - if (narg > 2) { - if (string(args[2]) == "padding") - padding = true; - else if (string(args[2]) == "nopadding") - padding = false; - else - return string ("Could not scan activate mode's padding option " + string(args[2])); - myDet->setDeactivatedRxrPaddingMode(padding); - } - } - int ret = myDet->setDeactivatedRxrPaddingMode(); - sprintf(ans,"%d %s", myDet->activate(), ret == 1 ? "padding" : (ret == 0 ? "nopadding" : "unknown")); - } - else if(cmd=="r_online"){ - if (action==PUT_ACTION) { - if (sscanf(args[1],"%d",&ival)) - myDet->setReceiverOnline(ival); - else - return string("Could not scan online mode ")+string(args[1]); - } - sprintf(ans,"%d",myDet->setReceiverOnline()); - } - else{ - if (action==PUT_ACTION) - return string("cannot set"); - myDet->setReceiverOnline(ONLINE_FLAG); - strcpy(ans,myDet->checkReceiverOnline().c_str()); - if(!strlen(ans)) - strcpy(ans,"All receiver online"); - else - strcat(ans," :Not all receiver online"); - } - - return ans; -} - -string slsDetectorCommand::helpOnline(int narg, char *args[], int action) { - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "online i \n sets the detector in online (1) or offline (0) mode"<< std::endl; - os << "r_online i \n sets the receiver in online (1) or offline (0) mode"<< std::endl; - os << "activate i [p]\n sets the detector in activated (1) or deactivated (0) mode (does not send data). p is optional and can be padding (default) or nonpadding for receivers for deactivated detectors. Only for Eiger."<< std::endl; - } - if (action==GET_ACTION || action==HELP_ACTION) { - os << "online \n gets the detector online (1) or offline (0) mode"<< std::endl; - os << "checkonline \n returns the hostnames of all detectors in offline mode"<< std::endl; - os << "r_online \n gets the receiver online (1) or offline (0) mode"<< std::endl; - os << "r_checkonline \n returns the hostnames of all receiver in offline mode"<< std::endl; - os << "activate \n gets the detector activated (1) or deactivated (0) mode. And padding or nonpadding for the deactivated receiver. Only for Eiger."<< std::endl; - } - return os.str(); - - -} - - - - -string slsDetectorCommand::cmdConfigureMac(int narg, char *args[], int action) { - - if (action==HELP_ACTION) { - return helpConfigureMac(narg,args,action); - } - int ret; - char ans[1000]; - - if (action==PUT_ACTION){ - myDet->setOnline(ONLINE_FLAG); - myDet->setReceiverOnline(ONLINE_FLAG); - ret=myDet->configureMAC(); - } - else - return string("Cannot get ")+cmd; - - sprintf(ans,"%d",ret); - return ans; -} - -string slsDetectorCommand::helpConfigureMac(int narg, char *args[], int action) { - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) - os << "configuremac i \n configures the MAC of the detector."<< std::endl; - if (action==GET_ACTION || action==HELP_ACTION) - os << "configuremac " << "Cannot get " << std::endl; - - return os.str(); -} - - -string slsDetectorCommand::cmdDetectorSize(int narg, char *args[], int action) { - - if (action==HELP_ACTION) - return helpDetectorSize(narg,args,action); - int ret, val=-1, pos=-1,i; - char ans[1000]; - - myDet->setOnline(ONLINE_FLAG); - - if (cmd == "roi") - myDet->setReceiverOnline(ONLINE_FLAG); - - if (action==PUT_ACTION) { - if (cmd=="maxmod") - return string("cannot put!"); - else if (cmd=="roimask"){ - if (!sscanf(args[1],"%d",&val)) - return string("could not scan ")+string(args[0])+string(" ")+string(args[1]); - } - else if (!sscanf(args[1],"%d",&val)) - return string("could not scan ")+string(args[0])+string(" ")+string(args[1]); - - if (cmd=="roi"){ - //debug number of arguments - if ((val<0) || (narg!=((val*4)+2)) ) - return helpDetectorSize(narg,args,action); - ROI allroi[val]; - // pos=1; - pos=2; - for(i=0;isetROI(val,allroi); - } - - if(cmd=="detsizechan"){ - if ((sscanf(args[1],"%d",&val)) && (val>0)) - myDet->setMaxNumberOfChannelsPerDetector(X,val); - if ((narg > 2) && (sscanf(args[2],"%d",&val)) && (val>0)) - myDet->setMaxNumberOfChannelsPerDetector(Y,val); - } - - if(cmd=="flippeddatax"){ - if ((!sscanf(args[1],"%d",&val)) || (val!=0 && val != 1)) - return string ("cannot scan flippeddata x mode: must be 0 or 1"); - myDet->setReceiverOnline(ONLINE_FLAG); - myDet->setFlippedData(X,val); - } - - if(cmd=="flippeddatay"){ - return string("Not required for this detector\n"); - if ((!sscanf(args[1],"%d",&val)) || (val!=0 && val != 1)) - return string ("cannot scan flippeddata y mode: must be 0 or 1"); - myDet->setReceiverOnline(ONLINE_FLAG); - myDet->setFlippedData(Y,val); - } - - if(cmd=="gappixels"){ - if ((!sscanf(args[1],"%d",&val)) || (val!=0 && val != 1)) - return string ("cannot scan gappixels mode: must be 0 or 1"); - myDet->setReceiverOnline(ONLINE_FLAG); - if (myDet->isMultiSlsDetectorClass()) // only in multi detector level to update offsets etc. - myDet->enableGapPixels(val); - } - - } - - if (cmd=="nmod" || cmd=="roimask") { - ret=myDet->setNumberOfModules(val); - } else if (cmd=="maxmod") { - ret=myDet->getMaxNumberOfModules(); - } else if (cmd=="dr") { - myDet->setReceiverOnline(ONLINE_FLAG); - ret=myDet->setDynamicRange(val); - } else if (cmd=="roi") { - ROI* r = myDet->getROI(ret); - if (myDet->isMultiSlsDetectorClass() && r != NULL) - delete [] r; - } else if (cmd=="detsizechan") { - sprintf(ans,"%d %d",myDet->getMaxNumberOfChannelsPerDetector(X),myDet->getMaxNumberOfChannelsPerDetector(Y)); - return string(ans); - } - else if(cmd=="flippeddatax"){ - myDet->setReceiverOnline(ONLINE_FLAG); - ret = myDet->getFlippedData(X); - } - else if(cmd=="flippeddatay"){ - return string("Not required for this detector\n"); - myDet->setReceiverOnline(ONLINE_FLAG); - ret = myDet->getFlippedData(Y); - } - else if(cmd=="gappixels"){ - myDet->setReceiverOnline(ONLINE_FLAG); - if (!myDet->isMultiSlsDetectorClass()) // only in multi detector level to update offsets etc. - return string("Cannot execute this command from slsDetector level. Please use multiSlsDetector level.\n"); - ret = myDet->enableGapPixels(); - } - - else - return string("unknown command ")+cmd; - - if (cmd=="roimask") - sprintf(ans,"0x%x",ret); - else - sprintf(ans,"%d",ret); - - return string(ans); - -} - - -string slsDetectorCommand::helpDetectorSize(int narg, char *args[], int action) { - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "nmod i \n sets the number of modules of the detector"<< std::endl; - os << "dr i \n sets the dynamic range of the detector"<< std::endl; - os << "roi i xmin xmax ymin ymax \n sets region of interest where i is number of rois;i=0 to clear rois"<< std::endl; - os << "detsizechan x y \n sets the maximum number of channels for complete detector set in both directions; -1 is no limit"<< std::endl; - os << "flippeddatax x \n sets if the data should be flipped on the x axis"<< std::endl; - os << "flippeddatay y \n sets if the data should be flipped on the y axis"<< std::endl; - os << "gappixels i \n enables/disables gap pixels in system (detector & receiver). 1 sets, 0 unsets. Used in EIGER only and multidetector level." << std::endl; - } - if (action==GET_ACTION || action==HELP_ACTION) { - os << "nmod \n gets the number of modules of the detector"<< std::endl; - os << "maxmod \n gets the maximum number of modules of the detector"<< std::endl; - os << "dr \n gets the dynamic range of the detector"<< std::endl; - os << "roi \n gets region of interest"<< std::endl; - os << "detsizechan \n gets the maximum number of channels for complete detector set in both directions; -1 is no limit"<< std::endl; - os << "flippeddatax\n gets if the data will be flipped on the x axis"<< std::endl; - os << "flippeddatay\n gets if the data will be flipped on the y axis"<< std::endl; - os << "gappixels\n gets if gap pixels is enabled in system. Used in EIGER only and multidetector level." << std::endl; - } - return os.str(); - - -} - - - -string slsDetectorCommand::cmdSettings(int narg, char *args[], int action) { - - if (action==HELP_ACTION) - return helpSettings(narg,args,action); - int val=-1;//ret, - char ans[1000]; - - - // portType index; - // if (sscanf(args[1],"%d",&val)) - // ; - // else - // return string("could not scan port number")+string(args[1]); - // } - - myDet->setOnline(ONLINE_FLAG); - - if (cmd=="settings") { - detectorSettings sett = GET_SETTINGS; - if (action==PUT_ACTION) { - sett = myDet->getDetectorSettings(string(args[1])); - if (sett == -1) - return string ("unknown settings scanned " + string(args[1])); - sett = myDet->setSettings(sett); - if (myDet->getDetectorsType() == EIGER) { - return myDet->getDetectorSettings(sett); - } - } - return myDet->getDetectorSettings(myDet->getSettings()); - } else if (cmd=="threshold") { - if (action==PUT_ACTION) { - if (!sscanf(args[1],"%d",&val)) { - return string("invalid threshold value"); - } - detectorType type = myDet->getDetectorsType(); - if (type != EIGER || (type == EIGER && narg<=2)) { - myDet->setThresholdEnergy(val); - } else { - detectorSettings sett= myDet->getDetectorSettings(string(args[2])); - if(sett == -1) - return string("invalid settings value"); - myDet->setThresholdEnergy(val, -1, sett); - } - } - sprintf(ans,"%d",myDet->getThresholdEnergy()); - return string(ans); - } else if (cmd=="thresholdnotb") { - if (action==PUT_ACTION) { - if (!sscanf(args[1],"%d",&val)) { - return string("invalid threshold value"); - } - detectorType type = myDet->getDetectorsType(); - if (type != EIGER) - return string("not implemented for this detector"); - if (narg<=2) { - myDet->setThresholdEnergy(val, -1, GET_SETTINGS, 0); - } else { - detectorSettings sett= myDet->getDetectorSettings(string(args[2])); - if(sett == -1) - return string("invalid settings value"); - myDet->setThresholdEnergy(val, -1, sett, 0); - } - } - sprintf(ans,"%d",myDet->getThresholdEnergy()); - return string(ans); - } else if (cmd=="trimbits") { - if (narg>=2) { - string sval=string(args[1]); -#ifdef VERBOSE - std::cout<< " trimfile " << sval << std::endl; -#endif - int ret = OK; - if (action==GET_ACTION) { - //create file names - ret = myDet->saveSettingsFile(sval, -1); - } else if (action==PUT_ACTION) { - ret = myDet->loadSettingsFile(sval,-1); - } - if (ret == OK) - return sval; - else return string("not successful"); - } - return myDet->getSettingsFile(); - } else if (cmd=="trim") { - if (action==GET_ACTION) - return string("cannot get!"); - - trimMode mode=NOISE_TRIMMING; - int par1=0, par2=0; - if (string(args[0]).find("trim:")==string::npos) - return helpSettings(narg,args,action); - else if (string(args[0]).find("noise")!=string::npos) { - // par1 is countlim; par2 is nsigma - mode=NOISE_TRIMMING; - par1=500; - par2=4; - } else if (string(args[0]).find("beam")!=string::npos){ - // par1 is countlim; par2 is nsigma - mode=BEAM_TRIMMING; - par1=1000; - par2=4; - } else if (string(args[0]).find("improve")!=string::npos) { - // par1 is maxit; if par2!=0 vthresh will be optimized - mode=IMPROVE_TRIMMING; - par1=5; - par2=0; - } else if (string(args[0]).find("fix")!=string::npos) { - // par1 is countlim; if par2<0 then trimwithlevel else trim with median - mode=FIXEDSETTINGS_TRIMMING; - par1=1000; - par2=1; - // }else if (string(args[0]).find("fix")!=string::npos) { - //mode=OFFLINE_TRIMMING; - } else { - return string("Unknown trim mode ")+cmd; - } - myDet->executeTrimming(mode, par1, par2); - string sval=string(args[1]); - myDet->saveSettingsFile(sval, -1); - return string("done"); - - } else if (cmd=="trimval") { - if (action==PUT_ACTION){ - if (sscanf(args[1],"%d",&val)) - myDet->setAllTrimbits(val); - else - return string("invalid trimbit value ")+cmd; - } - sprintf(ans,"%d",myDet->setAllTrimbits(-1)); - return ans; - } else if (cmd=="pedestal") { - if (action==GET_ACTION) - return string("cannot get"); - if (sscanf(args[1],"%d",&val)){ - sprintf(ans,"%d",myDet->calibratePedestal(val)); - return string(ans); - }else - return string("cannot parse frame number")+cmd; - - } - return string("unknown settings command ")+cmd; - -} - - -string slsDetectorCommand::helpSettings(int narg, char *args[], int action) { - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "settings s \n sets the settings of the detector - can be standard, fast, highgain, dynamicgain, lowgain, mediumgain, veryhighgain" - "lownoise, dynamichg0,fixgain1,fixgain2,forceswitchg1, forceswitchg2"<< std::endl; - os << "threshold eV [sett]\n sets the detector threshold in eV. If sett is provided for eiger, uses settings sett"<< std::endl; - os << "thresholdnotb eV [sett]\n sets the detector threshold in eV without loading trimbits. If sett is provided for eiger, uses settings sett"<< std::endl; - os << "trimbits fname\n loads the trimfile fname to the detector. If no extension is specified, the serial number of each module will be attached."<< std::endl; - os << "trim:mode fname\n trims the detector according to mode (can be noise, beam, improve, fix) and saves the resulting trimbits to file fname."<< std::endl; - os << "trimval i \n sets all the trimbits to i" << std::endl; - os << "pedestal i \n starts acquisition for i frames, calculates pedestal and writes back to fpga."<< std::endl; - - } - if (action==GET_ACTION || action==HELP_ACTION) { - os << "settings \n gets the settings of the detector"<< std::endl; - os << "threshold V\n gets the detector threshold"<< std::endl; - os << "thresholdnotb V\n gets the detector threshold"<< std::endl; - os << "trimbits [fname]\n returns the trimfile loaded on the detector. If fname is specified the trimbits are saved to file. If no extension is specified, the serial number of each module will be attached."<< std::endl; - os << "trimval \n returns the value all trimbits are set to. If they are different, returns -1." << std::endl; - } - return os.str(); - - -} - - - - - - - - - - -string slsDetectorCommand::cmdSN(int narg, char *args[], int action) { - - char answer[1000]; - - - if (action==PUT_ACTION) - return string("cannot set"); - - - if (action==HELP_ACTION) - return helpSN(narg, args, action); - - - if (cmd=="thisversion"){ - int64_t retval = myDet->getId(THIS_SOFTWARE_VERSION); - if (retval < 0) - sprintf(answer, "%d", -1); - else - sprintf(answer,"0x%lx", retval); - return string(answer); - } - - myDet->setOnline(ONLINE_FLAG); - - - if (cmd=="moduleversion") { - int ival=-1; - if (sscanf(args[0],"moduleversion:%d",&ival)) { - int64_t retval = myDet->getId(MODULE_FIRMWARE_VERSION, ival); - if (retval < 0) - sprintf(answer, "%d", -1); - else - sprintf(answer,"0x%lx", retval); - return string(answer); - } else - return string("undefined module number"); - } - if (cmd=="detectornumber") { - int64_t retval = myDet->getId(DETECTOR_SERIAL_NUMBER); - if (retval < 0) - sprintf(answer, "%d", -1); - else - sprintf(answer,"0x%lx", retval); - return string(answer); - } - if (cmd.find("modulenumber")!=string::npos) { - int ival=-1; - if (sscanf(args[0],"modulenumber:%d",&ival)) { - int64_t retval = myDet->getId(MODULE_SERIAL_NUMBER, ival); - if (retval < 0) - sprintf(answer, "%d", -1); - else - sprintf(answer,"0x%lx", retval); - return string(answer); - } else - return string("undefined module number"); - } - - if (cmd=="detectorversion") { - int64_t retval = myDet->getId(DETECTOR_FIRMWARE_VERSION); - if (retval < 0) - sprintf(answer, "%d", -1); - else - sprintf(answer,"0x%lx", retval); - return string(answer); - } - - if (cmd=="softwareversion") { - int64_t retval = myDet->getId(DETECTOR_SOFTWARE_VERSION); - if (retval < 0) - sprintf(answer, "%d", -1); - else - sprintf(answer,"0x%lx", retval); - return string(answer); - } - - if (cmd=="receiverversion") { - myDet->setReceiverOnline(ONLINE_FLAG); - int64_t retval = myDet->getId(RECEIVER_VERSION); - if (retval < 0) - sprintf(answer, "%d", -1); - else - sprintf(answer,"0x%lx", retval); - return string(answer); - } - - if (cmd=="checkdetversion") { - int retval = myDet->checkVersionCompatibility(CONTROL_PORT); - if (retval < 0) - sprintf(answer, "%d", -1); - sprintf(answer,"%s", retval == OK ? "compatible" : "incompatible"); - return string(answer); - } - - if (cmd=="checkrecversion") { - myDet->setReceiverOnline(ONLINE_FLAG); - int retval = myDet->checkVersionCompatibility(DATA_PORT); - if (retval < 0) - sprintf(answer, "%d", -1); - sprintf(answer,"%s", retval == OK ? "compatible" : "incompatible"); - return string(answer); - } - - return string("unknown id mode ")+cmd; - -} - -string slsDetectorCommand::helpSN(int narg, char *args[], int action) { - - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) { - os << "checkdetversion \n gets the version compatibility with detector server (if hostname is in shared memory). Only for Eiger, Jungfrau & Gotthard. Prints compatible/ incompatible."<< std::endl; - os << "checkrecversion \n gets the version compatibility with receiver server (if rx_hostname is in shared memory). Only for Eiger, Jungfrau & Gotthard. Prints compatible/ incompatible."<< std::endl; - os << "moduleversion:i \n gets the firmwareversion of the module i"<< std::endl; - os << "modulenumber:i \n gets the serial number of the module i"<< std::endl; - os << "detectornumber \n gets the serial number of the detector (MAC)"<< std::endl; - os << "detectorversion \n gets the firmware version of the detector"<< std::endl; - os << "softwareversion \n gets the software version of the detector"<< std::endl; - os << "thisversion \n gets the version of this software"<< std::endl; - os << "receiverversion \n gets the version of the receiver"<< std::endl; - } - return os.str(); - - - -} - - -string slsDetectorCommand::cmdDigiTest(int narg, char *args[], int action) { - - char answer[1000]; - - if (action==HELP_ACTION) - return helpSN(narg, args, action); - - - myDet->setOnline(ONLINE_FLAG); - - if (cmd=="bustest"){ - if (action==PUT_ACTION) - return string("cannot set ")+cmd; - sprintf(answer,"0x%x",myDet->digitalTest(DETECTOR_BUS_TEST)); - return string(answer); - } - - if (cmd=="digitest") { - if (action==PUT_ACTION) - return string("cannot set ")+cmd; - int ival=-1; - if (sscanf(args[0],"digitest:%d",&ival)) { - sprintf(answer,"0x%x",myDet->digitalTest(CHIP_TEST, ival)); - return string(answer); - } else - return string("undefined module number"); - } - - if (cmd=="digibittest") { - if (action==GET_ACTION) - return string("cannot get ")+cmd; - int ival=-1; - if (sscanf(args[1],"%d",&ival)) { - if((ival==0)||(ival==1)){ - sprintf(answer,"0x%x",myDet->digitalTest(DIGITAL_BIT_TEST,ival)); - return string(answer); - } - else - return string("Use only 0 or 1 to set/clear digital test bit\n"); - } else - return string("undefined number"); - } - - - return string("unknown digital test mode ")+cmd; - -} - -string slsDetectorCommand::helpDigiTest(int narg, char *args[], int action) { - - - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) { - os << "digitaltest:i \t performs digital test of the module i. Returns 0 if succeeded, otherwise error mask."<< std::endl; - os << "bustest \t performs test of the bus interface between FPGA and embedded Linux system. Can last up to a few minutes."<< std::endl; - } - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "digibittest i\t will perform test which will plot the unique channel identifier, instead of data."<< std::endl; - } - return os.str(); -} - -string slsDetectorCommand::cmdRegister(int narg, char *args[], int action) { - - - if (action==HELP_ACTION) - return helpRegister(narg, args, action); - - int addr, val,n; - char answer[1000]; - - myDet->setOnline(ONLINE_FLAG); - - - // "reg" // - - // "setbit" // - - // "clearbit" // - - // "getbit" // - - - - if (action==PUT_ACTION) { - if (cmd=="getbit") - return string("Cannot put"); - - if(narg<3) { - if (cmd=="reg") - return string("wrong usage: should specify both address and value (hexadecimal fomat) "); - else - return string("wrong usage: should specify both address (hexadecimal fomat) and bit number"); - - } - - if (sscanf(args[1],"%x",&addr)) - ; - else - return string("Could not scan address (hexadecimal fomat) ")+string(args[1]); - - - if (cmd=="reg") { - if (sscanf(args[2],"%x",&val)) - ; - else - return string("Could not scan value (hexadecimal fomat) ")+string(args[2]); - sprintf(answer,"0x%x",myDet->writeRegister(addr,val)); - } else if (cmd=="adcreg") { - if (sscanf(args[2],"%x",&val)) - ; - else - return string("Could not scan value (hexadecimal fomat) ")+string(args[2]); - sprintf(answer,"0x%x",myDet->writeAdcRegister(addr,val)); - } else { - - if (sscanf(args[2],"%d",&n)) - ; - else - return string("Could not scan bit number ")+string(args[2]); - - if (n<0 || n>31) - return string("Bit number out of range")+string(args[2]); - - if (cmd=="setbit") - sprintf(answer,"0x%x",myDet->setBit(addr,n)); - if (cmd=="clearbit") - sprintf(answer,"0x%x",myDet->clearBit(addr,n)); - } - - - } else { - if (cmd=="setbit") - return string("Cannot get"); - if (cmd=="clearbit") - return string("Cannot get"); - if (cmd=="adcreg") - return string("Cannot get"); - - if (cmd=="reg") { - if (narg<2) - return string("wrong usage: should specify address (hexadecimal fomat) "); - if (sscanf(args[1],"%x",&addr)) - ; - else - return string("Could not scan address (hexadecimal fomat) ")+string(args[1]); - - - sprintf(answer,"0x%x",myDet->readRegister(addr)); - - } - - if (cmd=="getbit") { - - if(narg<3) - return string("wrong usage: should specify both address (hexadecimal fomat) and bit number"); - - - if (sscanf(args[1],"%x",&addr)) - ; - else - return string("Could not scan address (hexadecimal fomat) ")+string(args[1]); - - if (sscanf(args[2],"%d",&n)) - ; - else - return string("Could not scan bit number ")+string(args[2]); - - if (n<0 || n>31) - return string("Bit number out of range")+string(args[2]); - - - sprintf(answer,"%d",(myDet->readRegister(addr) >> n) & 1); - } - } - - return string(answer); - - -} - -string slsDetectorCommand::helpRegister(int narg, char *args[], int action) { - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "reg addr val \n writes the register addr with the value val (hexadecimal format)"<< std::endl; - } - if (action==GET_ACTION || action==HELP_ACTION) { - os << "reg addr \n reads the register addr"<< std::endl; - } - return os.str(); - - - -} - - -string slsDetectorCommand::cmdDAC(int narg, char *args[], int action) { - - if (action==HELP_ACTION) - return helpDAC(narg, args, action); - - dacIndex dac; - dacs_t val=-1; - char answer[1000]; - int mode=0; - - int idac=-1; - if (sscanf(args[0],"dac:%d",&idac)==1) { - //printf("chiptestboard!\n"); - dac=(dacIndex)idac; - } - else if (cmd=="adcvpp") - dac=ADC_VPP; - else if (cmd=="vthreshold") - dac=THRESHOLD; - else if (cmd=="vcalibration") - dac=CALIBRATION_PULSE; - else if (cmd=="vtrimbit") - dac=TRIMBIT_SIZE; - else if (cmd=="vpreamp") - dac=PREAMP; - else if (cmd=="vshaper1") - dac=SHAPER1; - else if (cmd=="vshaper2") - dac=SHAPER2; - else if (cmd=="vhighvoltage") - dac=HV_NEW; - else if (cmd=="vapower") - dac=VA_POT; - else if (cmd=="vddpower") - dac=VDD_POT; - else if (cmd=="vshpower") - dac=VSH_POT; - else if (cmd=="viopower") - dac=VIO_POT; - else if (cmd=="vref_ds") - dac=G_VREF_DS; - else if (cmd=="vcascn_pb") - dac=G_VCASCN_PB; - else if (cmd=="vcascp_pb") - dac=G_VCASCP_PB; - else if (cmd=="vout_cm") - dac=G_VOUT_CM; - else if (cmd=="vcasc_out") - dac=G_VCASC_OUT; - else if (cmd=="vin_cm") - dac=G_VIN_CM; - else if (cmd=="vref_comp") - dac=G_VREF_COMP; - else if (cmd=="ib_test_c") - dac=G_IB_TESTC; - - else if (cmd=="dac0") - dac=V_DAC0; - else if (cmd=="dac1") - dac=V_DAC1; - else if (cmd=="dac2") - dac=V_DAC2; - else if (cmd=="dac3") - dac=V_DAC3; - else if (cmd=="dac4") - dac=V_DAC4; - else if (cmd=="dac5") - dac=V_DAC5; - else if (cmd=="dac6") - dac=V_DAC6; - else if (cmd=="dac7") - dac=V_DAC7; - - - - - else if (cmd== "vsvp") - dac=E_SvP; - else if (cmd=="vsvn") - dac=E_SvN; - else if (cmd=="vtr") - dac=E_Vtr; - else if (cmd=="vrf") - dac=E_Vrf; - else if (cmd=="vrs") - dac=E_Vrs; - else if (cmd== "vtgstv") - dac=E_Vtgstv; - else if (cmd== "vcmp_ll") - dac=E_Vcmp_ll; - else if (cmd=="vcmp_lr") - dac=E_Vcmp_lr; - else if (cmd== "vcall") - dac=E_cal; - else if (cmd== "vcmp_rl") - dac=E_Vcmp_rl; - else if (cmd== "vcmp_rr") - dac=E_Vcmp_rr; - else if (cmd== "rxb_rb") - dac=E_rxb_rb; - else if (cmd== "rxb_lb") - dac=E_rxb_lb; - else if (cmd== "vcp") - dac=E_Vcp; - else if (cmd=="vcn") - dac=E_Vcn; - else if (cmd== "vis") - dac=E_Vis; - else if (cmd== "iodelay") - dac=IO_DELAY; - else if (cmd== "v_a") - dac=V_POWER_A; - else if (cmd== "v_b") - dac=V_POWER_B; - else if (cmd== "v_c") - dac=V_POWER_C; - else if (cmd== "v_d") - dac=V_POWER_D; - else if (cmd== "v_io") - dac=V_POWER_IO; - else if (cmd== "v_chip") - dac=V_POWER_CHIP; - else if (cmd== "v_limit") - dac=V_LIMIT; - else if (cmd== "vIpre") - dac=M_vIpre; - else if (cmd== "vIbias") - dac=M_vIbias; - else if (cmd== "vIinSh") - dac=M_vIinSh; - else if (cmd== "VcdSh") - dac=M_VdcSh; - else if (cmd== "Vth1") - dac=THRESHOLD; - else if (cmd== "Vth2") - dac=M_Vth2; - else if (cmd== "Vth3") - dac=M_Vth3; - else if (cmd== "VPL") - dac=M_VPL; - else if (cmd== "Vtrim") - dac=TRIMBIT_SIZE; - else if (cmd== "casSh") - dac=M_casSh; - else if (cmd== "cas") - dac=M_cas; - else if (cmd== "vIcin") - dac=M_vIcin; - else if (cmd== "vIbiasSh") - dac=M_vIbiasSh; - else if (cmd== "vIpreOut") - dac=M_vIpreOut; - else if (cmd== "emin") - dac=ZMQ_emin; - else if (cmd== "emax") - dac=ZMQ_emax; - - else - return string("cannot decode dac ")+cmd; - - myDet->setOnline(ONLINE_FLAG); - - if (action==PUT_ACTION) { - - if(narg >= 3) - if(!strcasecmp(args[2],"mv")) - mode = 1; -#ifdef DACS_INT - - if (sscanf(args[1],"%d", &val)) -#else - if (sscanf(args[1],"%f", &val)) -#endif - ; - else - return string("cannot scan DAC value ")+string(args[1]); - - myDet->setDAC(val,dac,mode); - } - - else if(narg >= 2) - if(!strcasecmp(args[1],"mv")) - mode = 1; - -#ifdef DACS_INT - sprintf(answer,"%d",myDet->setDAC(-1,dac,mode)); -#else - sprintf(answer,"%f",myDet->setDAC(-1,dac,mode)); -#endif - if(mode) - strcat(answer," mV"); - return string(answer); - -} - - -string slsDetectorCommand::helpDAC(int narg, char *args[], int action) { - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "vthreshold dacu\t sets the detector threshold in dac units (0-1024) or mV. The energy is approx 800-15*keV" << std::endl; - os << std::endl; - - os << "vcalibration " << "dacu\t sets the calibration pulse amplitude in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vtrimbit " << "dacu\t sets the trimbit amplitude in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vpreamp " << "dacu\t sets the preamp feedback voltage in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vshaper1 " << "dacu\t sets the shaper1 feedback voltage in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vshaper2 " << "dacu\t sets the shaper2 feedback voltage in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vhighvoltage " << "dacu\t CHIPTEST BOARD ONLY - sets the detector HV in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vapower " << "dacu\t CHIPTEST BOARD ONLY - sets the analog power supply in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vddpower " << "dacu\t CHIPTEST BOARD ONLY - sets the digital power supply in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vshpower " << "dacu\t CHIPTEST BOARD ONLY - sets the comparator power supply in dac units (0-1024)." << std::endl; - os << std::endl; - os << "viopower " << "dacu\t CHIPTEST BOARD ONLY - sets the FPGA I/O power supply in dac units (0-1024)." << std::endl; - - - - os << "vrefds " << "dacu\t sets vrefds" << std::endl; - os << "vcascn_pb " << "dacu\t sets vcascn_pb" << std::endl; - os << "vcascp_pb " << "dacu\t sets vcascp_pb" << std::endl; - os << "vout_cm " << "dacu\t sets vout_cm" << std::endl; - os << "vin_cm " << "dacu\t sets vin_cm" << std::endl; - os << "vcasc_out " << "dacu\t sets vcasc_out" << std::endl; - os << "vref_comp " << "dacu\t sets vref_comp" << std::endl; - os << "ib_test_c " << "dacu\t sets ib_test_c" << std::endl; - - - os << "dac0 " << "dacu\t sets dac 0" << std::endl; - os << "dac1 " << "dacu\t sets dac 1" << std::endl; - os << "dac2 " << "dacu\t sets dac 2" << std::endl; - os << "dac3 " << "dacu\t sets dac 3" << std::endl; - os << "dac4 " << "dacu\t sets dac 4" << std::endl; - os << "dac5 " << "dacu\t sets dac 5" << std::endl; - os << "dac6 " << "dacu\t sets dac 6" << std::endl; - os << "dac7 " << "dacu\t sets dac 7" << std::endl; - - os << "vsvp" << "dacu\t sets vsvp" << std::endl; - os << "vsvn" << "dacu\t sets vsvn" << std::endl; - os << "vtr" << "dacu\t sets vtr" << std::endl; - os << "vrf" << "dacu\t sets vrf" << std::endl; - os << "vrs" << "dacu\t sets vrs" << std::endl; - os << "vtgstv" << "dacu\t sets vtgstv" << std::endl; - os << "vcmp_ll" << "dacu\t sets vcmp_ll" << std::endl; - os << "vcmp_lr" << "dacu\t sets vcmp_lr" << std::endl; - os << "vcall" << "dacu\t sets vcall" << std::endl; - os << "vcmp_rl" << "dacu\t sets vcmp_rl" << std::endl; - os << "vcmp_rr" << "dacu\t sets vcmp_rr" << std::endl; - os << "rxb_rb" << "dacu\t sets rxb_rb" << std::endl; - os << "rxb_lb" << "dacu\t sets rxb_lb" << std::endl; - os << "vcp" << "dacu\t sets vcp " << std::endl; - os << "vcn" << "dacu\t sets vcn " << std::endl; - os << "vis" << "dacu\t sets vis " << std::endl; - - - os << " mv if you want in mV else in dac units " << std::endl; - } - - if (action==GET_ACTION || action==HELP_ACTION) { - - os << "vthreshold \t Gets the detector threshold in dac units (0-1024). The energy is approx 800-15*keV" << std::endl; - os << std::endl; - - os << "vcalibration " << "dacu\t gets the calibration pulse amplitude in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vtrimbit " << "dacu\t gets the trimbit amplitude in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vpreamp " << "dacu\t gets the preamp feedback voltage in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vshaper1 " << "dacu\t gets the shaper1 feedback voltage in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vshaper2 " << "dacu\t gets the shaper2 feedback voltage in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vhighvoltage " << "dacu\t CHIPTEST BOARD ONLY - gets the detector HV in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vapower " << "dacu\t CHIPTEST BOARD ONLY - gets the analog power supply in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vddpower " << "dacu\t CHIPTEST BOARD ONLY - gets the digital power supply in dac units (0-1024)." << std::endl; - os << std::endl; - os << "vshpower " << "dacu\t CHIPTEST BOARD ONLY - gets the comparator power supply in dac units (0-1024)." << std::endl; - os << std::endl; - os << "viopower " << "dacu\t CHIPTEST BOARD ONLY - gets the FPGA I/O power supply in dac units (0-1024)." << std::endl; - os << std::endl; - - - os << "vrefds " << "\t gets vrefds" << std::endl; - os << "vcascn_pb " << "\t gets vcascn_pb" << std::endl; - os << "vcascp_pb " << "\t gets vcascp_pb" << std::endl; - os << "vout_cm " << "\t gets vout_cm" << std::endl; - os << "vin_cm " << "\t gets vin_cm" << std::endl; - os << "vcasc_out " << "\t gets vcasc_out" << std::endl; - os << "vref_comp " << "\t gets vref_comp" << std::endl; - os << "ib_test_c " << "\t gets ib_test_c" << std::endl; - - - os << "dac0 " << "\t gets dac 0" << std::endl; - os << "dac1 " << "\t gets dac 1" << std::endl; - os << "dac2 " << "\t gets dac 2" << std::endl; - os << "dac3 " << "\t gets dac 3" << std::endl; - os << "dac4 " << "\t gets dac 4" << std::endl; - os << "dac5 " << "\t gets dac 5" << std::endl; - os << "dac6 " << "\t gets dac 6" << std::endl; - os << "dac7 " << "\t gets dac 7" << std::endl; - - os << "vsvp" << "dacu\t gets vsvp" << std::endl; - os << "vsvn" << "dacu\t gets vsvn" << std::endl; - os << "vtr" << "dacu\t gets vtr" << std::endl; - os << "vrf" << "dacu\t gets vrf" << std::endl; - os << "vrs" << "dacu\t gets vrs" << std::endl; - os << "vtgstv" << "dacu\t gets vtgstv" << std::endl; - os << "vcmp_ll" << "dacu\t gets vcmp_ll" << std::endl; - os << "vcmp_lr" << "dacu\t gets vcmp_lr" << std::endl; - os << "vcall" << "dacu\t gets vcall" << std::endl; - os << "vcmp_rl" << "dacu\t gets vcmp_rl" << std::endl; - os << "vcmp_rr" << "dacu\t gets vcmp_rr" << std::endl; - os << "rxb_rb" << "dacu\t gets rxb_rb" << std::endl; - os << "rxb_lb" << "dacu\t gets rxb_lb" << std::endl; - os << "vcp" << "dacu\t gets vcp " << std::endl; - os << "vcn" << "dacu\t gets vcn " << std::endl; - os << "vis" << "dacu\t gets vis " << std::endl; - - - } - return os.str(); -} - - - -string slsDetectorCommand::cmdADC(int narg, char *args[], int action) { - - dacIndex adc; - int idac; - // double val=-1; - char answer[1000]; - - if (action==HELP_ACTION) - return helpADC(narg, args, action); - else if (action==PUT_ACTION) - return string("cannot set ")+cmd; - - if (sscanf(args[0],"adc:%d",&idac)==1) { - // printf("chiptestboard!\n"); - adc=(dacIndex)(idac+1000); - } else if (cmd=="temp_adc") - adc=TEMPERATURE_ADC; - else if (cmd=="temp_fpga") - adc=TEMPERATURE_FPGA; - else if (cmd=="temp_fpgaext") - adc=TEMPERATURE_FPGAEXT; - else if (cmd=="temp_10ge") - adc=TEMPERATURE_10GE; - else if (cmd=="temp_dcdc") - adc=TEMPERATURE_DCDC; - else if (cmd=="temp_sodl") - adc=TEMPERATURE_SODL; - else if (cmd=="temp_sodr") - adc=TEMPERATURE_SODR; - else if (cmd=="temp_fpgafl") - adc=TEMPERATURE_FPGA2; - else if (cmd=="temp_fpgafr") - adc=TEMPERATURE_FPGA3; - else if (cmd=="i_a") - adc=I_POWER_A; - else if (cmd=="i_b") - adc=I_POWER_B; - else if (cmd=="i_c") - adc=I_POWER_C; - else if (cmd=="i_d") - adc=I_POWER_D; - else if (cmd=="vm_a") - adc=V_POWER_A; - else if (cmd=="vm_b") - adc=V_POWER_B; - else if (cmd=="vm_c") - adc=V_POWER_C; - else if (cmd=="vm_d") - adc=V_POWER_D; - else if (cmd=="vm_io") - adc=V_POWER_IO; - else if (cmd=="i_io") - adc=I_POWER_IO; - else - return string("cannot decode adc ")+cmd; - - myDet->setOnline(ONLINE_FLAG); -#ifdef DACS_INT - if (myDet->getDetectorsType() == EIGER || myDet->getDetectorsType() == JUNGFRAU){ - int val = myDet->getADC(adc); - if (val == -1) - sprintf(answer,"%d",val); - else - sprintf(answer,"%.2f", (double)val/1000.000); - } - else sprintf(answer,"%d",myDet->getADC(adc)); -#else - sprintf(answer,"%f",myDet->getADC(adc)); -#endif - //if ((adc == TEMPERATURE_ADC) || (adc == TEMPERATURE_FPGA)) - if (adc<=100) - strcat(answer,"°C"); - else - strcat(answer,"mV"); - - return string(answer); - -} - -string slsDetectorCommand::helpADC(int narg, char *args[], int action) { - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "temp_adc " << "Cannot be set" << std::endl; - os << "temp_fpga " << "Cannot be set" << std::endl; - os << "temp_fpgaext " << "Cannot be set" << std::endl; - os << "temp_10ge " << "Cannot be set" << std::endl; - os << "temp_dcdc " << "Cannot be set" << std::endl; - os << "temp_sodl " << "Cannot be set" << std::endl; - os << "temp_sodr " << "Cannot be set" << std::endl; - os << "temp_fpgafl " << "Cannot be set" << std::endl; - os << "temp_fpgafr " << "Cannot be set" << std::endl; - } - if (action==GET_ACTION || action==HELP_ACTION) { - os << "temp_adc " << "\t gets the temperature of the adc" << std::endl; - os << "temp_fpga " << "\t gets the temperature of the fpga" << std::endl; - os << "temp_fpgaext " << "\t gets the temperature close to the fpga" << std::endl; - os << "temp_10ge " << "\t gets the temperature close to the 10GE" << std::endl; - os << "temp_dcdc " << "\t gets the temperature close to the dc dc converter" << std::endl; - os << "temp_sodl " << "\t gets the temperature close to the left so-dimm memory" << std::endl; - os << "temp_sodr " << "\t gets the temperature close to the right so-dimm memory" << std::endl; - os << "temp_fpgafl " << "\t gets the temperature of the left front end board fpga" << std::endl; - os << "temp_fpgafr " << "\t gets the temperature of the left front end board fpga" << std::endl; - } - return os.str(); -} - - - - -string slsDetectorCommand::cmdTempControl(int narg, char *args[], int action) { - char answer[1000]=""; - int val = -1; - - if (action==HELP_ACTION) - return helpTempControl(narg, args, action); - - myDet->setOnline(ONLINE_FLAG); - - if (cmd == "temp_threshold") { - if (action==PUT_ACTION) { - double fval=0.0; - if (!sscanf(args[1],"%lf", &fval)) - return string("cannot scan temp control value ")+string(args[1]); - val = fval * 1000; - myDet->setThresholdTemperature(val); - } - val = myDet->setThresholdTemperature(); - if (val == -1) - sprintf(answer,"%d",val); - else - sprintf(answer,"%.2f°C", (double)val/1000.000); - } - - else if (cmd == "temp_control") { - if (action==PUT_ACTION) { - if (!sscanf(args[1],"%d", &val)) - return string("cannot scan temp control value ")+string(args[1]); - if ((val!=0) && (val!=1)) - return string ("temp_control option must be 0 or 1"); - myDet->setTemperatureControl(val); - } - sprintf(answer,"%d", myDet->setTemperatureControl()); - } - - else if (cmd == "temp_event") { - if (action==PUT_ACTION) { - if (!sscanf(args[1],"%d", &val)) - return string("cannot scan temp control value ")+string(args[1]); - if (val!=0) - return string ("temp_event option must be 0 to clear event"); - myDet->setTemperatureEvent(val); - } - sprintf(answer,"%d", myDet->setTemperatureEvent()); - } - - else - return string ("cannot scan command " + cmd); - - return string(answer); -} - - - -string slsDetectorCommand::helpTempControl(int narg, char *args[], int action) { - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "temp_threshold t \t sets the threshold temperature. Jungfrau only" << std::endl; - os << "temp_control t \t Enables/Disables the temperature control. 1 enables, 0 disables. JUNGFRAU ONLY" << std::endl; - os << "temp_event t \t Resets over-temperative event. Put only with option 0 to clear event. JUNGFRAU ONLY." << std::endl; - } - if (action==GET_ACTION || action==HELP_ACTION) { - os << "temp_threshold \t gets the threshold temperature. Jungfrau only." << std::endl; - os << "temp_control \t gets temperature control enable. 1 enabled, 0 disabled. JUNGFRAU ONLY" << std::endl; - os << "temp_event \t gets over-temperative event. Gets 1 if temperature went over threshold and control is enabled, else 0. /Disables the temperature control. JUNGFRAU ONLY." << std::endl; - } - return os.str(); -} - - - -string slsDetectorCommand::cmdTiming(int narg, char *args[], int action){ -#ifdef VERBOSE - cout << string("Executing command ")+string(args[0])+string(" ( ")+cmd+string(" )\n"); -#endif - - if (action==HELP_ACTION) { - return helpTiming(narg,args,HELP_ACTION); - } - myDet->setOnline(ONLINE_FLAG); - if (action==PUT_ACTION) { - if (myDet->externalCommunicationType(string(args[1]))== GET_EXTERNAL_COMMUNICATION_MODE) return helpTiming(narg,args, action); - myDet->setExternalCommunicationMode(myDet->externalCommunicationType(string(args[1]))); - } - return myDet->externalCommunicationType(myDet->setExternalCommunicationMode()); - -} -string slsDetectorCommand::helpTiming(int narg, char *args[], int action){ - - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) - os << string("timing \t gets the timing mode of the detector (auto, trigger, ro_trigger, gating, triggered_gating)\n"); - if (action==PUT_ACTION || action==HELP_ACTION) - os << string("timing mode \t sets synchronization mode of the detector. Can be auto, trigger, ro_trigger, gating, triggered_gating \n"); - return os.str(); -} - - - -string slsDetectorCommand::cmdTimer(int narg, char *args[], int action) { - timerIndex index; - int64_t t=-1, ret; - double val, rval; - - char answer[1000]; - - - if (action==HELP_ACTION) - return helpTimer(narg, args, action); - - if (cmd=="exptime") - index=ACQUISITION_TIME; - else if (cmd=="subexptime") - index=SUBFRAME_ACQUISITION_TIME; - else if (cmd=="period") - index=FRAME_PERIOD; - else if (cmd=="subdeadtime") - index=SUBFRAME_DEADTIME; - else if (cmd=="delay") - index=DELAY_AFTER_TRIGGER; - else if (cmd=="gates") - index=GATES_NUMBER; - else if (cmd=="frames") - index=FRAME_NUMBER; - else if (cmd=="cycles") - index=CYCLES_NUMBER; - else if (cmd=="probes") - index=PROBES_NUMBER; - else if (cmd=="measurements") - index=MEASUREMENTS_NUMBER; - else if (cmd=="samples") - index=SAMPLES_JCTB; - else if (cmd=="storagecells") - index=STORAGE_CELL_NUMBER; - else if (cmd=="storagecell_start") { - myDet->setOnline(ONLINE_FLAG); - if (action==PUT_ACTION) { - int ival =-1; - if (!sscanf(args[1],"%d", &ival)) - return string("cannot scan storage cell start value ")+string(args[1]); - myDet->setStoragecellStart(ival); - } - sprintf(answer,"%d", myDet->setStoragecellStart()); - return string(answer); - } - else - return string("could not decode timer ")+cmd; - - - if (action==PUT_ACTION) { - if (sscanf(args[1],"%lf", &val)) - ;//printf("value:%0.9lf\n",val); - else - return string("cannot scan timer value ")+string(args[1]); - if (index==ACQUISITION_TIME || index==SUBFRAME_ACQUISITION_TIME || - index==FRAME_PERIOD || index==DELAY_AFTER_TRIGGER || - index == SUBFRAME_DEADTIME) { - // +0.5 for precision of eg.0.0000325 - t = ( val * 1E9 + 0.5); - }else t=(int64_t)val; - } - - - myDet->setOnline(ONLINE_FLAG); - myDet->setReceiverOnline(ONLINE_FLAG); - - ret=myDet->setTimer(index,t); - - if ((ret!=-1) && (index==ACQUISITION_TIME || index==SUBFRAME_ACQUISITION_TIME - || index==FRAME_PERIOD || index==DELAY_AFTER_TRIGGER || - index == SUBFRAME_DEADTIME)) { - rval=(double)ret*1E-9; - sprintf(answer,"%0.9f",rval); - } - else - sprintf(answer,"%lld",(long long int)ret); - - return string(answer); - - - - -} - - -string slsDetectorCommand::helpTimer(int narg, char *args[], int action) { - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "exptime t \t sets the exposure time in s" << std::endl; - os << "subexptime t \t sets the exposure time of subframe in s" << std::endl; - os << "period t \t sets the frame period in s" << std::endl; - os << "delay t \t sets the delay after trigger in s" << std::endl; - os << "frames t \t sets the number of frames per cycle (e.g. after each trigger)" << std::endl; - os << "cycles t \t sets the number of cycles (e.g. number of triggers)" << std::endl; - os << "probes t \t sets the number of probes to accumulate (max 3! cycles should be set to 1, frames to the number of pump-probe events)" << std::endl; - os << "samples t \t sets the number of samples expected from the jctb" << std::endl; - os << "storagecells t \t sets number of storage cells per acquisition. For very advanced users only! For JUNGFRAU only. Range: 0-15. The #images = #frames * #cycles * (#storagecells+1)." << std::endl; - os << "storagecell_start t \t sets the storage cell that stores the first acquisition of the series. Default is 15(0xf). For very advanced users only! For JUNGFRAU only. Range: 0-15." << std::endl; - os << "subdeadtime t \t sets sub frame dead time in s. Subperiod is set in the detector = subexptime + subdeadtime. This value is normally a constant in the config file. Used in EIGER only in 32 bit mode. " << std::endl; - os << std::endl; - - - } - if (action==GET_ACTION || action==HELP_ACTION) { - - os << "exptime \t gets the exposure time in s" << std::endl; - os << "subexptime \t gets the exposure time of subframe in s" << std::endl; - os << "period \t gets the frame period in s" << std::endl; - os << "delay \t gets the delay after trigger in s" << std::endl; - os << "frames \t gets the number of frames per cycle (e.g. after each trigger)" << std::endl; - os << "cycles \t gets the number of cycles (e.g. number of triggers)" << std::endl; - os << "probes \t gets the number of probes to accumulate" << std::endl; - os << "samples \t gets the number of samples expected from the jctb" << std::endl; - os << "storagecells \t gets number of storage cells per acquisition.For JUNGFRAU only." << std::endl; - os << "storagecell_start \t gets the storage cell that stores the first acquisition of the series." << std::endl; - os << "subperiod \t gets sub frame dead time in s. Used in EIGER in 32 bit only." << std::endl; - os << std::endl; - - } - return os.str(); - - - - - - - - -} - - -string slsDetectorCommand::cmdTimeLeft(int narg, char *args[], int action) { - timerIndex index; - int64_t ret; - double rval; - - char answer[1000]; - - - if (action==HELP_ACTION) - return helpTimeLeft(narg, args, action); - - if (cmd=="exptimel") - index=ACQUISITION_TIME; - else if (cmd=="periodl") - index=FRAME_PERIOD; - else if (cmd=="delayl") - index=DELAY_AFTER_TRIGGER; - else if (cmd=="gatesl") - index=GATES_NUMBER; - else if (cmd=="framesl") - index=FRAME_NUMBER; - else if (cmd=="cyclesl") - index=CYCLES_NUMBER; - else if (cmd=="probesl") - index=PROBES_NUMBER; - else if (cmd=="now") - index=ACTUAL_TIME; - else if (cmd=="timestamp") - index=MEASUREMENT_TIME; - else if (cmd=="nframes") - index=FRAMES_FROM_START; - else if (cmd=="measuredperiod") - index=MEASURED_PERIOD; - else if (cmd=="measuredsubperiod") - index=MEASURED_SUBPERIOD; - else - return string("could not decode timer ")+cmd; - - - if (action==PUT_ACTION) { - return string("cannot set ")+string(args[1]); - } - - - myDet->setOnline(ONLINE_FLAG); - - ret=myDet->getTimeLeft(index); - - if ((ret!=-1) && (index==ACQUISITION_TIME || index==FRAME_PERIOD || index==DELAY_AFTER_TRIGGER - || index==ACTUAL_TIME || index==MEASUREMENT_TIME || - MEASURED_PERIOD || MEASURED_SUBPERIOD)) - rval=(double)ret*1E-9; - else rval=ret; - - - sprintf(answer,"%0.9f",rval); - return string(answer); - - - - - -} - - -string slsDetectorCommand::helpTimeLeft(int narg, char *args[], int action) { - - - - ostringstream os; - if (action==GET_ACTION || action==HELP_ACTION) { - - os << "exptimel \t gets the exposure time left" << std::endl; - os << "periodl \t gets the frame period left" << std::endl; - os << "delayl \t gets the delay left" << std::endl; - os << "framesl \t gets the number of frames left" << std::endl; - os << "cyclesl \t gets the number of cycles left" << std::endl; - os << "probesl \t gets the number of probes left" << std::endl; - os << "measuredperiod \t gets the measured frame period (time between last frame and the previous one) in s. For Eiger only. Makes sense only for acquisitions of more than 1 frame." << std::endl; - os << "measuredsubperiod \t gets the measured subframe period (time between last subframe and the previous one) in s. For Eiger only and in 32 bit mode." << std::endl; - os << std::endl; - - } - return os.str(); - - - - -} - - - - - - - -string slsDetectorCommand::cmdSpeed(int narg, char *args[], int action) { - - speedVariable index; - int t=-1, ret; - - char answer[1000]; - - - if (action==HELP_ACTION) - return helpSpeed(narg, args, action); - - if (cmd=="clkdivider") - index=CLOCK_DIVIDER; - else if (cmd=="setlength") - index=SET_SIGNAL_LENGTH; - else if (cmd=="waitstates") - index=WAIT_STATES; - else if (cmd=="totdivider") - index=TOT_CLOCK_DIVIDER; - else if (cmd=="totdutycycle") - index=TOT_DUTY_CYCLE; - else if (cmd=="phasestep") { - index=PHASE_SHIFT; - t=100000; - } else if (cmd=="oversampling") - index=OVERSAMPLING; - else if (cmd=="adcclk") - index=ADC_CLOCK; - else if (cmd=="adcphase") { - index=ADC_PHASE; - t=100000; - } else if (cmd=="adcpipeline") - index=ADC_PIPELINE; - else if (cmd=="dbitclk") - index=DBIT_CLOCK; - else if (cmd=="dbitphase") { - index=DBIT_PHASE; - t=100000; - } else if (cmd=="dbitpipeline") - index=DBIT_PIPELINE; - else - return string("could not decode speed variable ")+cmd; - - - if (action==PUT_ACTION) { - if (sscanf(args[1],"%d", &t)) - ; - else - return string("cannot scan speed value ")+string(args[1]); - - } - - myDet->setOnline(ONLINE_FLAG); - - ret=myDet->setSpeed(index,t); - - sprintf(answer,"%d",ret); - return string(answer); - - - - -} - - -string slsDetectorCommand::helpSpeed(int narg, char *args[], int action) { - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - - os << "clkdivider c \t sets readout clock divider. For Jungfrau, it also overwrites adcphase to recommended default" << std::endl; - os << "setlength c\t sets the length of the set/reset signals (in clock cycles)" << std::endl; - os << "waitstates c \t sets the waitstates of the bus interface" << std::endl; - os << "totdivider c\t sets the clock divider in tot mode" << std::endl; - os << "totdutycycle c\t sets the duty cycle of the tot clock" << std::endl; - os << "adcphase c\t Sets phase of the sampling clock. For JUNGFRAU, setting speed (clkdivider) overwrites adcphase to its default recommended value. (Not for EIGER)" << std::endl; - os << std::endl; - - } - if (action==GET_ACTION || action==HELP_ACTION) { - - os << "clkdivider \t gets readout clock divider. For Jungfrau, it also overwrites adcphase to recommended default" << std::endl; - os << "setlength \t gets the length of the set/reset signals (in clock cycles)" << std::endl; - os << "waitstates \t gets the waitstates of the bus interface" << std::endl; - os << "totdivider \t gets the clock divider in tot mode" << std::endl; - os << "totdutycycle \t gets the duty cycle of the tot clock" << std::endl; - os << "adcphase \t gets phase of the sampling clock. For JUNGFRAU, setting speed (clkdivider) overwrites adcphase to its default recommended value. (Not for EIGER)" << std::endl; - os << std::endl; - - } - return os.str(); - - - - - - - - -} - - - - -string slsDetectorCommand::cmdAdvanced(int narg, char *args[], int action) { - - int retval; - char answer[1000]=""; - - if (action==HELP_ACTION) - return helpAdvanced(narg, args, action); - - if (cmd=="flags") { - - readOutFlags flag=GET_READOUT_FLAGS; - - - if (action==PUT_ACTION) { - string sval=string(args[1]); - if (sval=="none") - flag=NORMAL_READOUT; - else if (sval=="storeinram") - flag=STORE_IN_RAM; - else if (sval=="tot") - flag=TOT_MODE; - else if (sval=="continous") - flag=CONTINOUS_RO; - else if (sval=="parallel") - flag=PARALLEL; - else if (sval=="nonparallel") - flag=NONPARALLEL; - else if (sval=="safe") - flag=SAFE; - else if (sval=="digital") - flag=DIGITAL_ONLY; - else if (sval=="analog_digital") - flag=ANALOG_AND_DIGITAL; - else if (sval=="overflow") - flag=SHOW_OVERFLOW; - else if (sval=="nooverflow") - flag=NOOVERFLOW; - else if (sval=="pedestal") - flag=PEDESTAL; - else if (sval=="flatfield") - flag=FLAT; - else if (sval=="newpedestal") - flag=NEWPEDESTAL; - else if (sval=="newflatfield") - flag=NEWFLAT; - else if (sval=="frame") - flag=FRAME; - else if (sval=="analog") - flag=ANALOG; - else if (sval=="counting") - flag=COUNTING; - else if (sval=="interpolating") - flag=INTERPOLATING; - else - return string("could not scan flag ")+string(args[1]); - } - - myDet->setOnline(ONLINE_FLAG); - retval = myDet->setReadOutFlags(flag); - - // cout << hex << flag << " " << retval << endl; - - if(retval == NORMAL_READOUT) - return string("none"); - - if(retval & STORE_IN_RAM) - strcat(answer,"storeinram "); - if(retval & TOT_MODE) - strcat(answer,"tot "); - if(retval & CONTINOUS_RO) - strcat(answer,"continous "); - if(retval & PARALLEL) - strcat(answer,"parallel "); - if(retval & NONPARALLEL) - strcat(answer,"nonparallel "); - if(retval & SAFE) - strcat(answer,"safe "); - if (retval & DIGITAL_ONLY) - strcat(answer,"digital " ); - if (retval & ANALOG_AND_DIGITAL) - strcat(answer,"analog_digital "); - if (retval & SHOW_OVERFLOW) - strcat(answer,"overflow "); - if (retval & NOOVERFLOW) - strcat(answer,"nooverflow "); - if (retval & PEDESTAL) - strcat(answer,"pedestal "); - if (retval & NEWPEDESTAL) - strcat(answer,"newpedestal "); - if (retval & NEWFLAT) - strcat(answer,"newflat "); - if (retval & FLAT) - strcat(answer,"flatfield "); - if (retval & FRAME) - strcat(answer,"frame "); - if (retval & ANALOG) - strcat(answer,"analog "); - if (retval & COUNTING) - strcat(answer,"counting "); - if (retval & INTERPOLATING) - strcat(answer,"interpolating "); - if(strlen(answer)) - return string(answer); - - return string("unknown"); - - } else if (cmd=="extsig") { - externalSignalFlag flag=GET_EXTERNAL_SIGNAL_FLAG; - int is=-1; - if (sscanf(args[0],"extsig:%d",&is)) - ; - else - return string("could not scan signal number ")+string(args[0]); - - if (action==PUT_ACTION) { - flag=myDet->externalSignalType(args[1]); - if (flag==GET_EXTERNAL_SIGNAL_FLAG) - return string("could not scan external signal mode ")+string(args[1]); - } - myDet->setOnline(ONLINE_FLAG); - - return myDet->externalSignalType(myDet->setExternalSignalFlags(flag,is)); - - - } else if (cmd=="programfpga") { - if (action==GET_ACTION) - return string("cannot get"); - if(strstr(args[1],".pof")==NULL) - return string("wrong usage: programming file should have .pof extension"); - string sval=string(args[1]); -#ifdef VERBOSE - std::cout<< " programming file " << sval << std::endl; -#endif - myDet->setOnline(ONLINE_FLAG); - if(myDet->programFPGA(sval) == OK) - return string("successful"); - return string("unsuccessful"); - } - - - else if (cmd=="resetfpga") { - if (action==GET_ACTION) - return string("cannot get"); -#ifdef VERBOSE - std::cout<< " resetting fpga " << std::endl; -#endif - myDet->setOnline(ONLINE_FLAG); - if(myDet->resetFPGA() == OK) - return string("successful"); - return string("unsuccessful"); - } - - - else if (cmd=="powerchip") { - char ans[100]; - myDet->setOnline(ONLINE_FLAG); - if (action==PUT_ACTION){ - int ival = -1; - if (!sscanf(args[1],"%d",&ival)) - return string("could not scan powerchip parameter " + string(args[1])); - myDet->powerChip(ival); - } - sprintf(ans,"%d",myDet->powerChip()); - return string(ans); - } - - else if (cmd=="led") { - char ans[100]; - int val=0; - myDet->setOnline(ONLINE_FLAG); - if (action==PUT_ACTION){ - int ival = -1; - if (!sscanf(args[1],"%d",&ival)) - return string("could not scan powerchip parameter " + string(args[1])); - val=myDet->readRegister(0x4d); - myDet->writeRegister(0x4d,(val&(~1))|((~ival)&1));//config register - } - sprintf(ans,"%d",~(myDet->readRegister(0x4d))&1); - return string(ans); - } - - else if (cmd=="auto_comp_disable") { - char ans[100]; - myDet->setOnline(ONLINE_FLAG); - if (action==PUT_ACTION){ - int ival = -1; - if (!sscanf(args[1],"%d",&ival)) - return string("could not scan auto_comp_control parameter " + string(args[1])); - myDet->setAutoComparatorDisableMode(ival); - } - sprintf(ans,"%d",myDet->setAutoComparatorDisableMode()); - return string(ans); - } - else - return string("unknown command ")+cmd; - -} - - -string slsDetectorCommand::helpAdvanced(int narg, char *args[], int action) { - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - - os << "extsig:i mode \t sets the mode of the external signal i. can be \n \t \t \t off, \n \t \t \t gate_in_active_high, \n \t \t \t gate_in_active_low, \n \t \t \t trigger_in_rising_edge, \n \t \t \t trigger_in_falling_edge, \n \t \t \t ro_trigger_in_rising_edge, \n \t \t \t ro_trigger_in_falling_edge, \n \t \t \t gate_out_active_high, \n \t \t \t gate_out_active_low, \n \t \t \t trigger_out_rising_edge, \n \t \t \t trigger_out_falling_edge, \n \t \t \t ro_trigger_out_rising_edge, \n \t \t \t ro_trigger_out_falling_edge" << std::endl; - os << "flags mode \t sets the readout flags to mode. can be none, storeinram, tot, continous, parallel, nonparallel, safe, digital, analog_digital, overlow, nooverflow, unknown." << std::endl; - - os << "programfpga f \t programs the fpga with file f (with .pof extension)." << std::endl; - os << "resetfpga f \t resets fpga, f can be any value" << std::endl; - - os << "led s \t sets led status (0 off, 1 on)" << std::endl; - os << "powerchip i \t powers on or off the chip. i = 1 for on, i = 0 for off" << std::endl; - os << "auto_comp_disable i \t Currently not implemented. this mode disables the on-chip gain switching comparator automatically after 93.75% of exposure time (only for longer than 100us). 1 enables mode, 0 disables mode. By default, mode is disabled (comparator is enabled throughout). (JUNGFRAU only). " << std::endl; - } - if (action==GET_ACTION || action==HELP_ACTION) { - - os << "extsig:i \t gets the mode of the external signal i. can be \n \t \t \t off, \n \t \t \t gate_in_active_high, \n \t \t \t gate_in_active_low, \n \t \t \t trigger_in_rising_edge, \n \t \t \t trigger_in_falling_edge, \n \t \t \t ro_trigger_in_rising_edge, \n \t \t \t ro_trigger_in_falling_edge, \n \t \t \t gate_out_active_high, \n \t \t \t gate_out_active_low, \n \t \t \t trigger_out_rising_edge, \n \t \t \t trigger_out_falling_edge, \n \t \t \t ro_trigger_out_rising_edge, \n \t \t \t ro_trigger_out_falling_edge" << std::endl; - - os << "flags \t gets the readout flags. can be none, storeinram, tot, continous, parallel, nonparallel, safe, digital, analog_digital, overflow, nooverflow, unknown" << std::endl; - os << "led \t returns led status (0 off, 1 on)" << std::endl; - os << "powerchip \t gets if the chip has been powered on or off" << std::endl; - os << "auto_comp_disable \t Currently not implemented. gets if the automatic comparator diable mode is enabled/disabled" << std::endl; - - } - return os.str(); - - - - - - - - -} - - - - -string slsDetectorCommand::cmdConfiguration(int narg, char *args[], int action) { - - - - if (action==HELP_ACTION) - return helpConfiguration(narg, args, action); - - string sval; - - if (narg<2 && cmd != "rx_printconfig") - return string("should specify I/O file"); - - myDet->setOnline(ONLINE_FLAG); - - if (cmd=="config") { - if (action==PUT_ACTION) { - sval=string(args[1]); - myDet->readConfigurationFile(sval); - } else if (action==GET_ACTION) { - sval=string(args[1]); - myDet->writeConfigurationFile(sval); - } - return sval; - } else if (cmd=="rx_printconfig"){ - myDet->setReceiverOnline(ONLINE_FLAG); - if (action==PUT_ACTION) - return string("cannot put"); - myDet->printReceiverConfiguration(); - return string(""); - }else if (cmd=="parameters") { - myDet->setReceiverOnline(ONLINE_FLAG); - if (action==PUT_ACTION) { - sval=string(args[1]); - myDet->retrieveDetectorSetup(sval); - } else if (action==GET_ACTION) { - sval=string(args[1]); - myDet->dumpDetectorSetup(sval); - } - return sval; - } else if (cmd=="setup") { - myDet->setReceiverOnline(ONLINE_FLAG); - if (action==PUT_ACTION) { - sval=string(args[1]); - myDet->retrieveDetectorSetup(sval,2); - } else if (action==GET_ACTION) { - sval=string(args[1]); - myDet->dumpDetectorSetup(sval,2); - } - return sval; - } - return string("could not decode conf mode"); - - -} - - -string slsDetectorCommand::helpConfiguration(int narg, char *args[], int action) { - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - - os << "config fname \t sets the detector to the configuration contained in fname" << std::endl; - os << "parameters fname \t sets the detector parameters to those contained in fname" << std::endl; - os << "setup fname \t sets the detector complete detector setup to that contained in fname (extensions automatically generated), including trimfiles, ff coefficients etc." << std::endl; - - } - if (action==GET_ACTION || action==HELP_ACTION) { - os << "rx_printconfig \t prints the receiver configuration" << std::endl; - os << "config fname \t saves the detector to the configuration to fname" << std::endl; - os << "parameters fname \t saves the detector parameters to fname" << std::endl; - os << "setup fname \t saves the detector complete detector setup to fname (extensions automatically generated), including trimfiles, ff coefficients etc." << std::endl; - - } - - return os.str(); - - - - - - - - -} - - -string slsDetectorCommand::cmdReceiver(int narg, char *args[], int action) { - char answer[100]; - int ival = -1; - - if (action==HELP_ACTION) - return helpReceiver(narg, args, action); - - - myDet->setOnline(ONLINE_FLAG); - myDet->setReceiverOnline(ONLINE_FLAG); - - if(cmd=="receiver"){ - if (action==PUT_ACTION) { - if(!strcasecmp(args[1],"start")) - myDet->startReceiver(); - else if(!strcasecmp(args[1],"stop")) - myDet->stopReceiver(); - else - return helpReceiver(narg, args, action); - } - return myDet->runStatusType(myDet->getReceiverStatus()); - } - - - else if(cmd=="framescaught"){ - if (action==PUT_ACTION) - return string("cannot put"); - else{ - sprintf(answer,"%d",myDet->getFramesCaughtByReceiver()); - return string(answer); - } - } - - else if(cmd=="resetframescaught"){ - if (action==GET_ACTION) - return string("cannot get"); - else{ - if(myDet->resetFramesCaught() == FAIL) - strcpy(answer,"failed"); - else - strcpy(answer,"successful"); - return string(answer); - } - } - - else if(cmd=="frameindex"){ - if (action==PUT_ACTION) - return string("cannot put"); - else{ - sprintf(answer,"%d",myDet->getReceiverCurrentFrameIndex()); - return string(answer); - } - } - else if(cmd=="r_readfreq"){ - if (action==PUT_ACTION){ - if (!sscanf(args[1],"%d",&ival)) - return string("Could not scan read frequency mode ")+string(args[1]); - if(ival>=0) - myDet->setReadReceiverFrequency(ival); - } - sprintf(answer,"%d",myDet->setReadReceiverFrequency()); - return string(answer); - - } - else if(cmd=="r_compression"){ - if (action==PUT_ACTION){ - if (!sscanf(args[1],"%d",&ival)) - return string("Could not scan receiver compression input ")+string(args[1]); - if(ival>=0) - sprintf(answer,"%d",myDet->enableReceiverCompression(ival)); - }else - sprintf(answer,"%d",myDet->enableReceiverCompression()); - return string(answer); - - } - - else if(cmd=="tengiga"){ - if (action==PUT_ACTION){ - if (!sscanf(args[1],"%d",&ival)) - return string("Could not scan tengiga input ")+string(args[1]); - if(ival>=0) - sprintf(answer,"%d",myDet->enableTenGigabitEthernet(ival)); - }else - sprintf(answer,"%d",myDet->enableTenGigabitEthernet()); - return string(answer); - - } - - - else if(cmd=="rx_fifodepth"){ - if (action==PUT_ACTION){ - if (!sscanf(args[1],"%d",&ival)) - return string("Could not scan rx_fifodepth input ")+string(args[1]); - if(ival>=0) - sprintf(answer,"%d",myDet->setReceiverFifoDepth(ival)); - }else - sprintf(answer,"%d",myDet->setReceiverFifoDepth()); - return string(answer); - - } - - else if(cmd=="r_silent"){ - if (action==PUT_ACTION){ - if (!sscanf(args[1],"%d",&ival)) - return string("Could not scan r_online input ")+string(args[1]); - if(ival>=0) - sprintf(answer,"%d",myDet->setReceiverSilentMode(ival)); - }else - sprintf(answer,"%d",myDet->setReceiverSilentMode()); - return string(answer); - - } - - else if(cmd=="r_framesperfile") { - if (action==PUT_ACTION){ - if (sscanf(args[1],"%d",&ival)) { - myDet->setReceiverFramesPerFile(ival); - } else return string("could not scan max frames per file\n"); - } - char answer[100]; - memset(answer, 0, 100); - sprintf(answer,"%d", myDet->setReceiverFramesPerFile()); - return string(answer); - } - - else if(cmd=="r_discardpolicy") { - if (action==PUT_ACTION){ - frameDiscardPolicy f = myDet->getReceiverFrameDiscardPolicy(string(args[1])); - if (f == GET_FRAME_DISCARD_POLICY) - return string("could not scan frame discard policy. Options: nodiscard, discardempty, discardpartial\n"); - myDet->setReceiverFramesDiscardPolicy(f); - } - return myDet->getReceiverFrameDiscardPolicy(myDet->setReceiverFramesDiscardPolicy()); - } - - else if(cmd=="r_padding") { - if (action==PUT_ACTION){ - if (sscanf(args[1],"%d",&ival)) { - myDet->setReceiverPartialFramesPadding(ival); - } else return string("could not scan receiver padding enable\n"); - } - char answer[100]; - memset(answer, 0, 100); - sprintf(answer,"%d",myDet->setReceiverPartialFramesPadding()); - return string(answer); - } - - - - return string("could not decode command"); - -} - - - -string slsDetectorCommand::helpReceiver(int narg, char *args[], int action) { - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "receiver [status] \t starts/stops the receiver to listen to detector packets. - can be start, stop." << std::endl; - os << "resetframescaught [any value] \t resets frames caught by receiver" << std::endl; - os << "r_readfreq \t sets the gui read frequency of the receiver, 0 if gui requests frame, >0 if receiver sends every nth frame to gui" << std::endl; - os << "tengiga \t sets system to be configure for 10Gbe if set to 1, else 1Gbe if set to 0" << std::endl; - os << "rx_fifodepth [val]\t sets receiver fifo depth to val" << std::endl; - os << "r_silent [i]\t sets receiver in silent mode, ie. it will not print anything during real time acquisition. 1 sets, 0 unsets." << std::endl; - os << "r_framesperfile s\t sets the number of frames per file in receiver. 0 means infinite or all frames in a single file." << std::endl; - os << "r_discardpolicy s\t sets the frame discard policy in the receiver. nodiscard (default) - discards nothing, discardempty - discard only empty frames, discardpartial(fastest) - discards all partial frames." << std::endl; - os << "r_padding s\t enables/disables partial frames to be padded in the receiver. 0 does not pad partial frames(fastest), 1 (default) pads partial frames." << std::endl; - } - if (action==GET_ACTION || action==HELP_ACTION){ - os << "receiver \t returns the status of receiver - can be running or idle" << std::endl; - os << "framescaught \t returns the number of frames caught by receiver(average for multi)" << std::endl; - os << "frameindex \t returns the current frame index of receiver(average for multi)" << std::endl; - os << "r_readfreq \t returns the gui read frequency of the receiver" << std::endl; - os << "tengiga \t returns 1 if the system is configured for 10Gbe else 0 for 1Gbe" << std::endl; - os << "rx_fifodepth \t returns receiver fifo depth" << std::endl; - os << "r_silent \t returns receiver silent mode enable. 1 is silent, 0 not silent." << std::endl; - os << "r_framesperfile \t gets the number of frames per file in receiver. 0 means infinite or all frames in a single file." << std::endl; - os << "r_discardpolicy \t gets the frame discard policy in the receiver. nodiscard (default) - discards nothing, discardempty - discard only empty frames, discardpartial(fastest) - discards all partial frames." << std::endl; - os << "r_padding \t gets partial frames padding enable in the receiver. 0 does not pad partial frames(fastest), 1 (default) pads partial frames." << std::endl; - } - return os.str(); -} - -string slsDetectorCommand::helpPattern(int narg, char *args[], int action) { - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "pattern fname \t loads pattern file" << std::endl; - os << "patword addr word \t writes pattern word - only very advanced users!" << std::endl; - os << "patioctrl reg\t configures inputs/outputs of the chiptest board - only advanced users!" << std::endl; - os << "patclkctrl reg\t configures output clk enable of the chiptest board- only advanced users! " << std::endl; - os << "patlimits addr1 addr2\t defines pattern limits between addr1 and addr2" << std::endl; - os << "patloop0 addr1 adrr2 \t configures the limits of the 0 loop " << std::endl; - os << "patloop1 addr1 adrr2 \t configures the limits of the 1 loop " << std::endl; - os << "patloop2 addr1 adrr2 \t configures the limits of the 2 loop " << std::endl; - os << "patnloop0 n \t sets number of cycles of the 0 loop " << std::endl; - os << "patnloop1 n \t sets number of cycles of the 1 loop " << std::endl; - os << "patnloop2 n \t sets number of cycles of the 2 loop " << std::endl; - os << "patwait0 addr \t configures pattern wait 0 address " << std::endl; - os << "patwait1 addr \t configures pattern wait 1 address " << std::endl; - os << "patwait2 addr \t configures pattern wait 2 address " << std::endl; - os << "patwaittime0 nclk \t sets wait 0 waiting time in clock number " << std::endl; - os << "patwaittime1 nclk \t sets wait 1 waiting time in clock number " << std::endl; - os << "patwaittime2 nclk \t sets wait 2 waiting time in clock number " << std::endl; - os << "adcinvert mask\t sets the adcinversion mask (hex)" << std::endl; - os << "adcdisable mask\t sets the adcdisable mask (hex)" << std::endl; - - } - if (action==GET_ACTION || action==HELP_ACTION){ - os << "pattern \t cannot get" << std::endl; - os << "patword \t cannot get" << std::endl; - os << "patioctrl \t returns inputs/outputs of the chiptest board - only advanced users!" << std::endl; - os << "patclkctrl\t returns output clk enable of the chiptest board- only advanced users! " << std::endl; - os << "patlimits \t returns pattern limits between addr1 and addr2" << std::endl; - os << "patloop0 \t returns the limits of the 0 loop " << std::endl; - os << "patloop1 \t returns the limits of the 1 loop " << std::endl; - os << "patloop2 \t returns the limits of the 2 loop " << std::endl; - os << "patnloop0 \t returns the number of cycles of the 0 loop " << std::endl; - os << "patnloop1 \t returns the number of cycles of the 1 loop " << std::endl; - os << "patnloop2 \t returns the number of cycles of the 2 loop " << std::endl; - os << "patwait0 \t returns the pattern wait 0 address " << std::endl; - os << "patwait1 \t returns the pattern wait 1 address " << std::endl; - os << "patwait2 \t returns the pattern wait 2 address " << std::endl; - os << "patwaittime0 \t returns the wait 0 waiting time in clock number " << std::endl; - os << "patwaittime1 \t returns the wait 1 waiting time in clock number " << std::endl; - os << "patwaittime2 \t returns the wait 2 waiting time in clock number " << std::endl; - os << "adcinvert \t returns the adcinversion mask " << std::endl; - - os << "adcdisable \t returns the adcdisable mask " << std::endl; - - } - return os.str(); - -} - - -string slsDetectorCommand::cmdPattern(int narg, char *args[], int action) { - - - if (action==HELP_ACTION) - return helpPattern(narg, args, action); - /******** - - Must implement set ctb functions in slsDetector and multiSlsDetector - - **********/ - string fname; - int addr, start, stop, n; - uint64_t word, t; - - myDet->setOnline(ONLINE_FLAG); - - ostringstream os; - if (cmd=="pattern") { - //get fname fron stdin - - if (action==PUT_ACTION) { - fname=string(args[1]); - os << myDet->setCTBPattern(fname); - } else if (action==GET_ACTION) - os << "Cannot get"; - } else if (cmd=="patword") { - - if (action==PUT_ACTION) { - //get addr, word from stdin - - if(narg<3) - return string("wrong usage: should specify both address and value (hexadecimal fomat) "); - - if (sscanf(args[1],"%x",&addr)) - ; - else - return string("Could not scan address (hexadecimal fomat) ")+string(args[1]); - - if (sscanf(args[2],"%lx",&word)) - ; - else - return string("Could not scan value (hexadecimal fomat) ")+string(args[2]); - - - os << hex << myDet->setCTBWord(addr,word) << dec; - } else if (action==GET_ACTION) - os << "Cannot get"; - - - } else if (cmd=="patioctrl") { - //get word from stdin - - if (action==PUT_ACTION) { - - if (sscanf(args[1],"%lx",&word)) - ; - else - return string("Could not scan value (hexadecimal fomat) ")+string(args[1]); - - - myDet->setCTBWord(-1,word); - } - - os << hex << myDet->setCTBWord(-1,-1) << dec; - } else if (cmd=="patclkctrl") { - //get word from stdin - - - - if (action==PUT_ACTION) { - - if (sscanf(args[1],"%lx",&word)) - ; - else - return string("Could not scan value (hexadecimal fomat) ")+string(args[1]); - - - myDet->setCTBWord(-2,word); - } - - os << hex << myDet->setCTBWord(-2,-1) << dec; - - - } else if (cmd=="patlimits") { - //get start, stop from stdin - if (action==PUT_ACTION) { - if(narg<3) return string("wrong usage: should specify both start and stop address (hexadecimal fomat) "); - n=-1; - if (sscanf(args[1],"%x",&start)) - ; - else - return string("Could not scan start address (hexadecimal fomat) ")+string(args[1]); - - - if (sscanf(args[2],"%x",&stop)) - ; - else - return string("Could not scan stop address (hexadecimal fomat) ")+string(args[2]); - - myDet->setCTBPatLoops(-1,start, stop,n); - } - - start=-1; - stop=-1; - n=-1; - myDet->setCTBPatLoops(-1,start, stop,n); - os << hex << start << " " << stop;// << " "<< dec << n ; - } else if (cmd=="patloop0") { - //get start, stop from stdin - - - //get start, stop from stdin - if (action==PUT_ACTION) { - if(narg<3) return string("wrong usage: should specify both start and stop address (hexadecimal fomat) "); - n=-1; - if (sscanf(args[1],"%x",&start)) - ; - else - return string("Could not scan start address (hexadecimal fomat) ")+string(args[1]); - - - if (sscanf(args[2],"%x",&stop)) - ; - else - return string("Could not scan stop address (hexadecimal fomat) ")+string(args[2]); - - myDet->setCTBPatLoops(0,start, stop,n); - } - - start=-1; - stop=-1; - n=-1; - myDet->setCTBPatLoops(0,start, stop,n); - os << hex << start << " " << stop;// << " "<< dec << n ; - - - } else if (cmd=="patloop1") { - - //get start, stop from stdin - if (action==PUT_ACTION) { - if(narg<3) return string("wrong usage: should specify both start and stop address (hexadecimal fomat) "); - n=-1; - if (sscanf(args[1],"%x",&start)) - ; - else - return string("Could not scan start address (hexadecimal fomat) ")+string(args[1]); - - - if (sscanf(args[2],"%x",&stop)) - ; - else - return string("Could not scan stop address (hexadecimal fomat) ")+string(args[2]); - - myDet->setCTBPatLoops(1,start, stop,n); - } - - start=-1; - stop=-1; - n=-1; - myDet->setCTBPatLoops(1,start, stop,n); - os << hex << start << " " << stop;// << " "<< dec << n ; - - - - - } else if (cmd=="patloop2") { - - //get start, stop from stdin - if (action==PUT_ACTION) { - if(narg<3) return string("wrong usage: should specify both start and stop address (hexadecimal fomat) "); - n=-1; - if (sscanf(args[1],"%x",&start)) - ; - else - return string("Could not scan start address (hexadecimal fomat) ")+string(args[1]); - - - if (sscanf(args[2],"%x",&stop)) - ; - else - return string("Could not scan stop address (hexadecimal fomat) ")+string(args[2]); - - myDet->setCTBPatLoops(2,start, stop,n) ; - } - - start=-1; - stop=-1; - n=-1; - myDet->setCTBPatLoops(2,start, stop,n); - os << hex << start << " " << stop << dec;// << " "<< dec << n ; - - - } else if (cmd=="patnloop0") { - start=-1; - stop=-1; - - - if (action==PUT_ACTION) { - - if (sscanf(args[1],"%d",&n)) - ; - else - return string("Could not scan number of loops ")+string(args[1]); - - - myDet->setCTBPatLoops(0,start, stop,n) ; - } - - - - start=-1; - stop=-1; - n=-1; - myDet->setCTBPatLoops(0,start, stop,n); - os << n ; - } else if (cmd=="patnloop1") { - - - start=-1; - stop=-1; - - - if (action==PUT_ACTION) { - - if (sscanf(args[1],"%d",&n)) - ; - else - return string("Could not scan number of loops ")+string(args[1]); - - - myDet->setCTBPatLoops(1,start, stop,n) ; - } - - - - start=-1; - stop=-1; - n=-1; - myDet->setCTBPatLoops(1,start, stop,n); - os << n ; - - - - - } else if (cmd=="patnloop2") { - - - start=-1; - stop=-1; - - - if (action==PUT_ACTION) { - - if (sscanf(args[1],"%d",&n)) - ; - else - return string("Could not scan number of loops ")+string(args[1]); - - - myDet->setCTBPatLoops(2,start, stop,n) ; - } - - - - start=-1; - stop=-1; - n=-1; - myDet->setCTBPatLoops(2,start, stop,n); - os << n ; - - - - } else if (cmd=="patwait0") { - - - - - if (action==PUT_ACTION) { - - if (sscanf(args[1],"%x",&addr)) - ; - else - return string("Could not scan wait address (hex format)")+string(args[1]); - - - myDet->setCTBPatWaitAddr(0,addr); - } - - - - os << hex << myDet->setCTBPatWaitAddr(0,-1) << dec; - - - - - - - } else if (cmd=="patwait1") { - - - if (action==PUT_ACTION) { - - if (sscanf(args[1],"%x",&addr)) - ; - else - return string("Could not scan wait address (hex format)")+string(args[1]); - - - myDet->setCTBPatWaitAddr(1,addr); - } - - - - os << hex << myDet->setCTBPatWaitAddr(1,-1) << dec; - - - - } else if (cmd=="patwait2") { - - if (action==PUT_ACTION) { - - if (sscanf(args[1],"%x",&addr)) - ; - else - return string("Could not scan wait address (hex format)")+string(args[1]); - - - myDet->setCTBPatWaitAddr(2,addr); - } - - - - os << hex << myDet->setCTBPatWaitAddr(2,-1) << dec ; - - } else if (cmd=="patwaittime0") { - - - - - - if (action==PUT_ACTION) { - - if (sscanf(args[1],"%ld",&t)) - ; - else - return string("Could not scan wait time")+string(args[1]); - - - myDet->setCTBPatWaitTime(0,t); - } - - - - os << myDet->setCTBPatWaitTime(0,-1); - - - - - - - - } else if (cmd=="patwaittime1") { - - if (action==PUT_ACTION) { - - if (sscanf(args[1],"%ld",&t)) - ; - else - return string("Could not scan wait time ")+string(args[1]); - - - myDet->setCTBPatWaitTime(1,t); - } - - - - os << myDet->setCTBPatWaitTime(1,-1); - - - - } else if (cmd=="patwaittime2") { - if (action==PUT_ACTION) { - - if (sscanf(args[1],"%ld",&t)) - ; - else - return string("Could not scan wait time ")+string(args[1]); - - - myDet->setCTBPatWaitTime(2,t); - } - - - - os << myDet->setCTBPatWaitTime(2,-1); - - } else if (cmd=="adcinvert") { - if (action==PUT_ACTION) { - - if (sscanf(args[1],"%x",&addr)) - ; - else - return string("Could not scan adcinvert reg ")+string(args[1]); - - - myDet->writeRegister(67,addr); - } - - - - os << hex << myDet->readRegister(67) << dec; - - } else if (cmd=="dut_clk") { - if (action==PUT_ACTION) { - - if (sscanf(args[1],"%x",&addr)) - ; - else - return string("Could not scan dut_clk reg ")+string(args[1]); - - - myDet->writeRegister(123,addr); //0x7b - } - - - - os << hex << myDet->readRegister(123) << dec; //0x7b - } else if (cmd=="adcdisable") { - - int nroi=0; - ROI roiLimits[MAX_ROIS]; - - if (action==PUT_ACTION) { - - if (sscanf(args[1],"%x",&addr)) - ; - else - return string("Could not scan adcdisable reg ")+string(args[1]); - - /******USE ROI?!?!?!?*********/ - // roiLimits[i].xmin;roiLimits[i].xmax;roiLimits[i].ymin;roiLimits[i].ymin;roiLimits[i].ymax - //int mask=1; - int ii=0; - while (ii<32) { - ++nroi; - roiLimits[nroi-1].xmin=ii; - roiLimits[nroi-1].ymin=0; - roiLimits[nroi-1].ymax=0; - while ((addr&(1<=32) - break; - } - if (ii>=32) { - break; - cout << "ROI "<< nroi << " xmin "<=32) - break; - } - roiLimits[nroi-1].xmax=ii-1; - if (ii>=32) { - cout << "ROI "<< nroi << " xmin "<setROI(nroi-1,roiLimits); - // myDet->writeRegister(94,addr); - // myDet->writeRegister(120,addr); - } - - ROI *aa=myDet->getROI(nroi); - - int reg=0xffffffff; - if (nroi<1) - reg=0; - else { - for (int iroi=0; iroixmin<< " xmax "<< (aa+iroi)->xmax<< endl; - for (int ich=(aa+iroi)->xmin; ich<=(aa+iroi)->xmax; ++ich) { - reg&=~(1<isMultiSlsDetectorClass() && aa != NULL) - delete [] aa; - - //os <<" "<< hex << myDet->readRegister(120) << dec; - - } - - - - else return helpPattern(narg, args, action); - - - - - - return os.str(); - -} - - - -string slsDetectorCommand::helpPulse(int narg, char *args[], int action) { - - ostringstream os; - if (action==PUT_ACTION || action==HELP_ACTION) { - os << "pulse [n] [x] [y] \t pulses pixel at coordinates (x,y) n number of times" << std::endl; - os << "pulsenmove [n] [x] [y]\t pulses pixel n number of times and moves relatively by x value (x axis) and y value(y axis)" << std::endl; - os << "pulsechip [n] \t pulses chip n number of times, while n=-1 will reset it to normal mode" << std::endl; - } - if (action==GET_ACTION || action==HELP_ACTION){ - os << "pulse \t cannot get" << std::endl; - os << "pulsenmove \t cannot get" << std::endl; - os << "pulsechip \t cannot get" << std::endl; - } - return os.str(); - -} - - -string slsDetectorCommand::cmdPulse(int narg, char *args[], int action) { - int retval = FAIL; - - if (action==HELP_ACTION) - return helpPulse(narg, args, action); - else if (action==GET_ACTION) - return string("cannot get ")+cmd; - - myDet->setOnline(ONLINE_FLAG); - - - int ival1=-1; - if (!sscanf(args[1],"%d",&ival1)) - return string("Could not scan 1st argument ")+string(args[1]); - - if (string(args[0])==string("pulsechip")) - retval = myDet->pulseChip(ival1); - - - else{ - //next commands requires 3 addnl. arguments - int ival2=-1,ival3=-1; - if(narg<4) - return string("insufficient arguments:\n" + helpPulse(narg, args, action)); - if (!sscanf(args[2],"%d",&ival2)) - return string("Could not scan 2nd argument ")+string(args[2]); - if (!sscanf(args[3],"%d",&ival3)) - return string("Could not scan 3rd argument ")+string(args[3]); - - - if (string(args[0])==string("pulse")) - retval = myDet->pulsePixel(ival1,ival2,ival3); - - else if (string(args[0])==string("pulsenmove")) - retval = myDet->pulsePixelNMove(ival1,ival2,ival3); - - else return string("could not decode command")+cmd; - - } - - - if(retval == OK) - return string(" successful"); - else - return string(" unsuccessful"); - -} - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/slsDetectorSoftware/slsDetector/slsDetectorCommand.h b/slsDetectorSoftware/slsDetector/slsDetectorCommand.h deleted file mode 100644 index a4a43e2a4..000000000 --- a/slsDetectorSoftware/slsDetector/slsDetectorCommand.h +++ /dev/null @@ -1,187 +0,0 @@ - -#ifndef SLS_DETECTOR_COMMAND_H -#define SLS_DETECTOR_COMMAND_H - - -#include "sls_detector_defs.h" -#include "slsDetectorUtils.h" - - - -/** @short This class handles the command line I/Os, help etc. of the text clients */ - - -class slsDetectorCommand : public virtual slsDetectorDefs { - - public: - - - slsDetectorCommand(slsDetectorUtils *det); - virtual ~slsDetectorCommand(){}; - - /* /\** */ - /* executes a set of string arguments according to a given format. It is used to read/write configuration file, dump and retrieve detector settings and for the command line interface command parsing */ - /* \param narg number of arguments */ - /* \param args array of string arguments */ - /* \param action can be PUT_ACTION or GET_ACTION (from text client even READOUT_ACTION for acquisition) */ - /* \returns answer string */ - /* *\/ */ - virtual std::string executeLine(int narg, char *args[], int action); - - /* /\** */ - /* returns the help for the executeLine command */ - /* \param os output stream to return the help to */ - /* \param action can be PUT_ACTION or GET_ACTION (from text client even READOUT_ACTION for acquisition) */ - /* *\/ */ - std::string helpLine(int narg, char *args[], int action=HELP_ACTION); - static std::string helpAcquire(int narg, char *args[], int action); - static std::string helpData(int narg, char *args[], int action); - static std::string helpFrame(int narg, char *args[], int action); - static std::string helpStatus(int narg, char *args[], int action); - static std::string helpDataStream(int narg, char *args[], int action); - static std::string helpFree(int narg, char *args[], int action); - static std::string helpHostname(int narg, char *args[], int action); - static std::string helpUser(int narg, char *args[], int action); - static std::string helpMaster(int narg, char *args[], int action); - static std::string helpSync(int narg, char *args[], int action); - static std::string helpExitServer(int narg, char *args[], int action); - static std::string helpSettingsDir(int narg, char *args[], int action); - static std::string helpCalDir(int narg, char *args[], int action); - static std::string helpTrimEn(int narg, char *args[], int action); - static std::string helpOutDir(int narg, char *args[], int action); - static std::string helpFileName(int narg, char *args[], int action); - static std::string helpFileIndex(int narg, char *args[], int action); - static std::string helpFlatField(int narg, char *args[], int action); - static std::string helpRateCorr(int narg, char *args[], int action); - static std::string helpBadChannels(int narg, char *args[], int action); - static std::string helpAngConv(int narg, char *args[], int action); - static std::string helpThreaded(int narg, char *args[], int action); - static std::string helpPositions(int narg, char *args[], int action); - static std::string helpScripts(int narg, char *args[], int action); - static std::string helpScans(int narg, char *args[], int action); - static std::string helpNetworkParameter(int narg, char *args[], int action); - static std::string helpPort(int narg, char *args[], int action); - static std::string helpLock(int narg, char *args[], int action); - static std::string helpLastClient(int narg, char *args[], int action); - static std::string helpOnline(int narg, char *args[], int action); - static std::string helpConfigureMac(int narg, char *args[], int action); - static std::string helpDetectorSize(int narg, char *args[], int action); - static std::string helpSettings(int narg, char *args[], int action); - static std::string helpSN(int narg, char *args[], int action); - static std::string helpDigiTest(int narg, char *args[], int action); - static std::string helpRegister(int narg, char *args[], int action); - static std::string helpDAC(int narg, char *args[], int action); - static std::string helpTimer(int narg, char *args[], int action); - static std::string helpTiming(int narg, char *args[], int action); - static std::string helpTimeLeft(int narg, char *args[], int action); - static std::string helpSpeed(int narg, char *args[], int action); - static std::string helpAdvanced(int narg, char *args[], int action); - static std::string helpConfiguration(int narg, char *args[], int action); - static std::string helpImage(int narg, char *args[], int action); - static std::string helpCounter(int narg, char *args[], int action); - static std::string helpADC(int narg, char *args[], int action); - static std::string helpTempControl(int narg, char *args[], int action); - static std::string helpEnablefwrite(int narg, char *args[], int action); - static std::string helpOverwrite(int narg, char *args[], int action); - static std::string helpReceiver(int narg, char *args[], int action); - static std::string helpPattern(int narg, char *args[], int action); - static std::string helpPulse(int narg, char *args[], int action); - - - - - - - - - - - - - private: - - - slsDetectorUtils *myDet; - - std::string cmdUnderDevelopment(int narg, char *args[], int action); - std::string cmdUnknown(int narg, char *args[], int action); - std::string cmdAcquire(int narg, char *args[], int action); - std::string cmdData(int narg, char *args[], int action); - std::string cmdFrame(int narg, char *args[], int action); - std::string cmdStatus(int narg, char *args[], int action); - std::string cmdDataStream(int narg, char *args[], int action); - std::string cmdFree(int narg, char *args[], int action); - std::string cmdHostname(int narg, char *args[], int action); - std::string cmdUser(int narg, char *args[], int action); - std::string cmdMaster(int narg, char *args[], int action); - std::string cmdSync(int narg, char *args[], int action); - std::string cmdHelp(int narg, char *args[], int action); - std::string cmdExitServer(int narg, char *args[], int action); - std::string cmdSettingsDir(int narg, char *args[], int action); - std::string cmdCalDir(int narg, char *args[], int action); - std::string cmdTrimEn(int narg, char *args[], int action); - std::string cmdOutDir(int narg, char *args[], int action); - std::string cmdFileName(int narg, char *args[], int action); - std::string cmdFileIndex(int narg, char *args[], int action); - std::string cmdFlatField(int narg, char *args[], int action); - std::string cmdRateCorr(int narg, char *args[], int action); - std::string cmdBadChannels(int narg, char *args[], int action); - std::string cmdAngConv(int narg, char *args[], int action); - std::string cmdThreaded(int narg, char *args[], int action); - std::string cmdPositions(int narg, char *args[], int action); - std::string cmdScripts(int narg, char *args[], int action); - std::string cmdScans(int narg, char *args[], int action); - std::string cmdNetworkParameter(int narg, char *args[], int action); - std::string cmdPort(int narg, char *args[], int action); - std::string cmdLock(int narg, char *args[], int action); - std::string cmdLastClient(int narg, char *args[], int action); - std::string cmdOnline(int narg, char *args[], int action); - std::string cmdConfigureMac(int narg, char *args[], int action); - std::string cmdDetectorSize(int narg, char *args[], int action); - std::string cmdSettings(int narg, char *args[], int action); - std::string cmdSN(int narg, char *args[], int action); - std::string cmdDigiTest(int narg, char *args[], int action); - std::string cmdRegister(int narg, char *args[], int action); - std::string cmdDAC(int narg, char *args[], int action); - std::string cmdTiming(int narg, char *args[], int action); - std::string cmdTimer(int narg, char *args[], int action); - std::string cmdTimeLeft(int narg, char *args[], int action); - std::string cmdSpeed(int narg, char *args[], int action); - std::string cmdAdvanced(int narg, char *args[], int action); - std::string cmdConfiguration(int narg, char *args[], int action); - std::string cmdImage(int narg, char *args[], int action); - std::string cmdCounter(int narg, char *args[], int action); - std::string cmdADC(int narg, char *args[], int action); - std::string cmdTempControl(int narg, char *args[], int action); - std::string cmdEnablefwrite(int narg, char *args[], int action); - std::string cmdOverwrite(int narg, char *args[], int action); - std::string cmdReceiver(int narg, char *args[], int action); - std::string cmdPattern(int narg, char *args[], int action); - std::string cmdPulse(int narg, char *args[], int action); - - - int numberOfCommands; - std::string cmd; - - typedef std::string (slsDetectorCommand::*MemFuncGetter)(int narg, char *args[], int action); - - - struct FuncTable - { - std::string m_pFuncName; - MemFuncGetter m_pFuncPtr; - }; - - - - FuncTable descrToFuncMap[1000]; - - - - -}; - - - -#endif - diff --git a/slsDetectorSoftware/slsDetector/slsDetectorUsers.cpp b/slsDetectorSoftware/slsDetector/slsDetectorUsers.cpp deleted file mode 100644 index 556777db1..000000000 --- a/slsDetectorSoftware/slsDetector/slsDetectorUsers.cpp +++ /dev/null @@ -1,523 +0,0 @@ -#include "slsDetectorUsers.h" -#include "detectorData.h" -#include "multiSlsDetector.h" -#include "multiSlsDetectorCommand.h" - - -using namespace std; - -slsDetectorUsers::slsDetectorUsers(int& ret, int id) : myDetector(0), myCmd(0){ - try { - myDetector=new multiSlsDetector(id); - } catch(...) { - ret = 1; - return; - } - myCmd=new multiSlsDetectorCommand(myDetector); - ret = 0; - -} - - -slsDetectorUsers::~slsDetectorUsers() { - if (myDetector) - delete myDetector; -} - -string slsDetectorUsers::getDetectorDeveloper(){ - return myDetector->getDetectorDeveloper(); -} - -int slsDetectorUsers::setOnline(int const online){ - return myDetector->setOnline(online); -} - -int slsDetectorUsers::setReceiverOnline(int const online){ - return myDetector->setReceiverOnline(online); -} - -void slsDetectorUsers::startMeasurement(){ - myDetector->acquire(0); -} - -int slsDetectorUsers::stopMeasurement(){ - return myDetector->stopAcquisition(); -} - -int slsDetectorUsers::getDetectorStatus(){ - return (int)myDetector->getRunStatus(); -} - -string slsDetectorUsers::getFilePath(){ - return myDetector->getFilePath(); -} - -string slsDetectorUsers::setFilePath(string s){ - return myDetector->setFilePath(s); -} - -string slsDetectorUsers::getFileName(){ - return myDetector->getFileName(); -} - -string slsDetectorUsers::setFileName(string s){ - return myDetector->setFileName(s); -} - -int slsDetectorUsers::getFileIndex(){ - return (int)myDetector->getFileIndex(); -} - -int slsDetectorUsers::setFileIndex(int i){ - return (int)myDetector->setFileIndex(i); -} - -string slsDetectorUsers::getFlatFieldCorrectionDir(){ - return myDetector->getFlatFieldCorrectionDir(); -} - -string slsDetectorUsers::setFlatFieldCorrectionDir(string dir){ - return myDetector->setFlatFieldCorrectionDir(dir); -} - -string slsDetectorUsers::getFlatFieldCorrectionFile(){ - return myDetector->getFlatFieldCorrectionFile(); -} - -int slsDetectorUsers::setFlatFieldCorrectionFile(string fname){ - return myDetector->setFlatFieldCorrectionFile(fname); -} - -int slsDetectorUsers::enableFlatFieldCorrection(int i){ - return myDetector->enableFlatFieldCorrection(i); -} - -int slsDetectorUsers::enableCountRateCorrection(int i){ - return myDetector->enableCountRateCorrection(i); -} - -int slsDetectorUsers::enablePixelMaskCorrection(int i){ - return myDetector->enablePixelMaskCorrection(i); -} -int slsDetectorUsers::enableAngularConversion(int i){ - return myDetector->enableAngularConversion(i); -} -int slsDetectorUsers::enableWriteToFile(int i){ - return myDetector->enableWriteToFile(i); -} - -int slsDetectorUsers::setPositions(int nPos, double *pos){ - return myDetector->setPositions(nPos, pos); -} - -int slsDetectorUsers::getPositions(double *pos){ - return myDetector->getPositions(pos); -} - -int slsDetectorUsers::setDetectorSize(int x0, int y0, int nx, int ny){ - // only one roi - slsDetectorDefs::ROI roi[1]; - roi[0].xmin = x0; - roi[0].ymin = y0; - roi[0].xmax = x0 + nx; - roi[0].ymax = y0 + ny; - return myDetector->setROI(1, roi); -} - -int slsDetectorUsers::getDetectorSize(int &x0, int &y0, int &nx, int &ny){ - // default (no roi) - y0=0; - x0=0; - nx=myDetector->getTotalNumberOfChannels(slsDetectorDefs::X); - ny=myDetector->getTotalNumberOfChannels(slsDetectorDefs::Y); - - int n = 0; - slsDetectorDefs::ROI* roi = myDetector->getROI(n); - - // roi - if (roi != NULL && n == 1) { - x0 = roi[0].xmin; - y0 = roi[0].ymin; - nx = roi[0].xmax - roi[0].xmin; - ny = roi[0].ymax - roi[0].ymin; - } - - if (roi != NULL) - delete [] roi; - - return nx*ny; -} - -int slsDetectorUsers::getMaximumDetectorSize(int &nx, int &ny){ - nx=myDetector->getMaxNumberOfChannelsPerDetector(slsDetectorDefs::X); - ny=myDetector->getMaxNumberOfChannelsPerDetector(slsDetectorDefs::Y); - return nx*ny; -} - -int slsDetectorUsers::setBitDepth(int i){ - return myDetector->setDynamicRange(i); -} - -int slsDetectorUsers::setSettings(int isettings){ - return myDetector->slsDetectorBase::setSettings(isettings); -} - -int slsDetectorUsers::getThresholdEnergy(){ - return myDetector->getThresholdEnergy(-1); -} - -int slsDetectorUsers::setThresholdEnergy(int e_eV){ - return myDetector->setThresholdEnergy(e_eV); -} - -int slsDetectorUsers::setThresholdEnergy(int e_ev, int tb, int isettings, int id) { - return myDetector->slsDetectorBase::setThresholdEnergy(e_ev, tb, isettings, id); -} - -double slsDetectorUsers::setExposureTime(double t, bool inseconds, int imod){ - if(!inseconds) - return myDetector->setExposureTime((int64_t)t,imod); - - // + 0.5 to round for precision lost from converting double to int64_t - int64_t tms = (int64_t)(t * (1E+9) + 0.5); - if (t < 0) tms = -1; - tms = myDetector->setExposureTime(tms,imod); - if (tms < 0) - return -1; - return ((1E-9) * (double)tms); -} - -double slsDetectorUsers::setExposurePeriod(double t, bool inseconds, int imod){ - if(!inseconds) - return myDetector->setExposurePeriod((int64_t)t,imod); - - // + 0.5 to round for precision lost from converting double to int64_t - int64_t tms = (int64_t)(t * (1E+9) + 0.5); - if (t < 0) tms = -1; - tms = myDetector->setExposurePeriod(tms,imod); - if (tms < 0) - return -1; - return ((1E-9) * (double)tms); -} - -double slsDetectorUsers::setDelayAfterTrigger(double t, bool inseconds, int imod){ - if(!inseconds) - return myDetector->setDelayAfterTrigger((int64_t)t,imod); - - // + 0.5 to round for precision lost from converting double to int64_t - int64_t tms = (int64_t)(t * (1E+9) + 0.5); - if (t < 0) tms = -1; - tms = myDetector->setDelayAfterTrigger(tms,imod); - if (tms < 0) - return -1; - return ((1E-9) * (double)tms); -} - -int64_t slsDetectorUsers::setNumberOfGates(int64_t t, int imod){ - return myDetector->setNumberOfGates(t,imod); -} - -int64_t slsDetectorUsers::setNumberOfFrames(int64_t t, int imod){ - return myDetector->setNumberOfFrames(t,imod); -} - -int64_t slsDetectorUsers::setNumberOfCycles(int64_t t, int imod){ - return myDetector->setNumberOfCycles(t,imod); -} - -int slsDetectorUsers::setTimingMode(int pol){ - return myDetector->setTimingMode(pol); -} - -int slsDetectorUsers::readConfigurationFile(string const fname){ - return myDetector->readConfigurationFile(fname); -} - -int slsDetectorUsers::dumpDetectorSetup(string const fname){ - return myDetector->dumpDetectorSetup(fname); -} - -int slsDetectorUsers::retrieveDetectorSetup(string const fname){ - return myDetector->retrieveDetectorSetup(fname); -} - -string slsDetectorUsers::getDetectorType(){ - return myDetector->sgetDetectorsType(); -} - -void slsDetectorUsers::initDataset(int refresh){ - myDetector->initDataset(refresh); -} - -void slsDetectorUsers::addFrame(double *data, double pos, double i0, double t, string fname, double var){ - myDetector->addFrame(data,pos,i0,t,fname,var); -} - - -void slsDetectorUsers::finalizeDataset(double *a, double *v, double *e, int &np){ - myDetector->finalizeDataset(a, v, e, np); -} - -int slsDetectorUsers::setReceiverMode(int n){ - return myDetector->setReadReceiverFrequency(n); -} - -int slsDetectorUsers::enableDataStreamingFromReceiver(int i){ - return myDetector->enableDataStreamingFromReceiver(i); -} - -int slsDetectorUsers::enableDataStreamingToClient(int i){ - return myDetector->enableDataStreamingToClient(i); -} - -int slsDetectorUsers::setReceiverDataStreamingOutPort(int i){ - return myDetector->setReceiverDataStreamingOutPort(i); -} - -int slsDetectorUsers::setClientDataStreamingInPort(int i){ - return myDetector->setClientDataStreamingInPort(i); -} - -string slsDetectorUsers::setReceiverDataStreamingOutIP(string ip){ - return myDetector->setReceiverDataStreamingOutIP(ip); -} - -string slsDetectorUsers::setClientDataStreamingInIP(string ip){ - return myDetector->setClientDataStreamingInIP(ip); -} - -int64_t slsDetectorUsers::getModuleFirmwareVersion(int imod){ - return myDetector->getModuleFirmwareVersion(imod); -} - -int64_t slsDetectorUsers::getModuleSerialNumber(int imod){ - return myDetector->getModuleSerialNumber(imod); -} - -int64_t slsDetectorUsers::getDetectorFirmwareVersion(int imod){ - return myDetector->getDetectorFirmwareVersion(imod); -} - -int64_t slsDetectorUsers::getDetectorSerialNumber(int imod){ - return myDetector->getDetectorSerialNumber(imod); -} - -int64_t slsDetectorUsers::getDetectorSoftwareVersion(int imod){ - return myDetector->getDetectorSoftwareVersion(imod); -} - -int64_t slsDetectorUsers::getThisSoftwareVersion(){ - return myDetector->getThisSoftwareVersion(); -} - -int slsDetectorUsers::enableGapPixels(int enable) { - return myDetector->enableGapPixels(enable); -} - -std::string slsDetectorUsers::setReceiverFramesDiscardPolicy(std::string f) { - return myDetector->getReceiverFrameDiscardPolicy( - myDetector->setReceiverFramesDiscardPolicy( - myDetector->getReceiverFrameDiscardPolicy(f))); -} - -int slsDetectorUsers::setReceiverPartialFramesPadding(int f) { - return myDetector->setReceiverPartialFramesPadding(f); -} - -int slsDetectorUsers::setReceiverFramesPerFile(int f) { - return myDetector->setReceiverFramesPerFile(f); -} - -int slsDetectorUsers::sendSoftwareTrigger() { - return myDetector->sendSoftwareTrigger(); -} - -double slsDetectorUsers::getMeasuredPeriod(bool inseconds, int imod) { - if(!inseconds) - return myDetector->getTimeLeft(slsReceiverDefs::MEASURED_PERIOD, imod); - - int64_t tms = myDetector->getTimeLeft(slsReceiverDefs::MEASURED_PERIOD, imod); - if (tms < 0) - return -1; - return ((1E-9) * (double)tms); -} - -double slsDetectorUsers::getMeasuredSubFramePeriod(bool inseconds, int imod) { - if(!inseconds) - return myDetector->getTimeLeft(slsReceiverDefs::MEASURED_SUBPERIOD, imod); - - int64_t tms = myDetector->getTimeLeft(slsReceiverDefs::MEASURED_SUBPERIOD, imod); - if (tms < 0) - return -1; - return ((1E-9) * (double)tms); -} - -void slsDetectorUsers::registerDataCallback(int( *userCallback)(detectorData*, int, int, void*), void *pArg){ - myDetector->registerDataCallback(userCallback,pArg); -} - -void slsDetectorUsers::registerRawDataCallback(int( *userCallback)(double*, int, void*), void *pArg){ - myDetector->registerRawDataCallback(userCallback,pArg); -} - -void slsDetectorUsers::registerAcquisitionFinishedCallback(int( *func)(double,int, void*), void *pArg){ - myDetector->registerAcquisitionFinishedCallback(func,pArg); -} - -void slsDetectorUsers::registerGetPositionCallback( double (*func)(void*),void *arg){ - myDetector->registerGetPositionCallback(func,arg); -} - -void slsDetectorUsers::registerConnectChannelsCallback( int (*func)(void*),void *arg){ - myDetector->registerConnectChannelsCallback(func,arg); -} - -void slsDetectorUsers::registerDisconnectChannelsCallback( int (*func)(void*),void *arg){ - myDetector->registerDisconnectChannelsCallback(func,arg); -} - -void slsDetectorUsers::registerGoToPositionCallback( int (*func)(double,void*),void *arg){ - myDetector->registerGoToPositionCallback(func,arg); -} - -void slsDetectorUsers::registerGoToPositionNoWaitCallback( int (*func)(double,void*),void *arg){ - myDetector->registerGoToPositionNoWaitCallback(func,arg); -} - -void slsDetectorUsers::registerGetI0Callback( double (*func)(int,void*),void *arg){ - myDetector->registerGetI0Callback(func,arg); -} - - -string slsDetectorUsers::putCommand(int narg, char *args[], int pos){ - if(narg < 2) - return string("Error: Insufficient Parameters"); - return myCmd->putCommand(narg, args, pos); -} - -string slsDetectorUsers::getCommand(int narg, char *args[], int pos){ - if(narg < 1) - return string("Error: Insufficient Parameters"); - return myCmd->getCommand(narg, args, pos); -} - - -int slsDetectorUsers::setClockDivider(int value) { - return myDetector->setClockDivider(value); -} - -int slsDetectorUsers::setParallelMode(int value) { - if(value >= 0) - myDetector->setParallelMode(value); - return myDetector->getParallelMode(); -} - -int slsDetectorUsers::setOverflowMode(int value) { - if(value >= 0) - myDetector->setOverflowMode(value); - return myDetector->getOverflowMode(); -} - -int slsDetectorUsers::setAllTrimbits(int val, int id) { - return myDetector->setAllTrimbits(val, id); -} - -int slsDetectorUsers::setDAC(string dac, int val, int id) { - int dacindex = myDetector->getDACIndex(dac); - if(dacindex == -1) return -9999; - return myDetector->setDACValue(val, dacindex, id); -} - -int slsDetectorUsers::getADC(string adc, int id) { - int adcindex = myDetector->getADCIndex(adc); - if(adcindex == -1) return -9999; - return myDetector->getADCValue(adcindex, id); -} - -int slsDetectorUsers::startReceiver() { - return myDetector->startReceiver(); -} - -int slsDetectorUsers::stopReceiver() { - return myDetector->stopReceiver(); -} - -int slsDetectorUsers::startAcquisition() { - return myDetector->startAcquisition(); -} - -int slsDetectorUsers::stopAcquisition() { - return myDetector->stopAcquisition(); -} - -int slsDetectorUsers::setReceiverSilentMode(int i) { - return myDetector->setReceiverSilentMode(i); -} - -int slsDetectorUsers::setHighVoltage(int i) { - return myDetector->setHighVoltage(i); -} - -int slsDetectorUsers::resetFramesCaughtInReceiver() { - return myDetector->resetFramesCaught(); -} - -int slsDetectorUsers::setReceiverFifoDepth(int i) { - return myDetector->setReceiverFifoDepth(i); -} - -int slsDetectorUsers::setFlowControl10G(int i) { - return myDetector->setFlowControl10G(i); -} - -int slsDetectorUsers::setTenGigabitEthernet(int i) { - return myDetector->enableTenGigabitEthernet(i); -} - -int slsDetectorUsers::getNMods() { - return myDetector->getNMods(); -} - -double slsDetectorUsers::setSubFrameExposureTime(double t, bool inseconds, int imod){ - if(!inseconds) - return myDetector->setSubFrameExposureTime((int64_t)t,imod); - else { - // + 0.5 to round for precision lost from converting double to int64_t - int64_t tms = (int64_t)(t * (1E+9) + 0.5); - if (t < 0) tms = -1; - tms = myDetector->setSubFrameExposureTime(tms,imod); - if (tms < 0) - return -1; - return ((1E-9) * (double)tms); - } -} - -double slsDetectorUsers::setSubFrameExposureDeadTime(double t, bool inseconds, int imod){ - if(!inseconds) - return myDetector->setSubFrameDeadTime((int64_t)t,imod); - else { - // + 0.5 to round for precision lost from converting double to int64_t - int64_t tms = (int64_t)(t * (1E+9) + 0.5); - if (t < 0) tms = -1; - tms = myDetector->setSubFrameDeadTime(tms,imod); - if (tms < 0) - return -1; - return ((1E-9) * (double)tms); - } -} - -int64_t slsDetectorUsers::setNumberOfStorageCells(int64_t t, int imod) { - return myDetector->setTimer(slsReceiverDefs::STORAGE_CELL_NUMBER, t, imod); -} - -int slsDetectorUsers::setStoragecellStart(int pos) { - return myDetector->setStoragecellStart(pos); -} - -int slsDetectorUsers::setROI(int n, slsDetectorDefs::ROI roiLimits[], int imod) { - return myDetector->setROI(n, roiLimits, imod); -} - -slsDetectorDefs::ROI* slsDetectorUsers::getROI(int &n, int imod) { - return myDetector->getROI(n, imod); -} diff --git a/slsDetectorSoftware/slsDetector/slsDetectorUsers.h b/slsDetectorSoftware/slsDetector/slsDetectorUsers.h deleted file mode 100644 index eece05be3..000000000 --- a/slsDetectorSoftware/slsDetector/slsDetectorUsers.h +++ /dev/null @@ -1,935 +0,0 @@ -#ifndef SLS_DETECTOR_USERS_H -#define SLS_DETECTOR_USERS_H - - - -/** - * - * - * - * @author Anna Bergamaschi - * @version 0.1alpha - */ - - - -class detectorData; -class multiSlsDetector; -class multiSlsDetectorCommand; - -#include "sls_detector_defs.h" - - -#include -#include - - - - - -/* - \mainpage -

API for SLS detectors data acquisition

-
-*/ -/** - \mainpage - - -

API for SLS detectors data acquisition

- -
- - Although the SLS detectors group delvelops several types of detectors (1/2D, counting/integrating etc.) it is common interest of the group to use a common platfor for data acquisition - - The architecture of the acquisitions system is intended as follows: - \li A socket server running on the detector (or more than one in some special cases) - \li C++ classes common to all detectors for client-server communication. These can be supplied to users as libraries and embedded also in acquisition systems which are not developed by the SLS - \li the possibility of using a Qt-based graphical user interface (with eventually root analisys capabilities) - \li the possibility of running all commands from command line. In order to ensure a fast operation of this so called "text client" the detector parameters should not be re-initialized everytime. For this reason a shared memory block is allocated where the main detector flags and parameters are stored - \li a Root library for data postprocessing and detector calibration (energy, angle). - - -slsDetectorUsers is a class to control the detector which should be instantiated by the users in their acquisition software (EPICS, spec etc.). A callback for dislaying the data can be registered. -More advanced configuration functions are not implemented and can be written in a configuration file tha can be read/written. - -slsReceiverUsers is a class to receive the data for detectors with external data receiver (e.g. GOTTHARD). Callbacks can be registered to process the data or save them in specific formats. - -detectorData is a structure containing the data and additional information which is used to return the data e.g. to the GUI for displaying them. - - -You can find examples of how this classes can be instatiated in mainClient.cpp and mainReceiver.cpp - - - \authors Anna Bergamaschi, Dhanya Thattil - @version 3.0 -

Currently supported detectors

-\li MYTHEN -\li GOTTHARD controls -\li GOTTHARD data receiver -\li EIGER -\li JUNGFRAU - - - -*/ - -/** - @short The slsDetectorUsers class is a minimal interface class which should be instantiated by the users in their acquisition software (EPICS, spec etc.). More advanced configuration functions are not implemented and can be written in a configuration or parameters file that can be read/written. - - Class for detector functionalities to embed the detector controls in the users custom interface e.g. EPICS, Lima etc. - -*/ - - -class slsDetectorUsers - { - - public: - - /** @short default constructor - * @param ret address of return value. It will be set to 0 for success, else 1 for failure - * @param id multi detector id - * in creating multidetector object - */ - slsDetectorUsers(int& ret, int id=0); - - /** @short virtual destructor */ - virtual ~slsDetectorUsers(); - - /** - @short useful to define subset of working functions - \returns "PSI" or "Dectris" - */ - std::string getDetectorDeveloper(); - - /** @short sets the onlineFlag - \param online can be: -1 returns wether the detector is in online (1) or offline (0) state; 0 detector in offline state; 1 detector in online state - \returns 0 (offline) or 1 (online) - */ - int setOnline(int const online=-1); - - /** @short sets the receivers onlineFlag - \param online can be: -1 returns wether the receiver is in online (1) or offline (0) state; 0 receiver in offline state; 1 receiver in online state - \returns 0 (offline) or 1 (online) - */ - int setReceiverOnline(int const online=-1); - - - /** - @short start measurement and acquires - \returns OK/FAIL - */ - void startMeasurement(); - - /** - @short stop measurement - \returns OK/FAIL - */ - int stopMeasurement(); - - /** - @short get run status - \returns status mask - */ - int getDetectorStatus(); - - /** - @short returns the default output files path - */ - std::string getFilePath(); - - /** - @short sets the default output files path - \param s file path - \returns file path - */ - std::string setFilePath(std::string s); - - /** - @short - \returns the default output files root name - */ - std::string getFileName(); - - /** - @short sets the default output files path - \param s file name - \returns the default output files root name - - */ - std::string setFileName(std::string s); - - /** - @short - \returns the default output file index - */ - int getFileIndex(); - - /** - @short sets the default output file index - \param i file index - \returns the default output file index - */ - int setFileIndex(int i); - - /** - @short get flat field corrections file directory - \returns flat field correction file directory - */ - std::string getFlatFieldCorrectionDir(); - - /** - @short set flat field corrections file directory - \param dir flat field correction file directory - \returns flat field correction file directory - */ - std::string setFlatFieldCorrectionDir(std::string dir); - - /** - @short get flat field corrections file name - \returns flat field correction file name - */ - std::string getFlatFieldCorrectionFile(); - - /** - @short set flat field correction file - \param fname name of the flat field file (or "" if disable) - \returns 0 if disable (or file could not be read), >0 otherwise - */ - int setFlatFieldCorrectionFile(std::string fname=""); - - - - /** - @short enable/disable flat field corrections (without changing file name) - \param i 0 disables, 1 enables, -1 gets - \returns 0 if ff corrections disabled, 1 if enabled - */ - int enableFlatFieldCorrection(int i=-1); - - /** - @short enable/disable count rate corrections - \param i 0 disables, 1 enables with default values, -1 gets - \returns 0 if count corrections disabled, 1 if enabled - */ - int enableCountRateCorrection(int i=-1); - - /** - @short enable/disable bad channel corrections - \param i 0 disables, 1 enables, -1 gets - \returns 0 if bad channels corrections disabled, 1 if enabled - */ - int enablePixelMaskCorrection(int i=-1); - - /** - @short enable/disable angular conversion - \param i 0 disables, 1 enables, -1 gets - \returns 0 if angular conversion disabled, 1 if enabled - */ - int enableAngularConversion(int i=-1); - - /**Enable write file function included*/ - - int enableWriteToFile(int i=-1); - - /** - @short set positions for the acquisition - \param nPos number of positions - \param pos array with the encoder positions - \returns number of positions - */ - int setPositions(int nPos, double *pos); - - /** - @short get positions for the acquisition - \param pos array which will contain the encoder positions - \returns number of positions - */ - int getPositions(double *pos=NULL); - - /** - @short sets the detector size (only 1 ROI) (not Mythen supported anymore) - \param x0 horizontal position origin in channel number (-1 unchanged) - \param y0 vertical position origin in channel number (-1 unchanged) - \param nx number of channels in horiziontal (-1 unchanged) - \param ny number of channels in vertical (-1 unchanged) - \returns OK/FAIL - */ - int setDetectorSize(int x0=-1, int y0=-1, int nx=-1, int ny=-1); - - /** - @short gets detector size (roi size if only one roi) (not Mythen supported anymore) - \param x0 horizontal position origin in channel number - \param y0 vertical position origin in channel number - \param nx number of channels in horiziontal - \param ny number of channels in vertical - \returns total number of channels - */ - int getDetectorSize(int &x0, int &y0, int &nx, int &ny); - /** - @short gets the maximum detector size - \param nx number of channels in horiziontal - \param ny number of channels in vertical - \returns OK/FAIL - */ - int getMaximumDetectorSize(int &nx, int &ny); - - - /** - @short set/get dynamic range - \param i dynamic range (-1 get) - \returns current dynamic range - */ - int setBitDepth(int i=-1); - - - - /** - @short set detector settings - \param isettings settings index (-1 gets) - \returns current settings - */ - int setSettings(int isettings=-1); - - /** - @short get threshold energy - \returns current threshold value for imod in ev (-1 failed) - */ - int getThresholdEnergy(); - - - /** - @short set threshold energy - \param e_eV threshold in eV - \returns current threshold value for imod in ev (-1 failed) - */ - int setThresholdEnergy(int e_eV); - - /** - @short set threshold energy with choice to load trimbits (eiger only) - \param e_ev threshold in ev - \param tb 1 loads trimbits, 0 does not load trimbits - \param isettings settings index (-1 uses current setting) - \param id module index (-1 for all) - \returns current threshold value in ev (-1 failed) - */ - int setThresholdEnergy(int e_ev, int tb, int isettings = -1, int id = -1); - - - /** - @short set/get exposure time value - \param t time in sn (-1 gets) - \param inseconds true if the value is in s, else ns - \param imod module number (-1 for all) - \returns timer set value in ns, or s if specified - */ - - double setExposureTime(double t=-1, bool inseconds=false, int imod = -1); - - /** - @short set/get exposure period - \param t time in ns (-1 gets) - \param inseconds true if the value is in s, else ns - \param imod module number (-1 for all) - \returns timer set value in ns, or s if specified - */ - double setExposurePeriod(double t=-1, bool inseconds=false, int imod = -1); - - /** - @short set/get delay after trigger - \param t time in ns (-1 gets) - \param inseconds true if the value is in s, else ns - \param imod module number (-1 for all) - \returns timer set value in ns, or s if specified - */ - double setDelayAfterTrigger(double t=-1, bool inseconds=false, int imod = -1); - - /** - @short set/get number of gates - \param t number of gates (-1 gets) - \param imod module number (-1 for all) - \returns number of gates - */ - int64_t setNumberOfGates(int64_t t=-1, int imod = -1); - - /** - @short set/get number of frames i.e. number of exposure per trigger - \param t number of frames (-1 gets) - \param imod module number (-1 for all) - \returns number of frames - */ - int64_t setNumberOfFrames(int64_t t=-1, int imod = -1); - - /** - @short set/get number of cycles i.e. number of triggers - \param t number of frames (-1 gets) - \param imod module number (-1 for all) - \returns number of frames - */ - int64_t setNumberOfCycles(int64_t t=-1, int imod = -1); - - /** - @short set/get the external communication mode - \param pol value to be set \sa getTimingMode - \returns current external communication mode - */ - int setTimingMode(int pol=-1); - - /** - @short Reads the configuration file -- will contain all the informations needed for the configuration (e.g. for a PSI detector caldir, settingsdir, angconv, badchannels, hostname etc.) - \param fname file name - \returns OK or FAIL - */ - int readConfigurationFile(std::string const fname); - - - /** - @short Reads the parameters from the detector and writes them to file - \param fname file to write to - \returns OK or FAIL - - */ - int dumpDetectorSetup(std::string const fname); - /** - @short Loads the detector setup from file - \param fname file to read from - \returns OK or FAIL - - */ - int retrieveDetectorSetup(std::string const fname); - - /** - @short useful for data plotting etc. - \returns Mythen, Eiger, Gotthard etc. - */ - std::string getDetectorType(); - - /** - @short sets the mode by which gui requests data from receiver - \param n is 0 for random requests for fast acquisitions and greater than 0 for nth read requests - \returns the mode set in the receiver - */ - int setReceiverMode(int n=-1); - - /** - @short register calbback for accessing detector final data, also enables data streaming in client and receiver (if receiver exists) - \param userCallback function for plotting/analyzing the data. Its arguments are the data structure d and the frame number f, s is for subframe number for eiger for 32 bit mode - \param pArg argument - */ - - void registerDataCallback(int( *userCallback)(detectorData* d, int f, int s, void*), void *pArg); - - /** - @short register callback for accessing raw data - if the rawDataCallback is registered, no filewriting/postprocessing will be carried on automatically by the software - the raw data are deleted by the software - \param userCallback function for postprocessing and saving the data - p is the pointer to the data, n is the number of channels - \param pArg argument - */ - - void registerRawDataCallback(int( *userCallback)(double* p, int n, void*), void *pArg); - - /** - @short function to initalize a set of measurements (reset binning if angular conversion, reset summing otherwise) - can be overcome by the user's functions thanks to the virtual property - \param refresh if 1, all parameters like ffcoefficients, badchannels, ratecorrections etc. are reset (should be called at least onece with this option), if 0 simply reset merging/ summation - */ - - virtual void initDataset(int refresh); - - - /** - @short adds frame to merging/summation - can be overcome by the user's functions thanks to the virtual property - \param data pointer to the raw data - \param pos encoder position - \param i0 beam monitor readout for intensity normalization (if 0 not performed) - \param t exposure time in seconds, required only if rate corrections - \param fname file name (unused since filewriting would be performed by the user) - \param var optional parameter - unused. - */ - - virtual void addFrame(double *data, double pos, double i0, double t, std::string fname, double var); - - /** - @short finalizes the data set returning the array of angles, values and errors to be used as final data - can be overcome by the user's functions thanks to the virtual property - \param a pointer to the array of angles - can be null if no angular coversion is required - \param v pointer to the array of values - \param e pointer to the array of errors - \param np reference returning the number of points - */ - - virtual void finalizeDataset(double *a, double *v, double *e, int &np); - - - /** Enable or disable streaming data from receiver (creates transmitting sockets) - * @param i 0 to disable 1 to enable -1 to only get the value - * @returns data streaming from receiver enable - */ - int enableDataStreamingFromReceiver(int i=-1); - - /** - * Enable data streaming to client (creates receiving sockets) - * @param i 0 to disable, 1 to enable, -1 to get the value - * @returns data streaming to client enable - */ - int enableDataStreamingToClient(int i=-1); - - /** (for expert users) - * Set/Get receiver streaming out ZMQ port - * For multi modules, it calculates (increments), sets the ports and restarts the sockets - * @param i sets, -1 gets - * @returns receiver streaming out ZMQ port (if multiple, of first receiver socket) - */ - int setReceiverDataStreamingOutPort(int i=-1); - - /** (for expert users) - * Set/Get client streaming in ZMQ port - * For multi modules, it calculates (increments), sets the ports and restarts the sockets - * @param i sets, -1 gets - * @returns client streaming in ZMQ port (if multiple, of first client socket) - */ - int setClientDataStreamingInPort(int i=-1); - - /** (for expert users) - * Set/Get receiver streaming out ZMQ IP - * By default, it is the IP of receiver hostname - * @param ip sets, empty std::string gets - * @returns receiver streaming out ZMQ IP - */ - std::string setReceiverDataStreamingOutIP(std::string ip=""); - - /** (for expert users) - * Set/Get client streaming in ZMQ IP - * By default, it is the IP of receiver hostname - * @param ip sets, empty std::string gets - * @returns client streaming in ZMQ IP - */ - std::string setClientDataStreamingInIP(std::string ip=""); - - /** - get get Module Firmware Version - @param imod module number - \returns id - */ - int64_t getModuleFirmwareVersion(int imod=-1); - - /** - get get Module Serial Number (only mythen) - @param imod module number - \returns id - */ - int64_t getModuleSerialNumber(int imod=-1); - - /** - get get Detector Firmware Version - @param imod module number - \returns id - */ - int64_t getDetectorFirmwareVersion(int imod=-1); - - /** - get get Detector Serial Number - @param imod module number - \returns id - */ - int64_t getDetectorSerialNumber(int imod=-1); - - /** - get get Detector Software Version - @param imod module number - \returns id - */ - int64_t getDetectorSoftwareVersion(int imod=-1); - - /** - get this Software Version - \returns id - */ - int64_t getThisSoftwareVersion(); - - /** - * Enable gap pixels, only for Eiger and for 8,16 and 32 bit mode. - * 4 bit mode gap pixels only in gui call back (registerDataCallback) - * @param enable 1 sets, 0 unsets, -1 gets - * @return gap pixel enable or -1 for error - */ - int enableGapPixels(int enable=-1); - - /** - * Sets the frames discard policy in receiver - * frame discard policy options: - * @param f nodiscard (default),discardempty, discardpartial (fastest), get to get the value - * @returns f nodiscard (default),discardempty, discardpartial (fastest) - */ - std::string setReceiverFramesDiscardPolicy(std::string f="get"); - - /** - * Sets the frame padding in receiver - * @param f 0 does not partial frames, 1 pads partial frames (-1 gets) - * @returns partial frames padding enable - */ - int setReceiverPartialFramesPadding(int f = -1); - - /** - * Sets the frames per file in receiver - * @param f frames per file, 0 is infinite ie. every frame in same file (-1 gets) - * @returns frames per file - */ - int setReceiverFramesPerFile(int f = -1); - - /** - * Sends a software internal trigger (EIGER only) - * @returns 0 for success, 1 for fail - */ - int sendSoftwareTrigger(); - - /** - * get measured period between previous two frames(EIGER only) - * @param inseconds true if the value is in s, else ns - * @param imod module number (-1 for all) - * @returns measured period - */ - double getMeasuredPeriod(bool inseconds=false, int imod = -1); - - /** - * get measured sub period between previous two sub frames in 32 bit mode (EIGER only) - * @param inseconds true if the value is in s, else ns - * @param imod module number (-1 for all) - * @returns measured sub period - */ - double getMeasuredSubFramePeriod(bool inseconds=false, int imod = -1); - - /** - @short register calbback for accessing detector final data - \param func function to be called at the end of the acquisition. gets detector status and progress index as arguments - \param pArg argument - */ - void registerAcquisitionFinishedCallback(int( *func)(double,int, void*), void *pArg); - - /** - @short register calbback for reading detector position - \param func function for reading the detector position - \param arg argument - */ - - void registerGetPositionCallback( double (*func)(void*),void *arg); - /** - @short register callback for connecting to the epics channels - \param func function for connecting to the epics channels - \param arg argument - */ - void registerConnectChannelsCallback( int (*func)(void*),void *arg); - /** - @short register callback to disconnect the epics channels - \param func function to disconnect the epics channels - \param arg argument - */ - void registerDisconnectChannelsCallback( int (*func)(void*),void *arg); - /** - @short register callback for moving the detector - \param func function for moving the detector - \param arg argument - */ - void registerGoToPositionCallback( int (*func)(double,void*),void *arg); - /** - @short register callback for moving the detector without waiting - \param func function for moving the detector - \param arg argument - */ - void registerGoToPositionNoWaitCallback( int (*func)(double,void*),void *arg); - /** - @short register calbback reading to I0 - \param func function for reading the I0 (called with parameter 0 before the acquisition, 1 after and the return value used as I0) - \param arg argument - */ - void registerGetI0Callback( double (*func)(int,void*),void *arg); - - /** - @short sets parameters in command interface http://www.psi.ch/detectors/UsersSupportEN/slsDetectorClientHowTo.pdf - \param narg value to be set - \param args value to be set - \param pos position of detector in multislsdetector list - \returns answer std::string - */ - std::string putCommand(int narg, char *args[], int pos=-1); - - /** - @short gets parameters in command interface http://www.psi.ch/detectors/UsersSupportEN/slsDetectorClientHowTo.pdf - \param narg value to be set - \param args value to be set - \param pos position of detector in multislsdetector list - \returns answer std::string - */ - std::string getCommand(int narg, char *args[], int pos=-1); - - /************************************************************************ - - ADVANCED FUNCTIONS - - *********************************************************************/ - /** - @short sets clock divider of detector - \param value value to be set (-1 gets) - \returns speed of detector - */ - int setClockDivider(int value); - - /** - @short sets parallel mode - \param value 0 for non parallel, 1 for parallel, 2 for safe mode (-1 gets) - \returns gets parallel mode - */ - int setParallelMode(int value); - - /** - * @short show saturated for overflow in subframes in 32 bit mode (eiger only) - * \param value 0 for do not show saturatd, 1 for show saturated (-1 gets) - * \returns overflow mode enable in 32 bit mode - */ - int setOverflowMode(int value); - - /** - @short sets all trimbits to value (only available for eiger) - \param val value to be set (-1 gets) - \param id module index (-1 for all) - \returns value set - */ - int setAllTrimbits(int val, int id = -1); - - /** - @short set dac value - \param dac dac as std::string. can be vcmp_ll, vcmp_lr, vcmp_rl, vcmp_rr, vthreshold, vrf, vrs, vtr, vcall, vcp. others not supported - \param val value to be set (-1 gets) - \param id module index (-1 for all) - \returns dac value or -1 (if id=-1 & dac value is different for all modules) or -9999 if dac std::string does not match - */ - int setDAC(std::string dac, int val, int id = -1); - - /** - @short get adc value - \param adc adc as std::string. can be temp_fpga, temp_fpgaext, temp_10ge, temp_dcdc, temp_sodl, temp_sodr, temp_fpgafl, temp_fpgafr. others not supported - \param id module index (-1 for all) - \returns adc value in millidegree Celsius or -1 (if id=-1 & adc value is different for all modules) or -9999 if adc std::string does not match - */ - int getADC(std::string adc, int id = -1); - - /** - @short start receiver listening mode - \returns returns OK or FAIL - */ - int startReceiver(); - - /** - @short stop receiver listening mode - \returns returns OK or FAIL - */ - int stopReceiver(); - - /** - start detector real time acquisition in non blocking mode - does not include scans, scripts, incrementing file index, s - tarting/stopping receiver, resetting frames caught in receiver - \returns OK if all detectors are properly started, FAIL otherwise - */ - int startAcquisition(); - - /** - stop detector real time acquisition - \returns OK if all detectors are properly started, FAIL otherwise - */ - int stopAcquisition(); - - /** - * set receiver in silent mode - * @param i 1 sets, 0 unsets (-1 gets) - * @returns silent mode of receiver - */ - int setReceiverSilentMode(int i); - - /** - * set high voltage - * @param i > 0 sets, 0 unsets, (-1 gets) - * @returns high voltage - */ - int setHighVoltage(int i); - - /** - * reset frames caught in receiver - * should be called before startReceiver() - * @returns OK or FAIL - */ - int resetFramesCaughtInReceiver(); - - /** - * set receiver fifo depth - * @param i number of images in fifo depth (-1 gets) - * @returns receiver fifo depth - */ - int setReceiverFifoDepth(int i = -1); - - /** - * set flow control for 10Gbe (Eiger only) - * @param i 1 sets, 0 unsets (-1 gets) - * @return flow control enable for 10 Gbe - */ - int setFlowControl10G(int i = -1); - - /** - * enable/disable 10GbE (Eiger only) - * @param i 1 sets, 0 unsets (-1 gets) - * @return 10GbE enable - */ - int setTenGigabitEthernet(int i = -1); - - /** - * returns total number of detector modules - * @returns the total number of detector modules - */ - int getNMods(); - - /** - * Set sub frame exposure time (only for Eiger) - * @param t sub frame exposure time (-1 gets) - * @param inseconds true if the value is in s, else ns - * @param imod module number (-1 for all) - * @returns sub frame exposure time in ns, or s if specified - */ - double setSubFrameExposureTime(double t=-1, bool inseconds=false, int imod = -1); - - /** - * Set sub frame dead time (only for Eiger) - * Very advanced feature. Meant to be a constant in config file by an expert for each individual module - * @param t sub frame dead time (-1 gets) - * @param inseconds true if the value is in s, else ns - * @param imod module number (-1 for all) - * @returns sub frame dead time in ns, or s if specified - */ - double setSubFrameExposureDeadTime(double t=-1, bool inseconds=false, int imod = -1); - - /** - * set/get number of additional storage cells (Jungfrau) - * @param t number of additional storage cells. Default is 0. (-1 gets) - * @param imod module number (-1 for all) - * @returns number of additional storage cells - */ - int64_t setNumberOfStorageCells(int64_t t=-1, int imod = -1); - - /** - * Set storage cell that stores first acquisition of the series (Jungfrau) - * @param pos storage cell index. Value can be 0 to 15. Default is 15. (-1 gets) - * @returns the storage cell that stores the first acquisition of the series - */ - int setStoragecellStart(int pos=-1); - - /** - * Set ROI (Gotthard) (>= 1 roi, but max 1 roi per module) - * At the moment only one set allowed - * @param n number of rois - * @param roiLimits array of roi - * @param imod module number (-1 for all) - * @returns OK or FAIL - */ - int setROI(int n=-1, slsDetectorDefs::ROI roiLimits[]=NULL, int imod = -1); - - /** - * Get ROI from each detector and convert it to the multi detector scale (Gotthard) - * >= 1 roi, but max 1 roi per module - * @param n number of rois - * @param imod module number (ignored) - * @returns pointer to array of ROI structure - */ - slsDetectorDefs::ROI* getROI(int &n, int imod = -1); - - /************************************************************************ - - STATIC FUNCTIONS - - *********************************************************************/ - - /** @short returns std::string from run status index - \param s run status index - \returns std::string error, waiting, running, data, finished or unknown when wrong index - */ - static std::string runStatusType(int s){ \ - switch (s) { \ - case 0: return std::string("idle"); \ - case 1: return std::string("error"); \ - case 2: return std::string("waiting"); \ - case 3: return std::string("finished"); \ - case 4: return std::string("data"); \ - case 5: return std::string("running"); \ - case 6: return std::string("stoppped"); \ - default: return std::string("unknown"); \ - }}; - - - - /** @short returns detector settings std::string from index - \param s can be standard, fast, highgain, dynamicgain, lowgain, mediumgain, veryhighgain - \returns setting index (-1 unknown std::string) - */ - - static int getDetectorSettings(std::string s){ \ - if (s=="standard") return 0; \ - if (s=="fast") return 1; \ - if (s=="highgain") return 2; \ - if (s=="dynamicgain") return 3; \ - if (s=="lowgain") return 4; \ - if (s=="mediumgain") return 5; \ - if (s=="veryhighgain") return 6; \ - return -1; }; - - /** @short returns detector settings std::string from index - \param s settings index - \returns standard, fast, highgain, dynamicgain, lowgain, mediumgain, veryhighgain, undefined when wrong index - */ - static std::string getDetectorSettings(int s){\ - switch(s) { \ - case 0: return std::string("standard");\ - case 1: return std::string("fast");\ - case 2: return std::string("highgain");\ - case 3: return std::string("dynamicgain"); \ - case 4: return std::string("lowgain"); \ - case 5: return std::string("mediumgain"); \ - case 6: return std::string("veryhighgain"); \ - default: return std::string("undefined"); \ - }}; - - - - /** - @short returns external communication mode std::string from index - \param f index for communication mode - \returns auto, trigger, ro_trigger, gating, triggered_gating, unknown when wrong mode - */ - - static std::string getTimingMode(int f){ \ - switch(f) { \ - case 0: return std::string( "auto"); \ - case 1: return std::string("trigger"); \ - case 2: return std::string("ro_trigger"); \ - case 3: return std::string("gating"); \ - case 4: return std::string("triggered_gating"); \ - case 5: return std::string("burst_trigger"); \ - default: return std::string( "unknown"); \ - } }; - - /** - @short returns external communication mode std::string from index - \param s index for communication mode - \returns auto, trigger, ro_trigger, gating, triggered_gating, unknown when wrong mode - */ - - static int getTimingMode(std::string s){ \ - if (s== "auto") return 0; \ - if (s== "trigger") return 1; \ - if (s== "ro_trigger") return 2; \ - if (s== "gating") return 3; \ - if (s== "triggered_gating") return 4; \ - return -1; }; - - - private: - multiSlsDetector *myDetector; - multiSlsDetectorCommand *myCmd; - }; - -#endif diff --git a/slsDetectorSoftware/slsDetector/slsDetectorUtils.cpp b/slsDetectorSoftware/slsDetector/slsDetectorUtils.cpp deleted file mode 100644 index e81ee57f5..000000000 --- a/slsDetectorSoftware/slsDetector/slsDetectorUtils.cpp +++ /dev/null @@ -1,950 +0,0 @@ -#include "slsDetectorUtils.h" -#include "usersFunctions.h" -#include "slsDetectorCommand.h" -#include "postProcessing.h" -#include "enCalLogClass.h" -#include "angCalLogClass.h" - -#include -#include -#include -#include //clock() -#include -using namespace std; - -slsDetectorUtils::slsDetectorUtils() { - - -#ifdef VERBOSE - cout << "setting callbacks" << endl; -#endif - acquisition_finished=NULL; - acqFinished_p=NULL; - measurement_finished=NULL; - measFinished_p=NULL; - progress_call=0; - pProgressCallArg=0; - registerGetPositionCallback(&defaultGetPosition, NULL); - registerConnectChannelsCallback(&defaultConnectChannels,NULL); - registerDisconnectChannelsCallback(&defaultDisconnectChannels,NULL); - registerGoToPositionCallback(&defaultGoToPosition,NULL); - registerGoToPositionNoWaitCallback(&defaultGoToPositionNoWait,NULL); - registerGetI0Callback(&defaultGetI0,NULL); -#ifdef VERBOSE - - registerAcquisitionFinishedCallback(&dummyAcquisitionFinished,this); - registerMeasurementFinishedCallback(&dummyMeasurementFinished,this); - cout << "done " << endl; -#endif - -}; - - - - - -int slsDetectorUtils::acquire(int delflag){ - - //ensure acquire isnt started multiple times by same client - if (isAcquireReady() == FAIL) - return FAIL; - -#ifdef VERBOSE - struct timespec begin,end; - clock_gettime(CLOCK_REALTIME, &begin); -#endif - - //in the real time acquisition loop, processing thread will wait for a post each time - sem_init(&sem_newRTAcquisition,1,0); - //in the real time acquistion loop, main thread will wait for processing thread to be done each time (which in turn waits for receiver/ext process) - sem_init(&sem_endRTAcquisition,1,0); - - - bool receiver = (setReceiverOnline()==ONLINE_FLAG); - if(!receiver){ - setDetectorIndex(-1); - } - - int nc=setTimer(CYCLES_NUMBER,-1); - int nf=setTimer(FRAME_NUMBER,-1); - if (nc==0) nc=1; - if (nf==0) nf=1; - int multiframe = nc*nf; - - progressIndex=0; - *stoppedFlag=0; - - angCalLogClass *aclog=NULL; - enCalLogClass *eclog=NULL; - int connectChannels=0; - -#ifdef VERBOSE - cout << "Acquire function "<< delflag << endl; - cout << "Stopped flag is "<< stoppedFlag << delflag << endl; -#endif - - void *status; - if ((*correctionMask&(1<< ANGULAR_CONVERSION)) || (*correctionMask&(1<< I0_NORMALIZATION)) || getActionMode(angCalLog) || (getScanMode(0)==positionScan)|| (getScanMode(1)==positionScan)) { - if (connectChannels==0) - if (connect_channels) { - connect_channels(CCarg); - connectChannels=1; - } - } - if (getActionMode(angCalLog)) { - aclog=new angCalLogClass(this); - } - if (getActionMode(enCalLog)) { - eclog=new enCalLogClass(this); - - } - - - setJoinThread(0); - positionFinished(0); - - - int nm=timerValue[MEASUREMENTS_NUMBER]; - if (nm<1) - nm=1; - - - int np=getNumberOfPositions(); - if (np<1) - np=1; - - - int ns0=1; - if (*actionMask & (1 << MAX_ACTIONS)) { - ns0=getScanSteps(0); - if (ns0<1) - ns0=1; - } - - int ns1=1; - if (*actionMask & (1 << (MAX_ACTIONS+1))) { - ns1=getScanSteps(1); - if (ns1<1) - ns1=1; - } - - // verify receiver is idle - if(receiver){ - pthread_mutex_lock(&mg); - if(getReceiverStatus()!=IDLE) - if(stopReceiver() == FAIL) - *stoppedFlag=1; - pthread_mutex_unlock(&mg); - } - - - if (*threadedProcessing) - startThread(delflag); -#ifdef VERBOSE - cout << " starting thread " << endl; -#endif - - //resets frames caught in receiver - if(receiver){ - pthread_mutex_lock(&mg); - if (resetFramesCaught() == FAIL) - *stoppedFlag=1; - pthread_mutex_unlock(&mg); - } - - - for(int im=0;im0) { - moveDetector(detPositions[ip]); - IncrementPositionIndex(); -#ifdef VERBOSE - std::cout<< "moving to position" << std::endl; -#endif - } - } else - break; - - - pthread_mutex_lock(&mp); - createFileName(); - pthread_mutex_unlock(&mp); - - // script before - if (*stoppedFlag==0) { - executeAction(scriptBefore); - } else - break; - - - // header before - if (*stoppedFlag==0) { - executeAction(headerBefore); - - if (*correctionMask&(1<< ANGULAR_CONVERSION) || aclog){ - positionFinished(0); - setCurrentPosition(getDetectorPosition()); - } - - if (aclog) - aclog->addStep(getCurrentPosition(), getCurrentFileName()); - - if (eclog) - eclog->addStep(setDAC(-1,THRESHOLD,0), getCurrentFileName()); - - - if (*correctionMask&(1<< I0_NORMALIZATION)) { - if (get_i0) - get_i0(0, IOarg); - } - - setCurrentFrameIndex(0); - - if (multiframe>1) - setFrameIndex(0); - else - setFrameIndex(-1); - - // file name and start receiver - if(receiver){ - pthread_mutex_lock(&mp); - createFileName(); - pthread_mutex_unlock(&mp); - //send receiver file name - pthread_mutex_lock(&mg); - setFileName(fileIO::getFileName()); - - if(startReceiver() == FAIL) { - cout << "Start receiver failed " << endl; - stopReceiver(); - *stoppedFlag=1; - pthread_mutex_unlock(&mg); - break; - } -#ifdef VERBOSE - cout << "Receiver started " << endl; -#endif - pthread_mutex_unlock(&mg); - - //let processing thread listen to these packets - sem_post(&sem_newRTAcquisition); - } -#ifdef VERBOSE - cout << "Acquiring " << endl; -#endif - startAndReadAll(); -#ifdef VERBOSE - cout << "detector finished" << endl; - cout << "returned! " << endl; -#endif - - - if (*correctionMask&(1<< I0_NORMALIZATION)) { - if (get_i0) - currentI0=get_i0(1,IOarg); - } -#ifdef VERBOSE - cout << "pos finished? " << endl; -#endif - - positionFinished(1); - -#ifdef VERBOSE - cout << "done! " << endl; -#endif - - - if (*threadedProcessing==0){ -#ifdef VERBOSE - cout << "start unthreaded process data " << endl; -#endif - processData(delflag); - } - - } else - break; - - while (dataQueueSize()) usleep(100000); - - // close file - if(!receiver){ - detectorType type = getDetectorsType(); - if ((type==GOTTHARD) || (type==MOENCH) || (type==JUNGFRAUCTB) ){ - if((*correctionMask)&(1<0) - nc=timerValue[CYCLES_NUMBER]; - - if (timerValue[MEASUREMENTS_NUMBER]>0) - nm=timerValue[MEASUREMENTS_NUMBER]; - - if (*numberOfPositions>0) - npos=*numberOfPositions; - - if ((nScanSteps[0]>0) && (*actionMask & (1 << MAX_ACTIONS))) - nscan[0]=nScanSteps[0]; - - if ((nScanSteps[1]>0) && (*actionMask & (1 << (MAX_ACTIONS+1)))) - nscan[1]=nScanSteps[1]; - - totalProgress=nm*nf*nc*npos*nscan[0]*nscan[1]; - -#ifdef VERBOSE - cout << "nc " << nc << endl; - cout << "nm " << nm << endl; - cout << "nf " << nf << endl; - cout << "npos " << npos << endl; - cout << "nscan[0] " << nscan[0] << endl; - cout << "nscan[1] " << nscan[1] << endl; - - cout << "Set total progress " << totalProgress << endl; -#endif - return totalProgress; -} - - - - - - - - - -int slsDetectorUtils::setBadChannelCorrection(string fname, int &nbadtot, int *badchanlist, int off){ - - int nbad; - int badlist[MAX_BADCHANS]; - - ifstream infile; - string str; - //int interrupt=0; - //int ich; - //int chmin,chmax; -#ifdef VERBOSE - std::cout << "utils: Setting bad channel correction to " << fname << std::endl; -#endif - // int modmi=0; - int modma=1; - int singlefile=0; - - string fn; - int offset=off; - - - nbadtot=0; - - if (fname=="" || fname=="none") { - ; - } else { - - if (fname.find(".sn")==string::npos && fname.find(".chans")==string::npos) { - modma=setNumberOfModules(); - singlefile=1; - } - - for (int im=0; im0 && nbadtot> sargname; - // if (ssstr.good()) { - strcpy(myargs[iargval],sargname.c_str()); - args[iargval]=myargs[iargval]; -#ifdef VERBOSE - std::cout<< args[iargval] << std::endl; -#endif - iargval++; - // } - skip=0; - } - - if (level!=2) { - if (string(args[0])==string("flatfield")) - skip=1; - else if (string(args[0])==string("badchannels")) - skip=1; - else if (string(args[0])==string("trimbits")) - skip=1; - } - if (skip==0) - cmd->executeLine(iargval,args,PUT_ACTION); - } - iline++; - } - delete cmd; - infile.close(); - - } else { - std::cout<< "Error opening " << fname << " for reading" << std::endl; - return FAIL; - } -#ifdef VERBOSE - std::cout<< "Read " << iline << " lines" << std::endl; -#endif - - if (getErrorMask()) - return FAIL; - - return OK; - - -} - - -int slsDetectorUtils::dumpDetectorSetup(string const fname, int level){ - - slsDetectorCommand *cmd; - detectorType type = getDetectorsType(); - string names[100]; - int nvar=0; - - // common config - names[nvar++]="fname"; - names[nvar++]="index"; - names[nvar++]="enablefwrite"; - names[nvar++]="overwrite"; - names[nvar++]="dr"; - names[nvar++]="settings"; - names[nvar++]="exptime"; - names[nvar++]="period"; - names[nvar++]="frames"; - names[nvar++]="cycles"; - names[nvar++]="measurements"; - names[nvar++]="timing"; - names[nvar++]="flatfield"; - names[nvar++]="badchannels"; - - switch (type) { - case EIGER: - names[nvar++]="flags"; - names[nvar++]="clkdivider"; - names[nvar++]="threshold"; - names[nvar++]="ratecorr"; - names[nvar++]="trimbits"; - break; - case GOTTHARD: - case PROPIX: - names[nvar++]="flags"; - names[nvar++]="delay"; - names[nvar++]="gates"; - names[nvar++]="ratecorr"; - break; - case JUNGFRAU: - names[nvar++]="flags"; - names[nvar++]="delay"; - names[nvar++]="gates"; - names[nvar++]="ratecorr"; - names[nvar++]="clkdivider"; - break; - case MYTHEN: - names[nvar++]="flags"; - names[nvar++]="threshold"; - names[nvar++]="delay"; - names[nvar++]="gates"; - names[nvar++]="probes"; - names[nvar++]="fineoff"; - names[nvar++]="ratecorr"; - names[nvar++]="trimbits"; - break; - case JUNGFRAUCTB: - names[nvar++]="dac:0"; - names[nvar++]="dac:1"; - names[nvar++]="dac:2"; - names[nvar++]="dac:3"; - names[nvar++]="dac:4"; - names[nvar++]="dac:5"; - names[nvar++]="dac:6"; - names[nvar++]="dac:7"; - names[nvar++]="dac:8"; - names[nvar++]="dac:9"; - names[nvar++]="dac:10"; - names[nvar++]="dac:11"; - names[nvar++]="dac:12"; - names[nvar++]="dac:13"; - names[nvar++]="dac:14"; - names[nvar++]="dac:15"; - names[nvar++]="adcvpp"; - - - - names[nvar++]="adcclk"; - names[nvar++]="clkdivider"; - names[nvar++]="adcphase"; - names[nvar++]="adcpipeline"; - names[nvar++]="adcinvert"; // - names[nvar++]="adcdisable"; - names[nvar++]="patioctrl"; - names[nvar++]="patclkctrl"; - names[nvar++]="patlimits"; - names[nvar++]="patloop0"; - names[nvar++]="patnloop0"; - names[nvar++]="patwait0"; - names[nvar++]="patwaittime0"; - names[nvar++]="patloop1"; - names[nvar++]="patnloop1"; - names[nvar++]="patwait1"; - names[nvar++]="patwaittime1"; - names[nvar++]="patloop2"; - names[nvar++]="patnloop2"; - names[nvar++]="patwait2"; - names[nvar++]="patwaittime2"; - break; - default: - break; - } - - - names[nvar++]="startscript"; - names[nvar++]="startscriptpar"; - names[nvar++]="stopscript"; - names[nvar++]="stopscriptpar"; - names[nvar++]="scriptbefore"; - names[nvar++]="scriptbeforepar"; - names[nvar++]="scriptafter"; - names[nvar++]="scriptafterpar"; - names[nvar++]="scan0script"; - names[nvar++]="scan0par"; - names[nvar++]="scan0prec"; - names[nvar++]="scan0steps"; - names[nvar++]="scan1script"; - names[nvar++]="scan1par"; - names[nvar++]="scan1prec"; - names[nvar++]="scan1steps"; - - - int iv=0; - string fname1; - - - - ofstream outfile; - char *args[4]; - for (int ia=0; ia<4; ia++) { - args[ia]=new char[1000]; - } - - - int nargs; - if (level==2) - nargs=2; - else - nargs=1; - - - if (level==2) { - fname1=fname+string(".config"); - writeConfigurationFile(fname1); - fname1=fname+string(".det"); - } else - fname1=fname; - - - - outfile.open(fname1.c_str(),ios_base::out); - if (outfile.is_open()) { - cmd=new slsDetectorCommand(this); - for (iv=0; ivexecuteLine(1,args,GET_ACTION) << std::endl; - } - - - strcpy(args[0],names[iv].c_str()); - if (level==2) { - fname1=fname+string(".ff"); - strcpy(args[1],fname1.c_str()); - } - outfile << names[iv] << " " << cmd->executeLine(nargs,args,GET_ACTION) << std::endl; - iv++; - - strcpy(args[0],names[iv].c_str()); - if (level==2) { - fname1=fname+string(".bad"); - strcpy(args[1],fname1.c_str()); - } - outfile << names[iv] << " " << cmd->executeLine(nargs,args,GET_ACTION) << std::endl; - iv++; - - - - if (level==2) { - strcpy(args[0],names[iv].c_str()); - size_t c=fname.rfind('/'); - if (cexecuteLine(nargs,args,GET_ACTION) << std::endl; - iv++; - - - } - - - delete cmd; - - outfile.close(); - } - else { - std::cout<< "Error opening parameters file " << fname1 << " for writing" << std::endl; - return FAIL; - } - -#ifdef VERBOSE - std::cout<< "wrote " < -} - -#include -#include -#include -#include -#include - - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - - -//#include "slsDetectorActions_Standalone.h" -#include "slsDetectorActions.h" -#include "postProcessing.h" - -//#define MAX_TIMERS 11 -#define MAXPOS 50 - -#define DEFAULT_HOSTNAME "localhost" -#define DEFAULT_SHM_KEY 5678 -#define THIS_REVISION "$Rev: 822 $" - -//test - -/** - @short class containing all the possible detector functionalities - - (used in the PSi command line interface) -*/ - - -class slsDetectorUtils : public slsDetectorActions, public postProcessing { - - - public: - - slsDetectorUtils(); - - virtual ~slsDetectorUtils(){}; - - /** - * Used when reference is slsDetectorUtils and to determine if command can be implemented as slsDetector/multiSlsDetector object/ - */ - virtual bool isMultiSlsDetectorClass()=0; - - virtual int getNumberOfDetectors(){return 1; }; - - - virtual int getMaxNumberOfChannelsPerDetector(dimension d){return -1;}; - - virtual int setMaxNumberOfChannelsPerDetector(dimension d,int i){return -1;}; - - /** sets the enable which determines if data will be flipped across x or y axis - * \param d axis across which data is flipped - * \param value 0 or 1 to reset/set or -1 to get value - * \return enable flipped data across x or y axis - */ - virtual int setFlippedData(dimension d=X, int value=-1)=0; - - /** - * Enable gap pixels, only for Eiger and for 8,16 and 32 bit mode. 4 bit mode gap pixels only in gui call back - * @param val 1 sets, 0 unsets, -1 gets - * @return gap pixel enable or -1 for error - */ - virtual int enableGapPixels(int val=-1) = 0; - - //int setPositions(int nPos, double *pos){return angularConversion::setPositions(nPos, pos);}; - - // int getPositions(double *pos=NULL){return angularConversion::getPositions(pos);}; - - using slsDetectorBase::setFlatFieldCorrection; - using slsDetectorBase::getDetectorsType; - using postProcessing::setBadChannelCorrection; - - int enableFlatFieldCorrection(int i=-1) {if (i>0) setFlatFieldCorrectionFile("default"); else if (i==0) setFlatFieldCorrectionFile(""); return getFlatFieldCorrection();}; - int enablePixelMaskCorrection(int i=-1) {if (i>0) setBadChannelCorrection("default"); else if (i==0) setBadChannelCorrection(""); return getBadChannelCorrection();}; - int enableCountRateCorrection(int i=-1) {if (i>0) setRateCorrection(-1); else if (i==0) setRateCorrection(0); return getRateCorrection();}; - - - /** - * Set/Get receiver streaming out ZMQ port - * For multi modules, it calculates (increments) and sets the ports - * @param i sets, -1 gets - * @returns receiver streaming out ZMQ port - */ - int setReceiverDataStreamingOutPort(int i) { \ - if (i >= 0) { \ - std::ostringstream ss; ss << i; std::string s = ss.str(); \ - int prev_streaming = enableDataStreamingFromReceiver(); \ - setNetworkParameter(RECEIVER_STREAMING_PORT, s); \ - if (prev_streaming) { \ - enableDataStreamingFromReceiver(0); \ - enableDataStreamingFromReceiver(1);}} \ - return atoi(getNetworkParameter(RECEIVER_STREAMING_PORT).c_str());}; \ - - /** - * Set/Get client streaming in ZMQ port - * For multi modules, it calculates (increments) and sets the ports - * @param i sets, -1 gets - * @returns client streaming in ZMQ port - */ - int setClientDataStreamingInPort(int i){ \ - if (i >= 0) { \ - std::ostringstream ss; ss << i; std::string s = ss.str(); \ - int prev_streaming = enableDataStreamingToClient(); \ - setNetworkParameter(CLIENT_STREAMING_PORT, s); \ - if (prev_streaming) { \ - enableDataStreamingToClient(0); \ - enableDataStreamingToClient(1);}} \ - return atoi(getNetworkParameter(CLIENT_STREAMING_PORT).c_str());}; \ - - /** - * Set/Get receiver streaming out ZMQ port - * For multi modules, it calculates (increments) and sets the ports - * @param i sets, -1 gets - * @returns receiver streaming out ZMQ port - */ - std::string setReceiverDataStreamingOutIP(std::string ip) { \ - if (ip.length()) { \ - int prev_streaming = enableDataStreamingFromReceiver(); \ - setNetworkParameter(RECEIVER_STREAMING_SRC_IP, ip); \ - if (prev_streaming) { \ - enableDataStreamingFromReceiver(0); \ - enableDataStreamingFromReceiver(1);}} \ - return getNetworkParameter(RECEIVER_STREAMING_SRC_IP);}; \ - - /** - * Set/Get client streaming in ZMQ port - * For multi modules, it calculates (increments) and sets the ports - * @param i sets, -1 gets - * @returns client streaming in ZMQ port - */ - std::string setClientDataStreamingInIP(std::string ip){ \ - if (ip.length()) { \ - int prev_streaming = enableDataStreamingToClient(); \ - setNetworkParameter(CLIENT_STREAMING_SRC_IP, ip); \ - if (prev_streaming) { \ - enableDataStreamingToClient(0); \ - enableDataStreamingToClient(1);}} \ - return getNetworkParameter(CLIENT_STREAMING_SRC_IP);}; \ - -// string getFilePath(){return fileIO::getFilePath();};; - // string setFilePath(string s){return fileIO::setFilePath(s);}; - - // string getFileName(){return fileIO::getFileName();}; - // string setFileName(string s){return fileIO::setFileName(s);}; - - // int getFileIndex(){return fileIO::getFileIndex();}; - // int setFileIndex(int s){return fileIO::setFileIndex(s);}; - - /* - int getScanPrecision(int i){return slsDetectorActions::getScanPrecision(i);}; - - int getActionMask() {return slsDetectorActions::getActionMask();}; - float getCurrentScanVariable(int i) {return slsDetectorActions::getCurrentScanVariable(i);}; - int getCurrentPositionIndex(){return angularConversion::getCurrentPositionIndex();}; - int getNumberOfPositions(){return angularConversion::getNumberOfPositions();}; - */ - - // int getActionMask() {return slsDetectorActions::getActionMask();}; - // double getCurrentScanVariable(int i) {return slsDetectorActions::getCurrentScanVariable(i);}; - // int getCurrentPositionIndex(){return angularConversion::getCurrentPositionIndex();}; - // int getNumberOfPositions(){return angularConversion::getNumberOfPositions();}; - - - // string getFlatFieldCorrectionDir(){return postProcessing::getFlatFieldCorrectionDir();}; - // string setFlatFieldCorrectionDir(string s){return postProcessing::setFlatFieldCorrectionDir(s);}; - // string getFlatFieldCorrectionFile(){return postProcessing::getFlatFieldCorrectionFile();}; - // int enableBadChannelCorrection(int i){return postProcessing::enableBadChannelCorrection(i);}; - // int enableAngularConversion(int i){return postProcessing::enableAngularConversion(i);}; - - - /** returns the detector hostname - \param pos position in the multi detector structure (is -1 returns concatenated hostnames divided by a +) - \returns hostname - */ - virtual std::string getHostname(int pos=-1)=0; - - - /** sets the detector hostname - \param name hostname - */ - virtual void setHostname(const char* name)=0; - - /** adds the detector hostnames to the end of the list - \param name hostname - */ - virtual void addMultipleDetectors(const char* name)=0; - - /** returns the detector type - \param pos position in the multi detector structure (is -1 returns type of detector with id -1) - \returns type - */ - virtual std::string sgetDetectorsType(int pos=-1)=0; - - /** - gets the network parameters (implemented for gotthard) - \param i network parameter type can be RECEIVER_IP, RECEIVER_MAC, SERVER_MAC - \returns parameter - - */ - virtual std::string getNetworkParameter(networkParameter i)=0; - - /** - sets the network parameters - must restart streaming in client/receiver if to do with zmq after calling this function - \param i network parameter type - \param s value to be set - \returns parameter - - */ - virtual std::string setNetworkParameter(networkParameter i, std::string s)=0; - - int setFlowControl10G(int i = -1) { - std::string sret=""; - if (i != -1) { - std::ostringstream o; - o << ((i >= 1) ? 1 : 0); - std::string sval = o.str(); - sret = setNetworkParameter(FLOW_CONTROL_10G, sval); - } else - sret = getNetworkParameter(FLOW_CONTROL_10G); - - return atoi(sret.c_str()); - } - - /** - changes/gets the port number - \param t type port type can be CONTROL_PORT, DATA_PORT, STOP_PORT - \param i new port number (<1024 gets) - \returns actual port number - */ - virtual int setPort(portType t, int i=-1)=0; - - /** - checks if the detector(s) are online/offline - \returns hostname if offline - */ - virtual std::string checkOnline()=0; - - /** - Digital test of the modules - \param mode test mode - \param imod module number for chip test or module firmware test - \returns OK or error mask - */ - virtual int digitalTest(digitalTestMode mode, int imod=0)=0; - - /** - execute trimming - \param mode trim mode - \param par1 if noise, beam or fixed setting trimming it is count limit, if improve maximum number of iterations - \param par2 if noise or beam nsigma, if improve par2!=means vthreshold will be optimized, if fixed settings par2<0 trimwith median, par2>=0 trim with level - \param imod module number (-1 all) - \returns OK or FAIl (FAIL also if some channel are 0 or 63 - */ - virtual int executeTrimming(trimMode mode, int par1, int par2, int imod=-1)=0; - - - /** - returns currently the loaded trimfile/settingsfile name - */ - virtual std::string getSettingsFile()=0; - - - /** - get current timer value - \param index timer index - \param imod module number - \returns elapsed time value in ns or number of...(e.g. frames, gates, probes) - */ - virtual int64_t getTimeLeft(timerIndex index, int imod = -1)=0; - - /** - * set storage cell that stores first acquisition of the series (Jungfrau only) - * \param value storage cell index. Value can be 0 to 15. (-1 gets) - * \returns the storage cell that stores the first acquisition of the series - */ - virtual int setStoragecellStart(int pos=-1)=0; - - - - /** sets the number of trim energies and their value \sa sharedSlsDetector - \param nen number of energies - \param en array of energies - \returns number of trim energies - - unused! - - */ - virtual int setTrimEn(int nen, int *en=NULL)=0; - - /** returns the number of trim energies and their value \sa sharedSlsDetector - \param en pointer to the array that will contain the trim energies (in ev) - \returns number of trim energies - - unused! - */ - virtual int getTrimEn(int *en=NULL)=0; - - - - /** - set/get the use of an external signal - \param pol meaning of the signal \sa externalSignalFlag - \param signalindex index of the signal - \returns current meaning of signal signalIndex - */ - virtual externalSignalFlag setExternalSignalFlags(externalSignalFlag pol=GET_EXTERNAL_SIGNAL_FLAG , int signalindex=0)=0; - - - - - /** sets/gets the value of important readout speed parameters - \param sp is the parameter to be set/get - \param value is the value to be set, if -1 get value - \returns current value for the specified parameter - \sa speedVariable - */ - virtual int setSpeed(speedVariable sp, int value=-1)=0; - - - - - - - /** - set/get readout flags - \param flag readout flag to be set - \returns current flag - */ - virtual int setReadOutFlags(readOutFlags flag=GET_READOUT_FLAGS)=0; - - - - - - int setBadChannelCorrection(std::string fname, int &nbadtot, int *badchanlist, int off=0); - - - - - - /** sets/gets position of the master in a multi detector structure - \param i position of the detector in the multidetector structure - \returns position of the master in a multi detector structure (-1 no master or always in slsDetector) - */ - virtual int setMaster(int i=-1){return -1;}; - - /** - Sets/gets the synchronization mode of the various detectors - \param sync syncronization mode - \returns current syncronization mode - */ - virtual synchronizationMode setSynchronization(synchronizationMode sync=GET_SYNCHRONIZATION_MODE)=0; - - - /** - returns the detector trimbit/settings directory - */ - virtual std::string getSettingsDir()=0; - - /** sets the detector trimbit/settings directory */ - virtual std::string setSettingsDir(std::string s)=0; - - /** - returns the location of the calibration files - */ - virtual std::string getCalDir()=0; - - /** - sets the location of the calibration files - */ - virtual std::string setCalDir(std::string s)=0; - - /** Frees the shared memory - should not be used except for debugging*/ - virtual void freeSharedMemory()=0; - - /** - * Get user details of shared memory - * @returns string with user details - */ - virtual std::string getUserDetails() = 0; - - /** adds the detector name in position pos - \param name of the detector to be added (should already exist in shared memory or at least be online) - \param pos position where it should be added (normally at the end of the list (default to -1) - \return the actual number of detectors or -1 if it failed (always for slsDetector) - */ - virtual int addSlsDetector(char* name, int pos=-1){return -1;}; - - - /** - Turns off the server - do not use except for debugging! - */ - virtual int exitServer()=0; - - - - - /** - Loads dark image or gain image to the detector - \param index can be DARK_IMAGE or GAIN_IMAGE - \fname file name to load data from - \returns OK or FAIL - */ - virtual int loadImageToDetector(imageType index,std::string const fname)=0; - - - /** - writes the counter memory block from the detector - \param startACQ is 1 to start acquisition after reading counter - \fname file fname to load data from - \returns OK or FAIL - */ - virtual int writeCounterBlockFile(std::string const fname,int startACQ=0)=0; - - - /** - Resets counter memory block in detector - \param startACQ is 1 to start acquisition after resetting counter - \returns OK or FAIL - */ - virtual int resetCounterBlock(int startACQ=0)=0; - - /** set/get counter bit in detector - * @param i is -1 to get, 0 to reset and any other value to set the counter bit - /returns the counter bit in detector - */ - virtual int setCounterBit(int i = -1)=0; - - - /** - asks and receives all data from the detector and puts them in a data queue - \returns pointer to the front of the queue or NULL. - */ - virtual int* readAll()=0; - - - - - /** performs a complete acquisition including scansand data processing - moves the detector to next position
- starts and reads the detector
- reads the IC (if required)
- reads the encoder (iof required for angualr conversion)
- processes the data (flat field, rate, angular conversion and merging ::processData()) - \param delflag 0 leaves the data in the final data queue - \returns OK or FAIL depending on if it already started - */ - - int acquire(int delflag=1); - - /** - * Give an internal software trigger to the detector (Eiger only) - * @return OK or FAIL - */ - virtual int sendSoftwareTrigger()=0; - - - - // double* convertAngles(){return convertAngles(currentPosition);}; - // virtual double* convertAngles(double pos)=0; - - virtual int setThresholdEnergy(int, int im=-1, detectorSettings isettings=GET_SETTINGS, int tb=1)=0; - virtual int setChannel(int64_t, int ich=-1, int ichip=-1, int imod=-1)=0; - - virtual double getRateCorrectionTau()=0; - virtual int* startAndReadAll()=0; - - virtual int getTotalNumberOfChannels()=0; - virtual int getTotalNumberOfChannels(dimension d)=0; - virtual int getMaxNumberOfChannels()=0; - virtual int getMaxNumberOfChannels(dimension d)=0; - - /** returns the enable if data will be flipped across x or y axis - * \param d axis across which data is flipped - * returns 1 or 0 - */ - virtual int getFlippedData(dimension d=X)=0; - - // virtual int getParameters(); - - - - - int setTotalProgress(); - - double getCurrentProgress(); - - - void incrementProgress(); - void setCurrentProgress(int i=0); - - - /** - write register - \param addr address - \param val value - \returns current register value - - DO NOT USE!!! ONLY EXPERT USER!!! - */ - virtual uint32_t writeRegister(uint32_t addr, uint32_t val)=0; - - - /** - write ADC register - \param addr address - \param val value - \returns current register value - - DO NOT USE!!! ONLY EXPERT USER!!! - */ - virtual int writeAdcRegister(int addr, int val)=0; - - - /** - read register - \param addr address - \returns current register value - - DO NOT USE!!! ONLY EXPERT USER!!! - */ - virtual uint32_t readRegister(uint32_t addr)=0; - - - /** - sets a bit in a register - \param addr address - \param n nth bit ranging from 0 to 31 - \returns current register value - - DO NOT USE!!! ONLY EXPERT USER!!! - */ - virtual uint32_t setBit(uint32_t addr, int n)=0; - - - /** - clear a bit in a register - \param addr address - \param n nth bit ranging from 0 to 31 - \returns current register value - - DO NOT USE!!! ONLY EXPERT USER!!! - */ - virtual uint32_t clearBit(uint32_t addr, int n)=0; - - - /** - Returns the IP of the last client connecting to the detector - */ - virtual std::string getLastClientIP()=0; - - - - /** - configures mac for gotthard readout - \returns OK or FAIL - */ - - virtual int configureMAC()=0; - - - /** loads the modules settings/trimbits reading from a file - \param fname file name . If not specified, extension is automatically generated! - \param imod module number, -1 means all modules - \returns OK or FAIL - */ - virtual int loadSettingsFile(std::string fname, int imod=-1)=0; - - /** programs FPGA with pof file - \param fname file name - \returns OK or FAIL - */ - virtual int programFPGA(std::string fname)=0; - - /** resets FPGA - \returns OK or FAIL - */ - virtual int resetFPGA()=0; - - /** power on/off the chip - \param ival on is 1, off is 0, -1 to get - \returns OK or FAIL - */ - virtual int powerChip(int ival= -1)=0; - - /** automatic comparator disable for Jungfrau only - \param ival on is 1, off is 0, -1 to get - \returns OK or FAIL - */ - virtual int setAutoComparatorDisableMode(int ival= -1)=0; - - /** saves the modules settings/trimbits writing to a file - \param fname file name . Axtension is automatically generated! - \param imod module number, -1 means all modules - \returns OK or FAIL - */ - virtual int saveSettingsFile(std::string fname, int imod=-1)=0; - - /** sets all the trimbits to a particular value - \param val trimbit value - \param imod module number, -1 means all modules - \returns OK or FAIL - */ - virtual int setAllTrimbits(int val, int imod=-1)=0; - - - - - /** - set dacs value - \param val value (in V) - \param index DAC index - \param mV 0 in dac units or 1 in mV - \param imod module number (if -1 alla modules) - \returns current DAC value - */ - virtual dacs_t setDAC(dacs_t val, dacIndex index , int mV, int imod=-1)=0; - - - /** - gets ADC value - \param index ADC index - \param imod module number - \returns current ADC value - */ - virtual dacs_t getADC(dacIndex index, int imod=-1)=0; - - /** - set/gets threshold temperature (Jungfrau only) - \param val value in millidegrees, -1 gets - \param imod module number, -1 is all - \returns threshold temperature in millidegrees - */ - virtual int setThresholdTemperature(int val=-1, int imod=-1)=0; - - /** - enables/disables temperature control (Jungfrau only) - \param val value, -1 gets - \param imod module number, -1 is all - \returns temperature control enable - */ - virtual int setTemperatureControl(int val=-1, int imod=-1)=0; - - /** - Resets/ gets over-temperature event (Jungfrau only) - \param val value, -1 gets - \param imod module number, -1 is all - \returns over-temperature event - */ - virtual int setTemperatureEvent(int val=-1, int imod=-1)=0; - - /** - get the maximum size of the detector - \param d dimension - \returns maximum number of modules that can be installed in direction d - */ - virtual int getMaxNumberOfModules(dimension d=X)=0; - - double moveDetector(double pos){if (go_to_position) go_to_position (pos,GTarg); else cout << "no move detector callback registered" << endl; return getDetectorPosition();}; - double getDetectorPosition(){double pos=-1; if (get_position) pos=get_position(POarg); else cout << "no get position callback registered" << endl; return pos;}; - - /** - Writes the configuration file -- will contain all the informations needed for the configuration (e.g. for a PSI detector caldir, settingsdir, angconv, badchannels etc.) - \param fname file name - \returns OK or FAIL - */ - virtual int writeConfigurationFile(std::string const fname)=0; - - - void registerGetPositionCallback( double (*func)(void*),void *arg){get_position=func; POarg=arg;}; - void registerConnectChannelsCallback( int (*func)(void*),void *arg){connect_channels=func; CCarg=arg;}; - void registerDisconnectChannelsCallback(int (*func)(void*),void*arg){disconnect_channels=func;DCarg=arg;}; - - void registerGoToPositionCallback( int (*func)(double, void*),void *arg){go_to_position=func;GTarg=arg;}; - void registerGoToPositionNoWaitCallback(int (*func)(double, void*),void*arg){go_to_position_no_wait=func;GTNarg=arg;}; - void registerGetI0Callback( double (*func)(int, void*),void *arg){get_i0=func;IOarg=arg;}; - - void registerAcquisitionFinishedCallback(int( *func)(double,int, void*), void *pArg){acquisition_finished=func; acqFinished_p=pArg;}; - void registerMeasurementFinishedCallback(int( *func)(int,int, void*), void *pArg){measurement_finished=func; measFinished_p=pArg;}; - - void registerProgressCallback(int( *func)(double,void*), void *pArg){progress_call=func; pProgressCallArg=pArg;}; - - - /** - Saves the detector setup to file - \param fname file to write to - \param level if 2 reads also trimbits, flat field, angular correction etc. and writes them to files with automatically added extension - \returns OK or FAIL - - */ - int dumpDetectorSetup(std::string const fname, int level=0); - - - /** - Loads the detector setup from file - \param fname file to read from - \param level if 2 reads also reads trimbits, angular conversion coefficients etc. from files with default extensions as generated by dumpDetectorSetup - \returns OK or FAIL - - */ - int retrieveDetectorSetup(std::string const fname, int level=0); - - static int dummyAcquisitionFinished(double prog,int status,void* p){cout <<"Acquisition finished callback! " << prog << " " << status << endl; return 0;} - static int dummyMeasurementFinished(int im,int findex,void* p){cout <<"Measurement finished callback! " << im << " " << findex << endl; return 0;} - - - - - //receiver - - - /** - Checks if the receiver is really online - */ - virtual std::string checkReceiverOnline()=0; - - /** - Returns the IP of the last client connecting to the receiver - */ - virtual std::string getReceiverLastClientIP()=0; - - - /** - Sets up the file directory - @param fileName fileDir file directory - \returns file dir - */ - virtual std::string setFilePath(std::string s="")=0; - - /** - Sets up the file name - @param fileName file name - \returns file name - */ - virtual std::string setFileName(std::string s="")=0; - - /** - Sets the max frames per file in receiver - @param f max frames per file - \returns max frames per file in receiver - */ - virtual int setReceiverFramesPerFile(int f = -1) = 0; - - /** - Sets the frames discard policy in receiver - @param f frames discard policy - \returns frames discard policy set in receiver - */ - virtual frameDiscardPolicy setReceiverFramesDiscardPolicy(frameDiscardPolicy f = GET_FRAME_DISCARD_POLICY) = 0; - - /** - Sets the partial frames padding enable in receiver - @param f partial frames padding enable - \returns partial frames padding enable in receiver - */ - virtual int setReceiverPartialFramesPadding(int f = -1) = 0; - - /** - Sets up the file format - @param f file format - \returns file format - */ - virtual fileFormat setFileFormat(fileFormat f=GET_FILE_FORMAT)=0; - - /** - \returns file dir - */ - virtual std::string getFilePath()=0; - - /** - \returns file name - */ - virtual std::string getFileName()=0; - - /** - \returns file name - */ - virtual fileFormat getFileFormat()=0; - - /** - \returns frames caught by receiver - */ - virtual int getFramesCaughtByReceiver()=0; - - /** gets the number of frames caught by any one receiver (to avoid using threadpool) - \returns number of frames caught by any one receiver (master receiver if exists) - */ - virtual int getFramesCaughtByAnyReceiver()=0; - - /** - \returns current frame index of receiver - */ -virtual int getReceiverCurrentFrameIndex()=0; - -/** - * resets framescaught - * @param index frames caught by receiver -*/ -virtual int resetFramesCaught()=0; - -/** - * Create Receiving Data Sockets - * @param destroy is true to destroy all the sockets - * @return OK or FAIL - */ -virtual int createReceivingDataSockets(const bool destroy = false){return -1;}; - - -/** Reads frames from receiver through a constant socket -*/ - -virtual void readFrameFromReceiver(){}; - -/** - Turns off the receiver server! -*/ -virtual int exitReceiver()=0; - -/** - Sets/Gets file overwrite enable - @param enable 1 or 0 to set/reset file overwrite enable - /returns file overwrite enable -*/ -virtual int overwriteFile(int enable=-1)=0; - - -/** - Sets/Gets receiver file write enable - @param enable 1 or 0 to set/reset file write enable - /returns file write enable -*/ -virtual int enableWriteToFile(int enable=-1)=0; - -/** Starts acquisition, calibrates pedestal and writes to fpga - /returns number of frames -*/ -virtual int calibratePedestal(int frames = 0)=0; - - -/** - set roi - \param n number of rois - \param roiLimits array of roi - \param imod module number (-1 for all) - \returns success or failure -*/ -virtual int setROI(int n=-1,ROI roiLimits[]=NULL, int imod = -1)=0; - -/** - get roi from each detector and convert it to the multi detector scale - \param n number of rois - \param imod module number (-1 for all) - \returns pointer to array of ROI structure -*/ -virtual ROI* getROI(int &n, int imod = -1)=0; - -/** Sets the read receiver frequency - if data required from receiver randomly readRxrFrequency=0, - else every nth frame to be sent to gui - @param freq is the receiver read frequency - /returns read receiver frequency - */ -virtual int setReadReceiverFrequency(int freq=-1)=0; - -/** - * Enable data streaming to client - * @param enable 0 to disable, 1 to enable, -1 to get the value - * @returns data streaming to client enable - */ -virtual int enableDataStreamingToClient(int enable=-1)=0; - -/** Enable or disable streaming data from receiver to client - * @param enable 0 to disable 1 to enable -1 to only get the value - * @returns data streaming from receiver enable -*/ -virtual int enableDataStreamingFromReceiver(int enable=-1)=0; - - -/** enable/disable or get data compression in receiver - * @param i is -1 to get, 0 to disable and 1 to enable - /returns data compression in receiver - */ -virtual int enableReceiverCompression(int i = -1)=0; - -/** enable/disable or 10Gbe - * @param i is -1 to get, 0 to disable and 1 to enable - /returns if 10Gbe is enabled - */ -virtual int enableTenGigabitEthernet(int i = -1)=0; - -/** set/get receiver fifo depth - * @param i is -1 to get, any other value to set the fifo deph - /returns the receiver fifo depth - */ -virtual int setReceiverFifoDepth(int i = -1)=0; - -/** set/get receiver silent mode - * @param i is -1 to get, 0 unsets silent mode, 1 sets silent mode - /returns the receiver silent mode enable - */ -virtual int setReceiverSilentMode(int i = -1)=0; - - /******** CTB funcs */ - - /** opens pattern file and sends pattern to CTB - @param fname pattern file to open - @returns OK/FAIL - */ - virtual int setCTBPattern(std::string fname)=0; - - - /** Writes a pattern word to the CTB - @param addr address of the word, -1 is I/O control register, -2 is clk control register - @param word 64bit word to be written, -1 gets - @returns actual value - */ - virtual uint64_t setCTBWord(int addr,uint64_t word=-1)=0; - - /** Sets the pattern or loop limits in the CTB - @param level -1 complete pattern, 0,1,2, loop level - @param start start address if >=0 - @param stop stop address if >=0 - @param n number of loops (if level >=0) - @returns OK/FAIL - */ - virtual int setCTBPatLoops(int level,int &start, int &stop, int &n)=0; - - - /** Sets the wait address in the CTB - @param level 0,1,2, wait level - @param addr wait address, -1 gets - @returns actual value - */ - virtual int setCTBPatWaitAddr(int level, int addr=-1)=0; - - /** Sets the wait time in the CTB - @param level 0,1,2, wait level - @param t wait time, -1 gets - @returns actual value - */ - virtual int setCTBPatWaitTime(int level, uint64_t t=-1)=0; - - /** - Pulse Pixel - \param n is number of times to pulse - \param x is x coordinate - \param y is y coordinate - \returns OK or FAIL - */ - virtual int pulsePixel(int n=0,int x=0,int y=0)=0; - - /** - Pulse Pixel and move by a relative value - \param n is number of times to pulse - \param x is relative x value - \param y is relative y value - \returns OK or FAIL - */ - virtual int pulsePixelNMove(int n=0,int x=0,int y=0)=0; - - /** - Pulse Chip - \param n is number of times to pulse - \returns OK or FAIL - */ - virtual int pulseChip(int n=0)=0; - - /** - Set acquiring flag in shared memory - \param b acquiring flag - */ - virtual void setAcquiringFlag(bool b=false)=0; - - /** - Get acquiring flag from shared memory - \returns acquiring flag - */ - virtual bool getAcquiringFlag() = 0; - - - /** - * Check if acquiring flag is set, set error if set - * \returns FAIL if not ready, OK if ready - */ - virtual bool isAcquireReady() = 0; - - - /** - * Check version compatibility with detector/receiver software - * (if hostname/rx_hostname has been set/ sockets created) - * \param p port type control port or data (receiver) port - * \returns FAIL for incompatibility, OK for compatibility - */ - virtual int checkVersionCompatibility(portType t) = 0; - - protected: - - - static const int64_t thisSoftwareVersion=0x20141013; - - - - //protected: - int *stoppedFlag; - int64_t *timerValue; - detectorSettings *currentSettings; - int *currentThresholdEV; - - - int totalProgress; - - int progressIndex; - - double (*get_position)(void*); - int (*go_to_position)(double, void*); - int (*go_to_position_no_wait)(double, void*); - int (*connect_channels)(void*); - int (*disconnect_channels)(void*); - double (*get_i0)(int, void*); - void *POarg,*CCarg,*DCarg,*GTarg,*GTNarg,*IOarg; - int (*acquisition_finished)(double,int,void*); - int (*measurement_finished)(int,int,void*); - void *acqFinished_p, *measFinished_p; - int (*progress_call)(double,void*); - void *pProgressCallArg; - - /** semaphore to let postprocessing thread continue for next scan/measurement */ - sem_t sem_newRTAcquisition; - /** semaphore to let main thread know it got all the dummy packets (also from ext. process) */ - sem_t sem_endRTAcquisition; - - -}; - - - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/AngularConversion_Standalone.cpp b/slsDetectorSoftware/slsDetectorAnalysis/AngularConversion_Standalone.cpp deleted file mode 100644 index 36f40e2bd..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/AngularConversion_Standalone.cpp +++ /dev/null @@ -1,527 +0,0 @@ -#include "AngularConversion_Standalone.h" - -#include -#include -#include -#include -#include "usersFunctions.h" - -using namespace std; - -angularConversion::angularConversion( int *np, double *pos, double *bs, double *fo, double *go): currentPosition(0), - currentPositionIndex(0), - numberOfPositions(np), - detPositions(pos), - binSize(bs), - fineOffset(fo), - globalOffset(go) - -{ - //angleFunctionPointer=0; - registerAngleFunctionCallback(&defaultAngleFunction,NULL); - registerCallBackGetChansPerMod(&defaultGetChansPerMod,this); - registerCallBackGetNumberofChannel(&defaultGetNumberofChannel,this); -} - -angularConversion::~angularConversion(){ - -} - -// int angularConversion::setAngularConversionPointer(angleConversionConstant *p, int *nm, int nch, int idet) { -// if (p) { -// angOff[idet]=p; -// nMods[idet]=nm; -// nCh[idet]=nch; -// } else { -// angOff[idet]=NULL; -// nMods[idet]=NULL; -// } - -// return OK; -// } - - - - -double* angularConversion::convertAngles(double pos) { - int imod=0; - double *ang=new double[totalNumberOfChannels]; - double enc=pos; - angleConversionConstant *p=NULL; - - int ch0=0; - int chlast=getChansPerMods(imod); - int nchmod=getChansPerMods(imod); - p=angConvs+imod; - if (moveFlag[imod]==0) - enc=0; - else - enc=pos; - - for (int ip=0; ip=chlast) { - imod++; - p=angConvs+imod; - if (moveFlag[imod]==0) - enc=0; - else - enc=pos; - - ch0=chlast; - nchmod=getChansPerMods(imod); - if (nchmod>0) - chlast+=nchmod; - } - - if (p) - ang[ip]=angle(ip-ch0, \ - enc, \ - (*fineOffset)+(*globalOffset), \ - p->r_conversion, \ - p->center, \ - p->offset, \ - p->tilt, \ - *angDirection ); - } - return ang; -} - - - -//static! -int angularConversion::readAngularConversion(string fname, int nmod, angleConversionConstant *angOff) { - - ifstream infile; - string ss; - -#ifdef VERBOSE - std::cout<< "Opening file "<< fname << std::endl; -#endif - infile.open(fname.c_str(), ios_base::in); - if (infile.is_open()) { - readAngularConversion(infile, nmod, angOff); - infile.close(); - } else { - std::cout<< "Could not open calibration file "<< fname << std::endl; - return -1; - } - return 0; -} - - -//static -int angularConversion::readAngularConversion( ifstream& infile, int nmod, angleConversionConstant *angOff) { - string str; - int mod; - double center, ecenter; - double r_conv, er_conv; - double off, eoff; - string ss; - int interrupt=0; - int nm=0; - //" module %i center %E +- %E conversion %E +- %E offset %f +- %f \n" - while (infile.good() and interrupt==0) { - getline(infile,str); -#ifdef VERBOSE - cout << "** mod " << nm << " " ; - std::cout<< str << std::endl; -#endif - istringstream ssstr(str); - ssstr >> ss >> mod; - ssstr >> ss >> center; - ssstr >> ss >> ecenter; - ssstr >> ss >> r_conv; - ssstr >> ss >> er_conv; - ssstr >> ss >> off; - ssstr >> ss >> eoff; - if (nm=0 ) { - angOff[nm].center=center; - angOff[nm].r_conversion=r_conv; - angOff[nm].offset=off; - angOff[nm].ecenter=ecenter; - angOff[nm].er_conversion=er_conv; - angOff[nm].eoffset=eoff; - } else - break; - //cout << nm<<" " << angOff[nm].offset << endl; - nm++; - if (nm>=nmod) - break; - - } - return nm; - } - -//static -int angularConversion:: writeAngularConversion(string fname, int nmod, angleConversionConstant *angOff) { - - ofstream outfile; - outfile.open (fname.c_str(),ios_base::out); - if (outfile.is_open()) - { - writeAngularConversion(outfile, nmod, angOff); - outfile.close(); - } else { - std::cout<< "Could not open file " << fname << "for writing"<< std::endl; - return -1; - } - //" module %i center %E +- %E conversion %E +- %E offset %f +- %f \n" - return 0; -} - - - -//static -int angularConversion:: writeAngularConversion(ofstream& outfile, int nmod, angleConversionConstant *angOff) { - - for (int imod=0; imod0) { - -#ifdef VERBOSE - cout << "finalize " << ibin << " "<< mm[ibin] << " " << mp[ibin]<< mv[ibin] << me[ibin] << endl; -#endif - mp[np]=mp[ibin]/mm[ibin]; - mv[np]=mv[ibin]/mm[ibin]; - me[np]=me[ibin]/mm[ibin]; - me[np]=sqrt(me[ibin]); - mm[np]=mm[ibin]; - np++; - } - } - return np; -} - -//static -int angularConversion::addToMerging(double *p1, double *v1, double *e1, double *mp, double *mv,double *me, int *mm, int nchans, double binsize,int nbins, int *badChanMask ) { - - - double binmi=-180.; - int ibin=0; - - if (p1==NULL) - return 0; - if (v1==NULL) - return FAIL; - - if (mp==NULL) //can be changed if we want to use a fixed bin algorithm! - return FAIL; - - if (mv==NULL) - return FAIL; - if (me==NULL) - return FAIL; - if (mm==NULL) - return FAIL; - if (nchans==0) - return FAIL; - - if (binsize<=0) - return FAIL; - - if (nbins<=0) - return FAIL; - - for (int ip=0; ip=0) { - mp[ibin]+=p1[ip]; - mv[ibin]+=v1[ip]; - if (e1) - me[ibin]+=(e1[ip]*e1[ip]); - else - me[ibin]+=v1[ip]; - mm[ibin]++; - -#ifdef VERBOSE - cout << "add " << ibin << " "<< mm[ibin] << " " << mp[ibin]<< mv[ibin] << me[ibin] << endl; -#endif - } else - return FAIL; - } - - - return OK; - -} - -int angularConversion::deleteMerging() { - - if (mergingBins) - delete [] mergingBins; - - if (mergingCounts) - delete [] mergingCounts; - - if (mergingErrors) - delete [] mergingErrors; - -} - - -int angularConversion::resetMerging() { - getAngularConversionParameter(BIN_SIZE); - - mergingBins=new double[nBins]; - - - mergingCounts=new double[nBins]; - - - mergingErrors=new double[nBins]; - - - mergingMultiplicity=new int[nBins]; - - return resetMerging(mergingBins, mergingCounts, mergingErrors, mergingMultiplicity); - -} - -int angularConversion::resetMerging(double *mp, double *mv, double *me, int *mm) { - getAngularConversionParameter(BIN_SIZE); - if (nBins) - return resetMerging(mp, mv, me, mm,nBins); - else - return FAIL; -} - - - - -int angularConversion::finalizeMerging() { - int np=finalizeMerging(mergingBins, mergingCounts, mergingErrors, mergingMultiplicity); - - if (mergingMultiplicity) - delete [] mergingMultiplicity; - - return np; - -} - - - - -int angularConversion::finalizeMerging(double *mp, double *mv, double *me, int *mm) { - if (nBins) - return finalizeMerging(mp, mv, me, mm, nBins); - else - return FAIL; -} - -int angularConversion::addToMerging(double *p1, double *v1, double *e1, int *badChanMask ) { - - return addToMerging(p1,v1,e1,mergingBins,mergingCounts, mergingErrors, mergingMultiplicity, badChanMask); - - -} - - -int angularConversion::addToMerging(double *p1, double *v1, double *e1, double *mp, double *mv,double *me, int *mm, int *badChanMask ) { - - int del=0; - - if (getAngularConversionParameter(BIN_SIZE)==0){ - cout << "no bin size " << endl; - return FAIL; - } - - if (nBins==0) { - cout << "no bins " << endl; - return FAIL; - } - - if (p1==NULL) { - del=1; - p1=convertAngles(); - } - - - int ret=addToMerging(p1, v1, e1, mp, mv,me, mm,getTotalNumberofChannels(), *binSize,nBins, badChanMask ); - - - if (del) { - delete [] p1; - p1=NULL; - } - return ret; -} - - - - /** - sets the value of s angular conversion parameter - \param c can be ANGULAR_DIRECTION, GLOBAL_OFFSET, FINE_OFFSET, BIN_SIZE - \param v the value to be set - \returns the actual value - */ - -double angularConversion::setAngularConversionParameter(angleConversionParameter c, double v){ - - - switch (c) { - case ANGULAR_DIRECTION: - if (v<0) - *angDirection=-1; - else - *angDirection=1; - return *angDirection; - case GLOBAL_OFFSET: - *globalOffset=v; - return *globalOffset; - case FINE_OFFSET: - *fineOffset=v; - return *fineOffset; - case BIN_SIZE: - if (v>0) { - *binSize=v; - nBins=360./(*binSize); - } - return *binSize; - case MOVE_FLAG: - if (moveFlag) { - if (v>0) - *moveFlag=1; - else if (v==0) - *moveFlag=0; - return *moveFlag; - } - return -1; - default: - return 0; - } -} - - /** - returns the value of an angular conversion parameter - \param c can be ANGULAR_DIRECTION, GLOBAL_OFFSET, FINE_OFFSET, BIN_SIZE - \returns the actual value - - */ - -double angularConversion::getAngularConversionParameter(angleConversionParameter c) { - - switch (c) { - case ANGULAR_DIRECTION: - return *angDirection; - case GLOBAL_OFFSET: - return *globalOffset; - case FINE_OFFSET: - return *fineOffset; - case BIN_SIZE: - if (*binSize>0) - nBins=360./(*binSize); - else - nBins=0; - return *binSize; - case MOVE_FLAG: - if (moveFlag) - return *moveFlag; - else - return -1; - default: - return 0; - } -} - - - -/** -int angularConversion::setAngularConversionFile(string fname) { - if (fname=="") { - setAngularCorrectionMask(0); -#ifdef VERBOSE - std::cout << "Unsetting angular conversion" << std::endl; -#endif - } else { - if (fname=="default") { - fname=string(angConvFile); - } - -#ifdef VERBOSE - std::cout << "Setting angular conversion to " << fname << std:: endl; -#endif - if (readAngularConversionFile(fname)>=0) { - setAngularCorrectionMask(1); - strcpy(angConvFile,fname.c_str()); - } - } - return setAngularCorrectionMask(); -} - - -*/ - - - /* - set positions for the acquisition - \param nPos number of positions - \param pos array with the encoder positions - \returns number of positions - */ -int angularConversion::setPositions(int nPos, double *pos){ - if (nPos>=0) - *numberOfPositions=nPos; - for (int ip=0; ip -#include - - - - //double angle(int ichan, double encoder, double totalOffset, double conv_r, double center, double offset, double tilt, int direction) - - -using namespace std; - -/** - @short Angular conversion constants needed for a detector module - */ -typedef struct { - double center; /**< center of the module (channel at which the radius is perpendicular to the module surface) */ - double ecenter; /**< error in the center determination */ - double r_conversion; /**< detector pixel size (or strip pitch) divided by the diffractometer radius */ - double er_conversion; /**< error in the r_conversion determination */ - double offset; /**< the module offset i.e. the position of channel 0 with respect to the diffractometer 0 */ - double eoffset; /**< error in the offset determination */ - double tilt; /**< ossible tilt in the orthogonal direction (unused)*/ - double etilt; /**< error in the tilt determination */ -} angleConversionConstant; - - -/** - -@short methods to set/unset the angular conversion and merge the data -class containing the methods to set/unset the angular conversion and merge the data - - -The angular conversion itself is defined by the angle() function defined in usersFunctions.cpp - -*/ -class angularConversion : public virtual slsDetectorDefs { //: public virtual slsDetectorBase { - - public: - /** default constructor */ - angularConversion(int*, double*, double*, double*, double*); - /** virtual destructor */ - virtual ~angularConversion(); - - - - //virtual int readAngularConversion(string fname)=0; - - - - - /** - - reads an angular conversion file - \param fname file to be read - \param nmod number of modules (maximum) to be read - \param angOff pointer to array of angleConversionConstants - \returns OK or FAIL - */ - static int readAngularConversion(string fname, int nmod, angleConversionConstant *angOff); - - /** - reads an angular conversion file - \param ifstream input file stream to be read - \param nmod number of modules (maximum) to be read - \param angOff pointer to array of angleConversionConstants - \returns OK or FAIL - - */ - static int readAngularConversion(ifstream& ifs, int nmod, angleConversionConstant *angOff); - /** - writes an angular conversion file - \param fname file to be written - \param nmod number of modules to be written - \param angOff pointer to array of angleConversionConstants - \returns OK or FAIL - */ - static int writeAngularConversion(string fname, int nmod, angleConversionConstant *angOff); - - /** - writes an angular conversion file - \param ofstream output file stream - \param nmod number of modules to be written - \param angOff pointer to array of angleConversionConstants - \returns OK or FAIL - */ - static int writeAngularConversion(ofstream& ofs, int nmod, angleConversionConstant *angOff); - - /** - sets the arrays of the merged data to 0. NB The array should be created with size nbins >= 360./getBinSize(); - \param mp already merged postions - \param mv already merged data - \param me already merged errors (squared sum) - \param mm multiplicity of merged arrays - \param nbins number of bins - \returns OK or FAIL - */ - static int resetMerging(double *mp, double *mv,double *me, int *mm, int nbins); - /** - sets the arrays of the merged data to 0. NB The array should be created with size >= 360./getBinSize(); - \param mp already merged postions - \param mv already merged data - \param me already merged errors (squared sum) - \param mm multiplicity of merged arrays - \returns OK or FAIL - */ - int resetMerging(double *mp, double *mv,double *me, int *mm); - - /** - creates the arrays for merging the data and sets them to 0. - */ - int resetMerging(); - - /** - merge dataset - \param p1 angular positions of dataset - \param v1 data - \param e1 errors - \param mp already merged postions - \param mv already merged data - \param me already merged errors (squared sum) - \param mm multiplicity of merged arrays - \param nchans number of channels - \param binsize size of angular bin - \param nb number of angular bins - \param badChanMask badchannelmask (if NULL does not correct for bad channels) - \returns OK or FAIL - */ - - static int addToMerging(double *p1, double *v1, double *e1, double *mp, double *mv,double *me, int *mm, int nchans, double binsize,int nb, int *badChanMask ); - - /** - merge dataset - \param p1 angular positions of dataset - \param v1 data - \param e1 errors - \param mp already merged postions - \param mv already merged data - \param me already merged errors (squared sum) - \param mm multiplicity of merged arrays - \param badChanMask badchannelmask (if NULL does not correct for bad channels) - \returns OK or FAIL - */ - - int addToMerging(double *p1, double *v1, double *e1, double *mp, double *mv,double *me, int *mm, int *badChanMask); - /** - merge dataset - \param p1 angular positions of dataset - \param v1 data - \param e1 errors - \param badChanMask badchannelmask (if NULL does not correct for bad channels) - \returns OK or FAIL - */ - - int addToMerging(double *p1, double *v1, double *e1,int *badChanMask); - - /** - calculates the "final" positions, data value and errors for the merged data - \param mp already merged postions - \param mv already merged data - \param me already merged errors (squared sum) - \param mm multiplicity of merged arrays - \param nb number of bins - \returns FAIL or the number of non empty bins (i.e. points belonging to the pattern) - */ - - static int finalizeMerging(double *mp, double *mv,double *me, int *mm, int nb); - /** - calculates the "final" positions, data value and errors for the merged data - \param mp already merged postions - \param mv already merged data - \param me already merged errors (squared sum) - \param mm multiplicity of merged arrays - \returns FAIL or the number of non empty bins (i.e. points belonging to the pattern) - */ - - int finalizeMerging(double *mp, double *mv,double *me, int *mm); - -/** - calculates the "final" positions, data value and errors for the merged data - \returns FAIL or the number of non empty bins (i.e. points belonging to the pattern) - */ - - int finalizeMerging(); - - - /** - set detector global offset - \param f global offset to be set - \returns actual global offset - */ - double setGlobalOffset(double f){return setAngularConversionParameter(GLOBAL_OFFSET,f);}; - - - /** - set detector fine offset - \param f global fine to be set - \returns actual fine offset - */ - double setFineOffset(double f){return setAngularConversionParameter(FINE_OFFSET,f);}; - - /** - get detector fine offset - \returns actual fine offset - */ - double getFineOffset(){return getAngularConversionParameter(FINE_OFFSET);}; - - /** - get detector global offset - \returns actual global offset - */ - double getGlobalOffset(){return getAngularConversionParameter(GLOBAL_OFFSET);}; - - /** - - set detector bin size - \param bs bin size to be set - \returns actual bin size - */ - double setBinSize(double bs){if (bs>0) nBins=360/bs; return setAngularConversionParameter(BIN_SIZE,bs);}; - - /** - get detector bin size - \returns detector bin size used for merging (approx angular resolution) - */ - double getBinSize() {return getAngularConversionParameter(BIN_SIZE);}; - - - - /** - - get angular direction - \returns actual angular direction (1 is channel number increasing with angle, -1 decreasing) - */ - int getAngularDirection(){return (int)getAngularConversionParameter(ANGULAR_DIRECTION);}; - - - /** - - set angular direction - \param d angular direction to be set (1 is channel number increasing with angle, -1 decreasing) - \returns actual angular direction (1 is channel number increasing with angle, -1 decreasing) - */ - int setAngularDirection(int d){return (int)setAngularConversionParameter(ANGULAR_DIRECTION, (double)d);}; - - /** - \returns number of angular bins in the merging (360./binsize) - */ - int getNumberOfAngularBins(){return nBins;}; - - - - /** - set angular conversion parameter - \param c parameter type (globaloffset, fineoffset, binsize, angular direction, move flag) - \param v value to be set - \returns actual value - */ - double setAngularConversionParameter(angleConversionParameter c, double v); - /** - get angular conversion parameter - \param c parameter type (globaloffset, fineoffset, binsize, angular direction, move flag) - \returns actual value - */ - double getAngularConversionParameter(angleConversionParameter c); - - - - - /** - set positions for the acquisition - \param nPos number of positions - \param pos array with the encoder positions - \returns number of positions - */ - virtual int setPositions(int nPos, double *pos); - /** - get positions for the acquisition - \param pos array which will contain the encoder positions - \returns number of positions - */ - virtual int getPositions(double *pos=NULL); - - /** - deletes the array of merged data - \returns OK - */ - int deleteMerging(); - - /** - \returns pointer to the array o merged positions - */ - double *getMergedPositions(){return mergingBins;}; - /** - \returns pointer to the array of merged counts - */ - double *getMergedCounts(){return mergingCounts;}; - /** - \returns pointer to the array of merged errors - */ - double *getMergedErrors(){return mergingErrors;}; - - - - -/* /\** */ -/* reads teh angular conversion file for the (multi)detector and writes it to shared memory */ -/* *\/ */ -/* virtual int readAngularConversionFile(string fname="")=0; */ - -/* /\** */ -/* get angular conversion */ -/* \param direction reference to diffractometer direction */ -/* \param angconv array that will be filled with the angular conversion constants */ -/* \returns 0 if angular conversion disabled, >0 otherwise */ -/* *\/ */ - virtual int getAngularConversion(int &direction, angleConversionConstant *angoff=NULL); - -/* /\** */ -/* pure virtual function */ -/* \param file name to be written (nmod and array of angular conversion constants default to the ones ot the slsDetector */ -/* *\/ */ -/* virtual int writeAngularConversion(string fname)=0; */ - - - - -/* /\** */ -/* \returns number of modules of the (multi)detector */ -/* *\/ */ -/* virtual int getNMods()=0; */ - -/* /\** */ -/* returns number of channels in the module */ -/* \param imod module number */ -/* \returns number of channels in the module */ -/* *\/ */ - - - static int defaultGetNumberofChannel(int nch, void *p=NULL ) { ((angularConversion*)p)->setTotalNumberOfChannels(nch); return 0;}; - static int defaultGetChansPerMod(int imod=0, void *p=NULL){ ((angularConversion*)p)->setChansPerMod(0,imod); return 0;}; - - int setChansPerMod(int nch, int imod=0){if (nch<0) return -1; if (imod>=0 && imod=0){ totalNumberOfChannels=i; return totalNumberOfChannels;} else return -1;}; - - -/* /\** */ -/* get the angular conversion contant of one modules */ -/* \param imod module number */ -/* \returns pointer to the angular conversion constant */ -/* *\/ */ -/* virtual angleConversionConstant *getAngularConversionPointer(int imod=0)=0; */ -/* /\** */ -/* \param imod module number */ -/* \returns move flag of the module (1 encoder is added to the angle, 0 not) */ -/* *\/ */ -/* virtual int getMoveFlag(int imod)=0; */ - -/* /\** */ -/* enables/disable the angular conversion */ -/* \param i 1 sets, 0 unsets,, -1 gets */ -/* \returns actual angular conversion flag */ -/* *\/ */ -/* virtual int setAngularCorrectionMask(int i=-1)=0; */ - - - - /** - converts channel number to angle - \param pos encoder position - \returns array of angles corresponding to the channels - */ - double* convertAngles(double pos); - /** - converts channel number to angle for the current encoder position - \returns array of angles corresponding to the channels - */ - double *convertAngles(){return convertAngles(currentPosition);}; - - - /** - returns number of positions - */ - int getNumberOfPositions() {return *numberOfPositions;}; - - int getChansPerMods(int imod) { return chansPerMod[imod];}; - int getTotalNumberofChannels(){ return totalNumberOfChannels;}; - - - void incrementPositionIndex() {currentPositionIndex++;}; - - void registerCallBackGetChansPerMod(int (*func)(int, void *),void *arg){ getChansPerModule=func;pChpermod=arg;}; - void registerCallBackGetNumberofChannel(int (*func)(int, void *),void *arg){ getNumberofChannel=func;pNumberofChannel=arg;}; - - protected: - - - - private: - - - int (*getChansPerModule)(int, void*); - int (*getNumberofChannel)(int, void*); - - void *pChpermod,*angPtr,*pNumberofChannel; - - - /** merging bins */ - double *mergingBins; - - /** merging counts */ - double *mergingCounts; - - /** merging errors */ - double *mergingErrors; - - /** merging multiplicity */ - int *mergingMultiplicity; - - double (*angle)(double, double, double, double, double, double, double, int); - - - - int totalNumberOfChannels; - - int moveFlag[MAXMODS*MAXDET]; - - /** pointer to number of positions for the acquisition*/ - int *numberOfPositions; - - /** pointer to the detector positions for the acquisition*/ - double *detPositions; - - - /** pointer to angular bin size*/ - double *binSize; - - int *correctionMask; - int chansPerMod[MAXMODS*MAXDET]; - int nMod; - angleConversionConstant angConvs[MAXMODS*MAXDET]; - int directions[MAXMODS*MAXDET]; - - - /** pointer to beamline fine offset*/ - double *fineOffset; - /** pointer to beamline global offset*/ - double *globalOffset; - /** pointer to beamline angular direction*/ - int *angDirection; - - /** pointer to detector move flag (1 moves with encoder, 0 not)*/ - // int *moveFlag; - - /** number of bins for angular conversion (360./binsize)*/ - int nBins; - - - - /** - current position of the detector - */ - double currentPosition; - /** - current position index of the detector - */ - int currentPositionIndex; - - - /** - returns current position index - */ - int getCurrentPositionIndex() {return currentPositionIndex;}; - - - - - - void registerAngleFunctionCallback(double( *fun)(double, double, double, double, double, double, double, int),void* arg) {angle = fun; angPtr=arg;}; - - -}; - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/FileIO_Standalone.cpp b/slsDetectorSoftware/slsDetectorAnalysis/FileIO_Standalone.cpp deleted file mode 100644 index 27bee95b3..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/FileIO_Standalone.cpp +++ /dev/null @@ -1,650 +0,0 @@ -#include "FileIO_Standalone.h" - - - - - -string fileIO::createFileName(char *filepath, char *filename, int aMask, double sv0, int prec0, double sv1, int prec1, int pindex, int npos, int findex) { - ostringstream osfn; - // string fn; - /*directory name +root file name */ - osfn << filepath << "/" << filename; - - // cout << osfn.str() << endl; - - // scan level 0 - if ( aMask& (1 << (MAX_ACTIONS))) - osfn << "_S" << fixed << setprecision(prec0) << sv0; - - //cout << osfn.str() << endl; - - //scan level 1 - if (aMask & (1 << (MAX_ACTIONS+1))) - osfn << "_s" << fixed << setprecision(prec1) << sv1; - - //cout << osfn.str() << endl; - - - //position - if (pindex>0 && pindex<=npos) - osfn << "_p" << pindex; - - //cout << osfn.str() << endl; - - // file index - osfn << "_" << findex; - - //cout << osfn.str() << endl; - - -#ifdef VERBOSE - cout << "created file name " << osfn.str() << endl; -#endif - - //cout << osfn.str() << endl; - //fn=oosfn.str()sfn.str(); - return osfn.str(); - -} - - - /* I/O */ - -/* generates file name without extension*/ - -string fileIO::createFileName(int aMask, double sv0, int prec0, double sv1, int prec1, int pindex, int npos) { - currentFileName=createFileName(filePath, \ - fileName, \ - aMask, \ - sv0, \ - prec0, \ - sv1, \ - prec1, \ - pindex, \ - npos, \ - *fileIndex \ - ); - return currentFileName; - -} - - -int fileIO::getFileIndexFromFileName(string fname) { - int i; - size_t dot=fname.rfind("."); - if (dot==string::npos) - return -1; - size_t uscore=fname.rfind("_"); - if (uscore==string::npos) - return -1; - - if (sscanf( fname.substr(uscore+1,dot-uscore-1).c_str(),"%d",&i)) { - - return i; - } - //#ifdef VERBOSE - cout << "******************************** cannot parse file index" << endl; - //#endif - return 0; -} - -int fileIO::getVariablesFromFileName(string fname, int &index, int &p_index, double &sv0, double &sv1) { - - int i; - double f; - string s; - - - index=-1; - p_index=-1; - sv0=-1; - sv1=-1; - - - // size_t dot=fname.rfind("."); - //if (dot==string::npos) - // return -1; - size_t uscore=fname.rfind("_"); - if (uscore==string::npos) - return -1; - s=fname; - - //if (sscanf(s.substr(uscore+1,dot-uscore-1).c_str(),"%d",&i)) { - if (sscanf(s.substr(uscore+1,s.size()-uscore-1).c_str(),"%d",&i)) { - index=i; -#ifdef VERBOSE - cout << "******************************** file index is " << index << endl; -#endif - //return i; - s=fname.substr(0,uscore); - } - else - cout << "******************************** cannot parse file index" << endl; - -#ifdef VERBOSE - cout << s << endl; -#endif - - - uscore=s.rfind("_"); - - - - - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"p%d",&i)) { - p_index=i; -#ifdef VERBOSE - cout << "******************************** position index is " << p_index << endl; -#endif - s=fname.substr(0,uscore); - } - else - cout << "******************************** cannot parse position index" << endl; - -#ifdef VERBOSE - cout << s << endl; -#endif - - - - - uscore=s.rfind("_"); - - - - - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"s%f",&f)) { - sv1=f; -#ifdef VERBOSE - cout << "******************************** scan variable 1 is " << sv1 << endl; -#endif - s=fname.substr(0,uscore); - } - else - cout << "******************************** cannot parse scan varable 1" << endl; - -#ifdef VERBOSE - cout << s << endl; - - -#endif - - uscore=s.rfind("_"); - - - - - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"S%f",&f)) { - sv0=f; -#ifdef VERBOSE - cout << "******************************** scan variable 0 is " << sv0 << endl; -#endif - } - else - cout << "******************************** cannot parse scan varable 0" << endl; - -#ifdef VERBOSE -#endif - - - - return index; -} - - - - - -int fileIO::writeDataFile(string fname, int nch, double *data, double *err, double *ang, char dataformat){ - - - ofstream outfile; - // int idata; - if (data==NULL) - return FAIL; - - // args|=0x10; // one line per channel! - - outfile.open (fname.c_str(),ios_base::out); - if (outfile.is_open()) - { - writeDataFile(outfile, nch, data, err, ang, dataformat, 0); - outfile.close(); - return OK; - } else { - std::cout<< "Could not open file " << fname << "for writing"<< std::endl; - return FAIL; - } -}; - - -int fileIO::writeDataFile(ofstream &outfile, int nch, double *data, double *err, double *ang, char dataformat, int offset){ - - - int idata; - if (data==NULL) - return FAIL; - - // args|=0x10; // one line per channel! - - cout << "Static file " << endl; - - - for (int ichan=0; ichan> ichan >> fdata; - //ich=ichan; - if (ssstr.fail() || ssstr.bad()) { - interrupt=1; - break; - } - // if (ich!=iline) - // std::cout<< "Channel number " << ichan << " does not match with line number " << iline << " " << dataformat << std::endl; - ich=iline; - if (ichan> fang >> fdata; - ich=iline; - } - if (ssstr.fail() || ssstr.bad()) { - interrupt=1; - break; - } - if (err) - ssstr >> ferr; - if (ssstr.fail() || ssstr.bad()) { - interrupt=1; - break; - } - if (ich=nch) { - interrupt=1; - break; - } - } - return iline; -}; - - - -int fileIO::readDataFile(string fname, int *data, int nch){ - - ifstream infile; - int iline=0;//ichan, idata, - //int interrupt=0; - string str; - -#ifdef VERBOSE - std::cout<< "Opening file "<< fname << std::endl; -#endif - infile.open(fname.c_str(), ios_base::in); - if (infile.is_open()) { - iline=readDataFile(infile, data, nch, 0); - infile.close(); - } else { - std::cout<< "Could not read file " << fname << std::endl; - return -1; - } - return iline; -}; - -int fileIO::readDataFile(ifstream &infile, int *data, int nch, int offset){ - - int ichan, idata, iline=0; - int interrupt=0; - string str; - - - while (infile.good() and interrupt==0) { - getline(infile,str); -#ifdef VERBOSE - std::cout<< str << std::endl; -#endif - istringstream ssstr(str); - ssstr >> ichan >> idata; - if (ssstr.fail() || ssstr.bad()) { - interrupt=1; - break; - } - // if (ichan!=iline) { -// std::cout<< " Expected channel "<< iline <<" but read channel "<< ichan << std::endl; -// interrupt=1; -// break; -// } else { - if (iline=offset) { - data[iline]=idata; - iline++; - } - } else { - interrupt=1; - break; - } - // } - } - return iline; -}; - - -int fileIO::readDataFile(string fname, short int *data, int nch){ - - ifstream infile; - int iline=0;//ichan, - //int interrupt=0; - string str; - -#ifdef VERBOSE - std::cout<< "Opening file "<< fname << std::endl; -#endif - infile.open(fname.c_str(), ios_base::in); - if (infile.is_open()) { - iline=readDataFile(infile, data, nch, 0); - infile.close(); - } else { - std::cout<< "Could not read file " << fname << std::endl; - return -1; - } - return iline; -}; - -int fileIO::readDataFile(ifstream &infile, short int *data, int nch, int offset){ - - int ichan, iline=0; - short int idata; - int interrupt=0; - string str; - while (infile.good() and interrupt==0) { - getline(infile,str); -#ifdef VERBOSE - ;//std::cout<< str << std::endl; -#endif - istringstream ssstr(str); - ssstr >> ichan >> idata; - if (ssstr.fail() || ssstr.bad()) { - interrupt=1; - break; - } - // if (ichan!=iline) { -// std::cout<< " Expected channel "<< iline <<" but read channel "<< ichan << std::endl; -// interrupt=1; -// break; -// } else { - if (iline=offset) { - data[iline]=idata; - iline++; - } - } else { - interrupt=1; - break; - } - // } -#ifdef VERBOSE - ;//std::cout<< "read " << iline <<" channels " << std::endl; -#endif - } - return iline; -} - - - -/*writes raw data file */ - -int fileIO::writeDataFile(string fname, double *data, double *err, double *ang, char dataformat, int nch){ - if (nch==-1) - nch=getTotalNumberofChannels();//getTotalNumberOfChannels(); - - return writeDataFile(fname, nch, data, err, ang, dataformat); - -} -int fileIO::writeDataFile(ofstream &outfile, double *data, double *err, double *ang, char dataformat, int nch, int offset){ - if (nch==-1) - nch=getTotalNumberofChannels(); - - return writeDataFile(outfile, nch, data, err, ang, dataformat, offset); - -} - - - - -int fileIO::writeDataFile(string fname, int *data){ - - return writeDataFile(fname, getTotalNumberofChannels(), data); -} - -int fileIO::writeDataFile(ofstream &outfile, int *data, int offset){ - - return writeDataFile(outfile, getTotalNumberofChannels(), data, offset); -} - - - - - -int fileIO::writeDataFile(string fname, short int *data){ - - return writeDataFile(fname, getTotalNumberofChannels(), data); -} - -int fileIO::writeDataFile(ofstream &outfile, short int *data, int offset){ - - return writeDataFile(outfile,getTotalNumberofChannels() , data, offset); -} - - - - -int fileIO::readDataFile(string fname, double *data, double *err, double *ang, char dataformat) { - return readDataFile(getTotalNumberofChannels(), fname, data, err, ang, dataformat); - -} - -int fileIO::readDataFile(ifstream &infile, double *data, double *err, double *ang, char dataformat, int offset) { - return readDataFile(getTotalNumberofChannels(), infile, data, err, ang, dataformat, offset); - -} - - - -int fileIO::readDataFile(string fname, int *data){ - - return readDataFile(fname, data, getTotalNumberofChannels()); -}; - - -int fileIO::readDataFile(ifstream &infile, int *data, int offset){ - - return readDataFile(infile, data, getTotalNumberofChannels(), offset); -}; - - - - - -int fileIO::readDataFile(string fname, short int *data){ - - return readDataFile(fname, data, getTotalNumberofChannels()); -}; - - -int fileIO::readDataFile(ifstream &infile, short int *data, int offset){ - - return readDataFile(infile, data, getTotalNumberofChannels(),offset); -}; - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/FileIO_Standalone.h b/slsDetectorSoftware/slsDetectorAnalysis/FileIO_Standalone.h deleted file mode 100644 index b94f6366f..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/FileIO_Standalone.h +++ /dev/null @@ -1,410 +0,0 @@ -#ifndef FILEIOSTD_H -#define FILEIOSTD_H - -//#include "slsDetectorBase.h" -#include "sls_detector_defs.h" -#include -#include -#include -#include -#include -#include -#include -#include - -; -/** - @short class handling the data file I/O flags -*/ - -class fileIO : public virtual slsDetectorDefs {//public virtual slsDetectorBase { - - - - public: - /** default constructor */ - fileIO(){}; - /** virtual destructor */ - virtual ~fileIO(){}; - - int setTotalNumberofChannels(int i){ if (i>=0) {totalNumberofChannels=i; return totalNumberofChannels;} else return -1;}; - int getTotalNumberofChannels(){ return totalNumberofChannels; }; - /** - sets the default output files path - \param s file path - \return actual file path - */ - string setFilePath(string s) {sprintf(filePath, s.c_str()); return string(filePath);}; - - /** - sets the default output files root name - \param s file name to be set - \returns actual file name - */ - string setFileName(string s) {sprintf(fileName, s.c_str()); return string(fileName);}; - - /** - sets the default output file index - \param i start file index to be set - \returns actual file index - */ - int setFileIndex(int i) {*fileIndex=i; return *fileIndex;}; - - - - /** - \returns the output files path - - */ - string getFilePath() {return string(filePath);}; - - /** - \returns the output files root name - */ - string getFileName() {return string(fileName);}; - - /** - \returns the output file index - */ - int getFileIndex() {return *fileIndex;}; - - - - - - - /** generates file name without extension - - always appends to file path and file name the run index. - - in case also appends the position index and the two level of scan varaibles with the specified precision - - Filenames will be of the form: filepath/filename(_Sy_sw_px)_i - where y is the scan0 variable, W is the scan 1 variable, x is the position index and i is the run index - \param filepath outdir - \param filename file root name - \param aMask action mask (scans, positions) - \param sv0 scan variable 0 - \param prec0 scan precision 0 - \param sv1 scan variable 1 - \param prec1 scan precision 1 - \param pindex position index - \param number of positions - \param findex file index - \returns file name without extension - */ - static string createFileName(char *filepath, char *filename, int aMask, double sv0, int prec0, double sv1, int prec1, int pindex, int npos, int findex); - - - string createFileName(int aMask, double sv0, int prec0, double sv1, int prec1, int pindex, int npos); - - - /** static function that returns the file index from the file name - \param fname file name - \returns file index - */ - int getFileIndexFromFileName(string fname); - - /** static function that returns the variables from the file name - \param fname file name - \param index reference to index - \param p_index reference to position index - \param sv0 reference to scan variable 0 - \param sv1 reference to scan variable 1 - \returns file index - */ - static int getVariablesFromFileName(string fname, int &index, int &p_index, double &sv0, double &sv1); - - - - - /** - - writes a data file - \param fname of the file to be written - \param data array of data values - \param err array of arrors on the data. If NULL no errors will be written - - \param ang array of angular values. If NULL data will be in the form chan-val(-err) otherwise ang-val(-err) - \param dataformat format of the data: can be 'i' integer or 'f' double (default) - \param nch number of channels to be written to file. if -1 defaults to the number of installed channels of the detector - \returns OK or FAIL if it could not write the file or data=NULL - - */ - virtual int writeDataFile(string fname, double *data, double *err=NULL, double *ang=NULL, char dataformat='f', int nch=-1); - - - /** - - writes a data file - \paramoutfile output file stream - \param data array of data values - \param err array of arrors on the data. If NULL no errors will be written - - \param ang array of angular values. If NULL data will be in the form chan-val(-err) otherwise ang-val(-err) - \param dataformat format of the data: can be 'i' integer or 'f' double (default) - \param nch number of channels to be written to file. if -1 defaults to the number of installed channels of the detector - \param offset start channel number - \returns OK or FAIL if it could not write the file or data=NULL - - */ - int writeDataFile(ofstream &outfile, double *data, double *err=NULL, double *ang=NULL, char dataformat='f', int nch=-1, int offset=0); - - - /** - writes a data file - \param fname of the file to be written - \param data array of data values - \returns OK or FAIL if it could not write the file or data=NULL - */ - virtual int writeDataFile(string fname, int *data); - - /** - writes a data file - \param outfile output file stream - \param data array of data values - \param offset start channel number - \returns OK or FAIL if it could not write the file or data=NULL - */ - int writeDataFile(ofstream &outfile, int *data, int offset=0); - - - - /** - writes a data file of short ints - \param fname of the file to be written - \param data array of data values - \returns OK or FAIL if it could not write the file or data=NULL - */ - virtual int writeDataFile(string fname, short int *data); - - /** - writes a data file of short ints - \param outfile output file stream - \param data array of data values - \param offset start channel number - \returns OK or FAIL if it could not write the file or data=NULL - */ - int writeDataFile(ofstream &outfile, short int *data, int offset=0); - - - /** - reads a data file - \param fname of the file to be read - \param data array of data values to be filled - \param err array of arrors on the data. If NULL no errors are expected on the file - - \param ang array of angular values. If NULL data are expected in the form chan-val(-err) otherwise ang-val(-err) - \param dataformat format of the data: can be 'i' integer or 'f' double (default) - \returns OK or FAIL if it could not read the file or data=NULL - */ - virtual int readDataFile(string fname, double *data, double *err=NULL, double *ang=NULL, char dataformat='f'); - - /** - reads a data file - \param ifstream input file stream - \param data array of data values to be filled - \param err array of arrors on the data. If NULL no errors are expected on the file - - \param ang array of angular values. If NULL data are expected in the form chan-val(-err) otherwise ang-val(-err) - \param offset start channel number to be expected - \returns OK or FAIL if it could not read the file or data=NULL - */ - int readDataFile(ifstream& infile, double *data, double *err=NULL, double *ang=NULL, char dataformat='f', int offset=0); - - /** - reads a raw data file - \param fname of the file to be read - \param data array of data values - \returns OK or FAIL if it could not read the file or data=NULL - */ - virtual int readDataFile(string fname, int *data); /** - reads a raw data file - \param infile input file stream - \param data array of data values - \param offset first channel number to be expected - \returns OK or FAIL if it could not read the file or data=NULL - */ - int readDataFile(ifstream &infile, int *data, int offset=0); - - /** - - reads a short int raw data file - \param fname of the file to be read - \param data array of data values - \returns OK or FAIL if it could not read the file or data=NULL - */ - virtual int readDataFile(string fname, short int *data); - /** - reads a short int raw data file - \param infile input file stream - \param data array of data values - \param offset first channel number to be expected - \returns OK or FAIL if it could not read the file or data=NULL - */ - int readDataFile(ifstream &infile, short int *data, int offset=0); - - /** - - writes a data file - \param fname of the file to be written - \param nch number of channels to be written - \param data array of data values - \param err array of arrors on the data. If NULL no errors will be written - \param ang array of angular values. If NULL data will be in the form chan-val(-err) otherwise ang-val(-err) - \param dataformat format of the data: can be 'i' integer or 'f' double (default) - \returns OK or FAIL if it could not write the file or data=NULL - - */ - - static int writeDataFile(string fname, int nch, double *data, double *err=NULL, double *ang=NULL, char dataformat='f'); - /** - writes a data file - \param outfile output file stream - \param nch number of channels to be written - \param data array of data values - \param err array of arrors on the data. If NULL no errors will be written - \param ang array of angular values. If NULL data will be in the form chan-val(-err) otherwise ang-val(-err) - \param dataformat format of the data: can be 'i' integer or 'f' double (default) - \param offset start channel number - \returns OK or FAIL if it could not write the file or data=NULL - */ - static int writeDataFile(ofstream &outfile, int nch, double *data, double *err=NULL, double *ang=NULL, char dataformat='f', int offset=0); - - /** - writes a raw data file - \param fname of the file to be written - \param nch number of channels - \param data array of data values - \returns OK or FAIL if it could not write the file or data=NULL - */ - static int writeDataFile(string fname,int nch, int *data); - - /** - writes a raw data file - \param outfile output file stream - \param nch number of channels - \param data array of data values - \param offset start channel number - \returns OK or FAIL if it could not write the file or data=NULL - */ - static int writeDataFile(ofstream &outfile,int nch, int *data, int offset=0); - - - /** - - writes a short int raw data file - \param fname of the file to be written - \param nch number of channels - \param data array of data values - \returns OK or FAIL if it could not write the file or data=NULL - */ - static int writeDataFile(string fname,int nch, short int *data); - - /** - writes a short int raw data file - \param outfile output file stream - \param nch number of channels - \param data array of data values - \param offset start channel number - \returns OK or FAIL if it could not write the file or data=NULL - */ - static int writeDataFile(ofstream &outfile,int nch, short int *data, int offset=0); - - - /** - reads a data file - \param nch number of channels - \param fname of the file to be read - \param data array of data values to be filled - \param err array of arrors on the data. If NULL no errors are expected on the file - \param ang array of angular values. If NULL data are expected in the form chan-val(-err) otherwise ang-val(-err) - \param dataformat format of the data: can be 'i' integer or 'f' double (default) - \returns number of channels read or -1 if it could not read the file or data=NULL - - */ - static int readDataFile(int nch, string fname, double *data, double *err=NULL, double *ang=NULL, char dataformat='f'); - /** - reads a data file - \param nch number of channels - \param infile input file stream - \param data array of data values to be filled - \param err array of arrors on the data. If NULL no errors are expected on the file - \param ang array of angular values. If NULL data are expected in the form chan-val(-err) otherwise ang-val(-err) - \param dataformat format of the data: can be 'i' integer or 'f' double (default) - \param offset start channel number - \returns number of channels read or -1 if it could not read the file or data=NULL - - */ - static int readDataFile(int nch, ifstream &infile, double *data, double *err=NULL, double *ang=NULL, char dataformat='f', int offset=0); - - /** - reads a raw data file - \param fname of the file to be read - \param data array of data values - \param nch number of channels - \returns OK or FAIL if it could not read the file or data=NULL - */ - static int readDataFile(string fname, int *data, int nch); - - /** - reads a raw data file - \param infile input file stream - \param data array of data values - \param nch number of channels - \param offset start channel value - \returns OK or FAIL if it could not read the file or data=NULL - */ - static int readDataFile(ifstream &infile, int *data, int nch, int offset); - - /** - reads a short int rawdata file - \param name of the file to be read - \param data array of data values - \param nch number of channels - \returns OK or FAIL if it could not read the file or data=NULL - */ - static int readDataFile(string fname, short int *data, int nch); - /** - reads a short int raw data file - \param infile input file stream - \param data array of data values - \param nch number of channels - \param offset start channel value - \returns OK or FAIL if it could not read the file or data=NULL - */ - static int readDataFile(ifstream &infile, short int *data, int nch, int offset); - - - - - - void incrementFileIndex() { (*fileIndex)++;}; - - string getCurrentFileName(){return currentFileName;}; - - protected: - string currentFileName; - - - int mask_action; - double currentscan_variable[1]; - int scan_precision[1]; - int currentpostion_i; - int noposition; - - /** output directory */ - char *filePath; - /** file root name */ - char *fileName; - /** file index */ - int *fileIndex; - - private: - - int totalNumberofChannels; - - -}; - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/Makefile b/slsDetectorSoftware/slsDetectorAnalysis/Makefile deleted file mode 100644 index 1b137d512..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/Makefile +++ /dev/null @@ -1,87 +0,0 @@ -#--------------------------------------------------- - - -include Makefile.arch - -#------------------------------------------------------------------------------ - -SLSDETO = TSlsDetectorDict.$(ObjSuf) energyCalibration.$(ObjSuf) angularCalibration.$(ObjSuf) - -SLSDETSO = libTSlsDetector.$(DllSuf) - -CXXFLAGS += -Wno-deprecated -#LIBS += -L../slsDetectorSoftware -lSlsDetector -pthread - -CXXFLAGS += -I ../usersFunctions - -HEADERS= energyCalibration.h angularCalibration.h -#------------------------------------------------------------------------------- - -#----------- do the shared library -$(SLSDETSO): $(SLSDETO) - @echo "Generating shared library $@..." - $(LD) $(SOFLAGS) $(LDFLAGS) -o $@ $(LIBS) $^ - - -# ---------- Default rule - -%.$(ObjSuf): %.cpp - @echo "Compiling source $@..." - $(CXX) $(CXXFLAGS) -c $< - - -#----------- do the dictionary -TSlsDetectorDict.$(SrcSuf): $(HEADERS) - @echo "Generating dictionary $@..." - rootcint -f $@ -c -p $^ - -#------------------------------------------------------------------------------- -all: $(SLSDETSO) - -clean: - @rm -f $(SLSDETO) core - -distclean: clean - @rm -f *Dict.* *.so *.o - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/Makefile.arch b/slsDetectorSoftware/slsDetectorAnalysis/Makefile.arch deleted file mode 100644 index 707a4e35b..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/Makefile.arch +++ /dev/null @@ -1,575 +0,0 @@ -# -*- mode: makefile -*- -# -# Makefile containing platform dependencies for ROOT based projects. -# -# Copyright (c) 2000 Rene Brun and Fons Rademakers -# -# Author: Fons Rademakers, 29/2/2000 - -ROOTCONFIG := root-config - -ARCH := $(shell $(ROOTCONFIG) --arch) -PLATFORM := $(shell $(ROOTCONFIG) --platform) -ALTCC := $(shell $(ROOTCONFIG) --cc) -ALTCXX := $(shell $(ROOTCONFIG) --cxx) -ALTF77 := $(shell $(ROOTCONFIG) --f77) -ALTLD := $(shell $(ROOTCONFIG) --ld) - -#CXX = -ObjSuf = o -SrcSuf = cpp -ExeSuf = -DllSuf = so -OutPutOpt = -o # keep whitespace after "-o" - -ifeq (debug,$(findstring debug,$(ROOTBUILD))) -OPT = -g -OPT2 = -g -else -ifneq ($(findstring debug, $(strip $(shell $(ROOTCONFIG) --config))),) -OPT = -g -OPT2 = -g -else -OPT = -O -OPT2 = -O2 -endif -endif - -ROOTCFLAGS := $(shell $(ROOTCONFIG) --cflags) -ROOTLDFLAGS := $(shell $(ROOTCONFIG) --ldflags) -ROOTLIBS := $(shell $(ROOTCONFIG) --libs) -ROOTGLIBS := $(shell $(ROOTCONFIG) --glibs) -HASTHREAD := $(shell $(ROOTCONFIG) --has-thread) -ROOTDICTTYPE := $(shell $(ROOTCONFIG) --dicttype) -NOSTUBS := $(shell $(ROOTCONFIG) --nostubs) -ROOTCINT := rootcint - -# Stub Functions Generation -ifeq ($(NOSTUBS),yes) - ROOTCINT = export CXXFLAGS="$(CXXFLAGS)"; $(ROOTSYS)/core/utils/src/rootcint_nostubs.sh -$(ROOTDICTTYPE) -endif - -ifeq ($(ARCH),hpuxacc) -# HP-UX 10.x with aCC -CXX = aCC -CXXFLAGS = $(OPT) +Z -LD = aCC -LDFLAGS = $(OPT) -z -SOFLAGS = -b -endif - -ifeq ($(ARCH),hpuxia64acc) -# HP-UX 11i 1.5 (IA-64) with aCC -CXX = aCC -CXXFLAGS = +DD64 $(OPT) +Z -LD = aCC -LDFLAGS = +DD64 $(OPT) -z -SOFLAGS = -b -endif - -ifeq ($(ARCH),hpuxgcc) -# HP-UX 10.x with g++ -CXXFLAGS = $(OPT) -fPIC -CXX = g++ -LD = g++ -LDFLAGS = $(OPT) -SOFLAGS = -fPIC -shared -endif - -ifeq ($(ARCH),hurddeb) -# GNU/Hurd -CXX = g++ -CXXFLAGS = $(OPT2) -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT2) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),aix) -# IBM AIX xlC 4.x -CXX = xlC -CXXFLAGS = $(OPT) -LD = xlC -LDFLAGS = $(OPT) -SOFLAGS = -DllSuf = a -endif - -ifeq ($(ARCH),aix5) -# IBM AIX xlC 5.x -CXX = xlC -CXXFLAGS = $(OPT) -LD = xlC -LDFLAGS = $(OPT) -SOFLAGS = -DllSuf = a -endif - -ifeq ($(ARCH),aixgcc) -# IBM AIX with GCC -CXX = g++ -CXXFLAGS = $(OPT) -LD = g++ -LDFLAGS = $(OPT) -SOFLAGS = -shared -DllSuf = a -EXPLLINKLIBS = $(ROOTLIBS) $(ROOTGLIBS) -endif - -ifeq ($(ARCH),solaris) -# Solaris CC -CXX = /opt/SUNWspro/bin/CC -CXXFLAGS = $(OPT) -KPIC -LD = /opt/SUNWspro/bin/CC -LDFLAGS = $(OPT) -SOFLAGS = -G -endif - -ifeq ($(ARCH),solarisCC5) -# Solaris CC 5.0 -CXX = CC -CXXFLAGS = $(OPT) -KPIC -LD = CC -LDFLAGS = $(OPT) -SOFLAGS = -G -endif - -ifeq ($(ARCH),solarisgcc) -# Solaris gcc -CXX = g++ -CXXFLAGS = $(OPT) -fPIC -LD = g++ -LDFLAGS = $(OPT) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),solariskcc) -# Solaris kcc -CXX = KCC --one_instantiation_per_object -CXXFLAGS = -O4 -KPIC -LD = KCC -LDFLAGS = -O4 -SOFLAGS = -endif - -ifeq ($(ARCH),solarisx86) -# Solaris CC on Intel -CXX = CC -CXXFLAGS = $(OPT) -KPIC -LD = CC -LDFLAGS = $(OPT) -SOFLAGS = -G -endif - -ifeq ($(ARCH),sgicc) -# SGI -CXX = CC -n32 -I/usr/include/CC.sgi -CXXFLAGS = $(OPT) -LD = CC -n32 -LANG:std -I/usr/include/CC.sgi -LDFLAGS = $(OPT) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),sgicc64) -# SGI -CXX = CC -64 -I/usr/include/CC.sgi -CXXFLAGS = $(OPT) -LD = CC -64 -LANG:std -I/usr/include/CC.sgi -LDFLAGS = $(OPT) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),sgigcc) -# SGI 6.x with gcc -CXX = g++ -CXXFLAGS = $(OPT) -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT) -Wl,-u,__builtin_new -Wl,-u,__builtin_delete -Wl,-u,__nw__FUiPv -SOFLAGS = -shared -endif - -ifeq ($(ARCH),sgin32gcc) -# SGI 6.x with gcc for n32 ABI -CXX = g++ -CXXFLAGS = $(OPT) -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT) -L/usr/lib32 -Wl,-woff,134 -lgen -SOFLAGS = -shared -endif - -ifeq ($(ARCH),sgikcc) -# SGI with KCC -CXX = KCC -n32 --one_instantiation_per_object -CXXFLAGS = $(OPT) -LD = KCC -n32 -LDFLAGS = $(OPT) -SOFLAGS = -endif - -ifeq ($(ARCH),alphagcc) -# Alpha/OSF with gcc -CXX = g++ -CXXFLAGS = $(OPT2) -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT2) -SOFLAGS = -Wl,-expect_unresolved,* -shared -endif - -ifeq ($(ARCH),alphakcc) -# Alpha/OSF with kai compiler (not yet valid) -CXX = KCC --one_instantiation_per_object -CXXFLAGS = $(OPT) -fPIC -LD = KCC -LDFLAGS = $(OPT) -SOFLAGS = -Wl,-expect_unresolved,* -shared -endif - -ifeq ($(ARCH),alphacxx6) -# Alpha/OSF with cxx6 -CXX = cxx -CXXFLAGS = $(OPT) -LD = cxx -LDFLAGS = $(OPT) -SOFLAGS = -shared -nocxxstd -Wl,-expect_unresolved,*,-msym -endif - -ifeq ($(ARCH),linuxdeb2ppc) -# Debian/Linux on the PowerPC -CXX = g++ -CXXFLAGS = $(OPT2) -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT2) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),linux) -# Linux with egcs, gcc 2.9x, gcc 3.x -CXX = g++ -CXXFLAGS = $(OPT2) -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT2) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),linuxkcc) -# Linux with the KAI compiler -CXX = KCC --one_instantiation_per_object -CXXFLAGS = $(OPT) -fPIC +K0 -LD = KCC -LDFLAGS = $(OPT) $(shell $(ROOTCONFIG) --cflags) -SOFLAGS = -endif - -ifeq ($(ARCH),linuxicc) -# Linux with Intel icc compiler -ICC_MAJOR := $(shell icc -v 2>&1 | awk '{ if (NR==1) print $$2 }' | \ - cut -d'.' -f1) -ICC_MINOR := $(shell icc -v 2>&1 | awk '{ if (NR==1) print $$2 }' | \ - cut -d'.' -f2) -CXX = icc -CXXFLAGS = $(OPT) -fPIC -wd1476 -LD = icpc -LDFLAGS = $(OPT) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),linuxppcgcc) -# PPC Linux with gcc and glibc -CXX = g++ -CXXFLAGS = $(OPT2) -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT2) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),linuxia64gcc) -# Itanium Linux with gcc 2.9x -CXX = g++ -CXXFLAGS = $(OPT2) -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT2) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),linuxia64sgi) -# Itanium Linux with sgiCC -CXX = sgiCC -CXXFLAGS = $(OPT) -Wall -fPIC -LD = gsgiCC -LDFLAGS = $(OPT) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),linuxia64ecc) -# Itanium Linux with Intel icc (was ecc) -ICC_MAJOR := $(shell icc -v 2>&1 | awk '{ if (NR==1) print $$2 }' | \ - cut -d'.' -f1) -ICC_MINOR := $(shell icc -v 2>&1 | awk '{ if (NR==1) print $$2 }' | \ - cut -d'.' -f2) -CXX = icc -CXXFLAGS = $(OPT) -fPIC -wd1476 -ftz -LD = icpc -LDFLAGS = $(OPT) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),linuxx8664gcc) -# AMD Opteron and Intel EM64T (64 bit mode) Linux with gcc 3.x -CXX = g++ -CXXFLAGS = $(OPT2) -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT2) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),linuxppc64gcc) -# PPC64 Linux with gcc 3.x -CXX = g++ -CXXFLAGS = $(OPT) -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),linuxx8664icc) -# AMD Opteron and Intel EM64T (64 bit mode) Linux with Intel icc compiler -CXX = icc -CXXFLAGS = $(OPT) -fPIC -wd1476 -wd1572 -LD = icpc -LDFLAGS = $(OPT) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),linuxalphagcc) -# Alpha Linux with gcc -CXX = g++ -CXXFLAGS = $(OPT2) -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT2) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),linuxmips) -# GNU/Linux on mips (BE/LE, O32/N32/N64) with gcc -CXX = g++ -CXXFLAGS = $(OPT2) -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT2) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),linuxhppa) -# GNU/Linux on hppa with gcc -CXX = g++ -CXXFLAGS = $(OPT2) -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT2) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),linuxarm) -# ARM Linux with egcs -CXX = g++ -CXXFLAGS = $(OPT) -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT) -SOFLAGS = -shared -endif - -ifeq ($(ARCH),freebsd4) -# FreeBSD with glibc -CXX = g++ -CXXFLAGS = $(OPT) -W -Wall -fPIC -LD = $(CXX) -LDFLAGS = $(OPT) -SOFLAGS = -shared -Wl,-x -endif - -ifeq ($(ARCH),freebsd5) -# FreeBSD with glibc -CXX = g++ -CXXFLAGS = $(OPT) -W -Wall -fPIC -LD = $(CXX) -LDFLAGS = $(OPT) -SOFLAGS = -shared -Wl,-x -endif - -ifeq ($(ARCH),freebsd7) -# FreeBSD with libc -CXX = g++ -CXXFLAGS = $(OPT) -W -Wall -fPIC -LD = $(CXX) -LDFLAGS = $(OPT) -SOFLAGS = -shared -Wl,-x -endif - -ifeq ($(ARCH),openbsd) -# OpenBSD with libc -CXX = g++ -CXXFLAGS = $(OPT) -pipe -W -Wall -fPIC -LD = g++ -LDFLAGS = $(OPT) -SOFLAGS = -shared -Wl,-x -endif - -ifeq ($(ARCH),macosx) -# MacOS X with cc (GNU cc 2.95.2 and gcc 3.3) -MACOSX_MINOR := $(shell sw_vers | sed -n 's/ProductVersion://p' | cut -d . -f 2) -MACOSXTARGET := MACOSX_DEPLOYMENT_TARGET=10.$(MACOSX_MINOR) -CXX = g++ -CXXFLAGS = $(OPT2) -pipe -Wall -W -Woverloaded-virtual -LD = $(MACOSXTARGET) g++ -LDFLAGS = $(OPT2) -# The SOFLAGS will be used to create the .dylib, -# the .so will be created separately -ifeq ($(subst $(MACOSX_MINOR),,1234),1234) -DllSuf = so -else -DllSuf = dylib -endif -UNDEFOPT = dynamic_lookup -ifneq ($(subst $(MACOSX_MINOR),,12),12) -UNDEFOPT = suppress -LD = g++ -endif -SOFLAGS = -dynamiclib -single_module -undefined $(UNDEFOPT) -install_name $(CURDIR)/ -endif - -ifeq ($(ARCH),macosxicc) -# MacOS X with Intel icc compiler -MACOSX_MINOR := $(shell sw_vers | sed -n 's/ProductVersion://p' | cut -d . -f 2) -MACOSXTARGET := MACOSX_DEPLOYMENT_TARGET=10.$(MACOSX_MINOR) -ifeq ($(MACOSX_MINOR),5) -MACOSX_MINOR := 4 -endif -CXX = icc -CXXFLAGS = $(OPT) -fPIC -wd1476 -LD = $(MACOSXTARGET) icpc -LDFLAGS = $(OPT) -# The SOFLAGS will be used to create the .dylib, -# the .so will be created separately -ifeq ($(subst $(MACOSX_MINOR),,1234),1234) -DllSuf = so -else -DllSuf = dylib -endif -SOFLAGS = -dynamiclib -single_module -undefined dynamic_lookup -install_name $(CURDIR)/ -endif - -ifeq ($(ARCH),macosx64) -# MacOS X >= 10.4 with gcc 64 bit mode (GNU gcc 4.*) -# Only specific option (-m64) comes from root-config -MACOSX_MINOR := $(shell sw_vers | sed -n 's/ProductVersion://p' | cut -d . -f 2) -MACOSXTARGET := MACOSX_DEPLOYMENT_TARGET=10.$(MACOSX_MINOR) -CXX = g++ -CXXFLAGS = $(OPT2) -pipe -Wall -W -Woverloaded-virtual -LD = $(MACOSXTARGET) g++ -LDFLAGS = $(OPT2) -# The SOFLAGS will be used to create the .dylib, -# the .so will be created separately -ifeq ($(subst $(MACOSX_MINOR),,1234),1234) -DllSuf = so -else -DllSuf = dylib -endif -SOFLAGS = -dynamiclib -single_module -undefined dynamic_lookup -install_name $(CURDIR)/ -endif - -ifeq ($(ARCH),macosxxlc) -# MacOS X with IBM xlC compiler -MACOSX_MINOR := $(shell sw_vers | sed -n 's/ProductVersion://p' | cut -d . -f 2) -MACOSXTARGET := MACOSX_DEPLOYMENT_TARGET=10.$(MACOSX_MINOR) -CXX = xlC -CXXFLAGS = $(OPT) -LD = $(MACOSXTARGET) xlC -LDFLAGS = $(OPT) -Wl,-bind_at_load -# The SOFLAGS will be used to create the .dylib, -# the .so will be created separately -DllSuf = dylib -UNDEFOPT = dynamic_lookup -ifneq ($(subst $(MACOSX_MINOR),,12),12) -UNDEFOPT = suppress -LD = xlC -endif -SOFLAGS = -qmkshrobj -single_module -undefined $(UNDEFOPT) -install_name $(CURDIR)/ -endif - -ifeq ($(ARCH),win32) -# Windows with the VC++ compiler -VC_MAJOR := $(shell unset VS_UNICODE_OUTPUT; cl.exe 2>&1 | awk '{ if (NR==1) print $$8 }' | \ - cut -d'.' -f1) -ObjSuf = obj -SrcSuf = cxx -ExeSuf = .exe -DllSuf = dll -OutPutOpt = -out: -CXX = cl -ifeq (debug,$(findstring debug,$(ROOTBUILD))) -CXXOPT = -Z7 -LDOPT = -debug -else -ifneq ($(findstring debug, $(strip $(shell $(ROOTCONFIG) --config))),) -CXXOPT = -Z7 -LDOPT = -debug -else -CXXOPT = -O2 -LDOPT = -opt:ref -endif -endif -ROOTINCDIR := -I$(shell cygpath -m `$(ROOTCONFIG) --incdir`) -CXXFLAGS = $(CXXOPT) -nologo $(ROOTINCDIR) -FIw32pragma.h -LD = link -LDFLAGS = $(LDOPT) -nologo -SOFLAGS = -DLL - -EXPLLINKLIBS = $(ROOTLIBS) $(ROOTGLIBS) -ifneq (,$(findstring $(VC_MAJOR),14 15)) -MT_EXE = mt -nologo -manifest $@.manifest -outputresource:$@\;1; rm -f $@.manifest -MT_DLL = mt -nologo -manifest $@.manifest -outputresource:$@\;2; rm -f $@.manifest -else -MT_EXE = -MT_DLL = -endif -endif - -ifeq ($(ARCH),win32gcc) -# Windows with gcc -DllSuf = dll -ExeSuf = .exe -CXX = g++ -CXXFLAGS = $(OPT) -pipe -Wall -Woverloaded-virtual -I/usr/X11R6/include -LD = g++ -LDFLAGS = $(OPT) -Wl,--enable-auto-import \ - -Wl,--enable-runtime-pseudo-reloc \ - -L/usr/X11R6/lib -SOFLAGS = -shared -Wl,--enable-auto-image-base \ - -Wl,--export-all-symbols -EXPLLINKLIBS = $(ROOTLIBS) $(ROOTGLIBS) -endif - -ifeq ($(CXX),) -$(error $(ARCH) invalid architecture) -endif - -CXXFLAGS += $(ROOTCFLAGS) -LDFLAGS += $(ROOTLDFLAGS) -LIBS = $(ROOTLIBS) $(SYSLIBS) -GLIBS = $(ROOTGLIBS) $(SYSLIBS) - -ifneq ($(ALTCC),) - CC = $(ALTCC) -endif -ifneq ($(ALTCXX),) - CXX = $(ALTCXX) -endif -ifneq ($(ALTF77),) - F77 = $(ALTF77) -endif -ifneq ($(ALTLD),) - LD = $(ALTLD) -endif - -ifneq ($(findstring g++, $(CXX)),) -GCC_MAJOR := $(shell $(CXX) -dumpversion 2>&1 | cut -d'.' -f1) -GCC_MINOR := $(shell $(CXX) -dumpversion 2>&1 | cut -d'.' -f2) -endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/TSlsDetectorDict.cpp b/slsDetectorSoftware/slsDetectorAnalysis/TSlsDetectorDict.cpp deleted file mode 100644 index 67c907790..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/TSlsDetectorDict.cpp +++ /dev/null @@ -1,691 +0,0 @@ -// -// File generated by rootcint at Thu Mar 29 16:09:00 2012 - -// Do NOT change. Changes will be lost next time file is generated -// - -#include "RConfig.h" //rootcint 4834 -#if !defined(R__ACCESS_IN_SYMBOL) -//Break the privacy of classes -- Disabled for the moment -#define private public -#define protected public -#endif - -// Since CINT ignores the std namespace, we need to do so in this file. -namespace std {} using namespace std; -#include "TSlsDetectorDict.h" - -#include "TClass.h" -#include "TBuffer.h" -#include "TMemberInspector.h" -#include "TError.h" - -#ifndef G__ROOT -#define G__ROOT -#endif - -#include "RtypesImp.h" -#include "TIsAProxy.h" - -// START OF SHADOWS - -namespace ROOT { - namespace Shadow { - } // of namespace Shadow -} // of namespace ROOT -// END OF SHADOWS - -namespace ROOT { - void energyCalibration_ShowMembers(void *obj, TMemberInspector &R__insp, char *R__parent); - static void energyCalibration_Dictionary(); - static void *new_energyCalibration(void *p = 0); - static void *newArray_energyCalibration(Long_t size, void *p); - static void delete_energyCalibration(void *p); - static void deleteArray_energyCalibration(void *p); - static void destruct_energyCalibration(void *p); - - // Function generating the singleton type initializer - static TGenericClassInfo *GenerateInitInstanceLocal(const ::energyCalibration*) - { - ::energyCalibration *ptr = 0; - static ::TVirtualIsAProxy* isa_proxy = new ::TIsAProxy(typeid(::energyCalibration),0); - static ::ROOT::TGenericClassInfo - instance("energyCalibration", "./energyCalibration.h", 168, - typeid(::energyCalibration), DefineBehavior(ptr, ptr), - 0, &energyCalibration_Dictionary, isa_proxy, 0, - sizeof(::energyCalibration) ); - instance.SetNew(&new_energyCalibration); - instance.SetNewArray(&newArray_energyCalibration); - instance.SetDelete(&delete_energyCalibration); - instance.SetDeleteArray(&deleteArray_energyCalibration); - instance.SetDestructor(&destruct_energyCalibration); - return &instance; - } - TGenericClassInfo *GenerateInitInstance(const ::energyCalibration*) - { - return GenerateInitInstanceLocal((::energyCalibration*)0); - } - // Static variable to force the class initialization - static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::energyCalibration*)0x0); R__UseDummy(_R__UNIQUE_(Init)); - - // Dictionary for non-ClassDef classes - static void energyCalibration_Dictionary() { - ::ROOT::GenerateInitInstanceLocal((const ::energyCalibration*)0x0)->GetClass(); - } - -} // end of namespace ROOT - -namespace ROOT { - void angularCalibration_ShowMembers(void *obj, TMemberInspector &R__insp, char *R__parent); - static void angularCalibration_Dictionary(); - static void *new_angularCalibration(void *p = 0); - static void *newArray_angularCalibration(Long_t size, void *p); - static void delete_angularCalibration(void *p); - static void deleteArray_angularCalibration(void *p); - static void destruct_angularCalibration(void *p); - - // Function generating the singleton type initializer - static TGenericClassInfo *GenerateInitInstanceLocal(const ::angularCalibration*) - { - ::angularCalibration *ptr = 0; - static ::TVirtualIsAProxy* isa_proxy = new ::TIsAProxy(typeid(::angularCalibration),0); - static ::ROOT::TGenericClassInfo - instance("angularCalibration", "./angularCalibration.h", 35, - typeid(::angularCalibration), DefineBehavior(ptr, ptr), - 0, &angularCalibration_Dictionary, isa_proxy, 0, - sizeof(::angularCalibration) ); - instance.SetNew(&new_angularCalibration); - instance.SetNewArray(&newArray_angularCalibration); - instance.SetDelete(&delete_angularCalibration); - instance.SetDeleteArray(&deleteArray_angularCalibration); - instance.SetDestructor(&destruct_angularCalibration); - return &instance; - } - TGenericClassInfo *GenerateInitInstance(const ::angularCalibration*) - { - return GenerateInitInstanceLocal((::angularCalibration*)0); - } - // Static variable to force the class initialization - static ::ROOT::TGenericClassInfo *_R__UNIQUE_(Init) = GenerateInitInstanceLocal((const ::angularCalibration*)0x0); R__UseDummy(_R__UNIQUE_(Init)); - - // Dictionary for non-ClassDef classes - static void angularCalibration_Dictionary() { - ::ROOT::GenerateInitInstanceLocal((const ::angularCalibration*)0x0)->GetClass(); - } - -} // end of namespace ROOT - -namespace ROOT { - // Wrappers around operator new - static void *new_energyCalibration(void *p) { - return p ? ::new((::ROOT::TOperatorNewHelper*)p) ::energyCalibration : new ::energyCalibration; - } - static void *newArray_energyCalibration(Long_t nElements, void *p) { - return p ? ::new((::ROOT::TOperatorNewHelper*)p) ::energyCalibration[nElements] : new ::energyCalibration[nElements]; - } - // Wrapper around operator delete - static void delete_energyCalibration(void *p) { - delete ((::energyCalibration*)p); - } - static void deleteArray_energyCalibration(void *p) { - delete [] ((::energyCalibration*)p); - } - static void destruct_energyCalibration(void *p) { - typedef ::energyCalibration current_t; - ((current_t*)p)->~current_t(); - } -} // end of namespace ROOT for class ::energyCalibration - -namespace ROOT { - // Wrappers around operator new - static void *new_angularCalibration(void *p) { - return p ? ::new((::ROOT::TOperatorNewHelper*)p) ::angularCalibration : new ::angularCalibration; - } - static void *newArray_angularCalibration(Long_t nElements, void *p) { - return p ? ::new((::ROOT::TOperatorNewHelper*)p) ::angularCalibration[nElements] : new ::angularCalibration[nElements]; - } - // Wrapper around operator delete - static void delete_angularCalibration(void *p) { - delete ((::angularCalibration*)p); - } - static void deleteArray_angularCalibration(void *p) { - delete [] ((::angularCalibration*)p); - } - static void destruct_angularCalibration(void *p) { - typedef ::angularCalibration current_t; - ((current_t*)p)->~current_t(); - } -} // end of namespace ROOT for class ::angularCalibration - -/******************************************************** -* TSlsDetectorDict.cpp -* CAUTION: DON'T CHANGE THIS FILE. THIS FILE IS AUTOMATICALLY GENERATED -* FROM HEADER FILES LISTED IN G__setup_cpp_environmentXXX(). -* CHANGE THOSE HEADER FILES AND REGENERATE THIS FILE. -********************************************************/ - -#ifdef G__MEMTEST -#undef malloc -#undef free -#endif - -#if defined(__GNUC__) && (__GNUC__ > 3) && (__GNUC_MINOR__ > 1) -#pragma GCC diagnostic ignored "-Wstrict-aliasing" -#endif - -extern "C" void G__cpp_reset_tagtableTSlsDetectorDict(); - -extern "C" void G__set_cpp_environmentTSlsDetectorDict() { - G__add_compiledheader("TObject.h"); - G__add_compiledheader("TMemberInspector.h"); - G__add_compiledheader("energyCalibration.h"); - G__add_compiledheader("angularCalibration.h"); - G__cpp_reset_tagtableTSlsDetectorDict(); -} -#include -extern "C" int G__cpp_dllrevTSlsDetectorDict() { return(30051515); } - -/********************************************************* -* Member function Interface Method -*********************************************************/ - -/* energyCalibration */ -static int G__TSlsDetectorDict_85_0_1(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - energyCalibration* p = NULL; - char* gvp = (char*) G__getgvp(); - int n = G__getaryconstruct(); - if (n) { - if ((gvp == (char*)G__PVOID) || (gvp == 0)) { - p = new energyCalibration[n]; - } else { - p = new((void*) gvp) energyCalibration[n]; - } - } else { - if ((gvp == (char*)G__PVOID) || (gvp == 0)) { - p = new energyCalibration; - } else { - p = new((void*) gvp) energyCalibration; - } - } - result7->obj.i = (long) p; - result7->ref = (long) p; - result7->type = 'u'; - result7->tagnum = G__get_linked_tagnum(&G__TSlsDetectorDictLN_energyCalibration); - return(1 || funcname || hash || result7 || libp) ; -} - -static int G__TSlsDetectorDict_85_0_2(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - switch (libp->paran) { - case 1: - G__letint(result7, 105, (long) ((energyCalibration*) G__getstructoffset())->setPlotFlag((int) G__int(libp->para[0]))); - break; - case 0: - G__letint(result7, 105, (long) ((energyCalibration*) G__getstructoffset())->setPlotFlag()); - break; - } - return(1 || funcname || hash || result7 || libp) ; -} - -static int G__TSlsDetectorDict_85_0_3(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - switch (libp->paran) { - case 1: - G__letint(result7, 105, (long) ((energyCalibration*) G__getstructoffset())->setScanSign((int) G__int(libp->para[0]))); - break; - case 0: - G__letint(result7, 105, (long) ((energyCalibration*) G__getstructoffset())->setScanSign()); - break; - } - return(1 || funcname || hash || result7 || libp) ; -} - -static int G__TSlsDetectorDict_85_0_4(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - switch (libp->paran) { - case 1: - G__letint(result7, 105, (long) ((energyCalibration*) G__getstructoffset())->setChargeSharing((int) G__int(libp->para[0]))); - break; - case 0: - G__letint(result7, 105, (long) ((energyCalibration*) G__getstructoffset())->setChargeSharing()); - break; - } - return(1 || funcname || hash || result7 || libp) ; -} - -// automatic copy constructor -static int G__TSlsDetectorDict_85_0_5(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) - -{ - energyCalibration* p; - void* tmp = (void*) G__int(libp->para[0]); - p = new energyCalibration(*(energyCalibration*) tmp); - result7->obj.i = (long) p; - result7->ref = (long) p; - result7->type = 'u'; - result7->tagnum = G__get_linked_tagnum(&G__TSlsDetectorDictLN_energyCalibration); - return(1 || funcname || hash || result7 || libp) ; -} - -// automatic destructor -typedef energyCalibration G__TenergyCalibration; -static int G__TSlsDetectorDict_85_0_6(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - char* gvp = (char*) G__getgvp(); - long soff = G__getstructoffset(); - int n = G__getaryconstruct(); - // - //has_a_delete: 0 - //has_own_delete1arg: 0 - //has_own_delete2arg: 0 - // - if (!soff) { - return(1); - } - if (n) { - if (gvp == (char*)G__PVOID) { - delete[] (energyCalibration*) soff; - } else { - G__setgvp((long) G__PVOID); - for (int i = n - 1; i >= 0; --i) { - ((energyCalibration*) (soff+(sizeof(energyCalibration)*i)))->~G__TenergyCalibration(); - } - G__setgvp((long)gvp); - } - } else { - if (gvp == (char*)G__PVOID) { - delete (energyCalibration*) soff; - } else { - G__setgvp((long) G__PVOID); - ((energyCalibration*) (soff))->~G__TenergyCalibration(); - G__setgvp((long)gvp); - } - } - G__setnull(result7); - return(1 || funcname || hash || result7 || libp) ; -} - -// automatic assignment operator -static int G__TSlsDetectorDict_85_0_7(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - energyCalibration* dest = (energyCalibration*) G__getstructoffset(); - *dest = *(energyCalibration*) libp->para[0].ref; - const energyCalibration& obj = *dest; - result7->ref = (long) (&obj); - result7->obj.i = (long) (&obj); - return(1 || funcname || hash || result7 || libp) ; -} - - -/* angularCalibration */ -static int G__TSlsDetectorDict_87_0_1(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - angularCalibration* p = NULL; - char* gvp = (char*) G__getgvp(); - int n = G__getaryconstruct(); - if (n) { - if ((gvp == (char*)G__PVOID) || (gvp == 0)) { - p = new angularCalibration[n]; - } else { - p = new((void*) gvp) angularCalibration[n]; - } - } else { - if ((gvp == (char*)G__PVOID) || (gvp == 0)) { - p = new angularCalibration; - } else { - p = new((void*) gvp) angularCalibration; - } - } - result7->obj.i = (long) p; - result7->ref = (long) p; - result7->type = 'u'; - result7->tagnum = G__get_linked_tagnum(&G__TSlsDetectorDictLN_angularCalibration); - return(1 || funcname || hash || result7 || libp) ; -} - -static int G__TSlsDetectorDict_87_0_2(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - switch (libp->paran) { - case 1: - G__letint(result7, 105, (long) ((angularCalibration*) G__getstructoffset())->setDirection((int) G__int(libp->para[0]))); - break; - case 0: - G__letint(result7, 105, (long) ((angularCalibration*) G__getstructoffset())->setDirection()); - break; - } - return(1 || funcname || hash || result7 || libp) ; -} - -static int G__TSlsDetectorDict_87_0_3(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - G__letdouble(result7, 102, (double) ((angularCalibration*) G__getstructoffset())->setEncoder((double) G__double(libp->para[0]))); - return(1 || funcname || hash || result7 || libp) ; -} - -static int G__TSlsDetectorDict_87_0_4(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - G__letdouble(result7, 102, (double) ((angularCalibration*) G__getstructoffset())->getEncoder()); - return(1 || funcname || hash || result7 || libp) ; -} - -static int G__TSlsDetectorDict_87_0_5(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - G__letdouble(result7, 102, (double) ((angularCalibration*) G__getstructoffset())->setTotalOffset((double) G__double(libp->para[0]))); - return(1 || funcname || hash || result7 || libp) ; -} - -static int G__TSlsDetectorDict_87_0_6(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - G__letdouble(result7, 102, (double) ((angularCalibration*) G__getstructoffset())->getTotalOffset()); - return(1 || funcname || hash || result7 || libp) ; -} - -static int G__TSlsDetectorDict_87_0_7(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - ((angularCalibration*) G__getstructoffset())->setAngularRange((double) G__double(libp->para[0]), (double) G__double(libp->para[1])); - G__setnull(result7); - return(1 || funcname || hash || result7 || libp) ; -} - -static int G__TSlsDetectorDict_87_0_8(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - ((angularCalibration*) G__getstructoffset())->getAngularRange(*(double*) G__doubleref(&libp->para[0]), *(double*) G__doubleref(&libp->para[1])); - G__setnull(result7); - return(1 || funcname || hash || result7 || libp) ; -} - -// automatic copy constructor -static int G__TSlsDetectorDict_87_0_9(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) - -{ - angularCalibration* p; - void* tmp = (void*) G__int(libp->para[0]); - p = new angularCalibration(*(angularCalibration*) tmp); - result7->obj.i = (long) p; - result7->ref = (long) p; - result7->type = 'u'; - result7->tagnum = G__get_linked_tagnum(&G__TSlsDetectorDictLN_angularCalibration); - return(1 || funcname || hash || result7 || libp) ; -} - -// automatic destructor -typedef angularCalibration G__TangularCalibration; -static int G__TSlsDetectorDict_87_0_10(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - char* gvp = (char*) G__getgvp(); - long soff = G__getstructoffset(); - int n = G__getaryconstruct(); - // - //has_a_delete: 0 - //has_own_delete1arg: 0 - //has_own_delete2arg: 0 - // - if (!soff) { - return(1); - } - if (n) { - if (gvp == (char*)G__PVOID) { - delete[] (angularCalibration*) soff; - } else { - G__setgvp((long) G__PVOID); - for (int i = n - 1; i >= 0; --i) { - ((angularCalibration*) (soff+(sizeof(angularCalibration)*i)))->~G__TangularCalibration(); - } - G__setgvp((long)gvp); - } - } else { - if (gvp == (char*)G__PVOID) { - delete (angularCalibration*) soff; - } else { - G__setgvp((long) G__PVOID); - ((angularCalibration*) (soff))->~G__TangularCalibration(); - G__setgvp((long)gvp); - } - } - G__setnull(result7); - return(1 || funcname || hash || result7 || libp) ; -} - -// automatic assignment operator -static int G__TSlsDetectorDict_87_0_11(G__value* result7, G__CONST char* funcname, struct G__param* libp, int hash) -{ - angularCalibration* dest = (angularCalibration*) G__getstructoffset(); - *dest = *(angularCalibration*) libp->para[0].ref; - const angularCalibration& obj = *dest; - result7->ref = (long) (&obj); - result7->obj.i = (long) (&obj); - return(1 || funcname || hash || result7 || libp) ; -} - - -/* Setting up global function */ - -/********************************************************* -* Member function Stub -*********************************************************/ - -/* energyCalibration */ - -/* angularCalibration */ - -/********************************************************* -* Global function Stub -*********************************************************/ - -/********************************************************* -* Get size of pointer to member function -*********************************************************/ -class G__Sizep2memfuncTSlsDetectorDict { - public: - G__Sizep2memfuncTSlsDetectorDict(): p(&G__Sizep2memfuncTSlsDetectorDict::sizep2memfunc) {} - size_t sizep2memfunc() { return(sizeof(p)); } - private: - size_t (G__Sizep2memfuncTSlsDetectorDict::*p)(); -}; - -size_t G__get_sizep2memfuncTSlsDetectorDict() -{ - G__Sizep2memfuncTSlsDetectorDict a; - G__setsizep2memfunc((int)a.sizep2memfunc()); - return((size_t)a.sizep2memfunc()); -} - - -/********************************************************* -* virtual base class offset calculation interface -*********************************************************/ - - /* Setting up class inheritance */ - -/********************************************************* -* Inheritance information setup/ -*********************************************************/ -extern "C" void G__cpp_setup_inheritanceTSlsDetectorDict() { - - /* Setting up class inheritance */ -} - -/********************************************************* -* typedef information setup/ -*********************************************************/ -extern "C" void G__cpp_setup_typetableTSlsDetectorDict() { - - /* Setting up typedef entry */ -} - -/********************************************************* -* Data Member information setup/ -*********************************************************/ - - /* Setting up class,struct,union tag member variable */ - - /* energyCalibration */ -static void G__setup_memvarenergyCalibration(void) { - G__tag_memvar_setup(G__get_linked_tagnum(&G__TSlsDetectorDictLN_energyCalibration)); - { energyCalibration *p; p=(energyCalibration*)0x1000; if (p) { } - G__memvar_setup((void*)0,85,0,0,G__get_linked_tagnum(&G__TSlsDetectorDictLN_energyCalibrationFunctions),-1,-1,4,"funcs=",0,(char*)NULL); - G__memvar_setup((void*)0,105,0,0,-1,-1,-1,4,"plot_flag=",0,"*< 0 does not plot, >0 plots (flags?) */"); - G__memvar_setup((void*)0,105,0,0,-1,-1,-1,4,"cs_flag=",0,"*< 0 functions without charge sharing contribution, >0 with charge sharing contribution */"); - } - G__tag_memvar_reset(); -} - - - /* angularCalibration */ -static void G__setup_memvarangularCalibration(void) { - G__tag_memvar_setup(G__get_linked_tagnum(&G__TSlsDetectorDictLN_angularCalibration)); - { angularCalibration *p; p=(angularCalibration*)0x1000; if (p) { } - G__memvar_setup((void*)0,105,0,0,-1,-1,-1,4,"direction=",0,"*< angulat direction of the detector -can be +1 or -1 */"); - G__memvar_setup((void*)0,102,0,0,-1,-1,-1,4,"encoder=",0,"*< position of the detector encoder */"); - G__memvar_setup((void*)0,102,0,0,-1,-1,-1,4,"totalOffset=",0,"*< total offset of the detector */"); - G__memvar_setup((void*)0,102,0,0,-1,-1,-1,4,"ang_min=",0,"*< minimum of the angular range for peak fitting*/"); - G__memvar_setup((void*)0,102,0,0,-1,-1,-1,4,"ang_max=",0,"*< maximum of the angular range for peak fitting */"); - } - G__tag_memvar_reset(); -} - -extern "C" void G__cpp_setup_memvarTSlsDetectorDict() { -} -/*********************************************************** -************************************************************ -************************************************************ -************************************************************ -************************************************************ -************************************************************ -************************************************************ -***********************************************************/ - -/********************************************************* -* Member function information setup for each class -*********************************************************/ -static void G__setup_memfuncenergyCalibration(void) { - /* energyCalibration */ - G__tag_memfunc_setup(G__get_linked_tagnum(&G__TSlsDetectorDictLN_energyCalibration)); - G__memfunc_setup("energyCalibration",1778,G__TSlsDetectorDict_85_0_1, 105, G__get_linked_tagnum(&G__TSlsDetectorDictLN_energyCalibration), -1, 0, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0); - G__memfunc_setup("setPlotFlag",1125,G__TSlsDetectorDict_85_0_2, 105, -1, -1, 0, 1, 1, 1, 0, "i - - 0 '-1' p", (char*)NULL, (void*) NULL, 0); - G__memfunc_setup("setScanSign",1122,G__TSlsDetectorDict_85_0_3, 105, -1, -1, 0, 1, 1, 1, 0, "i - - 0 '0' s", (char*)NULL, (void*) NULL, 0); - G__memfunc_setup("setChargeSharing",1634,G__TSlsDetectorDict_85_0_4, 105, -1, -1, 0, 1, 1, 1, 0, "i - - 0 '-1' p", (char*)NULL, (void*) NULL, 0); - // automatic copy constructor - G__memfunc_setup("energyCalibration", 1778, G__TSlsDetectorDict_85_0_5, (int) ('i'), G__get_linked_tagnum(&G__TSlsDetectorDictLN_energyCalibration), -1, 0, 1, 1, 1, 0, "u 'energyCalibration' - 11 - -", (char*) NULL, (void*) NULL, 0); - // automatic destructor - G__memfunc_setup("~energyCalibration", 1904, G__TSlsDetectorDict_85_0_6, (int) ('y'), -1, -1, 0, 0, 1, 1, 0, "", (char*) NULL, (void*) NULL, 0); - // automatic assignment operator - G__memfunc_setup("operator=", 937, G__TSlsDetectorDict_85_0_7, (int) ('u'), G__get_linked_tagnum(&G__TSlsDetectorDictLN_energyCalibration), -1, 1, 1, 1, 1, 0, "u 'energyCalibration' - 11 - -", (char*) NULL, (void*) NULL, 0); - G__tag_memfunc_reset(); -} - -static void G__setup_memfuncangularCalibration(void) { - /* angularCalibration */ - G__tag_memfunc_setup(G__get_linked_tagnum(&G__TSlsDetectorDictLN_angularCalibration)); - G__memfunc_setup("angularCalibration",1874,G__TSlsDetectorDict_87_0_1, 105, G__get_linked_tagnum(&G__TSlsDetectorDictLN_angularCalibration), -1, 0, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0); - G__memfunc_setup("setDirection",1261,G__TSlsDetectorDict_87_0_2, 105, -1, -1, 0, 1, 1, 1, 0, "i - - 0 '0' d", (char*)NULL, (void*) NULL, 0); - G__memfunc_setup("setEncoder",1036,G__TSlsDetectorDict_87_0_3, 102, -1, -1, 0, 1, 1, 1, 0, "f - - 0 - f", (char*)NULL, (void*) NULL, 0); - G__memfunc_setup("getEncoder",1024,G__TSlsDetectorDict_87_0_4, 102, -1, -1, 0, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0); - G__memfunc_setup("setTotalOffset",1463,G__TSlsDetectorDict_87_0_5, 102, -1, -1, 0, 1, 1, 1, 0, "f - - 0 - f", (char*)NULL, (void*) NULL, 0); - G__memfunc_setup("getTotalOffset",1451,G__TSlsDetectorDict_87_0_6, 102, -1, -1, 0, 0, 1, 1, 0, "", (char*)NULL, (void*) NULL, 0); - G__memfunc_setup("setAngularRange",1539,G__TSlsDetectorDict_87_0_7, 121, -1, -1, 0, 2, 1, 1, 0, -"f - - 0 - mi f - - 0 - ma", (char*)NULL, (void*) NULL, 0); - G__memfunc_setup("getAngularRange",1527,G__TSlsDetectorDict_87_0_8, 121, -1, -1, 0, 2, 1, 1, 0, -"f - - 1 - mi f - - 1 - ma", (char*)NULL, (void*) NULL, 0); - // automatic copy constructor - G__memfunc_setup("angularCalibration", 1874, G__TSlsDetectorDict_87_0_9, (int) ('i'), G__get_linked_tagnum(&G__TSlsDetectorDictLN_angularCalibration), -1, 0, 1, 1, 1, 0, "u 'angularCalibration' - 11 - -", (char*) NULL, (void*) NULL, 0); - // automatic destructor - G__memfunc_setup("~angularCalibration", 2000, G__TSlsDetectorDict_87_0_10, (int) ('y'), -1, -1, 0, 0, 1, 1, 0, "", (char*) NULL, (void*) NULL, 0); - // automatic assignment operator - G__memfunc_setup("operator=", 937, G__TSlsDetectorDict_87_0_11, (int) ('u'), G__get_linked_tagnum(&G__TSlsDetectorDictLN_angularCalibration), -1, 1, 1, 1, 1, 0, "u 'angularCalibration' - 11 - -", (char*) NULL, (void*) NULL, 0); - G__tag_memfunc_reset(); -} - - -/********************************************************* -* Member function information setup -*********************************************************/ -extern "C" void G__cpp_setup_memfuncTSlsDetectorDict() { -} - -/********************************************************* -* Global variable information setup for each class -*********************************************************/ -static void G__cpp_setup_global0() { - - /* Setting up global variables */ - G__resetplocal(); - - - G__resetglobalenv(); -} -extern "C" void G__cpp_setup_globalTSlsDetectorDict() { - G__cpp_setup_global0(); -} - -/********************************************************* -* Global function information setup for each class -*********************************************************/ -static void G__cpp_setup_func0() { - G__lastifuncposition(); - -} - -static void G__cpp_setup_func1() { -} - -static void G__cpp_setup_func2() { - - G__resetifuncposition(); -} - -extern "C" void G__cpp_setup_funcTSlsDetectorDict() { - G__cpp_setup_func0(); - G__cpp_setup_func1(); - G__cpp_setup_func2(); -} - -/********************************************************* -* Class,struct,union,enum tag information setup -*********************************************************/ -/* Setup class/struct taginfo */ -G__linked_taginfo G__TSlsDetectorDictLN_energyCalibrationFunctions = { "energyCalibrationFunctions" , 99 , -1 }; -G__linked_taginfo G__TSlsDetectorDictLN_energyCalibration = { "energyCalibration" , 99 , -1 }; -G__linked_taginfo G__TSlsDetectorDictLN_angularCalibration = { "angularCalibration" , 99 , -1 }; - -/* Reset class/struct taginfo */ -extern "C" void G__cpp_reset_tagtableTSlsDetectorDict() { - G__TSlsDetectorDictLN_energyCalibrationFunctions.tagnum = -1 ; - G__TSlsDetectorDictLN_energyCalibration.tagnum = -1 ; - G__TSlsDetectorDictLN_angularCalibration.tagnum = -1 ; -} - - -extern "C" void G__cpp_setup_tagtableTSlsDetectorDict() { - - /* Setting up class,struct,union tag entry */ - G__get_linked_tagnum_fwd(&G__TSlsDetectorDictLN_energyCalibrationFunctions); - G__tagtable_setup(G__get_linked_tagnum(&G__TSlsDetectorDictLN_energyCalibration),sizeof(energyCalibration),-1,1280,(char*)NULL,G__setup_memvarenergyCalibration,G__setup_memfuncenergyCalibration); - G__tagtable_setup(G__get_linked_tagnum(&G__TSlsDetectorDictLN_angularCalibration),sizeof(angularCalibration),-1,1280,(char*)NULL,G__setup_memvarangularCalibration,G__setup_memfuncangularCalibration); -} -extern "C" void G__cpp_setupTSlsDetectorDict(void) { - G__check_setup_version(30051515,"G__cpp_setupTSlsDetectorDict()"); - G__set_cpp_environmentTSlsDetectorDict(); - G__cpp_setup_tagtableTSlsDetectorDict(); - - G__cpp_setup_inheritanceTSlsDetectorDict(); - - G__cpp_setup_typetableTSlsDetectorDict(); - - G__cpp_setup_memvarTSlsDetectorDict(); - - G__cpp_setup_memfuncTSlsDetectorDict(); - G__cpp_setup_globalTSlsDetectorDict(); - G__cpp_setup_funcTSlsDetectorDict(); - - if(0==G__getsizep2memfunc()) G__get_sizep2memfuncTSlsDetectorDict(); - return; -} -class G__cpp_setup_initTSlsDetectorDict { - public: - G__cpp_setup_initTSlsDetectorDict() { G__add_setup_func("TSlsDetectorDict",(G__incsetup)(&G__cpp_setupTSlsDetectorDict)); G__call_setup_funcs(); } - ~G__cpp_setup_initTSlsDetectorDict() { G__remove_setup_func("TSlsDetectorDict"); } -}; -G__cpp_setup_initTSlsDetectorDict G__cpp_setup_initializerTSlsDetectorDict; - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/TSlsDetectorDict.h b/slsDetectorSoftware/slsDetectorAnalysis/TSlsDetectorDict.h deleted file mode 100644 index 0d2cea9fb..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/TSlsDetectorDict.h +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************** -* TSlsDetectorDict.h -* CAUTION: DON'T CHANGE THIS FILE. THIS FILE IS AUTOMATICALLY GENERATED -* FROM HEADER FILES LISTED IN G__setup_cpp_environmentXXX(). -* CHANGE THOSE HEADER FILES AND REGENERATE THIS FILE. -********************************************************************/ -#ifdef __CINT__ -#error TSlsDetectorDict.h/C is only for compilation. Abort cint. -#endif -#include -#include -#include -#include -#include -#define G__ANSIHEADER -#define G__DICTIONARY -#include "cint/G__ci.h" -extern "C" { -extern void G__cpp_setup_tagtableTSlsDetectorDict(); -extern void G__cpp_setup_inheritanceTSlsDetectorDict(); -extern void G__cpp_setup_typetableTSlsDetectorDict(); -extern void G__cpp_setup_memvarTSlsDetectorDict(); -extern void G__cpp_setup_globalTSlsDetectorDict(); -extern void G__cpp_setup_memfuncTSlsDetectorDict(); -extern void G__cpp_setup_funcTSlsDetectorDict(); -extern void G__set_cpp_environmentTSlsDetectorDict(); -} - - -#include "TObject.h" -#include "TMemberInspector.h" -#include "energyCalibration.h" -#include "angularCalibration.h" - -#ifndef G__MEMFUNCBODY -#endif - -extern G__linked_taginfo G__TSlsDetectorDictLN_energyCalibrationFunctions; -extern G__linked_taginfo G__TSlsDetectorDictLN_energyCalibration; -extern G__linked_taginfo G__TSlsDetectorDictLN_angularCalibration; - -/* STUB derived class for protected member access */ diff --git a/slsDetectorSoftware/slsDetectorAnalysis/angCalLogClass.h b/slsDetectorSoftware/slsDetectorAnalysis/angCalLogClass.h deleted file mode 100644 index b366b58a1..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/angCalLogClass.h +++ /dev/null @@ -1,153 +0,0 @@ -#ifndef ANGCALLOGCLASS_H -#define ANGCALLOGCLASS_H - -#include -#include -#ifdef __CINT__ -#define MYROOT -#endif - -#ifndef MYROOT -#include "slsDetectorCommand.h" -#include "slsDetectorUtils.h" -#include "sls_detector_defs.h" -#endif - -; - -class angCalLogClass { - - - public: - - -#ifndef MYROOT - angCalLogClass(slsDetectorUtils *det){ createVars(); - char cmd[1000]; \ - char *argv[2]; \ - argv[0]=cmd; \ - sprintf(cmd,"_%d.angcal",det->getFileIndex()); \ - outfile.open( std::string(det->getFilePath()+ std::string("/")+det->getFileName()+ std::string(cmd)).c_str()); \ - outfile.precision(8); - myDet=new slsDetectorCommand(det); \ - if (outfile.is_open()) { \ - for (int iv=0; ivexecuteLine(1,argv,slsDetectorDefs::GET_ACTION) << endl; \ - }; \ - }; \ - }; - ~angCalLogClass(){delete myDet; outfile.close();}; -#else - angCalLogClass() { createVars(); }; - ~angCalLogClass(){}; -#endif - - - int addStep(double pos, std::string fname) {std::cout.precision(5); outfile << pos << " " << fname << endl; return 0;}; - - - // - - int readHeader(std::ifstream &infile, int &maxmod, int &nmod, int &chanspermod, char *angconvfile, double &globaloff, double &fineoff, int &angdir, char *ffdir, char *fffile, char *badfile ) { \ - nmod=0; chanspermod=0; globaloff=0; fineoff=0; angdir=1; \ - strcpy(angconvfile,"none"); strcpy(ffdir,"none"); strcpy(fffile,"none"); strcpy(badfile,"none"); \ - char line[1000], myvar[100], myarg[100]; \ - float v; \ - for (int iv=0; ivcenter; \ - ecenter=acc->ecenter; \ - r_conversion=acc->r_conversion; \ - er_conversion=acc->er_conversion; \ - offset=acc->offset; \ - eoffset=acc->eoffset; \ - tilt=acc->tilt; \ - etilt=acc->etilt; \ - }; - - - -}; - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/angularCalibration.cpp b/slsDetectorSoftware/slsDetectorAnalysis/angularCalibration.cpp deleted file mode 100644 index 08fa890a3..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/angularCalibration.cpp +++ /dev/null @@ -1,471 +0,0 @@ -#include "angularCalibration.h" - -#include -#ifdef ROOT -#include -#include -#endif - -#include "usersFunctions.h" - -#ifdef __CINT -#include "usersFunctions.cpp" -#endif - -using namespace std; - -angularCalibration::angularCalibration(int nm): direction(1), -#ifdef ROOT - fpeak(NULL), - fangle(NULL), -#endif - encoder(0), - totalOffset(0), - ang_min(-180), - ang_max(180), - nmod(nm), - nchmod(1280), - angConv(NULL) -{ - -#ifdef ROOT -// Creates a Root function based on function peakfunction - TF1 *fpeak = new TF1("fpeak",this,&angularCalibration::peakFunction,ang_min,ang_max,5,"angularCalibration","peakFunction"); - -// Sets initial values and parameter names - // func->SetParameters((Double_t) PEAKHEIGHT, (Double_t) maxch,(Double_t) PEAKWIDTH,(Double_t) PEAKBACK); - fpeak->SetParNames("Number of Photons","Peak Position","Peak Width RMS","Background Offset", "Background Slope"); - - - TF1 *fangle = new TF1("fangle",this,&angularCalibration::angleFunction,0,1280,3,"angularCalibration","angleFunction"); - fangle->SetParNames("Center","Conversion Radius","Offset"); - -#endif - - angConv=new angleConversionConstant[nmod]; - -} - -angularCalibration::~angularCalibration(){ -#ifdef ROOT - delete fpeak; - delete fangle; - -#endif -} - - - -angleConversionConstant* angularCalibration::getAngularConversionConstant(int imod) { - if (imod>=0 && imod=0 && imodcenter; - angConv[imod].ecenter=a->ecenter; - angConv[imod].r_conversion=a->r_conversion; - angConv[imod].er_conversion=a->er_conversion; - angConv[imod].offset=a->offset; - angConv[imod].eoffset=a->eoffset; - angConv[imod].tilt=a->tilt; - angConv[imod].etilt=a->etilt; - - return angConv+imod; - } - return NULL; - - -} - - - - - -#ifdef ROOT - -Double_t angularCalibration::peakFunction(Double_t *x, Double_t *par) { - Double_t arg = 0; - if (par[2] != 0) arg = (x[0] - par[1])/par[2]; - return par[0]*TMath::Exp(-0.5*arg*arg)+par[3]+par[4]*(x[0]-par[1]); - -} - -Double_t angularCalibration::angleFunction(Double_t *x, Double_t *par) { - return par[2]-angle((int)x[0],0,0,par[1],par[0],0,0,direction); -} - - - - - - - -TF1 *fitPeak(TH1 *h) { - - TF1 *fitfun=NULL; - int chmod, imod; - double ang; - -// reads in a run and fits a gaussian to the peak as function -// of channel number also reads optical encoder - - -// find angular range in channels - -// is it necessary to discard fit with too many points? - for (int i=0;iGetNbinsX();i++) { - imod=i/nchmod; - chmod=i%(imod*nchmod); - ang=angle(chmod,encoder,totalOffset,angConv[imod].r_conversion, angConv[imod].center, angConv[imod].offset, angConv[imod].tilt, direction); - if ((ang>ang_min) && (angminang) && (angle(i)MAXINPEAK) { -// printf("too many points in angular range !\n"); -// return -1; // too many points in range -// } -// if ( data[i]> max) { -// max = (int) data[i]; -// maxch = i; -// } -// } -// } -// } else -// return -1; - -// npoints--; -// chmin= (int) x[0]; -// chmax= (int) x[npoints]; - -// printf("number of points in range %f-%f: %i \n",minang,maxang,npoints); -// printf("channel from minang to maxang %i - %i \n",chmin,chmax); -// printf("channel with max intensity %i \n",maxch); - -// TCanvas *c1; - -// TGraph *gr1 = new TGraph(npoints,anglefit,y); -// TGraph *gr2 = new TGraph(npoints,x,y); -// if (plotflag) { -// /* create canvas */ - -// c1 = new TCanvas(); -// c1->SetTitle("Si calibration data"); -// c1->Divide(1,2); - -// /* create graph */ - -// sprintf(name,"run number %i",nr); -// gr1->SetTitle(name); -// gr2->SetTitle(name); - -// c1->cd(1); -// gr1->Draw("AL*"); -// c1->cd(2); -// gr2->Draw("AL*"); -// } - -// /* do not fit if peak is close to edge of module */ -// if (abs(modfromchannel(maxch)*NCHMOD-maxch)Fit("fitpeak","B"); -// else -// gr2->Fit("fitpeak","B0"); - -// TF1 *fit = gr2->GetFunction("fitpeak"); - -// // writes the fit results into the par array -// fit->GetParameters(mypar); - -// printf("\n"); -// for (i=0;i<4;i++) { -// myerr[i] = fit->GetParError(i); // obtain fit parameter errors -// printf("parameter %i: %f +- %f \n",i,mypar[i],myerr[i]); -// } - -// chi2=fit->GetChisquare(); -// printf("chi2: %e\n",chi2); -// printf("\n\n"); - -// if (chi2>CHIMAX) { -// printf("chi2 too large!\n"); -// return -1; -// } - -// if (plotflag) -// c1->Update(); // necessary for axis titles! -// // c1->WaitPrimitive(); - -// return 0; - - return fitfun; - -} - - -#endif - - - -// // -// // for detector angular calibration -// // -// // loops over runs fits a peak in each run and then fits the parameters for -// // the angular calibration to the fitted peak and optical encoder values -// // -// // -// // note: -// // setting global offset is important to find peak in peak fitting! -// // also set peak height,width and background in defines at beginning -// // - -// void fitangle(char fname[80],char extension[10], int start, int stop, double startangle, double stopangle) { - -// int i,nfit,mod,npoints,nnpoints; -// double x[MAXINMODULE],y[MAXINMODULE],ex[MAXINMODULE],ey[MAXINMODULE],min,max; -// double xx[MAXINMODULE],yy[MAXINMODULE],exx[MAXINMODULE],eyy[MAXINMODULE]; - -// double channelfit[MAXRUN], channelerror[MAXRUN], encoderfit[MAXRUN]; -// int runnrfit[MAXRUN], modulenr[MAXRUN]; - - -// FILE *fp; -// char name[80]; -// TCanvas *c1,*c2; -// gROOT->Reset(); // reset root -// // gStyle->SetOptFit(1110); - -// nfit=0; -// for (i=start;iSetTitle("Si calibration data"); -// /* create graph for angle vs fitted channel number */ -// gr3->Draw("AL*"); - -// c1->Update(); // necessary for axis titles! -// c1->WaitPrimitive(); - -// delete c1; -// } -// TH1F *herr=new TH1F("herr","",100,0,0.002); - - -// for (mod=0;mod5) { - -// // create canvas -// if (plotflag) { -// TCanvas *c2 = new TCanvas(); -// c2->SetTitle("Si calibration data"); -// c2->Divide(1,3); -// } -// // create graph -// TGraphErrors *gr1 = new TGraphErrors(npoints,x,y,ex,ey); -// sprintf(name,"module number %i",mod); -// gr1->SetTitle(name); -// if (plotflag) { -// c2->cd(1); -// gr1->Draw("ALP"); -// } - - -// // Creates a Root function based on function anglefunction -// if (x[0]>x[npoints-1]) { -// min=x[npoints-1]; -// max=x[0]; -// } else { -// max=x[npoints-1]; -// min=x[0]; -// } - - -// TF1 *func = new TF1("fitangle",anglefunction,min,max,3); - -// // Sets initial values and parameter names -// func->SetParameters(640,0.0000656,-mod*5.0); -// func->SetParNames("center","conversion","offset"); -// func->FixParameter(0,640.0); -// if (plotflag) { -// gr1->Fit("fitangle"); // fit the function -// } else -// gr1->Fit("fitangle","0"); // fit the function - - -// // calculate the deviations of data points from fitted function and plot them -// for (i=0;iEval(x[i])-y[i]; -// } -// TGraph *gr4 = new TGraph(npoints,x,ey); -// sprintf(name,"module number %i deviations from fit",mod); -// gr4->SetTitle(name); - -// if (plotflag) { -// gr4->SetMarkerStyle(24); -// c2->cd(2); -// gr4->Draw("ALP"); -// } - - -// // iterate fit with outlying points excluded -// nnpoints=0; -// for (i=0;iFit("fitangle"); // fit the function -// } else -// gr3->Fit("fitangle","0"); // fit the function - - -// // calculate the deviations of data points from fitted function and plot them -// for (i=0;iEval(xx[i])-yy[i]; -// herr->Fill(eyy[i]); -// } - -// TGraph *gr5 = new TGraph(nnpoints,xx,eyy); -// sprintf(name,"module number %i deviations from fit second iteration",mod); -// if (plotflag) { -// c2->cd(3); -// gr5->SetTitle(name); -// gr5->SetMarkerStyle(24); - -// gr5->Draw("ALP"); - - -// c2->Update(); // necessary for axis titles? -// c2->WaitPrimitive(); - -// } - -// // writes the fit results into the par array -// // -// // get fit parameter -// func->GetParameters(mypar); - -// for (i=0;i<3;i++) { -// myerr[i] = func->GetParError(i); // obtain fit parameter errors -// printf("parameter %i: %E +- %E \n",i,mypar[i],myerr[i]); -// } -// printf("\n\n"); - -// center[mod]=mypar[0]; -// errcenter[mod]=myerr[0]; -// conversion[mod]=mypar[1]; -// errconversion[mod]=myerr[1]; -// moffset[mod]=mypar[2]; -// erroff[mod]=myerr[2]; - -// delete gr1; -// delete gr4; -// delete gr5; -// delete func; -// delete c2; -// } -// } -// //herr->GetXaxis()->SetMaxDigits(3); -// herr->GetXaxis()->SetTitle("Deviations from fit (deg)"); -// herr->Draw(); - - -// printf("\n\n\n"); -// for (mod=0;mod -#include -class TH1; -#endif - - //double angle(int ichan, double encoder, double totalOffset, double conv_r, double center, double offset, double tilt, int direction) - - - -class angularCalibration { - - public: - angularCalibration(int nm=48); - ~angularCalibration(); - - /** - sets the angular direction of the detector - \par d 1 or -1 set the angular direction, other valuse simply get - \returns the angular direction of the detector - */ - int setDirection(int d=0){if (d==-1 || d==1) direction=d; return direction;}; - - /** - sets the encoder position - \param f encoder position to be set - \returns current encoder position - */ - double setEncoder(double f) {encoder=f; return encoder;}; - - /** - gets the encoder position - \returns encoder position - */ - double getEncoder() {return encoder;}; - - /** - sets the totalOffset of the detector - \param f total offset to be set - \returns current total offset - */ - double setTotalOffset(double f) {totalOffset=f; return totalOffset;}; - - /** - gets the encoder position - \returns encoder position - */ - double getTotalOffset() {return totalOffset;}; - - - - - /** - sets the angular range for peak fitting - \param mi minimum of the angular range - \param ma maximum of the angular range - */ - void setAngularRange(double mi, double ma){ang_min=mi; ang_max=ma;}; - - - /** - gets the angular range for peak fitting - \param mi reference to the minimum of the angular range - \param ma reference to the maximum of the angular range - */ - void getAngularRange(double &mi, double &ma){mi=ang_min; ma=ang_max;}; - - - /** sets and returns the number of modules - \param nm number of modules to be set (<0 gets) - \return current number of modules - */ - int setNumberOfModules(int nm=-1) {if (nm>=0) nmod=nm; return nmod;}; - - /** sets and returns the number of channels per module - \param n number of channels per module to be set (<0 gets) - \return current number of channels per module - */ - int setChannelsPerModule(int n=-1) {if (n>0) nchmod=n; return nchmod;}; - - angleConversionConstant *getAngularConversionConstant(int imod=0); - angleConversionConstant *setAngularConversionConstant(angleConversionConstant *a, int imod=0); - - -#ifdef ROOT - - /** - Gaussian with pedestal describing a peak - par[0] is the heigh of the pean - par[1] is the peak position - par[2] is the peak width - par[3] is the background offset - par[4] is the background slope - */ - Double_t peakFunction(Double_t *x, Double_t *par); - - - /** - Angular conversion function - par[0] is the module center - par[1] is the conversion radius (pitch/radius) - par[2] is the module offset - */ - Double_t angleFunction(Double_t *x, Double_t *par); - - /** - Fits a peak for the angular calibration - \param h histogram channels versus intensity - \returns fitted function or NULL if fit failed - */ - TF1 *fitPeak(TH1 *h); - -#endif - - - private: - - int direction; /**< angular direction of the detector -can be +1 or -1 */ - -#ifdef ROOT - TF1 *fpeak; /**< Root function based on function peakFunction */ - - TF1 *fangle; /**< Root function based on function angleFunction */ - -#endif - double encoder; /**< position of the detector encoder */ - double totalOffset; /**< total offset of the detector */ - double ang_min; /**< minimum of the angular range for peak fitting*/ - double ang_max; /**< maximum of the angular range for peak fitting */ - - int nmod; - int nchmod; - - angleConversionConstant angConv[MAXMOD*MAXDET]; - - - - - -/* void fitangle(char fname[80],char extension[10], int start, int stop, double startangle, double stopangle); //fits all datasets and extracts the constants */ -/* int fitpeak(char fname[80],char extension[10], int nr, double minang, double maxang); // fits a peak from a pattern using nominal calibration constant */ - - -}; - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/angularConversion.cpp b/slsDetectorSoftware/slsDetectorAnalysis/angularConversion.cpp deleted file mode 100644 index 226e2dbc0..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/angularConversion.cpp +++ /dev/null @@ -1,308 +0,0 @@ -#include "angularConversion.h" - -#include -#include -#include -#include -#include - - -using namespace std; - -angularConversion::angularConversion(): angularConversionStatic(), currentPosition(0), - currentPositionIndex(0) - -{ - //angleFunctionPointer=0; - // registerAngleFunctionCallback(&defaultAngleFunction); - -} - -angularConversion::~angularConversion(){ - -} - - - - -double* angularConversion::convertAngles(double pos) { - - int nmod=getNMods(); - int *chansPerMod=new int[nmod]; - angleConversionConstant **angOff=new angleConversionConstant*[nmod]; - int *mF=new int[nmod]; - double fo=*fineOffset; - double go=*globalOffset; - int angdir=*angDirection; - - - - for (int im=0; im0) { - *binSize=v; - nBins=(int)(360./(*binSize))+1; - } - return *binSize; - case MOVE_FLAG: - if (moveFlag) { - if (v>0) - *moveFlag=1; - else if (v==0) - *moveFlag=0; - return *moveFlag; - } - return -1; - case SAMPLE_X: - if (sampleDisplacement) { - sampleDisplacement[X]=v; - return sampleDisplacement[X]; - } - return 0; - case SAMPLE_Y: - if (sampleDisplacement) { - sampleDisplacement[Y]=v; - return sampleDisplacement[Y]; - } - return 0; - default: - return 0; - } -} - - /** - returns the value of an angular conversion parameter - \param c can be ANGULAR_DIRECTION, GLOBAL_OFFSET, FINE_OFFSET, BIN_SIZE - \returns the actual value - - */ - -double angularConversion::getAngularConversionParameter(angleConversionParameter c) { - - switch (c) { - case ANGULAR_DIRECTION: - return *angDirection; - case GLOBAL_OFFSET: - return *globalOffset; - case FINE_OFFSET: - return *fineOffset; - case BIN_SIZE: - if (*binSize>0) - nBins=(int)(360./(*binSize))+1; - else - nBins=0; - return *binSize; - case MOVE_FLAG: - if (moveFlag) - return *moveFlag; - else - return -1; - default: - return 0; - } -} - - - - -int angularConversion::setAngularConversionFile(string fname) { - if (fname=="") { - setAngularCorrectionMask(0); -#ifdef VERBOSE - std::cout << "Unsetting angular conversion" << std::endl; -#endif - } else { - if (fname=="default") { - fname=string(angConvFile); - } - -#ifdef VERBOSE - std::cout << "Setting angular conversion to " << fname << std:: endl; -#endif - if (readAngularConversionFile(fname)>=0) { - setAngularCorrectionMask(1); - strcpy(angConvFile,fname.c_str()); - } - } - return setAngularCorrectionMask(); -} - - - - - - /* - set positions for the acquisition - \param nPos number of positions - \param pos array with the encoder positions - \returns number of positions - */ -int angularConversion::setPositions(int nPos, double *pos){ - if (nPos>=0) - *numberOfPositions=nPos; - for (int ip=0; ip -#include - -#include "angularConversionStatic.h" - - //double angle(int ichan, double encoder, double totalOffset, double conv_r, double center, double offset, double tilt, int direction) - - -// - -/** - @short Angular conversion constants needed for a detector module - */ - - -/** - -@short methods to set/unset the angular conversion and merge the data -class containing the methods to set/unset the angular conversion and merge the data - - -The angular conversion itself is defined by the angle() function defined in usersFunctions.cpp - -*/ -class angularConversion : public virtual slsDetectorBase, public angularConversionStatic - -{ - - public: - /** default constructor */ - angularConversion(); - /** virtual destructor */ - virtual ~angularConversion(); - - - - //virtual int readAngularConversion(string fname)=0; - - using angularConversionStatic::writeAngularConversion; - using angularConversionStatic::readAngularConversion; - - - - /** - pure virtual function - \param file name to be written (nmod and array of angular conversion constants default to the ones ot the slsDetector - */ - virtual int writeAngularConversion(std::string fname)=0; - /** - sets the arrays of the merged data to 0. NB The array should be created with size >= 360./getBinSize(); - \param mp already merged postions - \param mv already merged data - \param me already merged errors (squared sum) - \param mm multiplicity of merged arrays - \returns OK or FAIL - */ - int resetMerging(double *mp, double *mv,double *me, int *mm); - - /** - creates the arrays for merging the data and sets them to 0. - */ - int resetMerging(); - - - /** - merge dataset - \param p1 angular positions of dataset - \param v1 data - \param e1 errors - \param mp already merged postions - \param mv already merged data - \param me already merged errors (squared sum) - \param mm multiplicity of merged arrays - \param badChanMask badchannelmask (if NULL does not correct for bad channels) - \returns OK or FAIL - */ - - int addToMerging(double *p1, double *v1, double *e1, double *mp, double *mv,double *me, int *mm, int *badChanMask); - /** - merge dataset - \param p1 angular positions of dataset - \param v1 data - \param e1 errors - \param badChanMask badchannelmask (if NULL does not correct for bad channels) - \returns OK or FAIL - */ - - int addToMerging(double *p1, double *v1, double *e1,int *badChanMask); - - /** - calculates the "final" positions, data value and errors for the merged data - \param mp already merged postions - \param mv already merged data - \param me already merged errors (squared sum) - \param mm multiplicity of merged arrays - \returns FAIL or the number of non empty bins (i.e. points belonging to the pattern) - */ - - int finalizeMerging(double *mp, double *mv,double *me, int *mm); - -/** - calculates the "final" positions, data value and errors for the merged data - \returns FAIL or the number of non empty bins (i.e. points belonging to the pattern) - */ - - int finalizeMerging(); - - - /** - set detector global offset - \param f global offset to be set - \returns actual global offset - */ - double setGlobalOffset(double f){return setAngularConversionParameter(GLOBAL_OFFSET,f);}; - - - /** - set detector fine offset - \param f global fine to be set - \returns actual fine offset - */ - double setFineOffset(double f){return setAngularConversionParameter(FINE_OFFSET,f);}; - - /** - get detector fine offset - \returns actual fine offset - */ - double getFineOffset(){return getAngularConversionParameter(FINE_OFFSET);}; - - /** - get detector global offset - \returns actual global offset - */ - double getGlobalOffset(){return getAngularConversionParameter(GLOBAL_OFFSET);}; - - /** - - set detector bin size - \param bs bin size to be set - \returns actual bin size - */ - double setBinSize(double bs){if (bs>0) nBins=(int)(360./bs); return setAngularConversionParameter(BIN_SIZE,bs);}; - - /** - get detector bin size - \returns detector bin size used for merging (approx angular resolution) - */ - double getBinSize() {return getAngularConversionParameter(BIN_SIZE);}; - - - - /** - - get angular direction - \returns actual angular direction (1 is channel number increasing with angle, -1 decreasing) - */ - int getAngularDirection(){return (int)getAngularConversionParameter(ANGULAR_DIRECTION);}; - - - /** - - set angular direction - \param d angular direction to be set (1 is channel number increasing with angle, -1 decreasing) - \returns actual angular direction (1 is channel number increasing with angle, -1 decreasing) - */ - int setAngularDirection(int d){return (int)setAngularConversionParameter(ANGULAR_DIRECTION, (double)d);}; - - /** - \returns number of angular bins in the merging (360./binsize) - */ - int getNumberOfAngularBins(){return nBins;}; - - /** - get angular conversion - \param direction reference to diffractometer direction - \param angconv array that will be filled with the angular conversion constants - \returns 0 if angular conversion disabled, >0 otherwise - */ - virtual int getAngularConversion(int &direction, angleConversionConstant *angconv=NULL)=0; - - - /** - set angular conversion parameter - \param c parameter type (globaloffset, fineoffset, binsize, angular direction, move flag) - \param v value to be set - \returns actual value - */ - double setAngularConversionParameter(angleConversionParameter c, double v); - /** - get angular conversion parameter - \param c parameter type (globaloffset, fineoffset, binsize, angular direction, move flag) - \returns actual value - */ - double getAngularConversionParameter(angleConversionParameter c); - - - - - /** - set positions for the acquisition - \param nPos number of positions - \param pos array with the encoder positions - \returns number of positions - */ - virtual int setPositions(int nPos, double *pos); - /** - get positions for the acquisition - \param pos array which will contain the encoder positions - \returns number of positions - */ - virtual int getPositions(double *pos=NULL); - - /** - deletes the array of merged data - \returns OK - */ - int deleteMerging(); - - /** - \returns pointer to the array o merged positions - */ - double *getMergedPositions(){return mergingBins;}; - /** - \returns pointer to the array of merged counts - */ - double *getMergedCounts(){return mergingCounts;}; - /** - \returns pointer to the array of merged errors - */ - double *getMergedErrors(){return mergingErrors;}; - - - - /** - sets the angular conversion file - \param fname file to read - \returns angular conversion flag - */ - - int setAngularConversionFile(std::string fname); - - - /** - returns the angular conversion file - */ - std::string getAngularConversionFile(){if (setAngularCorrectionMask()) return std::string(angConvFile); else return std::string("none");}; - - - /** - reads teh angular conversion file for the (multi)detector and writes it to shared memory - */ - virtual int readAngularConversionFile(std::string fname="")=0; - - - - - - /** - \returns number of modules of the (multi)detector - */ - virtual int getNMods()=0; - - /** - returns number of channels in the module - \param imod module number - \returns number of channels in the module - */ - virtual int getChansPerMod(int imod=0)=0; - - /** - get the angular conversion contant of one modules - \param imod module number - \returns pointer to the angular conversion constant - */ - virtual angleConversionConstant *getAngularConversionPointer(int imod=0)=0; - - /** - converts channel number to angle - \param pos encoder position - \returns array of angles corresponding to the channels - */ - double* convertAngles(double pos); - - - - /** - converts channel number to angle for the current encoder position - \returns array of angles corresponding to the channels - */ - double *convertAngles(){return convertAngles(currentPosition);}; - - /** - \param imod module number - \returns move flag of the module (1 encoder is added to the angle, 0 not) - Shold be module dependent! - */ - virtual int getMoveFlag(int imod)=0; - - /** - returns number of positions - */ - int getNumberOfPositions() {return *numberOfPositions;}; - - - - protected: - - - /** pointer to number of positions for the acquisition*/ - int *numberOfPositions; - - /** pointer to the detector positions for the acquisition*/ - double *detPositions; - - /** pointer to angular conversion file name*/ - char *angConvFile; - - /** pointer to angular bin size*/ - double *binSize; - - /** pointer to beamlien fine offset*/ - double *fineOffset; - /** pointer to beamlien global offset*/ - double *globalOffset; - /** pointer to beamlien angular direction*/ - int *angDirection; - /** pointer to detector move flag (1 moves with encoder, 0 not)*/ - int *moveFlag; - - /** number of bins for angular conversion (360./binsize)*/ - int nBins; - - - - double *sampleDisplacement; - - /** - current position of the detector - */ - double currentPosition; - /** - current position index of the detector - */ - int currentPositionIndex; - - - /** - enables/disable the angular conversion - \param i 1 sets, 0 unsets,, -1 gets - \returns actual angular conversion flag - */ - virtual int setAngularCorrectionMask(int i=-1)=0; - - /** - returns current position index - */ - int getCurrentPositionIndex() {return currentPositionIndex;}; - void incrementPositionIndex() {currentPositionIndex++;}; - void resetPositionIndex() {currentPositionIndex=0;}; - - - - - - - private: - - - - - // int nChans; - // int nMods; - // int chansPerMod; - // int moveFlag; - - - - - /** merging bins */ - double *mergingBins; - - /** merging counts */ - double *mergingCounts; - - /** merging errors */ - double *mergingErrors; - - /** merging multiplicity */ - int *mergingMultiplicity; - -}; - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/angularConversionStatic.cpp b/slsDetectorSoftware/slsDetectorAnalysis/angularConversionStatic.cpp deleted file mode 100644 index 0e9df564b..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/angularConversionStatic.cpp +++ /dev/null @@ -1,461 +0,0 @@ -#include "angularConversionStatic.h" - -#include -#include -#include -#include -#include "angleConversionConstant.h" - -#include "sls_detector_defs.h" -#include "angleFunction.h" -using namespace std; - -angularConversionStatic::angularConversionStatic() -{ - //angleFunctionPointer=0; - registerAngleFunctionCallback(&defaultAngleFunction); - -} - -angularConversionStatic::~angularConversionStatic(){ - -} - - - -double* angularConversionStatic::convertAngles(double pos, int nch, int *chansPerMod, angleConversionConstant **angOff, int *mF, double fo, double go, int angdir) { - - // cout << "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP convert angles " << endl; - - int imod=0; - double *ang=new double[nch]; - double enc=pos; - angleConversionConstant *p=NULL; - - int ch0=0; - int chlast=chansPerMod[0]-1; - int nchmod=chansPerMod[0]; - p=angOff[imod]; - if (mF[imod]==0) - enc=0; - else - enc=pos; - - for (int ip=0; ipchlast) { - imod++; - p=angOff[imod]; - if (mF[imod]==0) - enc=0; - else - enc=pos; - -#ifdef VERBOSE - if (p) - cout << enc << endl << fo+go << endl << p->r_conversion << endl << p->center << endl << p->offset << endl << p->tilt << angdir << endl; - else - cout << "no ang conv " << endl; -#endif - - ch0=chlast+1; - nchmod=chansPerMod[imod]; - if (nchmod>0) - chlast=ch0+nchmod-1; - } - - if (p) - ang[ip]=angle(ip-ch0, \ - enc, \ - fo+go, \ - p->r_conversion, \ - p->center, \ - p->offset, \ - p->tilt, \ - angdir ); -#ifdef VERBOSE - cout << "ip " << ip << " ch0 " << ch0 << " chlast " << chlast << " imod " << imod << endl; -#endif - } - return ang; -} - - - - - - -double angularConversionStatic::convertAngle(double pos, int ich, angleConversionConstant *p, int mF, double fo, double go, int angdir) { - - // cout << "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP convert angle " << endl; - // if (p) - // cout << pos << endl << fo+go << endl << p->r_conversion << endl << p->center << endl << p->offset << endl << mF << endl << angdir << endl; - // else - // cout << "no ang conv " << endl; - - double enc=0, trans=0; - double ang=0; - - switch (mF) { - case 0: - enc=0; - trans=0; - break; - case 1: - enc=pos; - trans=0; - break; - case -1: - enc=-pos; - trans=0; - break; - case 2: - enc=0; - trans=pos; - break; - case -2: - enc=0; - trans=-pos; - break; - default: - enc=0; - trans=0; - } - - if (p) - ang=angle(ich, \ - enc, \ - fo+go, \ - p->r_conversion, \ - p->center, \ - p->offset, \ - trans, \ - angdir ); - // cout << ich << " " << ang << endl << endl; - return ang; - - - -} - - - - - - - - - - - -double angularConversionStatic::convertAngle(double pos, int ich, int *chansPerMod, angleConversionConstant **angOff, int *mF, double fo, double go, int angdir) { - - // cout << "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP convert angles xx" << endl; - int imod=0; - double ang; - // double enc=0, trans=0; - angleConversionConstant *p=NULL; - - int ch0=0; - int chlast=chansPerMod[0]-1; - int nchmod=chansPerMod[0]; - - - - while (ich>chlast) { - imod++; - ch0=chlast+1; - nchmod=chansPerMod[imod]; - chlast=ch0+nchmod-1; - } - - p=angOff[imod]; - - - ang=convertAngle(pos, ich-ch0, p, mF[imod], fo, go, angdir); - - return ang; - -} - - - -//static! -int angularConversionStatic::readAngularConversion(string fname, int nmod, angleConversionConstant *angOff) { - - ifstream infile; - string ss; - -#ifdef VERBOSE - std::cout<< "Opening file "<< fname << std::endl; -#endif - infile.open(fname.c_str(), ios_base::in); - if (infile.is_open()) { - readAngularConversion(infile, nmod, angOff); - infile.close(); - } else { - std::cout<< "Could not open calibration file "<< fname << std::endl; - return -1; - } - return 0; -} - - -//static -int angularConversionStatic::readAngularConversion( ifstream& infile, int nmod, angleConversionConstant *angOff) { - string str; - int mod; - double center, ecenter, pitch, epitch; - double r_conv, er_conv; - double off, eoff; - string ss; - int interrupt=0; - int nm=0; - int newangconv=0; - //" module %i center %E +- %E conversion %E +- %E offset %f +- %f \n" - while (infile.good() and interrupt==0) { - getline(infile,str); -#ifdef VERBOSE - cout << "** mod " << nm << " " ; - std::cout<< str << std::endl; -#endif - istringstream ssstr(str); - ssstr >> ss >> mod; - ssstr >> ss >> center; - if (ss==string("center")) - newangconv=0; - else - newangconv=1; - ssstr >> ss >> ecenter; - if (newangconv) { - ssstr >> ss >> pitch; - ssstr >> ss >> epitch; - } - ssstr >> ss >> r_conv; - ssstr >> ss >> er_conv; - ssstr >> ss >> off; - ssstr >> ss >> eoff; -#ifdef VERBOSE - cout << nm << " " << nmod << endl; -#endif - if (nm=0 ) { - angOff[nm].center=center; - angOff[nm].r_conversion=r_conv; - angOff[nm].offset=off; - angOff[nm].ecenter=ecenter; - angOff[nm].er_conversion=er_conv; - angOff[nm].eoffset=eoff; - - if (newangconv!=0) { - // } else { - - angOff[nm].tilt=pitch; - angOff[nm].etilt=epitch; - - } - // cout << angOff[nm].center << " " << - // angOff[nm].r_conversion << " " << - // angOff[nm].offset << endl; - - } else - break; -#ifdef VERBOSE - cout << nm<<" " << angOff[nm].offset << endl; -#endif - nm++; - if (nm>=nmod) - break; - - - - - } - return nm; - } - -//static -int angularConversionStatic:: writeAngularConversion(string fname, int nmod, angleConversionConstant *angOff) { - - ofstream outfile; - outfile.open (fname.c_str(),ios_base::out); - if (outfile.is_open()) - { - writeAngularConversion(outfile, nmod, angOff); - outfile.close(); - } else { - std::cout<< "Could not open file " << fname << "for writing"<< std::endl; - return -1; - } - //" module %i center %E +- %E conversion %E +- %E offset %f +- %f \n" - return 0; -} - - - -//static -int angularConversionStatic:: writeAngularConversion(ofstream& outfile, int nmod, angleConversionConstant *angOff) { - - for (int imod=0; imod0) { - #ifdef VERBOSE - cout << "finalize " << ibin << " "<< mm[ibin] << " " << mp[ibin]<< " " << mv[ibin] << " " << me[ibin] << endl; - #endif - mp[np]=mp[ibin]/mm[ibin]; - mv[np]=mv[ibin]/mm[ibin]; - me[np]=me[ibin]/mm[ibin]; - me[np]=sqrt(me[ibin]); - mm[np]=mm[ibin]; - np++; - } - } - // cout << endl ; - return np; -} - -//static -int angularConversionStatic::addToMerging(double *p1, double *v1, double *e1, double *mp, double *mv,double *me, int *mm, int nchans, double binsize,int nbins, int *badChanMask ) { - - - // cout << "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP add to merging " << endl; - double binmi=-180.; - int ibin=0; - - if (p1==NULL) - return 0; - if (v1==NULL) - return slsDetectorDefs::FAIL; - - if (mp==NULL) //can be changed if we want to use a fixed bin algorithm! - return slsDetectorDefs::FAIL; - - if (mv==NULL) - return slsDetectorDefs::FAIL; - if (me==NULL) - return slsDetectorDefs::FAIL; - if (mm==NULL) - return slsDetectorDefs::FAIL; - if (nchans==0) - return slsDetectorDefs::FAIL; - - if (binsize<=0) - return slsDetectorDefs::FAIL; - - if (nbins<=0) - return slsDetectorDefs::FAIL; - - for (int ip=0; ip=0) { - mp[ibin]+=p1[ip]; - mv[ibin]+=v1[ip]; - if (e1) - me[ibin]+=(e1[ip]*e1[ip]); - else - me[ibin]+=v1[ip]; - mm[ibin]++; - -// #ifdef VERBOSE -// cout << "add " << ibin << " "<< mm[ibin] << " " << mp[ibin]<< mv[ibin] << me[ibin] << endl; -// #endif - } else - return slsDetectorDefs::FAIL; - } - - - return slsDetectorDefs::OK; - -} - -int angularConversionStatic::addPointToMerging(double p1, double v1, double e1, double *mp, double *mv,double *me, int *mm, double binsize,int nbins) { - - - // cout << "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP add point to merging "<< v1 << " " << e1 << endl; - double binmi=-180.; - int ibin=0; - - - if (mp==NULL) //can be changed if we want to use a fixed bin algorithm! - return slsDetectorDefs::FAIL; - - if (mv==NULL) - return slsDetectorDefs::FAIL; - if (me==NULL) - return slsDetectorDefs::FAIL; - if (mm==NULL) - return slsDetectorDefs::FAIL; - - if (binsize<=0) - return slsDetectorDefs::FAIL; - - if (nbins<=0) - return slsDetectorDefs::FAIL; - - - ibin=(int)((p1-binmi)/binsize); - - - if (ibin=0) { - // cout << "before " << ibin << " " << mp[ibin] << " " << mv[ibin] << " " << me[ibin] << endl; - mp[ibin]+=p1; - mv[ibin]+=v1; - if (e1) - me[ibin]+=(e1*e1); - else - me[ibin]+=v1; - mm[ibin]++; - // cout << "after " << ibin << " " << mp[ibin] << " " << mv[ibin] << " " << me[ibin] << endl; - -// #ifdef VERBOSE -// cout << "add " << ibin << " "<< mm[ibin] << " " << mp[ibin]<< mv[ibin] << me[ibin] << endl; -// #endif - } else { - cout << "Bin out of range! " << ibin << endl; - return slsDetectorDefs::FAIL; - } - - return slsDetectorDefs::OK; - -} diff --git a/slsDetectorSoftware/slsDetectorAnalysis/angularConversionStatic.h b/slsDetectorSoftware/slsDetectorAnalysis/angularConversionStatic.h deleted file mode 100644 index ec1b47d6b..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/angularConversionStatic.h +++ /dev/null @@ -1,184 +0,0 @@ - -#ifndef ANGULARCONVERSIONSTATIC_H -#define ANGULARCONVERSIONSTATIC_H - -#ifdef __CINT -#define MYROOT -#endif - - - - -#include -#include - -//#include "angleConversionConstant.h" - - - //double angle(int ichan, double encoder, double totalOffset, double conv_r, double center, double offset, double tilt, int direction) - -class angleConversionConstant; - -; - -/** - @short Angular conversion constants needed for a detector module - */ - - -/** - -@short methods to set/unset the angular conversion and merge the data -class containing the methods to set/unset the angular conversion and merge the data - - -The angular conversion itself is defined by the angle() function defined in usersFunctions.cpp - -*/ -class angularConversionStatic -// : public virtual slsDetectorDefs -{ - - public: - /** default constructor */ - angularConversionStatic(); - /** virtual destructor */ - virtual ~angularConversionStatic(); - - - - //virtual int readAngularConversion(std::string fname)=0; - - - - - /** - - reads an angular conversion file - \param fname file to be read - \param nmod number of modules (maximum) to be read - \param angOff pointer to array of angleConversionConstants - \returns OK or FAIL - */ - static int readAngularConversion(std::string fname, int nmod, angleConversionConstant *angOff); - - /** - reads an angular conversion file - \param ifstream input file stream to be read - \param nmod number of modules (maximum) to be read - \param angOff pointer to array of angleConversionConstants - \returns OK or FAIL - - */ - static int readAngularConversion(std::ifstream& ifs, int nmod, angleConversionConstant *angOff); - /** - writes an angular conversion file - \param fname file to be written - \param nmod number of modules to be written - \param angOff pointer to array of angleConversionConstants - \returns OK or FAIL - */ - static int writeAngularConversion(std::string fname, int nmod, angleConversionConstant *angOff); - - /** - writes an angular conversion file - \param ofstream output file stream - \param nmod number of modules to be written - \param angOff pointer to array of angleConversionConstants - \returns OK or FAIL - */ - static int writeAngularConversion(std::ofstream& ofs, int nmod, angleConversionConstant *angOff); - - /** - sets the arrays of the merged data to 0. NB The array should be created with size nbins >= 360./getBinSize(); - \param mp already merged postions - \param mv already merged data - \param me already merged errors (squared sum) - \param mm multiplicity of merged arrays - \param nbins number of bins - \returns OK or FAIL - */ - static int resetMerging(double *mp, double *mv,double *me, int *mm, int nbins); - - /** - merge dataset - \param p1 angular positions of dataset - \param v1 data - \param e1 errors - \param mp already merged postions - \param mv already merged data - \param me already merged errors (squared sum) - \param mm multiplicity of merged arrays - \param nchans number of channels - \param binsize size of angular bin - \param nb number of angular bins - \param badChanMask badchannelmask (if NULL does not correct for bad channels) - \returns OK or FAIL - */ - - static int addToMerging(double *p1, double *v1, double *e1, double *mp, double *mv,double *me, int *mm, int nchans, double binsize,int nb, int *badChanMask=NULL); - - - /** - merge dataset - \param p1 angular positions of dataset - \param v1 data - \param e1 errors - \param mp already merged postions - \param mv already merged data - \param me already merged errors (squared sum) - \param mm multiplicity of merged arrays - \param nchans number of channels - \param binsize size of angular bin - \param nb number of angular bins - \param badChanMask badchannelmask (if NULL does not correct for bad channels) - \returns OK or FAIL - */ - - static int addPointToMerging(double p1, double v1, double e1, double *mp, double *mv,double *me, int *mm, double binsize, int nb); - - - /** - calculates the "final" positions, data value and errors for the merged data - \param mp already merged postions - \param mv already merged data - \param me already merged errors (squared sum) - \param mm multiplicity of merged arrays - \param nb number of bins - \returns FAIL or the number of non empty bins (i.e. points belonging to the pattern) - */ - - static int finalizeMerging(double *mp, double *mv,double *me, int *mm, int nb); - - /** - converts channel number to angle - \param pos encoder position - \returns array of angles corresponding to the channels - */ - - double* convertAngles(double pos, int nch, int *chansPerMod, angleConversionConstant **angOff, int *mF, double fo, double go, int angdir); - - double convertAngle(double pos, int ich, int *chansPerMod, angleConversionConstant **angOff, int *mF, double fo, double go, int angdir); - - - double convertAngle(double pos, int ich, angleConversionConstant *angOff, int mF, double fo, double go, int angdir); - - - - protected: - - - - - int registerAngleFunctionCallback(double (*fun)(double, double, double, double, double, double, double, int)) {angle = fun; return 0;}; - - - double (*angle)(double, double, double, double, double, double, double, int); - - - // private: - - -}; - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/badChannelCorrections.h b/slsDetectorSoftware/slsDetectorAnalysis/badChannelCorrections.h deleted file mode 100644 index 5cc290e1c..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/badChannelCorrections.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef BAD_CHANNEL_CORRECTIONS_H -#define BAD_CHANNEL_CORRECTIONS_H - - -#include -#include -#include -#include - -// -class badChannelCorrections{ - - public: - - static int readBadChannelCorrectionFile(std::string fname, int &nbad, int *badlist){ std::ifstream infile(fname.c_str()); int nb=-1; if (infile.is_open()) {nb=readBadChannelCorrectionFile(infile,nbad,badlist); infile.close();}; return nb;}; - - - - static int readBadChannelCorrectionFile(std::ifstream &infile, int &nbad, int *badlist, int moff=0){ \ - int interrupt=0; \ - int ich; \ - int chmin,chmax; \ - std::string str; \ - nbad=0; \ - while (infile.good() and interrupt==0) { \ - getline(infile,str); \ - std::istringstream ssstr; \ - ssstr.str(str); \ - if (ssstr.bad() || ssstr.fail() || infile.eof()) { \ - interrupt=1; \ - break; \ - } \ - if (str.find('-')!=std::string::npos) { \ - ssstr >> chmin ; \ - ssstr.str(str.substr(str.find('-')+1,str.size())); \ - ssstr >> chmax; \ - for (ich=chmin; ich<=chmax; ich++) { \ - badlist[nbad]=ich; \ - nbad++; \ - } \ - } else { \ - ssstr >> ich; \ - badlist[nbad]=ich; \ - nbad++; \ - } \ - } \ - return nbad; }; - - - static int setBadChannelCorrection(std::ifstream &infile, int &nbad, int *badlist, int moff){ \ - int retval=readBadChannelCorrectionFile(infile,nbad,badlist); \ - for (int ich=0; ich -#include -#ifndef DETECTOR_DATA_H -#define DETECTOR_DATA_H -/** - @short data structure to hold the detector data after postprocessing (e.g. to plot, store in a root tree etc.) - */ -class detectorData { - public: - /** @short The constructor - \param val pointer to the data in double data type(valid only for MYTHEN) - \param err pointer to errors - \param ang pointer to the angles - \param f_ind file index - \param fname file name to which the data are saved - \param np number of points in x coordinate defaults to the number of detector channels (1D detector) or dimension in x (2D detector) - \param ny dimension in y (2D detector) - \param cval pointer to data in char* format (valid only for non MYTHEN detectors) - \param dbytes number of bytes of image pointed to by cval pointer (valid only for non MYTHEN detectors) - \param dr dynamic range or bits per pixel (valid only for non MYTHEN detectors) - \param file_ind file index - */ - detectorData(double *val=NULL, double *err=NULL, double *ang=NULL, double f_ind=-1, - const char *fname="", int np=-1, int ny=1, char *cval=NULL, int dbytes=0, int dr=0, - long long int file_ind=-1) : - values(val), errors(err), angles(ang), progressIndex(f_ind), - npoints(np), npy(ny), cvalues(cval), databytes(dbytes), - dynamicRange(dr), dgainvalues(NULL), fileIndex(file_ind) { - strcpy(fileName,fname); - }; - - /** - @short The destructor - deletes also the arrays pointing to data/errors/angles if not NULL - cvalues are deleted by caller - */ - ~detectorData() {if (values) delete [] values; if (errors) delete [] errors; - if (angles) delete [] angles; if(dgainvalues) delete [] dgainvalues;}; - //private: - double *values; /**< @short pointer to the data as double array (MYTHEN only) */ - double *errors; /**< @short pointer to the errors */ - double *angles;/**< @short pointer to the angles (NULL if no angular conversion) */ - double progressIndex;/**< @short file index */ - char fileName[1000];/**< @short file name */ - int npoints;/**< @short number of points */ - int npy;/**< @short dimensions in y coordinate*/ - char* cvalues; /**< @short pointer to the data as char arary (non MYTHEN detectors) */ - int databytes; /**< @short number of bytes of data. Used with cvalues */ - int dynamicRange; /**< @short dynamic range */ - double* dgainvalues; /**< @short pointer to gain data as double array */ - long long int fileIndex; /**< @short file index */ -}; - - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/annotated.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/annotated.html deleted file mode 100644 index 0af77f9f8..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/annotated.html +++ /dev/null @@ -1,28 +0,0 @@ - - -Class List - - - - - - -

Class List

Here are the classes, structs, unions and interfaces with brief descriptions: - - -
energyCalibration
energyCalibrationFunctionsEnergy calibration functions
-
Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classenergyCalibration-members.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classenergyCalibration-members.html deleted file mode 100644 index 4923725d9..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classenergyCalibration-members.html +++ /dev/null @@ -1,55 +0,0 @@ - - -Member List - - - - - - -

energyCalibration Member List

This is the complete list of members for energyCalibration, including all inherited members.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
amplenergyCalibration [private]
bg_offsetenergyCalibration [private]
bg_slopeenergyCalibration [private]
calibrate(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff, int integral=1)energyCalibration [private]
calibrateScurves(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff)energyCalibration [inline]
calibrateSpectra(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff)energyCalibration [inline]
cs_flagenergyCalibration [private]
cs_slopeenergyCalibration [private]
energyCalibration()energyCalibration
fit_maxenergyCalibration [private]
fit_minenergyCalibration [private]
fitFunction(TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar)energyCalibration [private]
fitSCurve(TH1 *h1, Double_t *mypar, Double_t *emypar)energyCalibration
fitSpectrum(TH1 *h1, Double_t *mypar, Double_t *emypar)energyCalibration
flexenergyCalibration [private]
fscurveenergyCalibration [private]
fspectrumenergyCalibration [private]
funcsenergyCalibration [private]
getFitRange(Double_t &mi, Double_t &ma)energyCalibration [inline]
getStartParameters(Double_t *par)energyCalibration
initFitFunction(TF1 *fun, TH1 *h1)energyCalibration [private]
linearCalibration(int nscan, Double_t *en, Double_t *een, Double_t *fl, Double_t *efl, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff)energyCalibration
noiseenergyCalibration [private]
plot_flagenergyCalibration [private]
setChargeSharing(int p=-1)energyCalibration
setFitRange(Double_t mi, Double_t ma)energyCalibration [inline]
setPlotFlag(int p=-1)energyCalibration [inline]
setScanSign(int s=0)energyCalibration [inline]
setStartParameters(Double_t *par)energyCalibration
~energyCalibration()energyCalibration


Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classenergyCalibration.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classenergyCalibration.html deleted file mode 100644 index 5ad0b2776..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classenergyCalibration.html +++ /dev/null @@ -1,1026 +0,0 @@ - - -energyCalibration Class Reference - - - - - - -

energyCalibration Class Reference

#include <energyCalibration.h> -

-List of all members. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Public Member Functions

 energyCalibration ()
 ~energyCalibration ()
int setPlotFlag (int p=-1)
int setScanSign (int s=0)
int setChargeSharing (int p=-1)
void setFitRange (Double_t mi, Double_t ma)
void getFitRange (Double_t &mi, Double_t &ma)
void setStartParameters (Double_t *par)
void getStartParameters (Double_t *par)
TF1 * fitSCurve (TH1 *h1, Double_t *mypar, Double_t *emypar)
TF1 * fitSpectrum (TH1 *h1, Double_t *mypar, Double_t *emypar)
TGraphErrors * linearCalibration (int nscan, Double_t *en, Double_t *een, Double_t *fl, Double_t *efl, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff)
TGraphErrors * calibrateScurves (int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff)
TGraphErrors * calibrateSpectra (int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff)

Private Member Functions

TGraphErrors * calibrate (int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff, int integral=1)
void initFitFunction (TF1 *fun, TH1 *h1)
TF1 * fitFunction (TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar)

Private Attributes

int plot_flag
int cs_flag
Double_t fit_min
Double_t fit_max
Double_t bg_offset
Double_t bg_slope
Double_t flex
Double_t noise
Double_t ampl
Double_t cs_slope
energyCalibrationFunctionsfuncs
TF1 * fscurve
TF1 * fspectrum
-


Detailed Description

-class alowing the energy calibration of photon counting and anlogue detectors -

-


Constructor & Destructor Documentation

- -
-
- - - - - - - - -
energyCalibration::energyCalibration (  ) 
-
-
- -

-default constructor - creates the function with which the s-curves will be fitted -

-

- -

-
- - - - - - - - -
energyCalibration::~energyCalibration (  ) 
-
-
- -

-default destructor - deletes the function with which the s-curves will be fitted -

-

-


Member Function Documentation

- -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TGraphErrors* energyCalibration::calibrate (int  nscan,
Double_t *  en,
Double_t *  een,
TH1F **  h1,
Double_t &  gain,
Double_t &  off,
Double_t &  egain,
Double_t &  eoff,
int  integral = 1 
) [private]
-
-
- -

-calculates gain and offset for the set of energies

Parameters:
- - - - - - - - -
nscan number of energy scans
en array of energies (nscan long)
een array of errors on energies (nscan long) - can be NULL!
h1 array of TH1
gain reference to gain resulting from the fit
offset reference to offset resulting from the fit
integral 1 is an s-curve set (default), 0 spectra
-
-
Returns:
graph energy vs peak/inflection point
- -
-

- -

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TGraphErrors* energyCalibration::calibrateScurves (int  nscan,
Double_t *  en,
Double_t *  een,
TH1F **  h1,
Double_t &  gain,
Double_t &  off,
Double_t &  egain,
Double_t &  eoff 
) [inline]
-
-
- -

-calculates gain and offset for the set of energy scans

Parameters:
- - - - - - - - - -
nscan number of energy scans
en array of energies (nscan long)
een array of errors on energies (nscan long) - can be NULL!
h1 array of TH1
gain reference to gain resulting from the fit
off reference to offset resulting from the fit
egain reference to error on the gain resulting from the fit
eoff reference to the error on the offset resulting from the fit
-
-
Returns:
graph energy vs inflection point
- -
-

- -

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TGraphErrors* energyCalibration::calibrateSpectra (int  nscan,
Double_t *  en,
Double_t *  een,
TH1F **  h1,
Double_t &  gain,
Double_t &  off,
Double_t &  egain,
Double_t &  eoff 
) [inline]
-
-
- -

-calculates gain and offset for the set of energy spectra

Parameters:
- - - - - - - - - -
nscan number of energy scans
en array of energies (nscan long)
een array of errors on energies (nscan long) - can be NULL!
h1 array of TH1
gain reference to gain resulting from the fit
off reference to offset resulting from the fit
egain reference to error on the gain resulting from the fit
eoff reference to the error on the offset resulting from the fit
-
-
Returns:
graph energy vs peak
- -
-

- -

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TF1* energyCalibration::fitFunction (TF1 *  fun,
TH1 *  h1,
Double_t *  mypar,
Double_t *  emypar 
) [private]
-
-
- -

-Perfors the fit according to the flags specified and returns the fitted function

Parameters:
- - - - - -
fun function to fit
h1 histogram to fit
mypar pointer to fit parameters array
emypar pointer to fit parameter errors
-
-
Returns:
the fitted function - can be used e.g. to get the Chi2 or similar
- -
-

- -

-
- - - - - - - - - - - - - - - - - - - - - - - - -
TF1* energyCalibration::fitSCurve (TH1 *  h1,
Double_t *  mypar,
Double_t *  emypar 
)
-
-
- -

-fits histogram with the s-curve function

Parameters:
- - - - -
h1 1d-histogram to be fitted
mypar pointer to fit parameters array
emypar pointer to fit parameter errors
-
-
Returns:
the fitted function - can be used e.g. to get the Chi2 or similar
- -
-

- -

-
- - - - - - - - - - - - - - - - - - - - - - - - -
TF1* energyCalibration::fitSpectrum (TH1 *  h1,
Double_t *  mypar,
Double_t *  emypar 
)
-
-
- -

-fits histogram with the spectrum

Parameters:
- - - - -
h1 1d-histogram to be fitted
mypar pointer to fit parameters array
emypar pointer to fit parameter errors
-
-
Returns:
the fitted function - can be used e.g. to get the Chi2 or similar
- -
-

- -

-
- - - - - - - - - - - - - - - - - - -
void energyCalibration::getFitRange (Double_t &  mi,
Double_t &  ma 
) [inline]
-
-
- -

-gets the s-curve fit range

Parameters:
- - - -
mi reference for minimum of the fit range (-1 is histogram x-min)
ma reference for maximum of the fit range (-1 is histogram x-max)
-
- -
-

- -

-
- - - - - - - - - -
void energyCalibration::getStartParameters (Double_t *  par  ) 
-
-
- -

-get start parameters for the s-curve function

Parameters:
- - -
par parameters, -1 means auto-calculated par[0] is the pedestal par[1] is the slope of the pedestal par[2] is the inflection point par[3] is the RMS par[4] is the amplitude par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) -- always positive
-
- -
-

- -

-
- - - - - - - - - - - - - - - - - - -
void energyCalibration::initFitFunction (TF1 *  fun,
TH1 *  h1 
) [private]
-
-
- -

-Initializes the start parameters and the range of the fit depending on the histogram characteristics and/or on the start parameters specified by the user

Parameters:
- - - -
fun pointer to function to be initialized
h1 histogram from which to extract the range and start parameters, if not already specified by the user
-
- -
-

- -

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TGraphErrors* energyCalibration::linearCalibration (int  nscan,
Double_t *  en,
Double_t *  een,
Double_t *  fl,
Double_t *  efl,
Double_t &  gain,
Double_t &  off,
Double_t &  egain,
Double_t &  eoff 
)
-
-
- -

-calculates gain and offset for the set of inflection points

Parameters:
- - - - - - - - - - -
nscan number of energy scans
en array of energies (nscan long)
een array of errors on energies (nscan long) - can be NULL!
fl array of inflection points (nscan long)
efl array of errors on the inflection points (nscan long)
gain reference to gain resulting from the fit
off reference to offset resulting from the fit
egain reference to error on the gain resulting from the fit
eoff reference to the error on the offset resulting from the fit
-
-
Returns:
graph energy vs inflection point
- -
-

- -

-
- - - - - - - - - -
int energyCalibration::setChargeSharing (int  p = -1  ) 
-
-
- -

-sets plot flag

Parameters:
- - -
p plot flag (-1 gets, 0 unsets, >0 plot)
-
-
Returns:
current plot flag
- -
-

- -

-
- - - - - - - - - - - - - - - - - - -
void energyCalibration::setFitRange (Double_t  mi,
Double_t  ma 
) [inline]
-
-
- -

-sets the s-curve fit range

Parameters:
- - - -
mi minimum of the fit range (-1 is histogram x-min)
ma maximum of the fit range (-1 is histogram x-max)
-
- -
-

- -

-
- - - - - - - - - -
int energyCalibration::setPlotFlag (int  p = -1  )  [inline]
-
-
- -

-sets plot flag

Parameters:
- - -
p plot flag (-1 gets, 0 unsets, >0 plot)
-
-
Returns:
current plot flag
- -
-

- -

-
- - - - - - - - - -
int energyCalibration::setScanSign (int  s = 0  )  [inline]
-
-
- -

-sets scan sign

Parameters:
- - -
s can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) otherwise gets
-
-
Returns:
current scan sign can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions)
- -
-

- -

-
- - - - - - - - - -
void energyCalibration::setStartParameters (Double_t *  par  ) 
-
-
- -

-set start parameters for the s-curve function

Parameters:
- - -
par parameters, -1 sets to auto-calculation par[0] is the pedestal par[1] is the slope of the pedestal par[2] is the inflection point par[3] is the RMS par[4] is the amplitude par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) -- always positive
-
- -
-

-


Member Data Documentation

- -
-
- - - - -
Double_t energyCalibration::ampl [private]
-
-
- -

-start value for the number of photons -

-

- -

-
- - - - -
Double_t energyCalibration::bg_offset [private]
-
-
- -

-start value for the background pedestal -

-

- -

-
- - - - -
Double_t energyCalibration::bg_slope [private]
-
-
- -

-start value for the background slope -

-

- -

-
- - - - -
int energyCalibration::cs_flag [private]
-
-
- -

-0 functions without charge sharing contribution, >0 with charge sharing contribution -

-

- -

-
- - - - -
Double_t energyCalibration::cs_slope [private]
-
-
- -

-start value for the charge sharing slope -

-

- -

-
- - - - -
Double_t energyCalibration::fit_max [private]
-
-
- -

-maximum of the s-curve fitting range, -1 is histogram x-max -

-

- -

-
- - - - -
Double_t energyCalibration::fit_min [private]
-
-
- -

-minimum of the s-curve fitting range, -1 is histogram x-min -

-

- -

-
- - - - -
Double_t energyCalibration::flex [private]
-
-
- -

-start value for the inflection point -

-

- -

-
- - - - -
TF1* energyCalibration::fscurve [private]
-
-
- -

-function with which the s-curve will be fitted -

-

- -

-
- - - - -
TF1* energyCalibration::fspectrum [private]
-
-
- -

-function with which the spectrum will be fitted -

-

- -

- -
- -

- -

-

- -

-
- - - - -
Double_t energyCalibration::noise [private]
-
-
- -

-start value for the noise -

-

- -

-
- - - - -
int energyCalibration::plot_flag [private]
-
-
- -

-0 does not plot, >0 plots (flags?) -

-

-


The documentation for this class was generated from the following file: -
Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classenergyCalibrationFunctions-members.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classenergyCalibrationFunctions-members.html deleted file mode 100644 index 6e87b92ca..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classenergyCalibrationFunctions-members.html +++ /dev/null @@ -1,38 +0,0 @@ - - -Member List - - - - - - -

energyCalibrationFunctions Member List

This is the complete list of members for energyCalibrationFunctions, including all inherited members.

- - - - - - - - - - - - - -
energyCalibrationFunctions(int s=-1)energyCalibrationFunctions [inline]
erfFuncFluo(Double_t *x, Double_t *par)energyCalibrationFunctions
erfFunction(Double_t *x, Double_t *par)energyCalibrationFunctions
erfFunctionChargeSharing(Double_t *x, Double_t *par)energyCalibrationFunctions
gaussChargeSharing(Double_t *x, Double_t *par)energyCalibrationFunctions
kth_smallest(int *a, int n, int k)energyCalibrationFunctions [static]
median(float *x, int n)energyCalibrationFunctions [static]
quick_select(int arr[], int n)energyCalibrationFunctions [static]
scurve(Double_t *x, Double_t *par)energyCalibrationFunctions
scurveFluo(Double_t *x, Double_t *par)energyCalibrationFunctions
setScanSign(int s=0)energyCalibrationFunctions [inline]
signenergyCalibrationFunctions [private]
spectrum(Double_t *x, Double_t *par)energyCalibrationFunctions


Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classenergyCalibrationFunctions.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classenergyCalibrationFunctions.html deleted file mode 100644 index 2a0dfd405..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classenergyCalibrationFunctions.html +++ /dev/null @@ -1,428 +0,0 @@ - - -energyCalibrationFunctions Class Reference - - - - - - -

energyCalibrationFunctions Class Reference

Energy calibration functions. -More... -

-#include <energyCalibration.h> -

-List of all members. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Public Member Functions

 energyCalibrationFunctions (int s=-1)
int setScanSign (int s=0)
Double_t gaussChargeSharing (Double_t *x, Double_t *par)
Double_t erfFunction (Double_t *x, Double_t *par)
Double_t erfFunctionChargeSharing (Double_t *x, Double_t *par)
Double_t erfFuncFluo (Double_t *x, Double_t *par)
Double_t spectrum (Double_t *x, Double_t *par)
Double_t scurve (Double_t *x, Double_t *par)
Double_t scurveFluo (Double_t *x, Double_t *par)

Static Public Member Functions

static float median (float *x, int n)
static int quick_select (int arr[], int n)
static int kth_smallest (int *a, int n, int k)

Private Attributes

int sign
-


Detailed Description

-Energy calibration functions. -

-class containing all the possible energy calibration functions (scurves with and without charge sharing, gaussian spectrum with and without charge sharing, possibility of chosing the sign of the X-axis) -

-


Constructor & Destructor Documentation

- -
-
- - - - - - - - - -
energyCalibrationFunctions::energyCalibrationFunctions (int  s = -1  )  [inline]
-
-
- -

- -

-

-


Member Function Documentation

- -
-
- - - - - - - - - - - - - - - - - - -
Double_t energyCalibrationFunctions::erfFuncFluo (Double_t *  x,
Double_t *  par 
)
-
-
- -

-Double Erf function with charge sharing slope par[0] is the pedestal par[1] is the slope of the pedestal par[2] is the inflection point of the first energy par[3] is the RMS of the first energy par[4] is the amplitude of the first energy par[5] is the angual coefficient of the charge sharing slope of the first energy (scales with par[3]) par[6] is the inflection point of the second energy par[7] is the RMS of the second energy par[8] is the amplitude of the second energy par[9] is the angual coefficient of the charge sharing slope of the second energy (scales with par[8]) -

-

- -

-
- - - - - - - - - - - - - - - - - - -
Double_t energyCalibrationFunctions::erfFunction (Double_t *  x,
Double_t *  par 
)
-
-
- -

-Basic erf function par[0] is the inflection point par[1] is the RMS par[2] is the amplitude -

-

- -

-
- - - - - - - - - - - - - - - - - - -
Double_t energyCalibrationFunctions::erfFunctionChargeSharing (Double_t *  x,
Double_t *  par 
)
-
-
- -

-Erf function with charge sharing slope par[0] is the pedestal par[1] is the slope of the pedestal par[2] is the inflection point par[3] is the RMS par[4] is the amplitude par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) -

-

- -

-
- - - - - - - - - - - - - - - - - - -
Double_t energyCalibrationFunctions::gaussChargeSharing (Double_t *  x,
Double_t *  par 
)
-
-
- -

-Gaussian Function with charge sharing pedestal par[0] is the absolute height of the background pedestal par[1] is the slope of the background pedestal par[2] is the gaussian peak position par[3] is the RMS of the gaussian (and of the pedestal) par[4] is the height of the function par[5] is the fractional height of the charge sharing pedestal (scales with par[3]) -

-

- -

-
- - - - - - - - - - - - - - - - - - - - - - - - -
static int energyCalibrationFunctions::kth_smallest (int *  a,
int  n,
int  k 
) [static]
-
-
- -

-Calculates the median of an array of n elements (swaps the arrays!) -

-

- -

-
- - - - - - - - - - - - - - - - - - -
static float energyCalibrationFunctions::median (float *  x,
int  n 
) [static]
-
-
- -

-Calculates the median of an array of n elements -

-

- -

-
- - - - - - - - - - - - - - - - - - -
static int energyCalibrationFunctions::quick_select (int  arr[],
int  n 
) [static]
-
-
- -

-Calculates the median of an array of n elements (swaps the arrays!) -

-

- -

-
- - - - - - - - - - - - - - - - - - -
Double_t energyCalibrationFunctions::scurve (Double_t *  x,
Double_t *  par 
)
-
-
- -

-Erf function with charge sharing slope with the correct scan sign par[0] is the pedestal par[1] is the slope of the pedestal par[2] is the inflection point par[3] is the RMS par[4] is the amplitude par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) -

-

- -

-
- - - - - - - - - - - - - - - - - - -
Double_t energyCalibrationFunctions::scurveFluo (Double_t *  x,
Double_t *  par 
)
-
-
- -

-Double Erf function with charge sharing slope par[0] is the pedestal par[1] is the slope of the pedestal par[2] is the inflection point of the first energy par[3] is the RMS of the first energy par[4] is the amplitude of the first energy par[5] is the angual coefficient of the charge sharing slope of the first energy (scales with par[3]) par[6] is the inflection point of the second energy par[7] is the RMS of the second energy par[8] is the amplitude of the second energy par[9] is the angual coefficient of the charge sharing slope of the second energy (scales with par[8]) -

-

- -

-
- - - - - - - - - -
int energyCalibrationFunctions::setScanSign (int  s = 0  )  [inline]
-
-
- -

-sets scan sign

Parameters:
- - -
s can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) otherwise gets
-
-
Returns:
current scan sign can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions)
- -
-

- -

-
- - - - - - - - - - - - - - - - - - -
Double_t energyCalibrationFunctions::spectrum (Double_t *  x,
Double_t *  par 
)
-
-
- -

-static function Gaussian with charge sharing pedestal with the correct scan sign par[0] is the absolute height of the background pedestal par[1] is the fractional height of the charge sharing pedestal (scales with par[3] par[2] is the gaussian peak position par[3] is the RMS of the gaussian (and of the pedestal) par[4] is the height of the function -

-

-


Member Data Documentation

- -
-
- - - - -
int energyCalibrationFunctions::sign [private]
-
-
- -

- -

-

-


The documentation for this class was generated from the following file: -
Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classes.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classes.html deleted file mode 100644 index 4cc7a4ddd..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/classes.html +++ /dev/null @@ -1,69 +0,0 @@ - - - - - -Alphabetical List - - - - - - - - - -
-

Class Index

- -
  E  
-
energyCalibration   energyCalibrationFunctions   
-
- - - - -
- -
- -
Generated on Tue Mar 20 17:21:14 2012 by  - -doxygen 1.6.0
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/doxygen.css b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/doxygen.css deleted file mode 100644 index 5d583694e..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/doxygen.css +++ /dev/null @@ -1,358 +0,0 @@ -BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV { - font-family: Geneva, Arial, Helvetica, sans-serif; -} -BODY,TD { - font-size: 90%; -} -H1 { - text-align: center; - font-size: 160%; -} -H2 { - font-size: 120%; -} -H3 { - font-size: 100%; -} -CAPTION { font-weight: bold } -DIV.qindex { - width: 100%; - background-color: #e8eef2; - border: 1px solid #84b0c7; - text-align: center; - margin: 2px; - padding: 2px; - line-height: 140%; -} -DIV.nav { - width: 100%; - background-color: #e8eef2; - border: 1px solid #84b0c7; - text-align: center; - margin: 2px; - padding: 2px; - line-height: 140%; -} -DIV.navtab { - background-color: #e8eef2; - border: 1px solid #84b0c7; - text-align: center; - margin: 2px; - margin-right: 15px; - padding: 2px; -} -TD.navtab { - font-size: 70%; -} -A.qindex { - text-decoration: none; - font-weight: bold; - color: #1A419D; -} -A.qindex:visited { - text-decoration: none; - font-weight: bold; - color: #1A419D -} -A.qindex:hover { - text-decoration: none; - background-color: #ddddff; -} -A.qindexHL { - text-decoration: none; - font-weight: bold; - background-color: #6666cc; - color: #ffffff; - border: 1px double #9295C2; -} -A.qindexHL:hover { - text-decoration: none; - background-color: #6666cc; - color: #ffffff; -} -A.qindexHL:visited { text-decoration: none; background-color: #6666cc; color: #ffffff } -A.el { text-decoration: none; font-weight: bold } -A.elRef { font-weight: bold } -A.code:link { text-decoration: none; font-weight: normal; color: #0000FF} -A.code:visited { text-decoration: none; font-weight: normal; color: #0000FF} -A.codeRef:link { font-weight: normal; color: #0000FF} -A.codeRef:visited { font-weight: normal; color: #0000FF} -A:hover { text-decoration: none; background-color: #f2f2ff } -DL.el { margin-left: -1cm } -.fragment { - font-family: monospace, fixed; - font-size: 95%; -} -PRE.fragment { - border: 1px solid #CCCCCC; - background-color: #f5f5f5; - margin-top: 4px; - margin-bottom: 4px; - margin-left: 2px; - margin-right: 8px; - padding-left: 6px; - padding-right: 6px; - padding-top: 4px; - padding-bottom: 4px; -} -DIV.ah { background-color: black; font-weight: bold; color: #ffffff; margin-bottom: 3px; margin-top: 3px } - -DIV.groupHeader { - margin-left: 16px; - margin-top: 12px; - margin-bottom: 6px; - font-weight: bold; -} -DIV.groupText { margin-left: 16px; font-style: italic; font-size: 90% } -BODY { - background: white; - color: black; - margin-right: 20px; - margin-left: 20px; -} -TD.indexkey { - background-color: #e8eef2; - font-weight: bold; - padding-right : 10px; - padding-top : 2px; - padding-left : 10px; - padding-bottom : 2px; - margin-left : 0px; - margin-right : 0px; - margin-top : 2px; - margin-bottom : 2px; - border: 1px solid #CCCCCC; -} -TD.indexvalue { - background-color: #e8eef2; - font-style: italic; - padding-right : 10px; - padding-top : 2px; - padding-left : 10px; - padding-bottom : 2px; - margin-left : 0px; - margin-right : 0px; - margin-top : 2px; - margin-bottom : 2px; - border: 1px solid #CCCCCC; -} -TR.memlist { - background-color: #f0f0f0; -} -P.formulaDsp { text-align: center; } -IMG.formulaDsp { } -IMG.formulaInl { vertical-align: middle; } -SPAN.keyword { color: #008000 } -SPAN.keywordtype { color: #604020 } -SPAN.keywordflow { color: #e08000 } -SPAN.comment { color: #800000 } -SPAN.preprocessor { color: #806020 } -SPAN.stringliteral { color: #002080 } -SPAN.charliteral { color: #008080 } -.mdescLeft { - padding: 0px 8px 4px 8px; - font-size: 80%; - font-style: italic; - background-color: #FAFAFA; - border-top: 1px none #E0E0E0; - border-right: 1px none #E0E0E0; - border-bottom: 1px none #E0E0E0; - border-left: 1px none #E0E0E0; - margin: 0px; -} -.mdescRight { - padding: 0px 8px 4px 8px; - font-size: 80%; - font-style: italic; - background-color: #FAFAFA; - border-top: 1px none #E0E0E0; - border-right: 1px none #E0E0E0; - border-bottom: 1px none #E0E0E0; - border-left: 1px none #E0E0E0; - margin: 0px; -} -.memItemLeft { - padding: 1px 0px 0px 8px; - margin: 4px; - border-top-width: 1px; - border-right-width: 1px; - border-bottom-width: 1px; - border-left-width: 1px; - border-top-color: #E0E0E0; - border-right-color: #E0E0E0; - border-bottom-color: #E0E0E0; - border-left-color: #E0E0E0; - border-top-style: solid; - border-right-style: none; - border-bottom-style: none; - border-left-style: none; - background-color: #FAFAFA; - font-size: 80%; -} -.memItemRight { - padding: 1px 8px 0px 8px; - margin: 4px; - border-top-width: 1px; - border-right-width: 1px; - border-bottom-width: 1px; - border-left-width: 1px; - border-top-color: #E0E0E0; - border-right-color: #E0E0E0; - border-bottom-color: #E0E0E0; - border-left-color: #E0E0E0; - border-top-style: solid; - border-right-style: none; - border-bottom-style: none; - border-left-style: none; - background-color: #FAFAFA; - font-size: 80%; -} -.memTemplItemLeft { - padding: 1px 0px 0px 8px; - margin: 4px; - border-top-width: 1px; - border-right-width: 1px; - border-bottom-width: 1px; - border-left-width: 1px; - border-top-color: #E0E0E0; - border-right-color: #E0E0E0; - border-bottom-color: #E0E0E0; - border-left-color: #E0E0E0; - border-top-style: none; - border-right-style: none; - border-bottom-style: none; - border-left-style: none; - background-color: #FAFAFA; - font-size: 80%; -} -.memTemplItemRight { - padding: 1px 8px 0px 8px; - margin: 4px; - border-top-width: 1px; - border-right-width: 1px; - border-bottom-width: 1px; - border-left-width: 1px; - border-top-color: #E0E0E0; - border-right-color: #E0E0E0; - border-bottom-color: #E0E0E0; - border-left-color: #E0E0E0; - border-top-style: none; - border-right-style: none; - border-bottom-style: none; - border-left-style: none; - background-color: #FAFAFA; - font-size: 80%; -} -.memTemplParams { - padding: 1px 0px 0px 8px; - margin: 4px; - border-top-width: 1px; - border-right-width: 1px; - border-bottom-width: 1px; - border-left-width: 1px; - border-top-color: #E0E0E0; - border-right-color: #E0E0E0; - border-bottom-color: #E0E0E0; - border-left-color: #E0E0E0; - border-top-style: solid; - border-right-style: none; - border-bottom-style: none; - border-left-style: none; - color: #606060; - background-color: #FAFAFA; - font-size: 80%; -} -.search { color: #003399; - font-weight: bold; -} -FORM.search { - margin-bottom: 0px; - margin-top: 0px; -} -INPUT.search { font-size: 75%; - color: #000080; - font-weight: normal; - background-color: #e8eef2; -} -TD.tiny { font-size: 75%; -} -a { - color: #1A41A8; -} -a:visited { - color: #2A3798; -} -.dirtab { padding: 4px; - border-collapse: collapse; - border: 1px solid #84b0c7; -} -TH.dirtab { background: #e8eef2; - font-weight: bold; -} -HR { height: 1px; - border: none; - border-top: 1px solid black; -} - -/* Style for detailed member documentation */ -.memtemplate { - font-size: 80%; - color: #606060; - font-weight: normal; -} -.memnav { - background-color: #e8eef2; - border: 1px solid #84b0c7; - text-align: center; - margin: 2px; - margin-right: 15px; - padding: 2px; -} -.memitem { - padding: 4px; - background-color: #eef3f5; - border-width: 1px; - border-style: solid; - border-color: #dedeee; - -moz-border-radius: 8px 8px 8px 8px; -} -.memname { - white-space: nowrap; - font-weight: bold; -} -.memdoc{ - padding-left: 10px; -} -.memproto { - background-color: #d5e1e8; - width: 100%; - border-width: 1px; - border-style: solid; - border-color: #84b0c7; - font-weight: bold; - -moz-border-radius: 8px 8px 8px 8px; -} -.paramkey { - text-align: right; -} -.paramtype { - white-space: nowrap; -} -.paramname { - color: #602020; - font-style: italic; -} -/* End Styling for detailed member documentation */ - -/* for the tree view */ -.ftvtree { - font-family: sans-serif; - margin:0.5em; -} -.directory { font-size: 9pt; font-weight: bold; } -.directory h3 { margin: 0px; margin-top: 1em; font-size: 11pt; } -.directory > h3 { margin-top: 0; } -.directory p { margin: 0px; white-space: nowrap; } -.directory div { display: none; margin: 0px; } -.directory img { vertical-align: -30%; } - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/doxygen.png b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/doxygen.png deleted file mode 100644 index f0a274bba..000000000 Binary files a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/doxygen.png and /dev/null differ diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/energyCalibration_8h-source.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/energyCalibration_8h-source.html deleted file mode 100644 index 64e8c0558..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/energyCalibration_8h-source.html +++ /dev/null @@ -1,164 +0,0 @@ - - -energyCalibration.h Source File - - - - - - -

energyCalibration.h

Go to the documentation of this file.
00001 
-00002 #ifndef ENERGYCALIBRATION_H
-00003 #define ENERGYCALIBRATION_H
-00004 
-00005 #include <TROOT.h>
-00006 #include <TF1.h>
-00007 
-00008 using namespace std;
-00009 
-00010 class TH1F;
-00011 class TGraphErrors;
-00012 
-00013 
-00014 
-00015 
-00016 
-00017 const float conven=1000./3.6; 
-00018 const float el=1.67E-4; 
-00050 class energyCalibrationFunctions {
-00051 
-00052  public:
-00053   
-00054   energyCalibrationFunctions(int s=-1) {setScanSign(s);};
-00055   
-00060   int setScanSign(int s=0) {if (s==1 || s==-1) sign=s; return sign;};;
-00061   
-00062 
-00072   Double_t gaussChargeSharing(Double_t *x, Double_t *par);
-00073 
-00080 Double_t erfFunction(Double_t *x, Double_t *par) ;
-00081 
-00090 Double_t erfFunctionChargeSharing(Double_t *x, Double_t *par);
-00091   
-00105 Double_t erfFuncFluo(Double_t *x, Double_t *par);
-00106 
-00107 
-00109   static float median(float *x, int n);
-00111   static int quick_select(int arr[], int n);
-00113   static int kth_smallest(int *a, int n, int k);
-00114 
-00115   
-00124   Double_t spectrum(Double_t *x, Double_t *par);
-00125 
-00126 
-00135   Double_t scurve(Double_t *x, Double_t *par);
-00136 
-00137 
-00138 
-00151   Double_t scurveFluo(Double_t *x, Double_t *par);
-00152 
-00153 
-00154  private:
-00155   int sign;
-00156     
-00157 
-00158 };
-00159 
-00165 class energyCalibration  {
-00166 
-00167 
-00168  public:
-00172   energyCalibration();
-00173     
-00177   ~energyCalibration();
-00178     
-00183   int setPlotFlag(int p=-1) {if (p>=0) plot_flag=p; return plot_flag;};
-00184 
-00189   int setScanSign(int s=0) {return funcs->setScanSign(s);};
-00190   
-00195   int setChargeSharing(int p=-1);
-00196   
-00201   void setFitRange(Double_t mi, Double_t ma){fit_min=mi; fit_max=ma;};
-00202 
-00207   void getFitRange(Double_t &mi, Double_t &ma){mi=fit_min; ma=fit_max;};
-00208 
-00209 
-00219   void setStartParameters(Double_t *par);
-00220   
-00230   void getStartParameters(Double_t *par);
-00231 
-00239   TF1 *fitSCurve(TH1 *h1, Double_t *mypar, Double_t *emypar);
-00240 
-00241 
-00249   TF1 *fitSpectrum(TH1 *h1, Double_t *mypar, Double_t *emypar);
-00250 
-00251 
-00265   TGraphErrors* linearCalibration(int nscan, Double_t *en, Double_t *een, Double_t *fl, Double_t *efl, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff);  
-00266 
-00279   TGraphErrors* calibrateScurves(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff){return calibrate(nscan, en, een, h1, gain, off, egain, eoff, 1);};    
-00280 
-00293   TGraphErrors* calibrateSpectra(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff){return calibrate(nscan, en, een, h1, gain, off, egain, eoff, 0);};  
-00294 
-00295 
-00296 
-00297  private:
-00309   TGraphErrors* calibrate(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff, int integral=1);  
-00310 
-00311 
-00319   void initFitFunction(TF1 *fun, TH1 *h1);
-00320 
-00321 
-00330   TF1 *fitFunction(TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar);  
-00331 
-00332 
-00333   int plot_flag; 
-00335   int cs_flag; 
-00337   Double_t fit_min; 
-00338   Double_t fit_max; 
-00340   Double_t bg_offset; 
-00341   Double_t bg_slope; 
-00342   Double_t flex; 
-00343   Double_t noise; 
-00344   Double_t ampl; 
-00345   Double_t cs_slope; 
-00347   energyCalibrationFunctions *funcs;
-00348 
-00349   TF1 *fscurve; 
-00351   TF1 *fspectrum; 
-00354 };
-00355 
-00356 #endif
-00357 
-00358 
-00359 
-00360 
-00361 
-00362 
-00363 
-00364 
-00365 
-00366 
-00367 
-00368 
-00369 
-00370 
-00371 
-00372 
-00373 
-00374 
-00375 
-

Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/energyCalibration_8h.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/energyCalibration_8h.html deleted file mode 100644 index a25ed2496..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/energyCalibration_8h.html +++ /dev/null @@ -1,76 +0,0 @@ - - -energyCalibration.h File Reference - - - - - - -

energyCalibration.h File Reference

#include <TROOT.h>
-#include <TF1.h>
- -

-Go to the source code of this file. - - - - - - - - - - - - - - - -

Namespaces

namespace  std

Classes

class  energyCalibrationFunctions
 Energy calibration functions. More...
class  energyCalibration

Variables

const float conven = 1000./3.6
const float el = 1.67E-4
-


Variable Documentation

- -
-
- - - - -
const float conven = 1000./3.6
-
-
- -

-electrons/keV -

-

- -

-
- - - - -
const float el = 1.67E-4
-
-
- -

-electron charge in fC -

-

-


Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/energyCalibration_8h_source.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/energyCalibration_8h_source.html deleted file mode 100644 index fc14ca380..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/energyCalibration_8h_source.html +++ /dev/null @@ -1,190 +0,0 @@ - - - - - -energyCalibration.h Source File - - - - - - - - - - - - - -
- -
- -
Generated on Tue Mar 20 17:21:14 2012 by  - -doxygen 1.6.0
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/files.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/files.html deleted file mode 100644 index a0ea14100..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/files.html +++ /dev/null @@ -1,27 +0,0 @@ - - -File Index - - - - - - -

File List

Here is a list of all files with brief descriptions: - -
energyCalibration.h [code]
-
Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/functions.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/functions.html deleted file mode 100644 index 2dc86e2c0..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/functions.html +++ /dev/null @@ -1,126 +0,0 @@ - - -Class Members - - - - - - -
- -
-
- -
- -

-Here is a list of all class members with links to the classes they belong to: -

-

- a -

-

- b -

-

- c -

-

- e -

-

- f -

-

- g -

-

- i -

-

- k -

-

- l -

-

- m -

-

- n -

-

- p -

-

- q -

-

- s -

-

- ~ -

-
Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/functions_func.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/functions_func.html deleted file mode 100644 index a82a14a3a..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/functions_func.html +++ /dev/null @@ -1,63 +0,0 @@ - - -Class Members - Functions - - - - - - -
- -
-  -

-

-
Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/functions_vars.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/functions_vars.html deleted file mode 100644 index 3eb5ab2c3..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/functions_vars.html +++ /dev/null @@ -1,49 +0,0 @@ - - -Class Members - Variables - - - - - - -
- -
-  -

-

-
Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/globals.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/globals.html deleted file mode 100644 index 6867e7583..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/globals.html +++ /dev/null @@ -1,36 +0,0 @@ - - -Class Members - - - - - - -
- -
-Here is a list of all file members with links to the files they belong to: -

-

-
Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/globals_vars.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/globals_vars.html deleted file mode 100644 index efb3d3424..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/globals_vars.html +++ /dev/null @@ -1,36 +0,0 @@ - - -Class Members - - - - - - -
- -
-  -

-

-
Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/index.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/index.html deleted file mode 100644 index 8e6122ad2..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/index.html +++ /dev/null @@ -1,25 +0,0 @@ - - -Common Root library for SLS detectors data analysis - - - - - -

Common Root library for SLS detectors data analysis

-

-

-Introduction

-We know very well s-curves etc. but at the end everybody uses different functions ;-).

-Motivation

-It would be greate to use everybody the same functions...
Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/installdox b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/installdox deleted file mode 100755 index 9b89fe025..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/installdox +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/perl - -%subst = ( ); -$quiet = 0; - -if (open(F,"search.cfg")) -{ - $_= ; s/[ \t\n]*$//g ; $subst{"_doc"} = $_; - $_= ; s/[ \t\n]*$//g ; $subst{"_cgi"} = $_; -} - -while ( @ARGV ) { - $_ = shift @ARGV; - if ( s/^-// ) { - if ( /^l(.*)/ ) { - $v = ($1 eq "") ? shift @ARGV : $1; - ($v =~ /\/$/) || ($v .= "/"); - $_ = $v; - if ( /(.+)\@(.+)/ ) { - if ( exists $subst{$1} ) { - $subst{$1} = $2; - } else { - print STDERR "Unknown tag file $1 given with option -l\n"; - &usage(); - } - } else { - print STDERR "Argument $_ is invalid for option -l\n"; - &usage(); - } - } - elsif ( /^q/ ) { - $quiet = 1; - } - elsif ( /^\?|^h/ ) { - &usage(); - } - else { - print STDERR "Illegal option -$_\n"; - &usage(); - } - } - else { - push (@files, $_ ); - } -} - -foreach $sub (keys %subst) -{ - if ( $subst{$sub} eq "" ) - { - print STDERR "No substitute given for tag file `$sub'\n"; - &usage(); - } - elsif ( ! $quiet && $sub ne "_doc" && $sub ne "_cgi" ) - { - print "Substituting $subst{$sub} for each occurence of tag file $sub\n"; - } -} - -if ( ! @files ) { - if (opendir(D,".")) { - foreach $file ( readdir(D) ) { - $match = ".html"; - next if ( $file =~ /^\.\.?$/ ); - ($file =~ /$match/) && (push @files, $file); - ($file =~ "tree.js") && (push @files, $file); - } - closedir(D); - } -} - -if ( ! @files ) { - print STDERR "Warning: No input files given and none found!\n"; -} - -foreach $f (@files) -{ - if ( ! $quiet ) { - print "Editing: $f...\n"; - } - $oldf = $f; - $f .= ".bak"; - unless (rename $oldf,$f) { - print STDERR "Error: cannot rename file $oldf\n"; - exit 1; - } - if (open(F,"<$f")) { - unless (open(G,">$oldf")) { - print STDERR "Error: opening file $oldf for writing\n"; - exit 1; - } - if ($oldf ne "tree.js") { - while () { - s/doxygen\=\"([^ \"\:\t\>\<]*)\:([^ \"\t\>\<]*)\" (href|src)=\"\2/doxygen\=\"$1:$subst{$1}\" \3=\"$subst{$1}/g; - print G "$_"; - } - } - else { - while () { - s/\"([^ \"\:\t\>\<]*)\:([^ \"\t\>\<]*)\", \"\2/\"$1:$subst{$1}\" ,\"$subst{$1}/g; - print G "$_"; - } - } - } - else { - print STDERR "Warning file $f does not exist\n"; - } - unlink $f; -} - -sub usage { - print STDERR "Usage: installdox [options] [html-file [html-file ...]]\n"; - print STDERR "Options:\n"; - print STDERR " -l tagfile\@linkName tag file + URL or directory \n"; - print STDERR " -q Quiet mode\n\n"; - exit 1; -} diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/namespaces.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/namespaces.html deleted file mode 100644 index f3343cb4d..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/namespaces.html +++ /dev/null @@ -1,22 +0,0 @@ - - -Namespace Index - - - - - -

Namespace List

Here is a list of all namespaces with brief descriptions: - -
std
-
Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/namespacestd.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/namespacestd.html deleted file mode 100644 index 7f96b5d3c..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/namespacestd.html +++ /dev/null @@ -1,24 +0,0 @@ - - -std Namespace Reference - - - - - -

std Namespace Reference

-

- - -
-


Generated on Tue Mar 27 16:32:29 2012 by  - -doxygen 1.4.7
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_61.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_61.html deleted file mode 100644 index dbc525140..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_61.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- ampl - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_62.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_62.html deleted file mode 100644 index 1587baf85..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_62.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - -
-
Loading...
-
-
- bg_offset - energyCalibration -
-
-
-
- bg_slope - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_63.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_63.html deleted file mode 100644 index 9f05baa3d..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_63.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - -
-
Loading...
-
-
- calibrate - energyCalibration -
-
-
-
- conven - energyCalibration.h -
-
-
-
- cs_slope - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_65.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_65.html deleted file mode 100644 index d8cc513ff..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_65.html +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - -
-
Loading...
-
-
- el - energyCalibration.h -
-
- - - -
-
- erfFuncFluo - energyCalibrationFunctions -
-
-
-
- erfFunction - energyCalibrationFunctions -
-
-
-
- erfFunctionChargeSharing - energyCalibrationFunctions -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_66.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_66.html deleted file mode 100644 index bd1572f3b..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_66.html +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - -
-
Loading...
-
-
- fit_max - energyCalibration -
-
-
-
- fit_min - energyCalibration -
-
-
-
- fitSCurve - energyCalibration -
-
-
-
- flex - energyCalibration -
-
-
-
- fscurve - energyCalibration -
-
-
-
- funcs - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_67.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_67.html deleted file mode 100644 index a5fbc8718..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_67.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - -
-
Loading...
-
-
- gaussChargeSharing - energyCalibrationFunctions -
-
-
-
- getFitRange - energyCalibration -
-
-
-
- getStartParameters - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_6b.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_6b.html deleted file mode 100644 index 40cf25174..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_6b.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- kth_smallest - energyCalibrationFunctions -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_6c.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_6c.html deleted file mode 100644 index 6ddf1903c..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_6c.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- linearCalibration - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_6d.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_6d.html deleted file mode 100644 index d7612fe26..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_6d.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- median - energyCalibrationFunctions -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_6e.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_6e.html deleted file mode 100644 index 7ee4200c2..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_6e.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- noise - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_70.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_70.html deleted file mode 100644 index 402fa63cb..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_70.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- plot_flag - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_71.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_71.html deleted file mode 100644 index 0c68aa1c7..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_71.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- quick_select - energyCalibrationFunctions -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_73.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_73.html deleted file mode 100644 index 52cede178..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_73.html +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - -
-
Loading...
-
-
- scurve - energyCalibrationFunctions -
-
-
-
- scurveFluo - energyCalibrationFunctions -
-
-
-
- setFitRange - energyCalibration -
-
-
-
- setPlotFlag - energyCalibration -
-
- -
-
- setStartParameters - energyCalibration -
-
-
-
- sign - energyCalibrationFunctions -
-
-
-
- spectrum - energyCalibrationFunctions -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_7e.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_7e.html deleted file mode 100644 index 22b73eeab..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/all_7e.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- ~energyCalibration - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/classes_65.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/classes_65.html deleted file mode 100644 index 0cd426302..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/classes_65.html +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - -
-
Loading...
- - -
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/close.png b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/close.png deleted file mode 100644 index 9342d3dfe..000000000 Binary files a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/close.png and /dev/null differ diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/files_65.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/files_65.html deleted file mode 100644 index 72afed66a..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/files_65.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - -
-
Loading...
- -
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_63.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_63.html deleted file mode 100644 index dbde61421..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_63.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- calibrate - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_65.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_65.html deleted file mode 100644 index 4aac8500d..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_65.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - -
-
Loading...
-
-
- energyCalibration - energyCalibration -
-
-
-
- energyCalibrationFunctions - energyCalibrationFunctions -
-
-
-
- erfFuncFluo - energyCalibrationFunctions -
-
-
-
- erfFunction - energyCalibrationFunctions -
-
-
-
- erfFunctionChargeSharing - energyCalibrationFunctions -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_66.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_66.html deleted file mode 100644 index e1b9f157c..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_66.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- fitSCurve - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_67.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_67.html deleted file mode 100644 index a5fbc8718..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_67.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - -
-
Loading...
-
-
- gaussChargeSharing - energyCalibrationFunctions -
-
-
-
- getFitRange - energyCalibration -
-
-
-
- getStartParameters - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_6b.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_6b.html deleted file mode 100644 index 40cf25174..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_6b.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- kth_smallest - energyCalibrationFunctions -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_6c.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_6c.html deleted file mode 100644 index 6ddf1903c..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_6c.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- linearCalibration - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_6d.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_6d.html deleted file mode 100644 index d7612fe26..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_6d.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- median - energyCalibrationFunctions -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_71.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_71.html deleted file mode 100644 index 0c68aa1c7..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_71.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- quick_select - energyCalibrationFunctions -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_73.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_73.html deleted file mode 100644 index 4daf9bb0f..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_73.html +++ /dev/null @@ -1,64 +0,0 @@ - - - - - - -
-
Loading...
-
-
- scurve - energyCalibrationFunctions -
-
-
-
- scurveFluo - energyCalibrationFunctions -
-
-
-
- setFitRange - energyCalibration -
-
-
-
- setPlotFlag - energyCalibration -
-
- -
-
- setStartParameters - energyCalibration -
-
-
-
- spectrum - energyCalibrationFunctions -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_7e.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_7e.html deleted file mode 100644 index 22b73eeab..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/functions_7e.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- ~energyCalibration - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/nomatches.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/nomatches.html deleted file mode 100644 index fd9248fe3..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/nomatches.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - -
-
No Matches
-
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/search.css b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/search.css deleted file mode 100644 index d263b9724..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/search.css +++ /dev/null @@ -1,198 +0,0 @@ -/*---------------- Search Box */ - -#MSearchBox { - padding: 0px; - margin: 0px; - border: none; - border: 1px solid #84B0C7; - white-space: nowrap; - -moz-border-radius: 8px; - -webkit-border-top-left-radius: 8px; - -webkit-border-top-right-radius: 8px; - -webkit-border-bottom-left-radius: 8px; - -webkit-border-bottom-right-radius: 8px; -} -#MSearchField { - font: 9pt Arial, Verdana, sans-serif; - color: #999999; - background-color: #FFFFFF; - font-style: normal; - cursor: text; - padding: 1px 1px; - margin: 0px 6px 0px 0px; - border: none; - outline: none; - vertical-align: middle; -} -.MSearchBoxActive #MSearchField { - color: #000000; -} -#MSearchSelect { - float : none; - display : inline; - background : none; - font: 9pt Verdana, sans-serif; - border: none; - margin: 0px 0px 0px 6px; - vertical-align: middle; - padding: 0px 0px; -} - -#MSearchClose { - float : none; - display : none; - background : none; - border: none; - margin: 0px 4px 0px 0px; - padding: 0px 0px; - outline: none; -} - -#MSearchCloseImg { - vertical-align: middle; -} - -.MSearchBoxLeft { - display: block; - text-align: left; - float: left; - margin-left: 6px; -} -.MSearchBoxRight { - display: block; - float: right; - text-align: right; - margin-right: 6px; -} -.MSearchBoxSpacer { - font-size: 0px; - clear: both; -} -.MSearchBoxRow { - font-size: 0px; - clear: both; -} - -/*---------------- Search filter selection */ - -#MSearchSelectWindow { - display: none; - position: absolute; - left: 0; top: 0; - border: 1px solid #A0A0A0; - background-color: #FAFAFA; - z-index: 1; - padding-top: 4px; - padding-bottom: 4px; - -moz-border-radius: 4px; - -webkit-border-top-left-radius: 4px; - -webkit-border-top-right-radius: 4px; - -webkit-border-bottom-left-radius: 4px; - -webkit-border-bottom-right-radius: 4px; - -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15); - } -.SelectItem { - font: 8pt Arial, Verdana, sans-serif; - padding-left: 2px; - padding-right: 12px; - border: 0px; -} -span.SelectionMark { - margin-right: 4px; - font-family: monospace; - outline-style: none; - text-decoration: none; -} -a.SelectItem { - display: block; - outline-style: none; - color: #000000; - text-decoration: none; - padding-left: 6px; - padding-right: 12px; -} -a.SelectItem:focus, -a.SelectItem:active { - color: #000000; - outline-style: none; - text-decoration: none; -} -a.SelectItem:hover { - color: #FFFFFF; - background-color: #2A50E4; - outline-style: none; - text-decoration: none; - cursor: pointer; - display: block; -} - -/*---------------- Search results window */ - -iframe#MSearchResults { - width: 60ex; - height: 15em; - } -#MSearchResultsWindow { - display: none; - position: absolute; - left: 0; top: 0; - border: 1px solid #000000; - background-color: #EEF3F5; - } - -/* ----------------------------------- */ - - -#SRIndex { - clear:both; - padding-bottom: 15px; -} - -.SREntry { - font-size: 10pt; - padding-left: 1ex; -} -.SRPage .SREntry { - font-size: 8pt; - padding: 1px 5px; -} -body.SRPage { - margin: 5px 2px; -} - -.SRChildren { - padding-left: 3ex; padding-bottom: .5em -} -.SRPage .SRChildren { - display: none; -} -.SRSymbol { - font-weight: bold; color: #153788; - font-family: Arial, Verdana, sans-serif; - text-decoration: none; - outline: none; -} - -a.SRScope { - display: block; - color: #153788; - font-family: Arial, Verdana, sans-serif; - text-decoration: none; - outline: none; -} - -a.SRSymbol:focus, a.SRSymbol:active, -a.SRScope:focus, a.SRScope:active { - text-decoration: underline; -} - -.SRPage .SRStatus { - padding: 2px 5px; - font-size: 8pt; - font-style: italic; -} - -.SRResult { - display: none; -} - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/search.js b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/search.js deleted file mode 100644 index 4fadd5247..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/search.js +++ /dev/null @@ -1,734 +0,0 @@ -// Search script generated by doxygen -// Copyright (C) 2009 by Dimitri van Heesch. - -// The code in this file is loosly based on main.js, part of Natural Docs, -// which is Copyright (C) 2003-2008 Greg Valure -// Natural Docs is licensed under the GPL. - -var indexSectionsWithContent = -{ - 0: "000000000000000000000000000000000000000000000000000000000000000001110111000111101101000000000010", - 1: "000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000", - 2: "000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000", - 3: "000000000000000000000000000000000000000000000000000000000000000000010111000111000101000000000010", - 4: "000000000000000000000000000000000000000000000000000000000000000001110110000000101001000000000000" -}; - -var indexSectionNames = -{ - 0: "all", - 1: "classes", - 2: "files", - 3: "functions", - 4: "variables" -}; - -function convertToId(search) -{ - var result = ''; - for (i=0;i do a search - { - this.Search(); - } - } - - this.OnSearchSelectKey = function(evt) - { - var e = (evt) ? evt : window.event; // for IE - if (e.keyCode==40 && this.searchIndex0) // Up - { - this.searchIndex--; - this.OnSelectItem(this.searchIndex); - } - else if (e.keyCode==13 || e.keyCode==27) - { - this.OnSelectItem(this.searchIndex); - this.CloseSelectionWindow(); - this.DOMSearchField().focus(); - } - return false; - } - - // --------- Actions - - // Closes the results window. - this.CloseResultsWindow = function() - { - this.DOMPopupSearchResultsWindow().style.display = 'none'; - this.DOMSearchClose().style.display = 'none'; - this.Activate(false); - } - - this.CloseSelectionWindow = function() - { - this.DOMSearchSelectWindow().style.display = 'none'; - } - - // Performs a search. - this.Search = function() - { - this.keyTimeout = 0; - - // strip leading whitespace - var searchValue = this.DOMSearchField().value.replace(/^ +/, ""); - - var code = searchValue.toLowerCase().charCodeAt(0); - var hexCode; - if (code<16) - { - hexCode="0"+code.toString(16); - } - else - { - hexCode=code.toString(16); - } - - var resultsPage; - var resultsPageWithSearch; - var hasResultsPage; - - if (indexSectionsWithContent[this.searchIndex].charAt(code-32) == '1') - { - resultsPage = this.resultsPath + '/' + indexSectionNames[this.searchIndex] + '_' + hexCode + '.html'; - resultsPageWithSearch = resultsPage+'?'+escape(searchValue); - hasResultsPage = true; - } - else // nothing available for this search term - { - resultsPage = this.resultsPath + '/nomatches.html'; - resultsPageWithSearch = resultsPage; - hasResultsPage = false; - } - - window.frames.MSearchResults.location.href = resultsPageWithSearch; - var domPopupSearchResultsWindow = this.DOMPopupSearchResultsWindow(); - - if (domPopupSearchResultsWindow.style.display!='block') - { - var domSearchBox = this.DOMSearchBox(); - this.DOMSearchClose().style.display = 'inline'; - if (this.insideFrame) - { - var domPopupSearchResults = this.DOMPopupSearchResults(); - domPopupSearchResultsWindow.style.position = 'relative'; - domPopupSearchResultsWindow.style.display = 'block'; - var width = document.body.clientWidth - 8; // the -8 is for IE :-( - domPopupSearchResultsWindow.style.width = width + 'px'; - domPopupSearchResults.style.width = width + 'px'; - } - else - { - var domPopupSearchResults = this.DOMPopupSearchResults(); - var left = getXPos(domSearchBox) + domSearchBox.offsetWidth; - var top = getYPos(domSearchBox) + domSearchBox.offsetHeight + 1; - domPopupSearchResultsWindow.style.display = 'block'; - left -= domPopupSearchResults.offsetWidth; - domPopupSearchResultsWindow.style.top = top + 'px'; - domPopupSearchResultsWindow.style.left = left + 'px'; - } - } - - this.lastSearchValue = searchValue; - this.lastResultsPage = resultsPage; - } - - // -------- Activation Functions - - // Activates or deactivates the search panel, resetting things to - // their default values if necessary. - this.Activate = function(isActive) - { - if (isActive || // open it - this.DOMPopupSearchResultsWindow().style.display == 'block' - ) - { - this.DOMSearchBox().className = 'MSearchBoxActive'; - - var searchField = this.DOMSearchField(); - - if (searchField.value == this.searchLabel) // clear "Search" term upon entry - { - searchField.value = ''; - this.searchActive = true; - } - } - else if (!isActive) // directly remove the panel - { - this.DOMSearchBox().className = 'MSearchBoxInactive'; - this.DOMSearchField().value = this.searchLabel; - this.searchActive = false; - this.lastSearchValue = '' - this.lastResultsPage = ''; - } - } -} - -// ----------------------------------------------------------------------- - -// The class that handles everything on the search results page. -function SearchResults(name) -{ - // The number of matches from the last run of . - this.lastMatchCount = 0; - this.lastKey = 0; - this.repeatOn = false; - - // Toggles the visibility of the passed element ID. - this.FindChildElement = function(id) - { - var parentElement = document.getElementById(id); - var element = parentElement.firstChild; - - while (element && element!=parentElement) - { - if (element.nodeName == 'DIV' && element.className == 'SRChildren') - { - return element; - } - - if (element.nodeName == 'DIV' && element.hasChildNodes()) - { - element = element.firstChild; - } - else if (element.nextSibling) - { - element = element.nextSibling; - } - else - { - do - { - element = element.parentNode; - } - while (element && element!=parentElement && !element.nextSibling); - - if (element && element!=parentElement) - { - element = element.nextSibling; - } - } - } - } - - this.Toggle = function(id) - { - var element = this.FindChildElement(id); - if (element) - { - if (element.style.display == 'block') - { - element.style.display = 'none'; - } - else - { - element.style.display = 'block'; - } - } - } - - // Searches for the passed string. If there is no parameter, - // it takes it from the URL query. - // - // Always returns true, since other documents may try to call it - // and that may or may not be possible. - this.Search = function(search) - { - if (!search) // get search word from URL - { - search = window.location.search; - search = search.substring(1); // Remove the leading '?' - search = unescape(search); - } - - search = search.replace(/^ +/, ""); // strip leading spaces - search = search.replace(/ +$/, ""); // strip trailing spaces - search = search.toLowerCase(); - search = convertToId(search); - - var resultRows = document.getElementsByTagName("div"); - var matches = 0; - - var i = 0; - while (i < resultRows.length) - { - var row = resultRows.item(i); - if (row.className == "SRResult") - { - var rowMatchName = row.id.toLowerCase(); - rowMatchName = rowMatchName.replace(/^sr\d*_/, ''); // strip 'sr123_' - - if (search.length<=rowMatchName.length && - rowMatchName.substr(0, search.length)==search) - { - row.style.display = 'block'; - matches++; - } - else - { - row.style.display = 'none'; - } - } - i++; - } - document.getElementById("Searching").style.display='none'; - if (matches == 0) // no results - { - document.getElementById("NoMatches").style.display='block'; - } - else // at least one result - { - document.getElementById("NoMatches").style.display='none'; - } - this.lastMatchCount = matches; - return true; - } - - // return the first item with index index or higher that is visible - this.NavNext = function(index) - { - var focusItem; - while (1) - { - var focusName = 'Item'+index; - focusItem = document.getElementById(focusName); - if (focusItem && focusItem.parentNode.parentNode.style.display=='block') - { - break; - } - else if (!focusItem) // last element - { - break; - } - focusItem=null; - index++; - } - return focusItem; - } - - this.NavPrev = function(index) - { - var focusItem; - while (1) - { - var focusName = 'Item'+index; - focusItem = document.getElementById(focusName); - if (focusItem && focusItem.parentNode.parentNode.style.display=='block') - { - break; - } - else if (!focusItem) // last element - { - break; - } - focusItem=null; - index--; - } - return focusItem; - } - - this.ProcessKeys = function(e) - { - if (e.type == "keydown") - { - this.repeatOn = false; - this.lastKey = e.keyCode; - } - else if (e.type == "keypress") - { - if (!this.repeatOn) - { - if (this.lastKey) this.repeatOn = true; - return false; // ignore first keypress after keydown - } - } - else if (e.type == "keyup") - { - this.lastKey = 0; - this.repeatOn = false; - } - return this.lastKey!=0; - } - - this.Nav = function(evt,itemIndex) - { - var e = (evt) ? evt : window.event; // for IE - if (e.keyCode==13) return true; - if (!this.ProcessKeys(e)) return false; - - if (this.lastKey==38) // Up - { - var newIndex = itemIndex-1; - var focusItem = this.NavPrev(newIndex); - if (focusItem) - { - var child = this.FindChildElement(focusItem.parentNode.parentNode.id); - if (child && child.style.display == 'block') // children visible - { - var n=0; - var tmpElem; - while (1) // search for last child - { - tmpElem = document.getElementById('Item'+newIndex+'_c'+n); - if (tmpElem) - { - focusItem = tmpElem; - } - else // found it! - { - break; - } - n++; - } - } - } - if (focusItem) - { - focusItem.focus(); - } - else // return focus to search field - { - parent.document.getElementById("MSearchField").focus(); - } - } - else if (this.lastKey==40) // Down - { - var newIndex = itemIndex+1; - var focusItem; - var item = document.getElementById('Item'+itemIndex); - var elem = this.FindChildElement(item.parentNode.parentNode.id); - if (elem && elem.style.display == 'block') // children visible - { - focusItem = document.getElementById('Item'+itemIndex+'_c0'); - } - if (!focusItem) focusItem = this.NavNext(newIndex); - if (focusItem) focusItem.focus(); - } - else if (this.lastKey==39) // Right - { - var item = document.getElementById('Item'+itemIndex); - var elem = this.FindChildElement(item.parentNode.parentNode.id); - if (elem) elem.style.display = 'block'; - } - else if (this.lastKey==37) // Left - { - var item = document.getElementById('Item'+itemIndex); - var elem = this.FindChildElement(item.parentNode.parentNode.id); - if (elem) elem.style.display = 'none'; - } - else if (this.lastKey==27) // Escape - { - parent.searchBox.CloseResultsWindow(); - parent.document.getElementById("MSearchField").focus(); - } - else if (this.lastKey==13) // Enter - { - return true; - } - return false; - } - - this.NavChild = function(evt,itemIndex,childIndex) - { - var e = (evt) ? evt : window.event; // for IE - if (e.keyCode==13) return true; - if (!this.ProcessKeys(e)) return false; - - if (this.lastKey==38) // Up - { - if (childIndex>0) - { - var newIndex = childIndex-1; - document.getElementById('Item'+itemIndex+'_c'+newIndex).focus(); - } - else // already at first child, jump to parent - { - document.getElementById('Item'+itemIndex).focus(); - } - } - else if (this.lastKey==40) // Down - { - var newIndex = childIndex+1; - var elem = document.getElementById('Item'+itemIndex+'_c'+newIndex); - if (!elem) // last child, jump to parent next parent - { - elem = this.NavNext(itemIndex+1); - } - if (elem) - { - elem.focus(); - } - } - else if (this.lastKey==27) // Escape - { - parent.searchBox.CloseResultsWindow(); - parent.document.getElementById("MSearchField").focus(); - } - else if (this.lastKey==13) // Enter - { - return true; - } - return false; - } -} diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/search.png b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/search.png deleted file mode 100644 index 9dd2396db..000000000 Binary files a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/search.png and /dev/null differ diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_61.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_61.html deleted file mode 100644 index dbc525140..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_61.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- ampl - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_62.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_62.html deleted file mode 100644 index 1587baf85..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_62.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - -
-
Loading...
-
-
- bg_offset - energyCalibration -
-
-
-
- bg_slope - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_63.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_63.html deleted file mode 100644 index 6a2de4531..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_63.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - -
-
Loading...
-
-
- conven - energyCalibration.h -
-
-
-
- cs_slope - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_65.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_65.html deleted file mode 100644 index b199804b0..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_65.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- el - energyCalibration.h -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_66.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_66.html deleted file mode 100644 index d0ae5492f..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_66.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - -
-
Loading...
-
-
- fit_max - energyCalibration -
-
-
-
- fit_min - energyCalibration -
-
-
-
- flex - energyCalibration -
-
-
-
- fscurve - energyCalibration -
-
-
-
- funcs - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_6e.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_6e.html deleted file mode 100644 index 7ee4200c2..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_6e.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- noise - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_70.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_70.html deleted file mode 100644 index 402fa63cb..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_70.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- plot_flag - energyCalibration -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_73.html b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_73.html deleted file mode 100644 index 786cf3968..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/search/variables_73.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - -
-
Loading...
-
-
- sign - energyCalibrationFunctions -
-
-
Searching...
-
No Matches
- -
- - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/tab_b.gif b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/tab_b.gif deleted file mode 100644 index 0d623483f..000000000 Binary files a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/tab_b.gif and /dev/null differ diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/tab_l.gif b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/tab_l.gif deleted file mode 100644 index 9b1e6337c..000000000 Binary files a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/tab_l.gif and /dev/null differ diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/tab_r.gif b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/tab_r.gif deleted file mode 100644 index ce9dd9f53..000000000 Binary files a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/tab_r.gif and /dev/null differ diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/tabs.css b/slsDetectorSoftware/slsDetectorAnalysis/docs/html/tabs.css deleted file mode 100644 index a61552a67..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/html/tabs.css +++ /dev/null @@ -1,102 +0,0 @@ -/* tabs styles, based on http://www.alistapart.com/articles/slidingdoors */ - -DIV.tabs -{ - float : left; - width : 100%; - background : url("tab_b.gif") repeat-x bottom; - margin-bottom : 4px; -} - -DIV.tabs UL -{ - margin : 0px; - padding-left : 10px; - list-style : none; -} - -DIV.tabs LI, DIV.tabs FORM -{ - display : inline; - margin : 0px; - padding : 0px; -} - -DIV.tabs FORM -{ - float : right; -} - -DIV.tabs A -{ - float : left; - background : url("tab_r.gif") no-repeat right top; - border-bottom : 1px solid #84B0C7; - font-size : x-small; - font-weight : bold; - text-decoration : none; -} - -DIV.tabs A:hover -{ - background-position: 100% -150px; -} - -DIV.tabs A:link, DIV.tabs A:visited, -DIV.tabs A:active, DIV.tabs A:hover -{ - color: #1A419D; -} - -DIV.tabs SPAN -{ - float : left; - display : block; - background : url("tab_l.gif") no-repeat left top; - padding : 5px 9px; - white-space : nowrap; -} - -DIV.tabs INPUT -{ - float : right; - display : inline; - font-size : 1em; -} - -DIV.tabs TD -{ - font-size : x-small; - font-weight : bold; - text-decoration : none; -} - - - -/* Commented Backslash Hack hides rule from IE5-Mac \*/ -DIV.tabs SPAN {float : none;} -/* End IE5-Mac hack */ - -DIV.tabs A:hover SPAN -{ - background-position: 0% -150px; -} - -DIV.tabs LI#current A -{ - background-position: 100% -150px; - border-width : 0px; -} - -DIV.tabs LI#current SPAN -{ - background-position: 0% -150px; - padding-bottom : 6px; -} - -DIV.nav -{ - background : none; - border : none; - border-bottom : 1px solid #84B0C7; -} diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/FreeSans.ttf b/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/FreeSans.ttf deleted file mode 100644 index b550b90ba..000000000 Binary files a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/FreeSans.ttf and /dev/null differ diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/Makefile b/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/Makefile deleted file mode 100644 index 776fcf968..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/Makefile +++ /dev/null @@ -1,39 +0,0 @@ -all: clean refman.dvi - -ps: refman.ps - -pdf: refman.pdf - -ps_2on1: refman_2on1.ps - -pdf_2on1: refman_2on1.pdf - -refman.ps: refman.dvi - dvips -o refman.ps refman.dvi - -refman.pdf: refman.ps - ps2pdf refman.ps refman.pdf - -refman.dvi: refman.tex doxygen.sty - echo "Running latex..." - latex refman.tex - echo "Running makeindex..." - makeindex refman.idx - echo "Rerunning latex...." - latex refman.tex - latex_count=5 ; \ - while egrep -s 'Rerun (LaTeX|to get cross-references right)' refman.log && [ $$latex_count -gt 0 ] ;\ - do \ - echo "Rerunning latex...." ;\ - latex refman.tex ;\ - latex_count=`expr $$latex_count - 1` ;\ - done - -refman_2on1.ps: refman.ps - psnup -2 refman.ps >refman_2on1.ps - -refman_2on1.pdf: refman_2on1.ps - ps2pdf refman_2on1.ps refman_2on1.pdf - -clean: - rm -f *.ps *.dvi *.aux *.toc *.idx *.ind *.ilg *.log *.out refman.pdf diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/annotated.tex b/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/annotated.tex deleted file mode 100644 index dc3097571..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/annotated.tex +++ /dev/null @@ -1,5 +0,0 @@ -\section{Class List} -Here are the classes, structs, unions and interfaces with brief descriptions:\begin{CompactList} -\item\contentsline{section}{\bf{energy\-Calibration} }{\pageref{classenergyCalibration}}{} -\item\contentsline{section}{\bf{energy\-Calibration\-Functions} (Energy calibration functions )}{\pageref{classenergyCalibrationFunctions}}{} -\end{CompactList} diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/classenergyCalibration.tex b/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/classenergyCalibration.tex deleted file mode 100644 index ca62e39dd..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/classenergyCalibration.tex +++ /dev/null @@ -1,337 +0,0 @@ -\section{energy\-Calibration Class Reference} -\label{classenergyCalibration}\index{energyCalibration@{energyCalibration}} -{\tt \#include $<$energy\-Calibration.h$>$} - -\subsection*{Public Member Functions} -\begin{CompactItemize} -\item -\bf{energy\-Calibration} () -\item -\bf{$\sim$energy\-Calibration} () -\item -int \bf{set\-Plot\-Flag} (int p=-1) -\item -int \bf{set\-Scan\-Sign} (int s=0) -\item -int \bf{set\-Charge\-Sharing} (int p=-1) -\item -void \bf{set\-Fit\-Range} (Double\_\-t mi, Double\_\-t ma) -\item -void \bf{get\-Fit\-Range} (Double\_\-t \&mi, Double\_\-t \&ma) -\item -void \bf{set\-Start\-Parameters} (Double\_\-t $\ast$par) -\item -void \bf{get\-Start\-Parameters} (Double\_\-t $\ast$par) -\item -TF1 $\ast$ \bf{fit\-SCurve} (TH1 $\ast$h1, Double\_\-t $\ast$mypar, Double\_\-t $\ast$emypar) -\item -TF1 $\ast$ \bf{fit\-Spectrum} (TH1 $\ast$h1, Double\_\-t $\ast$mypar, Double\_\-t $\ast$emypar) -\item -TGraph\-Errors $\ast$ \bf{linear\-Calibration} (int nscan, Double\_\-t $\ast$en, Double\_\-t $\ast$een, Double\_\-t $\ast$fl, Double\_\-t $\ast$efl, Double\_\-t \&gain, Double\_\-t \&off, Double\_\-t \&egain, Double\_\-t \&eoff) -\item -TGraph\-Errors $\ast$ \bf{calibrate\-Scurves} (int nscan, Double\_\-t $\ast$en, Double\_\-t $\ast$een, TH1F $\ast$$\ast$h1, Double\_\-t \&gain, Double\_\-t \&off, Double\_\-t \&egain, Double\_\-t \&eoff) -\item -TGraph\-Errors $\ast$ \bf{calibrate\-Spectra} (int nscan, Double\_\-t $\ast$en, Double\_\-t $\ast$een, TH1F $\ast$$\ast$h1, Double\_\-t \&gain, Double\_\-t \&off, Double\_\-t \&egain, Double\_\-t \&eoff) -\end{CompactItemize} -\subsection*{Private Member Functions} -\begin{CompactItemize} -\item -TGraph\-Errors $\ast$ \bf{calibrate} (int nscan, Double\_\-t $\ast$en, Double\_\-t $\ast$een, TH1F $\ast$$\ast$h1, Double\_\-t \&gain, Double\_\-t \&off, Double\_\-t \&egain, Double\_\-t \&eoff, int integral=1) -\item -void \bf{init\-Fit\-Function} (TF1 $\ast$fun, TH1 $\ast$h1) -\item -TF1 $\ast$ \bf{fit\-Function} (TF1 $\ast$fun, TH1 $\ast$h1, Double\_\-t $\ast$mypar, Double\_\-t $\ast$emypar) -\end{CompactItemize} -\subsection*{Private Attributes} -\begin{CompactItemize} -\item -int \bf{plot\_\-flag} -\item -int \bf{cs\_\-flag} -\item -Double\_\-t \bf{fit\_\-min} -\item -Double\_\-t \bf{fit\_\-max} -\item -Double\_\-t \bf{bg\_\-offset} -\item -Double\_\-t \bf{bg\_\-slope} -\item -Double\_\-t \bf{flex} -\item -Double\_\-t \bf{noise} -\item -Double\_\-t \bf{ampl} -\item -Double\_\-t \bf{cs\_\-slope} -\item -\bf{energy\-Calibration\-Functions} $\ast$ \bf{funcs} -\item -TF1 $\ast$ \bf{fscurve} -\item -TF1 $\ast$ \bf{fspectrum} -\end{CompactItemize} - - -\subsection{Detailed Description} -class alowing the energy calibration of photon counting and anlogue detectors - - - -\subsection{Constructor \& Destructor Documentation} -\index{energyCalibration@{energy\-Calibration}!energyCalibration@{energyCalibration}} -\index{energyCalibration@{energyCalibration}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}energy\-Calibration::energy\-Calibration ()}\label{classenergyCalibration_16f0658d2b526f52784057b2166efd22} - - -default constructor - creates the function with which the s-curves will be fitted \index{energyCalibration@{energy\-Calibration}!~energyCalibration@{$\sim$energyCalibration}} -\index{~energyCalibration@{$\sim$energyCalibration}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}energy\-Calibration::$\sim$energy\-Calibration ()}\label{classenergyCalibration_3bae2b9c26893daa8f583758509c844f} - - -default destructor - deletes the function with which the s-curves will be fitted - -\subsection{Member Function Documentation} -\index{energyCalibration@{energy\-Calibration}!calibrate@{calibrate}} -\index{calibrate@{calibrate}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}TGraph\-Errors$\ast$ energy\-Calibration::calibrate (int {\em nscan}, Double\_\-t $\ast$ {\em en}, Double\_\-t $\ast$ {\em een}, TH1F $\ast$$\ast$ {\em h1}, Double\_\-t \& {\em gain}, Double\_\-t \& {\em off}, Double\_\-t \& {\em egain}, Double\_\-t \& {\em eoff}, int {\em integral} = {\tt 1})\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_378daeddde40b6127ee6ed595506928c} - - -calculates gain and offset for the set of energies \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em nscan}]number of energy scans \item[{\em en}]array of energies (nscan long) \item[{\em een}]array of errors on energies (nscan long) - can be NULL! \item[{\em h1}]array of TH1 \item[{\em gain}]reference to gain resulting from the fit \item[{\em offset}]reference to offset resulting from the fit \item[{\em integral}]1 is an s-curve set (default), 0 spectra \end{description} -\end{Desc} -\begin{Desc} -\item[Returns:]graph energy vs peak/inflection point \end{Desc} -\index{energyCalibration@{energy\-Calibration}!calibrateScurves@{calibrateScurves}} -\index{calibrateScurves@{calibrateScurves}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}TGraph\-Errors$\ast$ energy\-Calibration::calibrate\-Scurves (int {\em nscan}, Double\_\-t $\ast$ {\em en}, Double\_\-t $\ast$ {\em een}, TH1F $\ast$$\ast$ {\em h1}, Double\_\-t \& {\em gain}, Double\_\-t \& {\em off}, Double\_\-t \& {\em egain}, Double\_\-t \& {\em eoff})\hspace{0.3cm}{\tt [inline]}}\label{classenergyCalibration_6f5ee6771522a31e4fe1eca143e2aa9b} - - -calculates gain and offset for the set of energy scans \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em nscan}]number of energy scans \item[{\em en}]array of energies (nscan long) \item[{\em een}]array of errors on energies (nscan long) - can be NULL! \item[{\em h1}]array of TH1 \item[{\em gain}]reference to gain resulting from the fit \item[{\em off}]reference to offset resulting from the fit \item[{\em egain}]reference to error on the gain resulting from the fit \item[{\em eoff}]reference to the error on the offset resulting from the fit \end{description} -\end{Desc} -\begin{Desc} -\item[Returns:]graph energy vs inflection point \end{Desc} -\index{energyCalibration@{energy\-Calibration}!calibrateSpectra@{calibrateSpectra}} -\index{calibrateSpectra@{calibrateSpectra}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}TGraph\-Errors$\ast$ energy\-Calibration::calibrate\-Spectra (int {\em nscan}, Double\_\-t $\ast$ {\em en}, Double\_\-t $\ast$ {\em een}, TH1F $\ast$$\ast$ {\em h1}, Double\_\-t \& {\em gain}, Double\_\-t \& {\em off}, Double\_\-t \& {\em egain}, Double\_\-t \& {\em eoff})\hspace{0.3cm}{\tt [inline]}}\label{classenergyCalibration_092637f656c0b88d57797e3ebd0f3e58} - - -calculates gain and offset for the set of energy spectra \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em nscan}]number of energy scans \item[{\em en}]array of energies (nscan long) \item[{\em een}]array of errors on energies (nscan long) - can be NULL! \item[{\em h1}]array of TH1 \item[{\em gain}]reference to gain resulting from the fit \item[{\em off}]reference to offset resulting from the fit \item[{\em egain}]reference to error on the gain resulting from the fit \item[{\em eoff}]reference to the error on the offset resulting from the fit \end{description} -\end{Desc} -\begin{Desc} -\item[Returns:]graph energy vs peak \end{Desc} -\index{energyCalibration@{energy\-Calibration}!fitFunction@{fitFunction}} -\index{fitFunction@{fitFunction}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}TF1$\ast$ energy\-Calibration::fit\-Function (TF1 $\ast$ {\em fun}, TH1 $\ast$ {\em h1}, Double\_\-t $\ast$ {\em mypar}, Double\_\-t $\ast$ {\em emypar})\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_fe1c6dc5f56d12fe06569f401da19729} - - -Perfors the fit according to the flags specified and returns the fitted function \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em fun}]function to fit \item[{\em h1}]histogram to fit \item[{\em mypar}]pointer to fit parameters array \item[{\em emypar}]pointer to fit parameter errors \end{description} -\end{Desc} -\begin{Desc} -\item[Returns:]the fitted function - can be used e.g. to get the Chi2 or similar \end{Desc} -\index{energyCalibration@{energy\-Calibration}!fitSCurve@{fitSCurve}} -\index{fitSCurve@{fitSCurve}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}TF1$\ast$ energy\-Calibration::fit\-SCurve (TH1 $\ast$ {\em h1}, Double\_\-t $\ast$ {\em mypar}, Double\_\-t $\ast$ {\em emypar})}\label{classenergyCalibration_0dcd8e06e31f7b70488a012db12b2bf8} - - -fits histogram with the s-curve function \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em h1}]1d-histogram to be fitted \item[{\em mypar}]pointer to fit parameters array \item[{\em emypar}]pointer to fit parameter errors \end{description} -\end{Desc} -\begin{Desc} -\item[Returns:]the fitted function - can be used e.g. to get the Chi2 or similar \end{Desc} -\index{energyCalibration@{energy\-Calibration}!fitSpectrum@{fitSpectrum}} -\index{fitSpectrum@{fitSpectrum}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}TF1$\ast$ energy\-Calibration::fit\-Spectrum (TH1 $\ast$ {\em h1}, Double\_\-t $\ast$ {\em mypar}, Double\_\-t $\ast$ {\em emypar})}\label{classenergyCalibration_7d22b28cd2fad3d334f15f3d6dc7975a} - - -fits histogram with the spectrum \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em h1}]1d-histogram to be fitted \item[{\em mypar}]pointer to fit parameters array \item[{\em emypar}]pointer to fit parameter errors \end{description} -\end{Desc} -\begin{Desc} -\item[Returns:]the fitted function - can be used e.g. to get the Chi2 or similar \end{Desc} -\index{energyCalibration@{energy\-Calibration}!getFitRange@{getFitRange}} -\index{getFitRange@{getFitRange}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}void energy\-Calibration::get\-Fit\-Range (Double\_\-t \& {\em mi}, Double\_\-t \& {\em ma})\hspace{0.3cm}{\tt [inline]}}\label{classenergyCalibration_bfb02327a6897bd97525c01697a1ba4f} - - -gets the s-curve fit range \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em mi}]reference for minimum of the fit range (-1 is histogram x-min) \item[{\em ma}]reference for maximum of the fit range (-1 is histogram x-max) \end{description} -\end{Desc} -\index{energyCalibration@{energy\-Calibration}!getStartParameters@{getStartParameters}} -\index{getStartParameters@{getStartParameters}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}void energy\-Calibration::get\-Start\-Parameters (Double\_\-t $\ast$ {\em par})}\label{classenergyCalibration_fc7411b7a3191748dfcc90f86b823bf4} - - -get start parameters for the s-curve function \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em par}]parameters, -1 means auto-calculated par[0] is the pedestal par[1] is the slope of the pedestal par[2] is the inflection point par[3] is the RMS par[4] is the amplitude par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) -- always positive \end{description} -\end{Desc} -\index{energyCalibration@{energy\-Calibration}!initFitFunction@{initFitFunction}} -\index{initFitFunction@{initFitFunction}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}void energy\-Calibration::init\-Fit\-Function (TF1 $\ast$ {\em fun}, TH1 $\ast$ {\em h1})\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_3e84328c11772b6263224340ec924e37} - - -Initializes the start parameters and the range of the fit depending on the histogram characteristics and/or on the start parameters specified by the user \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em fun}]pointer to function to be initialized \item[{\em h1}]histogram from which to extract the range and start parameters, if not already specified by the user \end{description} -\end{Desc} -\index{energyCalibration@{energy\-Calibration}!linearCalibration@{linearCalibration}} -\index{linearCalibration@{linearCalibration}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}TGraph\-Errors$\ast$ energy\-Calibration::linear\-Calibration (int {\em nscan}, Double\_\-t $\ast$ {\em en}, Double\_\-t $\ast$ {\em een}, Double\_\-t $\ast$ {\em fl}, Double\_\-t $\ast$ {\em efl}, Double\_\-t \& {\em gain}, Double\_\-t \& {\em off}, Double\_\-t \& {\em egain}, Double\_\-t \& {\em eoff})}\label{classenergyCalibration_c7f46f2d051f28211681e851f99d3fc4} - - -calculates gain and offset for the set of inflection points \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em nscan}]number of energy scans \item[{\em en}]array of energies (nscan long) \item[{\em een}]array of errors on energies (nscan long) - can be NULL! \item[{\em fl}]array of inflection points (nscan long) \item[{\em efl}]array of errors on the inflection points (nscan long) \item[{\em gain}]reference to gain resulting from the fit \item[{\em off}]reference to offset resulting from the fit \item[{\em egain}]reference to error on the gain resulting from the fit \item[{\em eoff}]reference to the error on the offset resulting from the fit \end{description} -\end{Desc} -\begin{Desc} -\item[Returns:]graph energy vs inflection point \end{Desc} -\index{energyCalibration@{energy\-Calibration}!setChargeSharing@{setChargeSharing}} -\index{setChargeSharing@{setChargeSharing}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}int energy\-Calibration::set\-Charge\-Sharing (int {\em p} = {\tt -1})}\label{classenergyCalibration_e2809b419799e8b199944f185d4ebab8} - - -sets plot flag \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em p}]plot flag (-1 gets, 0 unsets, $>$0 plot) \end{description} -\end{Desc} -\begin{Desc} -\item[Returns:]current plot flag \end{Desc} -\index{energyCalibration@{energy\-Calibration}!setFitRange@{setFitRange}} -\index{setFitRange@{setFitRange}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}void energy\-Calibration::set\-Fit\-Range (Double\_\-t {\em mi}, Double\_\-t {\em ma})\hspace{0.3cm}{\tt [inline]}}\label{classenergyCalibration_695cef5428a833d515172d987774f67b} - - -sets the s-curve fit range \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em mi}]minimum of the fit range (-1 is histogram x-min) \item[{\em ma}]maximum of the fit range (-1 is histogram x-max) \end{description} -\end{Desc} -\index{energyCalibration@{energy\-Calibration}!setPlotFlag@{setPlotFlag}} -\index{setPlotFlag@{setPlotFlag}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}int energy\-Calibration::set\-Plot\-Flag (int {\em p} = {\tt -1})\hspace{0.3cm}{\tt [inline]}}\label{classenergyCalibration_3d9af0857f7a68b7e4519917ea97e6be} - - -sets plot flag \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em p}]plot flag (-1 gets, 0 unsets, $>$0 plot) \end{description} -\end{Desc} -\begin{Desc} -\item[Returns:]current plot flag \end{Desc} -\index{energyCalibration@{energy\-Calibration}!setScanSign@{setScanSign}} -\index{setScanSign@{setScanSign}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}int energy\-Calibration::set\-Scan\-Sign (int {\em s} = {\tt 0})\hspace{0.3cm}{\tt [inline]}}\label{classenergyCalibration_7dbf1676b30ffe90c5aa917f1b2b77ee} - - -sets scan sign \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em s}]can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) otherwise gets \end{description} -\end{Desc} -\begin{Desc} -\item[Returns:]current scan sign can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) \end{Desc} -\index{energyCalibration@{energy\-Calibration}!setStartParameters@{setStartParameters}} -\index{setStartParameters@{setStartParameters}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}void energy\-Calibration::set\-Start\-Parameters (Double\_\-t $\ast$ {\em par})}\label{classenergyCalibration_ba156f5290f7b404d7b8ea735fd7e7bf} - - -set start parameters for the s-curve function \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em par}]parameters, -1 sets to auto-calculation par[0] is the pedestal par[1] is the slope of the pedestal par[2] is the inflection point par[3] is the RMS par[4] is the amplitude par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) -- always positive \end{description} -\end{Desc} - - -\subsection{Member Data Documentation} -\index{energyCalibration@{energy\-Calibration}!ampl@{ampl}} -\index{ampl@{ampl}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t \bf{energy\-Calibration::ampl}\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_77b954cd513271d2cfafee6033435584} - - -start value for the number of photons \index{energyCalibration@{energy\-Calibration}!bg_offset@{bg\_\-offset}} -\index{bg_offset@{bg\_\-offset}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t \bf{energy\-Calibration::bg\_\-offset}\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_aa11f256a8b0a94c28a98d068013b327} - - -start value for the background pedestal \index{energyCalibration@{energy\-Calibration}!bg_slope@{bg\_\-slope}} -\index{bg_slope@{bg\_\-slope}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t \bf{energy\-Calibration::bg\_\-slope}\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_9676e5cc2757c723c2262d641fb4b8b4} - - -start value for the background slope \index{energyCalibration@{energy\-Calibration}!cs_flag@{cs\_\-flag}} -\index{cs_flag@{cs\_\-flag}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}int \bf{energy\-Calibration::cs\_\-flag}\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_ce0be11dcc8418db3c7c2b139a015c96} - - -0 functions without charge sharing contribution, $>$0 with charge sharing contribution \index{energyCalibration@{energy\-Calibration}!cs_slope@{cs\_\-slope}} -\index{cs_slope@{cs\_\-slope}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t \bf{energy\-Calibration::cs\_\-slope}\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_ca1efedbfea0ad5c9ea2d794e3fb368d} - - -start value for the charge sharing slope \index{energyCalibration@{energy\-Calibration}!fit_max@{fit\_\-max}} -\index{fit_max@{fit\_\-max}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t \bf{energy\-Calibration::fit\_\-max}\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_e979386a3f787ef706f4a9ec5bf41d7d} - - -maximum of the s-curve fitting range, -1 is histogram x-max \index{energyCalibration@{energy\-Calibration}!fit_min@{fit\_\-min}} -\index{fit_min@{fit\_\-min}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t \bf{energy\-Calibration::fit\_\-min}\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_262f574732186cdd8d3a11344d03d0bb} - - -minimum of the s-curve fitting range, -1 is histogram x-min \index{energyCalibration@{energy\-Calibration}!flex@{flex}} -\index{flex@{flex}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t \bf{energy\-Calibration::flex}\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_b99d770f1c9af68d591ed20847813ad1} - - -start value for the inflection point \index{energyCalibration@{energy\-Calibration}!fscurve@{fscurve}} -\index{fscurve@{fscurve}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}TF1$\ast$ \bf{energy\-Calibration::fscurve}\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_57706a328324c25dd9f8ba6d1486e4ce} - - -function with which the s-curve will be fitted \index{energyCalibration@{energy\-Calibration}!fspectrum@{fspectrum}} -\index{fspectrum@{fspectrum}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}TF1$\ast$ \bf{energy\-Calibration::fspectrum}\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_2ee734ab28b78dc5786a7ba430f8baa5} - - -function with which the spectrum will be fitted \index{energyCalibration@{energy\-Calibration}!funcs@{funcs}} -\index{funcs@{funcs}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}\bf{energy\-Calibration\-Functions}$\ast$ \bf{energy\-Calibration::funcs}\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_e9b3307bf858331241871bde42fdd24e} - - -\index{energyCalibration@{energy\-Calibration}!noise@{noise}} -\index{noise@{noise}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t \bf{energy\-Calibration::noise}\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_4461206397e2442c92be9151ee231ec5} - - -start value for the noise \index{energyCalibration@{energy\-Calibration}!plot_flag@{plot\_\-flag}} -\index{plot_flag@{plot\_\-flag}!energyCalibration@{energy\-Calibration}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}int \bf{energy\-Calibration::plot\_\-flag}\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibration_4edfb157df3624be677177dec0f9555b} - - -0 does not plot, $>$0 plots (flags?) - -The documentation for this class was generated from the following file:\begin{CompactItemize} -\item -\bf{energy\-Calibration.h}\end{CompactItemize} diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/classenergyCalibrationFunctions.tex b/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/classenergyCalibrationFunctions.tex deleted file mode 100644 index 1e8920959..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/classenergyCalibrationFunctions.tex +++ /dev/null @@ -1,135 +0,0 @@ -\section{energy\-Calibration\-Functions Class Reference} -\label{classenergyCalibrationFunctions}\index{energyCalibrationFunctions@{energyCalibrationFunctions}} -Energy calibration functions. - - -{\tt \#include $<$energy\-Calibration.h$>$} - -\subsection*{Public Member Functions} -\begin{CompactItemize} -\item -\bf{energy\-Calibration\-Functions} (int s=-1) -\item -int \bf{set\-Scan\-Sign} (int s=0) -\item -Double\_\-t \bf{gauss\-Charge\-Sharing} (Double\_\-t $\ast$x, Double\_\-t $\ast$par) -\item -Double\_\-t \bf{erf\-Function} (Double\_\-t $\ast$x, Double\_\-t $\ast$par) -\item -Double\_\-t \bf{erf\-Function\-Charge\-Sharing} (Double\_\-t $\ast$x, Double\_\-t $\ast$par) -\item -Double\_\-t \bf{erf\-Func\-Fluo} (Double\_\-t $\ast$x, Double\_\-t $\ast$par) -\item -Double\_\-t \bf{spectrum} (Double\_\-t $\ast$x, Double\_\-t $\ast$par) -\item -Double\_\-t \bf{scurve} (Double\_\-t $\ast$x, Double\_\-t $\ast$par) -\item -Double\_\-t \bf{scurve\-Fluo} (Double\_\-t $\ast$x, Double\_\-t $\ast$par) -\end{CompactItemize} -\subsection*{Static Public Member Functions} -\begin{CompactItemize} -\item -static float \bf{median} (float $\ast$x, int n) -\item -static int \bf{quick\_\-select} (int arr[$\,$], int n) -\item -static int \bf{kth\_\-smallest} (int $\ast$a, int n, int k) -\end{CompactItemize} -\subsection*{Private Attributes} -\begin{CompactItemize} -\item -int \bf{sign} -\end{CompactItemize} - - -\subsection{Detailed Description} -Energy calibration functions. - -class containing all the possible energy calibration functions (scurves with and without charge sharing, gaussian spectrum with and without charge sharing, possibility of chosing the sign of the X-axis) - - - -\subsection{Constructor \& Destructor Documentation} -\index{energyCalibrationFunctions@{energy\-Calibration\-Functions}!energyCalibrationFunctions@{energyCalibrationFunctions}} -\index{energyCalibrationFunctions@{energyCalibrationFunctions}!energyCalibrationFunctions@{energy\-Calibration\-Functions}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}energy\-Calibration\-Functions::energy\-Calibration\-Functions (int {\em s} = {\tt -1})\hspace{0.3cm}{\tt [inline]}}\label{classenergyCalibrationFunctions_8c17162b89f3b2e642004e7c88a22ac2} - - - - -\subsection{Member Function Documentation} -\index{energyCalibrationFunctions@{energy\-Calibration\-Functions}!erfFuncFluo@{erfFuncFluo}} -\index{erfFuncFluo@{erfFuncFluo}!energyCalibrationFunctions@{energy\-Calibration\-Functions}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t energy\-Calibration\-Functions::erf\-Func\-Fluo (Double\_\-t $\ast$ {\em x}, Double\_\-t $\ast$ {\em par})}\label{classenergyCalibrationFunctions_a5fbe9da48bc2ef90b699e06ea8c5111} - - -Double Erf function with charge sharing slope par[0] is the pedestal par[1] is the slope of the pedestal par[2] is the inflection point of the first energy par[3] is the RMS of the first energy par[4] is the amplitude of the first energy par[5] is the angual coefficient of the charge sharing slope of the first energy (scales with par[3]) par[6] is the inflection point of the second energy par[7] is the RMS of the second energy par[8] is the amplitude of the second energy par[9] is the angual coefficient of the charge sharing slope of the second energy (scales with par[8]) \index{energyCalibrationFunctions@{energy\-Calibration\-Functions}!erfFunction@{erfFunction}} -\index{erfFunction@{erfFunction}!energyCalibrationFunctions@{energy\-Calibration\-Functions}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t energy\-Calibration\-Functions::erf\-Function (Double\_\-t $\ast$ {\em x}, Double\_\-t $\ast$ {\em par})}\label{classenergyCalibrationFunctions_2da1e3b9a10d23233256f8c2234f2457} - - -Basic erf function par[0] is the inflection point par[1] is the RMS par[2] is the amplitude \index{energyCalibrationFunctions@{energy\-Calibration\-Functions}!erfFunctionChargeSharing@{erfFunctionChargeSharing}} -\index{erfFunctionChargeSharing@{erfFunctionChargeSharing}!energyCalibrationFunctions@{energy\-Calibration\-Functions}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t energy\-Calibration\-Functions::erf\-Function\-Charge\-Sharing (Double\_\-t $\ast$ {\em x}, Double\_\-t $\ast$ {\em par})}\label{classenergyCalibrationFunctions_8d1b3d0f8b30423dad56d8ce5323a4a8} - - -Erf function with charge sharing slope par[0] is the pedestal par[1] is the slope of the pedestal par[2] is the inflection point par[3] is the RMS par[4] is the amplitude par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) \index{energyCalibrationFunctions@{energy\-Calibration\-Functions}!gaussChargeSharing@{gaussChargeSharing}} -\index{gaussChargeSharing@{gaussChargeSharing}!energyCalibrationFunctions@{energy\-Calibration\-Functions}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t energy\-Calibration\-Functions::gauss\-Charge\-Sharing (Double\_\-t $\ast$ {\em x}, Double\_\-t $\ast$ {\em par})}\label{classenergyCalibrationFunctions_e9582e5c46d27ad25d6139d0386698f7} - - -Gaussian Function with charge sharing pedestal par[0] is the absolute height of the background pedestal par[1] is the slope of the background pedestal par[2] is the gaussian peak position par[3] is the RMS of the gaussian (and of the pedestal) par[4] is the height of the function par[5] is the fractional height of the charge sharing pedestal (scales with par[3]) \index{energyCalibrationFunctions@{energy\-Calibration\-Functions}!kth_smallest@{kth\_\-smallest}} -\index{kth_smallest@{kth\_\-smallest}!energyCalibrationFunctions@{energy\-Calibration\-Functions}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}static int energy\-Calibration\-Functions::kth\_\-smallest (int $\ast$ {\em a}, int {\em n}, int {\em k})\hspace{0.3cm}{\tt [static]}}\label{classenergyCalibrationFunctions_7d9a7b8d0c8ff69638a5fbb9f4c04b90} - - -Calculates the median of an array of n elements (swaps the arrays!) \index{energyCalibrationFunctions@{energy\-Calibration\-Functions}!median@{median}} -\index{median@{median}!energyCalibrationFunctions@{energy\-Calibration\-Functions}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}static float energy\-Calibration\-Functions::median (float $\ast$ {\em x}, int {\em n})\hspace{0.3cm}{\tt [static]}}\label{classenergyCalibrationFunctions_37f557bacb75213073c8d421cc1240f4} - - -Calculates the median of an array of n elements \index{energyCalibrationFunctions@{energy\-Calibration\-Functions}!quick_select@{quick\_\-select}} -\index{quick_select@{quick\_\-select}!energyCalibrationFunctions@{energy\-Calibration\-Functions}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}static int energy\-Calibration\-Functions::quick\_\-select (int {\em arr}[$\,$], int {\em n})\hspace{0.3cm}{\tt [static]}}\label{classenergyCalibrationFunctions_a3ab0e7c3c862fb51dfda78f1b09a55c} - - -Calculates the median of an array of n elements (swaps the arrays!) \index{energyCalibrationFunctions@{energy\-Calibration\-Functions}!scurve@{scurve}} -\index{scurve@{scurve}!energyCalibrationFunctions@{energy\-Calibration\-Functions}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t energy\-Calibration\-Functions::scurve (Double\_\-t $\ast$ {\em x}, Double\_\-t $\ast$ {\em par})}\label{classenergyCalibrationFunctions_e220482622e88a46b12498b0e4d8113a} - - -Erf function with charge sharing slope with the correct scan sign par[0] is the pedestal par[1] is the slope of the pedestal par[2] is the inflection point par[3] is the RMS par[4] is the amplitude par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) \index{energyCalibrationFunctions@{energy\-Calibration\-Functions}!scurveFluo@{scurveFluo}} -\index{scurveFluo@{scurveFluo}!energyCalibrationFunctions@{energy\-Calibration\-Functions}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t energy\-Calibration\-Functions::scurve\-Fluo (Double\_\-t $\ast$ {\em x}, Double\_\-t $\ast$ {\em par})}\label{classenergyCalibrationFunctions_4eba39623b518d67a63192970a78f530} - - -Double Erf function with charge sharing slope par[0] is the pedestal par[1] is the slope of the pedestal par[2] is the inflection point of the first energy par[3] is the RMS of the first energy par[4] is the amplitude of the first energy par[5] is the angual coefficient of the charge sharing slope of the first energy (scales with par[3]) par[6] is the inflection point of the second energy par[7] is the RMS of the second energy par[8] is the amplitude of the second energy par[9] is the angual coefficient of the charge sharing slope of the second energy (scales with par[8]) \index{energyCalibrationFunctions@{energy\-Calibration\-Functions}!setScanSign@{setScanSign}} -\index{setScanSign@{setScanSign}!energyCalibrationFunctions@{energy\-Calibration\-Functions}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}int energy\-Calibration\-Functions::set\-Scan\-Sign (int {\em s} = {\tt 0})\hspace{0.3cm}{\tt [inline]}}\label{classenergyCalibrationFunctions_716759a1ae09ea3c841f824af3ece415} - - -sets scan sign \begin{Desc} -\item[Parameters:] -\begin{description} -\item[{\em s}]can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) otherwise gets \end{description} -\end{Desc} -\begin{Desc} -\item[Returns:]current scan sign can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) \end{Desc} -\index{energyCalibrationFunctions@{energy\-Calibration\-Functions}!spectrum@{spectrum}} -\index{spectrum@{spectrum}!energyCalibrationFunctions@{energy\-Calibration\-Functions}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}Double\_\-t energy\-Calibration\-Functions::spectrum (Double\_\-t $\ast$ {\em x}, Double\_\-t $\ast$ {\em par})}\label{classenergyCalibrationFunctions_015eb05dc34b77642ab2a2a9f126f170} - - -static function Gaussian with charge sharing pedestal with the correct scan sign par[0] is the absolute height of the background pedestal par[1] is the fractional height of the charge sharing pedestal (scales with par[3] par[2] is the gaussian peak position par[3] is the RMS of the gaussian (and of the pedestal) par[4] is the height of the function - -\subsection{Member Data Documentation} -\index{energyCalibrationFunctions@{energy\-Calibration\-Functions}!sign@{sign}} -\index{sign@{sign}!energyCalibrationFunctions@{energy\-Calibration\-Functions}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}int \bf{energy\-Calibration\-Functions::sign}\hspace{0.3cm}{\tt [private]}}\label{classenergyCalibrationFunctions_4fc7c435169b5bf4672cf654270097d0} - - - - -The documentation for this class was generated from the following file:\begin{CompactItemize} -\item -\bf{energy\-Calibration.h}\end{CompactItemize} diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/doxygen.sty b/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/doxygen.sty deleted file mode 100644 index ff2b57e23..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/doxygen.sty +++ /dev/null @@ -1,78 +0,0 @@ -\NeedsTeXFormat{LaTeX2e} -\ProvidesPackage{doxygen} -\RequirePackage{calc} -\RequirePackage{array} -\pagestyle{fancyplain} -\newcommand{\clearemptydoublepage}{\newpage{\pagestyle{empty}\cleardoublepage}} -\renewcommand{\chaptermark}[1]{\markboth{#1}{}} -\renewcommand{\sectionmark}[1]{\markright{\thesection\ #1}} -\lhead[\fancyplain{}{\bfseries\thepage}] - {\fancyplain{}{\bfseries\rightmark}} -\rhead[\fancyplain{}{\bfseries\leftmark}] - {\fancyplain{}{\bfseries\thepage}} -\rfoot[\fancyplain{}{\bfseries\scriptsize Generated on Tue Mar 27 16:32:29 2012 by Doxygen }]{} -\lfoot[]{\fancyplain{}{\bfseries\scriptsize Generated on Tue Mar 27 16:32:29 2012 by Doxygen }} -\cfoot{} -\newenvironment{Code} -{\footnotesize} -{\normalsize} -\newcommand{\doxyref}[3]{\textbf{#1} (\textnormal{#2}\,\pageref{#3})} -\newenvironment{DocInclude} -{\footnotesize} -{\normalsize} -\newenvironment{VerbInclude} -{\footnotesize} -{\normalsize} -\newenvironment{Image} -{\begin{figure}[H]} -{\end{figure}} -\newenvironment{ImageNoCaption}{}{} -\newenvironment{CompactList} -{\begin{list}{}{ - \setlength{\leftmargin}{0.5cm} - \setlength{\itemsep}{0pt} - \setlength{\parsep}{0pt} - \setlength{\topsep}{0pt} - \renewcommand{\makelabel}{\hfill}}} -{\end{list}} -\newenvironment{CompactItemize} -{ - \begin{itemize} - \setlength{\itemsep}{-3pt} - \setlength{\parsep}{0pt} - \setlength{\topsep}{0pt} - \setlength{\partopsep}{0pt} -} -{\end{itemize}} -\newcommand{\PBS}[1]{\let\temp=\\#1\let\\=\temp} -\newlength{\tmplength} -\newenvironment{TabularC}[1] -{ -\setlength{\tmplength} - {\linewidth/(#1)-\tabcolsep*2-\arrayrulewidth*(#1+1)/(#1)} - \par\begin{tabular*}{\linewidth} - {*{#1}{|>{\PBS\raggedright\hspace{0pt}}p{\the\tmplength}}|} -} -{\end{tabular*}\par} -\newcommand{\entrylabel}[1]{ - {\parbox[b]{\labelwidth-4pt}{\makebox[0pt][l]{\textbf{#1}}\vspace{1.5\baselineskip}}}} -\newenvironment{Desc} -{\begin{list}{} - { - \settowidth{\labelwidth}{40pt} - \setlength{\leftmargin}{\labelwidth} - \setlength{\parsep}{0pt} - \setlength{\itemsep}{-4pt} - \renewcommand{\makelabel}{\entrylabel} - } -} -{\end{list}} -\newenvironment{Indent} - {\begin{list}{}{\setlength{\leftmargin}{0.5cm}} - \item[]\ignorespaces} - {\unskip\end{list}} -\setlength{\parindent}{0cm} -\setlength{\parskip}{0.2cm} -\addtocounter{secnumdepth}{1} -\sloppy -\usepackage[T1]{fontenc} diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/energyCalibration_8h.tex b/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/energyCalibration_8h.tex deleted file mode 100644 index 3c9d9f6c8..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/energyCalibration_8h.tex +++ /dev/null @@ -1,37 +0,0 @@ -\section{energy\-Calibration.h File Reference} -\label{energyCalibration_8h}\index{energyCalibration.h@{energyCalibration.h}} -{\tt \#include $<$TROOT.h$>$}\par -{\tt \#include $<$TF1.h$>$}\par -\subsection*{Namespaces} -\begin{CompactItemize} -\item -namespace \bf{std} -\end{CompactItemize} -\subsection*{Classes} -\begin{CompactItemize} -\item -class \bf{energy\-Calibration\-Functions} -\begin{CompactList}\small\item\em Energy calibration functions. \item\end{CompactList}\item -class \bf{energy\-Calibration} -\end{CompactItemize} -\subsection*{Variables} -\begin{CompactItemize} -\item -const float \bf{conven} = 1000./3.6 -\item -const float \bf{el} = 1.67E-4 -\end{CompactItemize} - - -\subsection{Variable Documentation} -\index{energyCalibration.h@{energy\-Calibration.h}!conven@{conven}} -\index{conven@{conven}!energyCalibration.h@{energy\-Calibration.h}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}const float \bf{conven} = 1000./3.6}\label{energyCalibration_8h_a48a6c1eb7d418c5d0618fbb161ae321} - - -electrons/ke\-V \index{energyCalibration.h@{energy\-Calibration.h}!el@{el}} -\index{el@{el}!energyCalibration.h@{energy\-Calibration.h}} -\subsubsection{\setlength{\rightskip}{0pt plus 5cm}const float \bf{el} = 1.67E-4}\label{energyCalibration_8h_d1db7b454cab6ae1749310d7f444849b} - - -electron charge in f\-C \ No newline at end of file diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/files.tex b/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/files.tex deleted file mode 100644 index d3d460d1e..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/files.tex +++ /dev/null @@ -1,4 +0,0 @@ -\section{File List} -Here is a list of all files with brief descriptions:\begin{CompactList} -\item\contentsline{section}{\bf{energy\-Calibration.h} }{\pageref{energyCalibration_8h}}{} -\end{CompactList} diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/index.tex b/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/index.tex deleted file mode 100644 index 4b31a1dff..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/index.tex +++ /dev/null @@ -1,3 +0,0 @@ -\section{Introduction}\label{index_intro_sec} -We know very well s-curves etc. but at the end everybody uses different functions ;-).\subsection{Motivation}\label{index_mot_sec} -It would be greate to use everybody the same functions... \ No newline at end of file diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/namespaces.tex b/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/namespaces.tex deleted file mode 100644 index c2ca33382..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/namespaces.tex +++ /dev/null @@ -1,4 +0,0 @@ -\section{Namespace List} -Here is a list of all namespaces with brief descriptions:\begin{CompactList} -\item\contentsline{section}{\bf{std} }{\pageref{namespacestd}}{} -\end{CompactList} diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/namespacestd.tex b/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/namespacestd.tex deleted file mode 100644 index a1732dd75..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/namespacestd.tex +++ /dev/null @@ -1,4 +0,0 @@ -\section{std Namespace Reference} -\label{namespacestd}\index{std@{std}} - - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/refman.tex b/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/refman.tex deleted file mode 100644 index 110991b6b..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/docs/latex/refman.tex +++ /dev/null @@ -1,46 +0,0 @@ -\documentclass[a4paper]{book} -\usepackage{a4wide} -\usepackage{makeidx} -\usepackage{fancyhdr} -\usepackage{graphicx} -\usepackage{multicol} -\usepackage{float} -\usepackage{textcomp} -\usepackage{alltt} -\usepackage{doxygen} -\makeindex -\setcounter{tocdepth}{1} -\renewcommand{\footrulewidth}{0.4pt} -\begin{document} -\begin{titlepage} -\vspace*{7cm} -\begin{center} -{\Large Reference Manual}\\ -\vspace*{1cm} -{\large Generated by Doxygen 1.4.7}\\ -\vspace*{0.5cm} -{\small Tue Mar 27 16:32:29 2012}\\ -\end{center} -\end{titlepage} -\clearemptydoublepage -\pagenumbering{roman} -\tableofcontents -\clearemptydoublepage -\pagenumbering{arabic} -\chapter{Common Root library for SLS detectors data analysis } -\label{index}\input{index} -\chapter{Namespace Index} -\input{namespaces} -\chapter{Class Index} -\input{annotated} -\chapter{File Index} -\input{files} -\chapter{Namespace Documentation} -\input{namespacestd} -\chapter{Class Documentation} -\input{classenergyCalibration} -\include{classenergyCalibrationFunctions} -\chapter{File Documentation} -\input{energyCalibration_8h} -\printindex -\end{document} diff --git a/slsDetectorSoftware/slsDetectorAnalysis/doxy.config b/slsDetectorSoftware/slsDetectorAnalysis/doxy.config deleted file mode 100644 index c6f5f7f13..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/doxy.config +++ /dev/null @@ -1,65 +0,0 @@ -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. -# Private class members and static file members will be hidden unless -# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES - -EXTRACT_ALL = YES - -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class -# will be included in the documentation. - -EXTRACT_PRIVATE = YES - -# If the EXTRACT_STATIC tag is set to YES all static members of a file -# will be included in the documentation. - -EXTRACT_STATIC = YES - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) -# defined locally in source files will be included in the documentation. -# If set to NO only classes defined in header files are included. - -EXTRACT_LOCAL_CLASSES = YES - -# This flag is only useful for Objective-C code. When set to YES local -# methods, which are defined in the implementation section but not in -# the interface are included in the documentation. -# If set to NO (the default) only methods in the interface are included. - -EXTRACT_LOCAL_METHODS = YES - -# If this flag is set to YES, the members of anonymous namespaces will be -# extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base -# name of the file that contains the anonymous namespace. By default -# anonymous namespace are hidden. - -EXTRACT_ANON_NSPACES = NO - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all -# undocumented members of documented classes, files or namespaces. -# If set to NO (the default) these members will be included in the -# various overviews, but no documentation section is generated. -# This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. -# If set to NO (the default) these classes will be included in the various -# overviews. This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all -# friend (class|struct|union) declarations. -# If set to NO (the default) these declarations will be included in the -# documentation. - -HIDE_FRIEND_COMPOUNDS = NO - -INPUT = energyCalibration.h - - -OUTPUT_DIRECTORY = docs - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/enCalLogClass.h b/slsDetectorSoftware/slsDetectorAnalysis/enCalLogClass.h deleted file mode 100644 index e3a010df4..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/enCalLogClass.h +++ /dev/null @@ -1,133 +0,0 @@ -#ifndef ENCALLOGCLASS_H -#define ENCALLOGCLASS_H - -#include -#include - - -#ifdef __CINT__ -#define MYROOT -#endif - -#ifndef MYROOT -#include "slsDetectorCommand.h" -#include "slsDetectorUtils.h" -#include "sls_detector_defs.h" -#endif - -; - -class enCalLogClass { - - - public: - -#ifndef MYROOT - enCalLogClass(slsDetectorUtils *det){ \ - char cmd[1000]; \ - char *argv[2]; \ - strcpy(vars[0],"settings"); \ - strcpy(vars[1],"type"); \ - strcpy(vars[2],"nmod"); \ - strcpy(vars[3],"modulenumber"); \ - argv[0]=cmd; \ - sprintf(cmd,"_%d.encal",det->getFileIndex()); \ - outfile.open(std::string(det->getFilePath()+std::string("/")+det->getFileName()+std::string(cmd)).c_str()); \ - myDet=new slsDetectorCommand(det); \ - strcpy(cmd,vars[0]); \ - outfile << cmd << " " << myDet->executeLine(1,argv,slsDetectorDefs::GET_ACTION) << endl; \ - strcpy(cmd,vars[1]); \ - outfile << cmd << " " << myDet->executeLine(1,argv,slsDetectorDefs::GET_ACTION) << endl; \ - strcpy(cmd,vars[2]); \ - outfile << cmd << " " << myDet->executeLine(1,argv,slsDetectorDefs::GET_ACTION) << endl; \ - for (int im=0; imsetNumberOfModules(); im++) { \ - sprintf(cmd,"%s:%d",vars[3],im); \ - outfile << cmd << " " << myDet->executeLine(1,argv,slsDetectorDefs::GET_ACTION) << endl; \ - } \ - }; - - ~enCalLogClass(){delete myDet; outfile.close();}; -#else - enCalLogClass() { \ - strcpy(vars[0],"settings"); \ - strcpy(vars[1],"type"); \ - strcpy(vars[2],"nmod"); \ - strcpy(vars[3],"modulenumber"); \ - }; - ~enCalLogClass(){}; -#endif - - - int addStep(double threshold, std::string fname) {outfile << threshold << " " << fname << endl; return 0;}; - - - // - - int readHeader(std::ifstream &infile, char *settings, int &nmod, int &chanspermod, int *mods ) { \ - nmod=0; strcpy(settings,"unknown"); chanspermod=0; \ - char line[1000],myarg[100]; \ - int dum; \ - for (int iv=0; iv<3; iv++) { \ - infile.getline(line,1000); \ - switch (iv) { \ - case 0: \ - sscanf(line,"settings %s", settings); \ - break; \ - case 1: \ - sscanf(line,"type %s", myarg); \ - if (std::string(myarg).find("Mythen")!=std::string::npos) \ - chanspermod=1280; \ - else if (std::string(myarg).find("Gotthard")!=std::string::npos) \ - chanspermod=1280; \ - else \ - chanspermod=65535; \ - break; \ - case 2: \ - sscanf(line,"nmod %d", &nmod); \ - break; \ - default: \ - ; \ - }; \ - if (infile.bad() || infile.eof()) { cout << "bad file "<< iv << endl; return -1;} \ - } \ - for (int im=0; im -#include -#include -#include -#endif - -#include - -#define max(a,b) ((a) > (b) ? (a) : (b)) -#define min(a,b) ((a) < (b) ? (a) : (b)) -#define ELEM_SWAP(a,b) { register int t=(a);(a)=(b);(b)=t; } - - -using namespace std; - -#ifdef MYROOT -Double_t energyCalibrationFunctions::gaussChargeSharing(Double_t *x, Double_t *par) { - Double_t f, arg=0; - if (par[3]!=0) arg=(x[0]-par[2])/par[3]; - f=par[4]*TMath::Exp(-1*arg*arg/2.); - f=f+par[5]*(par[4]/2*(TMath::Erfc(sign*arg/(TMath::Sqrt(2.)))))+par[0]-par[1]*sign*x[0]; - return f; -} - -// basic erf function -Double_t energyCalibrationFunctions::erfFunction(Double_t *x, Double_t *par) { - double arg=0; - if (par[1]!=0) arg=(par[0]-x[0])/par[1]; - return ((par[2]/2.*(1+TMath::Erf(sign*arg/(TMath::Sqrt(2)))))); -}; - - -Double_t energyCalibrationFunctions::erfFunctionChargeSharing(Double_t *x, Double_t *par) { - Double_t f; - - f=erfFunction(x, par+2)*(1+par[5]*(par[2]-x[0]))+par[0]-par[1]*x[0]*sign; - return f; -}; - - -Double_t energyCalibrationFunctions::erfFuncFluo(Double_t *x, Double_t *par) { - Double_t f; - f=erfFunctionChargeSharing(x, par)+erfFunction(x, par+6)*(1+par[9]*(par[6]-x[0])); - return f; -}; -#endif - -double energyCalibrationFunctions::median(double *x, int n){ - // sorts x into xmed array and returns median - // n is number of values already in the xmed array - double xmed[n]; - int k,i,j; - - for (i=0; i*(x+j)) - k++; - if (*(x+i)==*(x+j)) { - if (i>j) - k++; - } - } - xmed[k]=*(x+i); - } - k=n/2; - return xmed[k]; -} - - -int energyCalibrationFunctions::quick_select(int arr[], int n){ - int low, high ; - int median; - int middle, ll, hh; - - low = 0 ; high = n-1 ; median = (low + high) / 2; - for (;;) { - if (high <= low) /* One element only */ - return arr[median] ; - - if (high == low + 1) { /* Two elements only */ - if (arr[low] > arr[high]) - ELEM_SWAP(arr[low], arr[high]) ; - return arr[median] ; - } - - /* Find median of low, middle and high items; swap into position low */ - middle = (low + high) / 2; - if (arr[middle] > arr[high]) ELEM_SWAP(arr[middle], arr[high]) ; - if (arr[low] > arr[high]) ELEM_SWAP(arr[low], arr[high]) ; - if (arr[middle] > arr[low]) ELEM_SWAP(arr[middle], arr[low]) ; - - /* Swap low item (now in position middle) into position (low+1) */ - ELEM_SWAP(arr[middle], arr[low+1]) ; - - /* Nibble from each end towards middle, swapping items when stuck */ - ll = low + 1; - hh = high; - for (;;) { - do ll++; while (arr[low] > arr[ll]) ; - do hh--; while (arr[hh] > arr[low]) ; - - if (hh < ll) - break; - - ELEM_SWAP(arr[ll], arr[hh]) ; - } - - /* Swap middle item (in position low) back into correct position */ - ELEM_SWAP(arr[low], arr[hh]) ; - - /* Re-set active partition */ - if (hh <= median) - low = ll; - if (hh >= median) - high = hh - 1; - } -} - -int energyCalibrationFunctions::kth_smallest(int *a, int n, int k){ - register int i,j,l,m ; - register double x ; - - l=0 ; m=n-1 ; - while (lSetParNames("Background Offset","Background Slope","Inflection Point","Noise RMS", "Number of Photons","Charge Sharing Slope"); - - fspectrum=new TF1("fspectrum",funcs,&energyCalibrationFunctions::spectrum,0,1000,6,"energyCalibrationFunctions","spectrum"); - fspectrum->SetParNames("Background Pedestal","Background slope", "Peak position","Noise RMS", "Number of Photons","Charge Sharing Pedestal"); - -#endif - - -} - - - -void energyCalibration::fixParameter(int ip, Double_t val){ - - fscurve->FixParameter(ip, val); - fspectrum->FixParameter(ip, val); -} - - -void energyCalibration::releaseParameter(int ip){ - - fscurve->ReleaseParameter(ip); - fspectrum->ReleaseParameter(ip); -} - - - - - - - -energyCalibration::~energyCalibration(){ -#ifdef MYROOT - delete fscurve; - delete fspectrum; -#endif - -} - -#ifdef MYROOT - - - -TH1F* energyCalibration::createMedianHistogram(TH2F* h2, int ch0, int nch) { - - if (h2==NULL || nch==0) - return NULL; - - double *x=new double[nch]; - TH1F *h1=NULL; - - double val=-1; - double me=0; - - - h1=new TH1F("median","Median",h2->GetYaxis()->GetNbins(),h2->GetYaxis()->GetXmin(),h2->GetYaxis()->GetXmax()); - - - for (int ib=0; ibGetXaxis()->GetNbins(); ib++) { - me=0; - for (int ich=0; ichGetBinContent(ch0+ich+1,ib+1); - me+=x[ich]; - } - cout << ib << " calculating median ch0=" << ch0 << " nch=" << nch << endl; - val=energyCalibrationFunctions::median(x, nch); - cout << "median=" << val << " mean= " << me/nch << endl; - h1->SetBinContent(ib+1,val); - } - delete [] x; - return h1; - - - -} - - - - - - - - - - - - - - -void energyCalibration::setStartParameters(Double_t *par){ - bg_offset=par[0]; - bg_slope=par[1]; - flex=par[2]; - noise=par[3]; - ampl=par[4]; - cs_slope=par[5]; -} - - -void energyCalibration::getStartParameters(Double_t *par){ - par[0]=bg_offset; - par[1]=bg_slope; - par[2]=flex; - par[3]=noise; - par[4]=ampl; - par[5]=cs_slope; -} - -#endif -int energyCalibration::setChargeSharing(int p) { - if (p>=0) { - cs_flag=p; -#ifdef MYROOT - if (p) { - fscurve->ReleaseParameter(5); - fspectrum->ReleaseParameter(1); - } else { - fscurve->FixParameter(5,0); - fspectrum->FixParameter(1,0); - } -#endif - } - - return cs_flag; -} - - -#ifdef MYROOT -void energyCalibration::initFitFunction(TF1 *fun, TH1 *h1) { - - Double_t min=fit_min, max=fit_max; - - Double_t mypar[6]; - - if (max==-1) - max=h1->GetXaxis()->GetXmax(); - - if (min==-1) - min=h1->GetXaxis()->GetXmin(); - - - if (bg_offset==-1) - mypar[0]=0; - else - mypar[0]=bg_offset; - - - if (bg_slope==-1) - mypar[1]=0; - else - mypar[1]=bg_slope; - - - if (flex==-1) - mypar[2]=(min+max)/2.; - else - mypar[2]=flex; - - - if (noise==-1) - mypar[3]=0.1; - else - mypar[3]=noise; - - if (ampl==-1) - mypar[4]=h1->GetBinContent(h1->GetXaxis()->FindBin(0.5*(max+min))); - else - mypar[4]=ampl; - - if (cs_slope==-1) - mypar[5]=0; - else - mypar[5]=cs_slope; - - fun->SetParameters(mypar); - - fun->SetRange(min,max); - -} - - -TF1* energyCalibration::fitFunction(TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar) { - - - TF1* fitfun; - - char fname[100]; - - strcpy(fname, fun->GetName()); - - if (plot_flag) { - h1->Fit(fname,"R"); - } else - h1->Fit(fname,"R0Q"); - - - fitfun= h1->GetFunction(fname); - fitfun->GetParameters(mypar); - for (int ip=0; ip<6; ip++) { - emypar[ip]=fitfun->GetParError(ip); - } - return fitfun; -} - -TF1* energyCalibration::fitSCurve(TH1 *h1, Double_t *mypar, Double_t *emypar) { - initFitFunction(fscurve,h1); - return fitFunction(fscurve, h1, mypar, emypar); -} - - - - - -TF1* energyCalibration::fitSpectrum(TH1 *h1, Double_t *mypar, Double_t *emypar) { - initFitFunction(fspectrum,h1); - return fitFunction(fspectrum, h1, mypar, emypar); -} - - - -TGraphErrors* energyCalibration::linearCalibration(int nscan, Double_t *en, Double_t *een, Double_t *fl, Double_t *efl, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff) { - - TGraphErrors *gr; - - Double_t mypar[2]; - - gr = new TGraphErrors(nscan,en,fl,een,efl); - - if (plot_flag) { - gr->Fit("pol1"); - gr->SetMarkerStyle(20); - } else - gr->Fit("pol1","0Q"); - - TF1 *fitfun= gr->GetFunction("pol1"); - fitfun->GetParameters(mypar); - - egain=fitfun->GetParError(1); - eoff=fitfun->GetParError(0); - - gain=funcs->setScanSign()*mypar[1]; - off=mypar[0]; - - return gr; -} - - -TGraphErrors* energyCalibration::calibrate(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff, int integral) { - - TH1F *h; - - Double_t mypar[6], emypar[6]; - Double_t fl[nscan], efl[nscan]; - - - for (int ien=0; ien -#include -class TH1F; -class TH2F; -class TGraphErrors; -#endif - - - - - - - -const double conven=1000./3.6; /**< electrons/keV */ -const double el=1.67E-4; /**< electron charge in fC */ - - - -/** - \mainpage Common Root library for SLS detectors data analysis - * - * \section intro_sec Introduction - We know very well s-curves etc. but at the end everybody uses different functions ;-). - - * \subsection mot_sec Motivation - It would be greate to use everybody the same functions... - -*/ - - -/** - * - * -@libdoc The energiCalibration class contains all the necessary functions for s-curve fitting and linear calibration of the threshold. - * - * @short Energy calibration functions - * @author Anna Bergamaschi - * @version 0.1alpha - - - */ - -/** - class containing all the possible energy calibration functions (scurves with and without charge sharing, gaussian spectrum with and without charge sharing, possibility of chosing the sign of the X-axis) - -*/ -class energyCalibrationFunctions { - - public: - - energyCalibrationFunctions(int s=-1) {setScanSign(s);}; - - /** sets scan sign - \param s can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) otherwise gets - \returns current scan sign can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) - */ - int setScanSign(int s=0) {if (s==1 || s==-1) sign=s; return sign;};; - - -#ifdef MYROOT - /** - Gaussian Function with charge sharing pedestal - par[0] is the absolute height of the background pedestal - par[1] is the slope of the background pedestal - par[2] is the gaussian peak position - par[3] is the RMS of the gaussian (and of the pedestal) - par[4] is the height of the function - par[5] is the fractional height of the charge sharing pedestal (scales with par[3]) - */ - Double_t gaussChargeSharing(Double_t *x, Double_t *par); - - /** - Basic erf function - par[0] is the inflection point - par[1] is the RMS - par[2] is the amplitude - */ -Double_t erfFunction(Double_t *x, Double_t *par) ; - - /** Erf function with charge sharing slope - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point - par[3] is the RMS - par[4] is the amplitude - par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) - */ -Double_t erfFunctionChargeSharing(Double_t *x, Double_t *par); - - /** Double Erf function with charge sharing slope - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point of the first energy - par[3] is the RMS of the first energy - par[4] is the amplitude of the first energy - par[5] is the angual coefficient of the charge sharing slope of the first energy (scales with par[3]) - par[6] is the inflection point of the second energy - par[7] is the RMS of the second energy - par[8] is the amplitude of the second energy - par[9] is the angual coefficient of the charge sharing slope of the second energy (scales with par[8]) - */ - -Double_t erfFuncFluo(Double_t *x, Double_t *par); - - - /** - static function Gaussian with charge sharing pedestal with the correct scan sign - par[0] is the absolute height of the background pedestal - par[1] is the fractional height of the charge sharing pedestal (scales with par[3] - par[2] is the gaussian peak position - par[3] is the RMS of the gaussian (and of the pedestal) - par[4] is the height of the function - */ - Double_t spectrum(Double_t *x, Double_t *par); - - - /** Erf function with charge sharing slope with the correct scan sign - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point - par[3] is the RMS - par[4] is the amplitude - par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) - */ - Double_t scurve(Double_t *x, Double_t *par); - - - - /** Double Erf function with charge sharing slope - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point of the first energy - par[3] is the RMS of the first energy - par[4] is the amplitude of the first energy - par[5] is the angual coefficient of the charge sharing slope of the first energy (scales with par[3]) - par[6] is the inflection point of the second energy - par[7] is the RMS of the second energy - par[8] is the amplitude of the second energy - par[9] is the angual coefficient of the charge sharing slope of the second energy (scales with par[8]) - */ - Double_t scurveFluo(Double_t *x, Double_t *par); - -#endif - -/** Calculates the median of an array of n elements */ - static double median(double *x, int n); -/** Calculates the median of an array of n elements (swaps the arrays!)*/ - static int quick_select(int arr[], int n); -/** Calculates the median of an array of n elements (swaps the arrays!)*/ - static int kth_smallest(int *a, int n, int k); - - private: - int sign; - - -}; - -/** - class alowing the energy calibration of photon counting and anlogue detectors - -*/ - -class energyCalibration { - - - public: - /** - default constructor - creates the function with which the s-curves will be fitted - */ - energyCalibration(); - - /** - default destructor - deletes the function with which the s-curves will be fitted - */ - ~energyCalibration(); - - /** sets plot flag - \param p plot flag (-1 gets, 0 unsets, >0 plot) - \returns current plot flag - */ - int setPlotFlag(int p=-1) {if (p>=0) plot_flag=p; return plot_flag;}; - - /** sets scan sign - \param s can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) otherwise gets - \returns current scan sign can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) - */ - int setScanSign(int s=0) {return funcs->setScanSign(s);}; - - /** sets plot flag - \param p plot flag (-1 gets, 0 unsets, >0 plot) - \returns current plot flag - */ - int setChargeSharing(int p=-1); - - - void fixParameter(int ip, Double_t val); - - void releaseParameter(int ip); - -#ifdef MYROOT - - static TH1F* createMedianHistogram(TH2F* h2, int ch0, int nch); - - - /** sets the s-curve fit range - \param mi minimum of the fit range (-1 is histogram x-min) - \param ma maximum of the fit range (-1 is histogram x-max) - */ - void setFitRange(Double_t mi, Double_t ma){fit_min=mi; fit_max=ma;}; - - /** gets the s-curve fit range - \param mi reference for minimum of the fit range (-1 is histogram x-min) - \param ma reference for maximum of the fit range (-1 is histogram x-max) - */ - void getFitRange(Double_t &mi, Double_t &ma){mi=fit_min; ma=fit_max;}; - - -/** set start parameters for the s-curve function - \param par parameters, -1 sets to auto-calculation - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point - par[3] is the RMS - par[4] is the amplitude - par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) -- always positive - */ - void setStartParameters(Double_t *par); - -/** get start parameters for the s-curve function - \param par parameters, -1 means auto-calculated - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point - par[3] is the RMS - par[4] is the amplitude - par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) -- always positive - */ - void getStartParameters(Double_t *par); - - /** - fits histogram with the s-curve function - \param h1 1d-histogram to be fitted - \param mypar pointer to fit parameters array - \param emypar pointer to fit parameter errors - \returns the fitted function - can be used e.g. to get the Chi2 or similar - */ - TF1 *fitSCurve(TH1 *h1, Double_t *mypar, Double_t *emypar); - - - /** - fits histogram with the spectrum - \param h1 1d-histogram to be fitted - \param mypar pointer to fit parameters array - \param emypar pointer to fit parameter errors - \returns the fitted function - can be used e.g. to get the Chi2 or similar - */ - TF1 *fitSpectrum(TH1 *h1, Double_t *mypar, Double_t *emypar); - - - /** - calculates gain and offset for the set of inflection points - \param nscan number of energy scans - \param en array of energies (nscan long) - \param een array of errors on energies (nscan long) - can be NULL! - \param fl array of inflection points (nscan long) - \param efl array of errors on the inflection points (nscan long) - \param gain reference to gain resulting from the fit - \param off reference to offset resulting from the fit - \param egain reference to error on the gain resulting from the fit - \param eoff reference to the error on the offset resulting from the fit - \returns graph energy vs inflection point - */ - TGraphErrors* linearCalibration(int nscan, Double_t *en, Double_t *een, Double_t *fl, Double_t *efl, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff); - - /** - calculates gain and offset for the set of energy scans - \param nscan number of energy scans - \param en array of energies (nscan long) - \param een array of errors on energies (nscan long) - can be NULL! - \param h1 array of TH1 - \param gain reference to gain resulting from the fit - \param off reference to offset resulting from the fit - \param egain reference to error on the gain resulting from the fit - \param eoff reference to the error on the offset resulting from the fit - \returns graph energy vs inflection point - */ - TGraphErrors* calibrateScurves(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff){return calibrate(nscan, en, een, h1, gain, off, egain, eoff, 1);}; - - /** - calculates gain and offset for the set of energy spectra - \param nscan number of energy scans - \param en array of energies (nscan long) - \param een array of errors on energies (nscan long) - can be NULL! - \param h1 array of TH1 - \param gain reference to gain resulting from the fit - \param off reference to offset resulting from the fit - \param egain reference to error on the gain resulting from the fit - \param eoff reference to the error on the offset resulting from the fit - \returns graph energy vs peak - */ - TGraphErrors* calibrateSpectra(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff){return calibrate(nscan, en, een, h1, gain, off, egain, eoff, 0);}; - - -#endif - private: - -#ifdef MYROOT - /** - calculates gain and offset for the set of energies - \param nscan number of energy scans - \param en array of energies (nscan long) - \param een array of errors on energies (nscan long) - can be NULL! - \param h1 array of TH1 - \param gain reference to gain resulting from the fit - \param off reference to offset resulting from the fit - \param egain reference to error on the gain resulting from the fit - \param eoff reference to the error on the offset resulting from the fit - \param integral 1 is an s-curve set (default), 0 spectra - \returns graph energy vs peak/inflection point - */ - TGraphErrors* calibrate(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff, int integral=1); - - - /** - Initializes the start parameters and the range of the fit depending on the histogram characteristics and/or on the start parameters specified by the user - \param fun pointer to function to be initialized - \param h1 histogram from which to extract the range and start parameters, if not already specified by the user - -*/ - - void initFitFunction(TF1 *fun, TH1 *h1); - - - /** - Performs the fit according to the flags specified and returns the fitted function - \param fun function to fit - \param h1 histogram to fit - \param mypar pointer to fit parameters array - \param emypar pointer to fit parameter errors - \returns the fitted function - can be used e.g. to get the Chi2 or similar - */ - TF1 *fitFunction(TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar); - -#endif - -#ifdef MYROOT - Double_t fit_min; /**< minimum of the s-curve fitting range, -1 is histogram x-min */ - Double_t fit_max; /**< maximum of the s-curve fitting range, -1 is histogram x-max */ - - Double_t bg_offset; /**< start value for the background pedestal */ - Double_t bg_slope; /**< start value for the background slope */ - Double_t flex; /**< start value for the inflection point */ - Double_t noise; /**< start value for the noise */ - Double_t ampl; /**< start value for the number of photons */ - Double_t cs_slope; /**< start value for the charge sharing slope */ - - - TF1 *fscurve; /**< function with which the s-curve will be fitted */ - - TF1 *fspectrum; /**< function with which the spectrum will be fitted */ - -#endif - - energyCalibrationFunctions *funcs; - int plot_flag; /**< 0 does not plot, >0 plots (flags?) */ - - int cs_flag; /**< 0 functions without charge sharing contribution, >0 with charge sharing contribution */ - -}; - -#endif - - - - - - - - - - - - - - - - - - - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/energyCalibrationMacro.C b/slsDetectorSoftware/slsDetectorAnalysis/energyCalibrationMacro.C deleted file mode 100644 index 5a4c4386f..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/energyCalibrationMacro.C +++ /dev/null @@ -1,24 +0,0 @@ -{ - - TH1F *h1[3]; - TH2F *h2=createScan("/scratch/stability_test/ag_source_S%d_10.raw",500,900,10,1280*2); - h1[0]=getCh(h2,500); - h1[1]=getCh(h2,300); - h1[2]=getCh(h2,700); - Double_t gain, offset, eg, eo; - Double_t en[3]={20,22,24}; - TH1F *h; - energyCalibration *e=new energyCalibration(); - e->setFitRange(500,700); - Double_t mypar[6]; - mypar[0]=0; //pedestal - mypar[1]=0; //pedestal slope - mypar[2]=-1; //inflection point - must be free for all energies and will be set at half of the scan range - mypar[3]=10; //noise rms - mypar[4]=1000; //number of photons - mypar[5]=0; //charge sharing slope - e->setFitParameters(mypar); - - TGraphErrors *gr=e->calibrate(3,en,NULL,h1,gain,offset,eg,eo); - -} diff --git a/slsDetectorSoftware/slsDetectorAnalysis/energyConversion.cpp b/slsDetectorSoftware/slsDetectorAnalysis/energyConversion.cpp deleted file mode 100644 index 91a555caa..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/energyConversion.cpp +++ /dev/null @@ -1,614 +0,0 @@ -#include "energyConversion.h" - -#include -#include -#include -#include - -#include "fileIOStatic.h" - -using namespace std; - - - - -int energyConversion::readCalibrationFile(string fname, double &gain, double &offset){ - - string str; - ifstream infile; -#ifdef VERBOSE - std::cout<< "Opening file "<< fname << std::endl; -#endif - infile.open(fname.c_str(), ios_base::in); - if (infile.is_open()) { - getline(infile,str); -#ifdef VERBOSE - std::cout<< str << std::endl; -#endif - istringstream ssstr(str); - ssstr >> offset >> gain; - infile.close(); - cout << "Calibration file loaded: " << fname << endl; - } else { - std::cout<< "Could not open calibration file "<< fname << std::endl; - gain=0.; - offset=0.; -#ifndef MYROOT - return FAIL; -#endif - return -1; - } -#ifndef MYROOT - return OK; -#endif - return 0; -}; - -int energyConversion::writeCalibrationFile(string fname, double gain, double offset){ - //std::cout<< "Function not yet implemented " << std::endl; - ofstream outfile; - outfile.open (fname.c_str()); - - // >> i/o operations here << - if (outfile.is_open()) { - outfile << offset << " " << gain << std::endl; - } else { - std::cout<< "Could not open calibration file "<< fname << " for writing" << std::endl; -#ifndef MYROOT - return FAIL; -#endif - return -1; - } - - outfile.close(); - -#ifndef MYROOT - return OK; -#endif - return 0; -}; - - -int energyConversion::readCalibrationFile(string fname, int *gain, int *offset){ - - string str; - ifstream infile; - double o,g; - int ig=0; -#ifdef VERBOSE - std::cout<< "Opening file "<< fname << std::endl; -#endif - infile.open(fname.c_str(), ios_base::in); - if (infile.is_open()) { - //get gain and offset - for (ig=0; ig<4; ig++) { - //while ( (getline(infile,str)) > -1) { - getline(infile,str); -#ifdef VERBOSE - std::cout<< str << std::endl; -#endif - istringstream ssstr(str); - ssstr >> o >> g; - offset[ig]=(int)(o*1000); - gain[ig]=(int)(g*1000); - // ig++; - if (ig>=4) - break; - } - infile.close(); - cout << "Calibration file loaded: " << fname << endl; - } else { - cout << "Could not open calibration file: "<< fname << std::endl; - gain[0]=0; - offset[0]=0; -#ifndef MYROOT - return FAIL; -#endif - return -1; - } -#ifndef MYROOT - return OK; -#endif - return 0; - -}; - -int energyConversion::writeCalibrationFile(string fname, int *gain, int *offset){ - //std::cout<< "Function not yet implemented " << std::endl; - ofstream outfile; - outfile.open (fname.c_str()); - // >> i/o operations here << - if (outfile.is_open()) { - for (int ig=0; ig<4; ig++) - outfile << ((double)offset[ig]/1000) << " " << ((double)gain[ig]/1000) << std::endl; - } else { - std::cout<< "Could not open calibration file "<< fname << " for writing" << std::endl; -#ifndef MYROOT - return FAIL; -#endif - return -1; - } - - outfile.close(); -#ifndef MYROOT - return OK; -#endif - return 0; -}; - - - -slsDetectorDefs::sls_detector_module* energyConversion::interpolateTrim(detectorType myDetectorType, sls_detector_module* a, sls_detector_module* b, const int energy, const int e1, const int e2, int tb){ - // only implemented for eiger currently (in terms of which dacs) - if(myDetectorType != EIGER) { - printf("Interpolation of Trim values not implemented for this detector!\n"); - return NULL; - } - - sls_detector_module* myMod = createModule(myDetectorType); - enum eiger_DacIndex{SVP,VTR,VRF,VRS,SVN,VTGSTV,VCMP_LL,VCMP_LR,CAL,VCMP_RL,RXB_RB,RXB_LB,VCMP_RR,VCP,VCN,VIS}; - - //Copy other dacs - int dacs_to_copy[] = {SVP,VTR,SVN,VTGSTV,RXB_RB,RXB_LB,VCN,VIS}; - int num_dacs_to_copy = sizeof(dacs_to_copy) / sizeof(dacs_to_copy[0]); - for (int i = 0; i < num_dacs_to_copy; ++i) { - if(a->dacs[dacs_to_copy[i]] != b->dacs[dacs_to_copy[i]]) { - deleteModule(myMod); - return NULL; - } - myMod->dacs[dacs_to_copy[i]] = a->dacs[dacs_to_copy[i]]; - } - - - //Copy irrelevant dacs (without failing): CAL - if (a->dacs[CAL] != b->dacs[CAL]) { - printf("Warning: DAC CAL differs in both energies (%d, %d)! ", - a->dacs[CAL], b->dacs[CAL]); - printf("Taking first: %d\n", a->dacs[CAL]); - } - myMod->dacs[CAL] = a->dacs[CAL]; - - - //Interpolate vrf, vcmp, vcp - int dacs_to_interpolate[] = {VRF,VCMP_LL,VCMP_LR,VCMP_RL,VCMP_RR,VCP, VRS}; - int num_dacs_to_interpolate = sizeof(dacs_to_interpolate) / sizeof(dacs_to_interpolate[0]); - for (int i = 0; i < num_dacs_to_interpolate; ++i) { - myMod->dacs[dacs_to_interpolate[i]] = linearInterpolation(energy, e1, e2, - a->dacs[dacs_to_interpolate[i]], b->dacs[dacs_to_interpolate[i]]); - } - - //Interpolate all trimbits - if(tb) { - for (int i = 0; inchan; i++) - myMod->chanregs[i] = linearInterpolation(energy, e1, e2, a->chanregs[i], b->chanregs[i]); - } - return myMod; -} - - - -#ifndef MYROOT - -/* I/O */ - - -slsDetectorDefs::sls_detector_module* energyConversion::readSettingsFile(string fname, detectorType myDetectorType, int& iodelay, int& tau, sls_detector_module* myMod, int tb){ - - - - - int nflag=0; - - - if (myMod==NULL) { - myMod=createModule(myDetectorType); - nflag=1; - } - - int id=0,i; - string names[100]; - string myfname; - string str; - ifstream infile; - ostringstream oss; - int iline=0; - string sargname; - int ival; - int ichan=0, ichip=0, idac=0; - int nch=((myMod->nchan)/(myMod->nchip)); - - //ascii settings/trim file - switch (myDetectorType) { - case MYTHEN: - break; - case MOENCH: - names[id++]="Vdac0"; - names[id++]="Vdac1"; - names[id++]="Vdac2"; - names[id++]="Vdac3"; - names[id++]="Vdac4"; - names[id++]="Vdac5"; - names[id++]="Vdac6"; - names[id++]="Vdac7"; - break; - case GOTTHARD: - case PROPIX: - names[id++]="Vref"; - names[id++]="VcascN"; - names[id++]="VcascP"; - names[id++]="Vout"; - names[id++]="Vcasc"; - names[id++]="Vin"; - names[id++]="Vref_comp"; - names[id++]="Vib_test"; - break; - case EIGER: - break; - case JUNGFRAU: - names[id++]="VDAC0"; - names[id++]="VDAC1"; - names[id++]="VDAC2"; - names[id++]="VDAC3"; - names[id++]="VDAC4"; - names[id++]="VDAC5"; - names[id++]="VDAC6"; - names[id++]="VDAC7"; - names[id++]="VDAC8"; - names[id++]="VDAC9"; - names[id++]="VDAC10"; - names[id++]="VDAC11"; - names[id++]="VDAC12"; - names[id++]="VDAC13"; - names[id++]="VDAC14"; - names[id++]="VDAC15"; - break; - default: - cout << "Unknown detector type - unknown format for settings file" << endl; - return NULL; - } - -#ifdef VERBOSE - std::cout<< "reading settings file for module number "<< myMod->module << std::endl; -#endif - myfname=fname; -#ifdef VERBOSE - std::cout<< "file name is "<< myfname << std::endl; -#endif - - switch (myDetectorType) { - - case MYTHEN: - infile.open(myfname.c_str(), ios_base::in); - if (infile.is_open()) { - for (int iarg=0; iargndac; iarg++) { - getline(infile,str); - iline++; - istringstream ssstr(str); - ssstr >> sargname >> ival; -#ifdef VERBOSE - std::cout<< sargname << " dac nr. " << idac << " is " << ival << std::endl; -#endif - myMod->dacs[idac]=ival; - idac++; - } - for (ichip=0; ichipnchip; ichip++) { - getline(infile,str); - iline++; -#ifdef VERYVERBOSE - std::cout<< str << std::endl; -#endif - istringstream ssstr(str); - ssstr >> sargname >> ival; -#ifdef VERYVERBOSE - std::cout<< "chip " << ichip << " " << sargname << " is " << ival << std::endl; -#endif - - myMod->chipregs[ichip]=ival; - for (ichan=0; ichannChans <<" iline " << iline<< std::endl; -#endif - iline++; - myMod->chanregs[ichip*nch+ichan]=0; - for (int iarg=0; iarg<6 ; iarg++) { - ssstr >> ival; - //if (ssstr.good()) { - switch (iarg) { - case 0: -#ifdef VERYVERBOSE - std::cout<< "trimbits " << ival ; -#endif - myMod->chanregs[ichip*nch+ichan]|=ival&TRIMBITMASK; - break; - case 1: -#ifdef VERYVERBOSE - std::cout<< " compen " << ival ; -#endif - myMod->chanregs[ichip*nch+ichan]|=ival<<9; - break; - case 2: -#ifdef VERYVERBOSE - std::cout<< " anen " << ival ; -#endif - myMod->chanregs[ichip*nch+ichan]|=ival<<8; - break; - case 3: -#ifdef VERYVERBOSE - std::cout<< " calen " << ival ; -#endif - myMod->chanregs[ichip*nch+ichan]|=ival<<7; - break; - case 4: -#ifdef VERBOSE - std::cout<< " outcomp " << ival ; -#endif - myMod->chanregs[ichip*nch+ichan]|=ival<<10; - break; - case 5: -#ifdef VERBOSE - std::cout<< " counts " << ival << std::endl; -#endif - myMod->chanregs[ichip*nch+ichan]|=ival<<11; - break; - default: - std::cout<< " too many columns" << std::endl; - break; - } - } - } - // } - } -#ifdef VERBOSE - std::cout<< "read " << ichan*ichip << " channels" <dacs,sizeof(dacs_t)*(myMod->ndac)); - infile.read((char*)&iodelay,sizeof(iodelay)); - infile.read((char*)&tau,sizeof(tau)); -#ifdef VERBOSE - for(int i=0;indac;i++) - std::cout << "dac " << i << ":" << myMod->dacs[i] << std::endl; - std::cout << "iodelay:" << iodelay << std::endl; - std::cout << "tau:" << tau << std::endl; -#endif - if(tb) { - infile.read((char*) myMod->chanregs,sizeof(int)*(myMod->nchan)); - if(infile.eof()){ - cout<> sargname >> ival; - for (i=0;idacs[i]=ival; - idac++; -#ifdef VERBOSE - std::cout<< sargname << " dac nr. " << idac << " is " << ival << std::endl; -#endif - break; - } - } - } - if (i < id) { -#ifdef VERBOSE - std::cout<< sargname << " dac nr. " << idac << " is " << ival << std::endl; -#endif - }else - std::cout<< "Unknown dac " << sargname << std::endl; - - infile.close(); - strcpy(settingsFile,fname.c_str()); - printf("Settings file loaded: %s\n",settingsFile); - return myMod; - - } - - //---------------------------------- - break; - - default: - std::cout<< "Unknown detector type - don't know how to read file" << myfname << std::endl; - infile.close(); - deleteModule(myMod); - return NULL; - - } - - printf("Error: Could not open settings file %s\n", myfname.c_str()); - if (nflag) - deleteModule(myMod); - - return NULL; - - - -}; - - -int energyConversion::writeSettingsFile(string fname, detectorType myDetectorType, sls_detector_module mod, int iodelay, int tau){ - - ofstream outfile; - - int nch=((mod.nchan)/(mod.nchip)); - - string names[100]; - int id=0; - switch (myDetectorType) { - case MYTHEN: - names[id++]="Vtrim"; - names[id++]="Vthresh"; - names[id++]="Rgsh1"; - names[id++]="Rgsh2"; - names[id++]="Rgpr"; - names[id++]="Vcal"; - names[id++]="outBuffEnable"; - break; - case MOENCH: - names[id++]="Vdac0"; - names[id++]="Vdac1"; - names[id++]="Vdac2"; - names[id++]="Vdac3"; - names[id++]="Vdac4"; - names[id++]="Vdac5"; - names[id++]="Vdac6"; - names[id++]="Vdac7"; - break; - case GOTTHARD: - case PROPIX: - names[id++]="Vref"; - names[id++]="VcascN"; - names[id++]="VcascP"; - names[id++]="Vout"; - names[id++]="Vcasc"; - names[id++]="Vin"; - names[id++]="Vref_comp"; - names[id++]="Vib_test"; - break; - case EIGER: - break; - case JUNGFRAU: - names[id++]="VDAC0"; - names[id++]="VDAC1"; - names[id++]="VDAC2"; - names[id++]="VDAC3"; - names[id++]="VDAC4"; - names[id++]="VDAC5"; - names[id++]="VDAC6"; - names[id++]="VDAC7"; - names[id++]="VDAC8"; - names[id++]="VDAC9"; - names[id++]="VDAC10"; - names[id++]="VDAC11"; - names[id++]="VDAC12"; - names[id++]="VDAC13"; - names[id++]="VDAC14"; - names[id++]="VDAC15"; - break; - default: - cout << "Unknown detector type - unknown format for settings file" << endl; - return FAIL; - } - - int iv, ichan, ichip; - int iv1, idac; - int nb; - - switch (myDetectorType) { - case EIGER: - outfile.open(fname.c_str(), ofstream::binary); - if (outfile.is_open()) { - iv = 1150; -#ifdef VERBOSE - for(int i=0;i(&iodelay), sizeof(iodelay)); - outfile.write(reinterpret_cast(&tau), sizeof(tau)); - outfile.write((char*)mod.chanregs, sizeof(int)*(mod.nchan)); - - outfile.close(); - return slsDetectorDefs::OK; - } - - printf("Could not open Settings file %s\n", fname.c_str()); - return slsDetectorDefs::FAIL; - default: - - - outfile.open(fname.c_str(), ios_base::out); - - if (outfile.is_open()) { - for (idac=0; idac>nb); - outfile << iv1 << " "; - nb=8; - iv1=((iv&(1<>nb); - outfile << iv1 << " "; - nb=7; - iv1=((iv&(1<>nb); - outfile <>nb); - outfile << iv1 << " "; - nb=11; - iv1= ((iv&0xfffff800)>>nb); - outfile << iv1 << std::endl; - } - } - } - outfile.close(); - return OK; - } - std::cout<< "could not open SETTINGS file " << fname << std::endl; - return FAIL; - - } - - -}; - - - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/energyConversion.h b/slsDetectorSoftware/slsDetectorAnalysis/energyConversion.h deleted file mode 100644 index 518c75c34..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/energyConversion.h +++ /dev/null @@ -1,147 +0,0 @@ -#ifndef ENERGYCONVERSION_H -#define ENERGYCONVERSION_H - -#ifdef __CINT__ -#define MYROOT -#define __cplusplus -#endif - -//#ifndef MYROOT -//#include "sls_receiver_defs.h" -#include "sls_detector_defs.h" -//#endif -#include -#include - - -/** - @short class handling the energy calibration and trim files IO -*/ - - -class energyConversion -//#ifndef MYROOT -: private virtual slsDetectorDefs - //#endif -{ - public: - /** default constrauctor */ - energyConversion(){}; - /** default destructor */ - virtual ~energyConversion(){}; - - - /** - reads a calibration file - \param fname file to be read - \param gain reference to the gain variable - \param offset reference to the offset variable - \returns OK if successful, else FAIL or -1 - - */ - static int readCalibrationFile(std::string fname, double &gain, double &offset); - - /** - writes a calibration file - \param fname file to be written - \param gain - \param offset - \returns OK if successful, else FAIL or -1 - */ - static int writeCalibrationFile(std::string fname, double gain, double offset); - - /** - reads a calibration file - \param fname file to be read - \param gain reference to the gain variable - \param offset reference to the offset variable - \returns OK if successful, else FAIL or -1 - */ - static int readCalibrationFile(std::string fname, int *gain, int *offset); - - /** - writes a calibration file - \param fname file to be written - \param gain reference to the gain variable - \param offset reference to the offset variable - \returns OK if successful, else FAIL or -1 - */ - static int writeCalibrationFile(std::string fname, int *gain, int *offset); - - - - //Template function to do linear interpolation between two points - template - V linearInterpolation(const E x, const E x1, const E x2, const V y1, const V y2){ - double k = static_cast(y2-y1)/(x2-x1); - double m = y1-k*x1; - int y = round( k*x+m ); - return static_cast(y); - } - - - /** - * interpolates dacs and trimbits between 2 trim files - \param myDetectorType detector type (needed for which dacs that neeeds to be interpolated & which kept same) - \param a first module structure - \param b second module structure - \param energy energy to trim at - \param e1 reference trim value - \param e2 reference trim value - \param tb 1 to include trimbits, 0 to exclude (used for eiger) - \returns the pointer to the module structure with interpolated values or NULL if error - */ - sls_detector_module* interpolateTrim(detectorType myDetectorType, sls_detector_module* a, sls_detector_module* b, const int energy, const int e1, const int e2, int tb=1); - - - -#ifndef MYROOT - - /** - reads a trim/settings file - \param fname name of the file to be read - \param myDetectorType detector type (needed for number of channels, chips, dacs etc.) - \param iodelay io delay (detector specific) - \param tau tau (detector specific) - \param myMod pointer to the module structure which has to be set.
If it is NULL a new module structure will be created - \param tb 1 to include trimbits, 0 to exclude (used for eiger) - \returns the pointer to myMod or NULL if reading the file failed - */ - - sls_detector_module* readSettingsFile(std::string fname, detectorType myDetectorType, int& iodelay, int& tau, sls_detector_module* myMod=NULL, int tb=1); - - /** - writes a trim/settings file - \param fname name of the file to be written - \param myDetectorType detector type (needed for number of channels, chips, dacs etc.) - \param mod module structure which has to be written to file - \param iodelay io delay (detector specific) - \param tau tau (detector specific) - \returns OK or FAIL if the file could not be written - - \sa ::sls_detector_module mythenDetector::writeSettingsFile(string, sls_detector_module) - */ - int writeSettingsFile(std::string fname, detectorType myDetectorType, sls_detector_module mod, int iodelay, int tau); - - /** allocates the momery for a detector module structure - \param myDetectorType detector type (needed for number of channels, chips, dacs etc.) - \returns pointer to detector module - */ - virtual sls_detector_module* createModule(detectorType myDetectorType)=0; - - /** - frees the memory of a detector module structure - \param myMod pointer to memeory to be freed - */ - virtual void deleteModule(sls_detector_module *myMod)=0; - - - protected: - /** pointer to settings file name */ - char *settingsFile; - - -#endif - -}; -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/fileIO.cpp b/slsDetectorSoftware/slsDetectorAnalysis/fileIO.cpp deleted file mode 100644 index 3bf92d45a..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/fileIO.cpp +++ /dev/null @@ -1,204 +0,0 @@ -#include "fileIO.h" - -using namespace std; - - -/* I/O */ - -/* generates file name without extension*/ - -string fileIO::createFileName() { - - pthread_mutex_lock(&mf); - currentFileName=fileIOStatic::createFileName(filePath, \ - fileName, \ - getActionMask(), \ - getCurrentScanVariable(0), \ - getScanPrecision(0), \ - getCurrentScanVariable(1), \ - getScanPrecision(1), \ - getCurrentPositionIndex(), \ - getNumberOfPositions(), \ - *fileIndex, \ - frameIndex, \ - detIndex \ - ); - - //if (getDetectorsType()==JUNGFRAUCTB) { - // nBytes=2*getTotalNumberOfChannels(); - //} else - nBytes=getDataBytes(); - pthread_mutex_unlock(&mf); - return currentFileName; - -} - - - -/* generates file prefix for receivers */ - -string fileIO::createReceiverFilePrefix() { - pthread_mutex_lock(&mf); - currentReceiverFilePrefix=fileIOStatic::createReceiverFilePrefix(fileName, \ - getActionMask(), \ - getCurrentScanVariable(0), \ - getScanPrecision(0), \ - getCurrentScanVariable(1), \ - getScanPrecision(1), \ - getCurrentPositionIndex(), \ - getNumberOfPositions(), \ - detIndex \ - ); - pthread_mutex_unlock(&mf); - return currentReceiverFilePrefix; - -} - - - -/*writes raw data file */ - -int fileIO::writeDataFile(string fname, double *data, double *err, double *ang, char dataformat, int nch){ - if (nch==-1) - nch=getTotalNumberOfChannels(); - - // cout << "Write filexxx...." << endl; - - return fileIOStatic::writeDataFile(fname, nch, data, err, ang, dataformat); - -} -int fileIO::writeDataFile(ofstream &outfile, double *data, double *err, double *ang, char dataformat, int nch, int offset){ - if (nch==-1) - nch=getTotalNumberOfChannels(); - - //cout << "Write file...." << endl; - - return fileIOStatic::writeDataFile(outfile, nch, data, err, ang, dataformat, offset); - -} - - -int fileIO::writeDataFile(string fname, int *data){ - - return fileIOStatic::writeDataFile(fname, getTotalNumberOfChannels(), data); -} - - - - -int fileIO::writeDataFile(ofstream &outfile, int *data, int offset){ - - // cout << "Write raw file...." << endl; - return fileIOStatic::writeDataFile(outfile, getTotalNumberOfChannels(), data, offset); -} - - - -int fileIO::writeDataFile(void *data, int iframe) { - - if (iframe<0) - iframe=frameIndex; - - if ((*framesPerFile)<2) - iframe=-1; - - if ((iframe%(*framesPerFile))==0 || (iframe<0) || filefd==0) { - createFileName(); - filefd = fopen((currentFileName+string(".raw")).c_str(), "w"); - } - - if (filefd){ -// fileIOStatic::writeBinaryDataFile(filefd,getDataBytes(), data); - cout <<"Writing "<< nBytes<< " dataBytes"<< endl; - fileIOStatic::writeBinaryDataFile(filefd,nBytes, data); - iframe++; - } - - if ((iframe%(*framesPerFile)==0) || (iframe<0)) { - if (filefd) - fclose(filefd); - filefd=NULL; - } - return 0; -} - - - -int fileIO::closeDataFile() { - // cout << "close file...." << endl; - if (filefd) - fclose(filefd); - filefd=NULL; - return 0; -} - - - - - -int fileIO::writeDataFile(string fname, short int *data){ - - cout << "Write raw file...." << endl; - return fileIOStatic::writeDataFile(fname, getTotalNumberOfChannels(), data); -} - - - - - - - - - -int fileIO::writeDataFile(ofstream &outfile, short int *data, int offset){ - - return fileIOStatic::writeDataFile(outfile, getTotalNumberOfChannels(), data, offset); -} - - - - - - - - - - -int fileIO::readDataFile(string fname, double *data, double *err, double *ang, char dataformat) { - return fileIOStatic::readDataFile(getTotalNumberOfChannels(), fname, data, err, ang, dataformat); - -} - -int fileIO::readDataFile(ifstream &infile, double *data, double *err, double *ang, char dataformat, int offset) { - return fileIOStatic::readDataFile(getTotalNumberOfChannels(), infile, data, err, ang, dataformat, offset); - -} - - - -int fileIO::readDataFile(string fname, int *data){ - - return fileIOStatic::readDataFile(fname, data, getTotalNumberOfChannels()); -}; - - -int fileIO::readDataFile(ifstream &infile, int *data, int offset){ - - return fileIOStatic::readDataFile(infile, data, getTotalNumberOfChannels(), offset); -}; - - - - - -int fileIO::readDataFile(string fname, short int *data){ - - return fileIOStatic::readDataFile(fname, data, getTotalNumberOfChannels()); -}; - - -int fileIO::readDataFile(ifstream &infile, short int *data, int offset){ - - return fileIOStatic::readDataFile(infile, data, getTotalNumberOfChannels(),offset); -}; - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/fileIO.h b/slsDetectorSoftware/slsDetectorAnalysis/fileIO.h deleted file mode 100644 index 1cc70cf55..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/fileIO.h +++ /dev/null @@ -1,420 +0,0 @@ -#ifndef FILEIO_H -#define FILEIO_H - -#include "slsDetectorBase.h" -#include "fileIOStatic.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// -/** - @short class handling the data file I/O flags -*/ - -class fileIO : public fileIOStatic, public virtual slsDetectorBase { - - - public: - - /* enum rawFileFormat { */ -/* ASCII, */ -/* BINARY */ -/* } */ - - - /** default constructor */ - fileIO(): fileIOStatic(){ - currentFrameIndex=-1; - frameIndex=-1; - detIndex=-1; - framesPerFile=&nframes; - nframes=1; - filefd = NULL; - pthread_mutex_t mp1 = PTHREAD_MUTEX_INITIALIZER; - mf=mp1; - pthread_mutex_init(&mf, NULL); - }; - - /** virtual destructor */ - virtual ~fileIO(){}; - - using fileIOStatic::readDataFile; - using fileIOStatic::writeDataFile; - using fileIOStatic::createFileName; - - int getFileIndexFromFileName(std::string fname){ - int ret; - pthread_mutex_lock(&mf); - ret=fileIOStatic::getFileIndexFromFileName(fname); - pthread_mutex_unlock(&mf); - return ret; - }; - int getIndicesFromFileName(std::string fname, int &index){ - int ret; - pthread_mutex_lock(&mf); - ret=fileIOStatic::getIndicesFromFileName(fname,index); - pthread_mutex_unlock(&mf); - return ret; - }; - - - - int getVariablesFromFileName(std::string fname, int &index, int &p_index, double &sv0, double &sv1){ - - int ret; - pthread_mutex_lock(&mf); - ret=fileIOStatic::getVariablesFromFileName(fname, index, p_index, sv0, sv1); - pthread_mutex_unlock(&mf); - return ret; - }; - - int getVariablesFromFileName(std::string fname, int &index, int &f_index, int &p_index, double &sv0, double &sv1, int &detindex){ - - - int ret; - pthread_mutex_lock(&mf); - ret=fileIOStatic::getVariablesFromFileName(fname, f_index, index, p_index, sv0, sv1, detindex); - pthread_mutex_unlock(&mf); - return ret; - }; - - /** - sets the default output files path - \param s file path - \return actual file path - */ - virtual std::string setFilePath(std::string s) { - pthread_mutex_lock(&mf); - sprintf(filePath, "%s", s.c_str()); - pthread_mutex_unlock(&mf); - return std::string(filePath); - }; - - /** - sets the default output files root name - \param s file name to be set - \returns actual file name - */ - virtual std::string setFileName(std::string s) { - pthread_mutex_lock(&mf); - sprintf(fileName, "%s", s.c_str()); - pthread_mutex_unlock(&mf); - return std::string(fileName);}; - - /** - sets the default output file index - \param i start file index to be set - \returns actual file index - */ - virtual int setFileIndex(int i) { - pthread_mutex_lock(&mf); - *fileIndex=i; - pthread_mutex_unlock(&mf); - return *fileIndex; - }; - - /** - sets the default output file frame index - \param i file frame index to be set - \returns actual file frame index - */ - virtual int setFrameIndex(int i) { - pthread_mutex_lock(&mf); - frameIndex=i; - pthread_mutex_unlock(&mf); - return frameIndex;}; - - /** - sets the default output current frame index - \param i current frame index to be set - \returns actual current frame index - */ - virtual int setCurrentFrameIndex(int i) { - pthread_mutex_lock(&mf); - currentFrameIndex=i; - pthread_mutex_unlock(&mf); - return currentFrameIndex; - }; - - /** - sets the default output file index - \param i frame index to be set - \returns actual frame index - */ - virtual int setFramesPerFile(int i) { - pthread_mutex_lock(&mf); - if (i>0) *framesPerFile=i; - pthread_mutex_unlock(&mf); - return *framesPerFile;}; - - /** - sets the default output file index - \param i detector index to be set - \returns actual detector index - */ - virtual int setDetectorIndex(int i) { - pthread_mutex_lock(&mf); - detIndex=i; - pthread_mutex_unlock(&mf); - return detIndex;}; - - /** - sets the default file format - \param i file format to be set - \returns actual file frame format - */ - virtual fileFormat setFileFormat(int i) { - pthread_mutex_lock(&mf); - *fileFormatType=(fileFormat)i; - pthread_mutex_unlock(&mf); - return *fileFormatType; }; - - - - /** - \returns the output files path - - */ - virtual std::string getFilePath() {return std::string(filePath);}; - /** - \returns the output files root name - */ - virtual std::string getFileName() {return std::string(fileName);}; - - /** - \returns the output file index - */ - virtual int getFileIndex() {return *fileIndex;}; - - /** - \returns the output file frame index - */ - virtual int getFrameIndex() {return frameIndex;}; - - /** - \returns the output current frame index - */ - virtual int getCurrentFrameIndex() {return currentFrameIndex;}; - - /** - \returns the detector index - */ - virtual int getDetectorIndex() {return detIndex;}; - - /** - \returns the max frames per file - */ - virtual int getFramesPerFile() {return *framesPerFile;}; - - /** - \returns the max frames per file - */ - virtual fileFormat getFileFormat() {return *fileFormatType;}; - - - std::string createFileName(); - - std::string createReceiverFilePrefix(); - - - /** - writes a data file - \param fname of the file to be written - \param data array of data values - \param err array of arrors on the data. If NULL no errors will be written - \param ang array of angular values. If NULL data will be in the form chan-val(-err) otherwise ang-val(-err) - \param dataformat format of the data: can be 'i' integer or 'f' double (default) - \param nch number of channels to be written to file. if -1 defaults to the number of installed channels of the detector - \returns OK or FAIL if it could not write the file or data=NULL - */ - virtual int writeDataFile(std::string fname, double *data, double *err=NULL, double *ang=NULL, char dataformat='f', int nch=-1); - - - /** - - writes a data file - \param outfile output file stream - \param data array of data values - \param err array of arrors on the data. If NULL no errors will be written - - \param ang array of angular values. If NULL data will be in the form chan-val(-err) otherwise ang-val(-err) - \param dataformat format of the data: can be 'i' integer or 'f' double (default) - \param nch number of channels to be written to file. if -1 defaults to the number of installed channels of the detector - \param offset start channel number - \returns OK or FAIL if it could not write the file or data=NULL - - */ - virtual int writeDataFile(std::ofstream &outfile, double *data, double *err=NULL, double *ang=NULL, char dataformat='f', int nch=-1, int offset=0); - - - /** - writes a data file - \param fname of the file to be written - \param data array of data values - \returns OK or FAIL if it could not write the file or data=NULL - */ - virtual int writeDataFile(std::string fname, int *data); - - - virtual int writeDataFile(void *data, int iframe=-1); - - int closeDataFile(); - /** - writes a data file - \param outfile output file stream - \param data array of data values - \param offset start channel number - \returns OK or FAIL if it could not write the file or data=NULL - */ - virtual int writeDataFile(std::ofstream &outfile, int *data, int offset=0); - - - - /** - writes a data file of short ints - \param fname of the file to be written - \param data array of data values - \returns OK or FAIL if it could not write the file or data=NULL - */ - virtual int writeDataFile(std::string fname, short int *data); - - - - - - - - /** - writes a data file of short ints - \param outfile output file stream - \param data array of data values - \param offset start channel number - \returns OK or FAIL if it could not write the file or data=NULL - */ - virtual int writeDataFile(std::ofstream &outfile, short int *data, int offset=0); - - - /** - reads a data file - \param fname of the file to be read - \param data array of data values to be filled - \param err array of arrors on the data. If NULL no errors are expected on the file - - \param ang array of angular values. If NULL data are expected in the form chan-val(-err) otherwise ang-val(-err) - \param dataformat format of the data: can be 'i' integer or 'f' double (default) - \returns OK or FAIL if it could not read the file or data=NULL - */ - virtual int readDataFile(std::string fname, double *data, double *err=NULL, double *ang=NULL, char dataformat='f'); - - /** - reads a data file - \param ifstream input file stream - \param data array of data values to be filled - \param err array of arrors on the data. If NULL no errors are expected on the file - - \param ang array of angular values. If NULL data are expected in the form chan-val(-err) otherwise ang-val(-err) - \param offset start channel number to be expected - \returns OK or FAIL if it could not read the file or data=NULL - */ - int readDataFile(std::ifstream& infile, double *data, double *err=NULL, double *ang=NULL, char dataformat='f', int offset=0); - - /** - reads a raw data file - \param fname of the file to be read - \param data array of data values - \returns OK or FAIL if it could not read the file or data=NULL -yes */ - virtual int readDataFile(std::string fname, int *data); - -/** - reads a raw data file - \param infile input file stream - \param data array of data values - \param offset first channel number to be expected - \returns OK or FAIL if it could not read the file or data=NULL - */ - int readDataFile(std::ifstream &infile, int *data, int offset=0); - - /** - - reads a short int raw data file - \param fname of the file to be read - \param data array of data values - \returns OK or FAIL if it could not read the file or data=NULL - */ - virtual int readDataFile(std::string fname, short int *data); - /** - reads a short int raw data file - \param infile input file stream - \param data array of data values - \param offset first channel number to be expected - \returns OK or FAIL if it could not read the file or data=NULL - */ - int readDataFile(std::ifstream &infile, short int *data, int offset=0); - - virtual int getDataBytes ( )=0; - friend class slsDetector; - - std::string getCurrentFileName(){return currentFileName;}; - protected: - - - void incrementFileIndex() { (*fileIndex)++; }; - - void incrementFrameIndex(int i) { frameIndex=frameIndex+i; }; - - void incrementCurrentFrameIndex() { (currentFrameIndex)++; }; - - void incrementDetectorIndex() { (detIndex)++; }; - - - std::string getCurrentReceiverFilePrefix(){return currentReceiverFilePrefix;}; - - - std::string currentFileName; - - std::string currentReceiverFilePrefix; - - - /** output directory */ - char *filePath; - /** file root name */ - char *fileName; - /** file index */ - int *fileIndex; - /** file frame index */ - int frameIndex; - /** current frame index */ - int currentFrameIndex; - /** detector id */ - int detIndex; - /** frames per file */ - int *framesPerFile; - /** file format */ - fileFormat *fileFormatType; - - private: - - - FILE *filefd; - std::ofstream fstream; - - int nframes; - // int fformat; - - - int nBytes; - - /** mutex to synchronize read/write fname */ - pthread_mutex_t mf; -}; - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/fileIOStatic.h b/slsDetectorSoftware/slsDetectorAnalysis/fileIOStatic.h deleted file mode 100644 index c76800791..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/fileIOStatic.h +++ /dev/null @@ -1,730 +0,0 @@ -#ifndef FILEIO_STATIC_H -#define FILEIO_STATIC_H - -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef __CINT -#define MYROOT -#endif - -using std::endl; -using std::cout; - -#include "sls_detector_defs.h" -// -/** - @short class handling the data file I/O flags -*/ - -class fileIOStatic { - - - - - public: - /** default constructor */ - fileIOStatic(){}; - /** virtual de`structor */ - virtual ~fileIOStatic(){}; - - - - - /** generates file name without extension - - always appends to file path and file name the run index. - - in case also appends the position index and the two level of scan varaibles with the specified precision - - Filenames will be of the form: filepath/(dz_)filename(_Sy_sw_px_fv)_i - where z is the detector index, y is the scan0 variable, W is the scan 1 variable, x is the position index, v is the frame index and i is the run index - \param filepath outdir - \param filename file root name - \param aMask action mask (scans, positions) - \param sv0 scan variable 0 - \param prec0 scan precision 0 - \param sv1 scan variable 1 - \param prec1 scan precision 1 - \param pindex position index - \param npos number of positions - \param findex file index - \param frameindex frame index - \param detindex detector id - \returns file name without extension - */ - static std::string createFileName(char *filepath, char *filename, int aMask, double sv0, int prec0, double sv1, int prec1, int pindex, int npos, int findex, int frameindex=-1, int detindex=-1){ \ - std::ostringstream osfn; \ - osfn << filepath << "/" << filename; \ - if ( aMask& (1 << (slsDetectorDefs::MAX_ACTIONS))) osfn << "_S" << std::fixed << std::setprecision(prec0) << sv0; \ - if (aMask & (1 << (slsDetectorDefs::MAX_ACTIONS+1))) osfn << "_s" << std::fixed << std::setprecision(prec1) << sv1; \ - if (pindex>0 && pindex<=npos) osfn << "_p" << pindex; \ - if(detindex>=0) osfn << "_d"<< detindex; \ - if(frameindex>=0) osfn << "_f" << frameindex; \ - osfn << "_" << findex; \ - return osfn.str(); \ - }; - - - /** generates file prefix for receivers without file path, frame index, file index or extension - - in case also appends the position index and the two level of scan varaibles with the specified precision - - File prefix will be of the form: (dz_)filename(_Sy_sw_px_) - where z is the detector index, y is the scan0 variable, W is the scan 1 variable and x is the position index - \param filename file root name - \param aMask action mask (scans, positions) - \param sv0 scan variable 0 - \param prec0 scan precision 0 - \param sv1 scan variable 1 - \param prec1 scan precision 1 - \param pindex position index - \param npos number of positions - \param detindex detector id - \returns file name without extension - */ - static std::string createReceiverFilePrefix(char *filename, int aMask, double sv0, int prec0, double sv1, int prec1, int pindex, int npos,int detindex=-1){ \ - std::ostringstream osfn; \ - osfn << filename; \ - if ( aMask& (1 << (slsDetectorDefs::MAX_ACTIONS))) osfn << "_S" << std::fixed << std::setprecision(prec0) << sv0; \ - if (aMask & (1 << (slsDetectorDefs::MAX_ACTIONS+1))) osfn << "_s" << std::fixed << std::setprecision(prec1) << sv1; \ - if (pindex>0 && pindex<=npos) osfn << "_p" << pindex; \ - if(detindex!=-1) osfn << "_d"<< detindex; \ - return osfn.str(); \ - }; - - - /** static function that returns the file index from the file name - \param fname file name - \returns file index - */ - static int getFileIndexFromFileName(std::string fname){ \ - int i; \ - size_t dot=fname.rfind("."); \ - if (dot==std::string::npos) \ - return -1; \ - size_t uscore=fname.rfind("_"); \ - if (uscore==std::string::npos) return -1; \ - if (sscanf( fname.substr(uscore+1,dot-uscore-1).c_str(),"%d",&i)) return i; \ - cout << "******************************** cannot parse file index" << endl; \ - return 0; \ - }; - - /** static function that returns the frame index and file index from the file name - \param fname file name - \param index reference to index - \returns frame index - */ - static int getIndicesFromFileName(std::string fname,int &index){ \ - int i; \ - std::string s; \ - size_t uscore=fname.rfind("_"); \ - if (uscore==std::string::npos) return -1; \ - s=fname; \ - if (sscanf(s.substr(uscore+1,s.size()-uscore-1).c_str(),"%d",&i)){ \ - index=i; \ - s=fname.substr(0,uscore); \ - } \ - /*else cout << "******************************** cannot parse file index" << endl; \*/ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"f%d",&i)){ \ - if(i==-1)return 0; \ - else return i; } \ - /*cout << "******************************** cannot parse frame index" << endl; \*/ - return 0; \ - }; - - - /** static function that returns the variables from the file name - \param fname file name - \param index reference to index - \param p_index reference to position index - \param sv0 reference to scan variable 0 - \param sv1 reference to scan variable 1 - \returns file index - */ - static int getVariablesFromFileName(std::string fname, int &index, int &p_index, double &sv0, double &sv1) { \ - int i; \ - double f; \ - std::string s; \ - index=-1; \ - p_index=-1; \ - sv0=-1; \ - sv1=-1; \ - size_t uscore=fname.rfind("_"); \ - if (uscore==std::string::npos) return -1; \ - s=fname; \ - if (sscanf(s.substr(uscore+1,s.size()-uscore-1).c_str(),"%d",&i)) { \ - index=i; \ - s=fname.substr(0,uscore); \ - } \ - /* else cout << "Warning: ******************************** cannot parse file index from " << s << endl; \*/ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"f%d",&i)) \ - s=fname.substr(0,uscore); \ - /*else cout << "Warning: ******************************** cannot parse frame index from " << s << endl; \*/ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"d%d",&i)) \ - s=fname.substr(0,uscore); \ - /* else cout << "Warning: ******************************** cannot parse detector index from " << s << endl; \*/ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"p%d",&i)) { \ - p_index=i; \ - s=fname.substr(0,uscore); \ - } \ - /* else cout << "Warning: ******************************** cannot parse position index from " << s << endl; \*/ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"s%lf",&f)) { \ - sv1=f; \ - s=fname.substr(0,uscore); \ - } \ - /* else cout << "Warning: ******************************** cannot parse scan varable 1 from " << s << endl; \*/ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"S%lf",&f)) { \ - sv0=f; \ - } \ - /* else cout << "Warning: ******************************** cannot parse scan varable 0 from " << s << endl; \*/ - return index; \ - }; - - - /** static function that returns the variables from the file name - \param fname file name - \param index reference to index - \param f_index reference to frame index - \param p_index reference to position index - \param sv0 reference to scan variable 0 - \param sv1 reference to scan variable 1 - \param detindex reference to detector id - \returns file index - */ - static int getVariablesFromFileName(std::string fname, int &index, int &f_index, int &p_index, double &sv0, double &sv1, int &detindex) { \ - int i; \ - double f; \ - std::string s; \ - index=-1; \ - p_index=-1; \ - sv0=-1; \ - sv1=-1; \ - size_t uscore=fname.rfind("_"); \ - if (uscore==std::string::npos) return -1; \ - s=fname; \ - if (sscanf(s.substr(uscore+1,s.size()-uscore-1).c_str(),"%d",&i)) { \ - index=i; \ - s=fname.substr(0,uscore); \ - } \ - /*else cout << "Warning: ******************************** cannot parse file index" << endl; \*/ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"f%d",&i)) { \ - f_index=i; \ - s=fname.substr(0,uscore); \ - } \ - /*else cout << "Warning: ******************************** cannot parse frame index" << endl; \*/ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"d%d",&i)) { \ - detindex=i; \ - s=fname.substr(0,uscore); \ - } \ - /* else cout << "Warning: ******************************** cannot parse detector id" << endl; \*/ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"p%d",&i)) { \ - p_index=i; \ - s=fname.substr(0,uscore); \ - } \ - /*else cout << "Warning: ******************************** cannot parse position index" << endl; \*/ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"s%lf",&f)) { \ - sv1=f; \ - s=fname.substr(0,uscore); \ - } \ - /*else cout << "Warning: ******************************** cannot parse scan varable 1" << endl; \*/ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"S%lf",&f)) { \ - sv0=f; \ - s=fname.substr(0,uscore); \ - } \ - /*else cout << "Warning: ******************************** cannot parse scan varable 0" << endl; \*/ - - return index; \ - }; - - - /** static function that verifies if the new file name containing new parameters matches all the given parameters - \param fname new complete file name prefix - \param index reference to index - \param f_index reference to frame index - \param p_index reference to position index - \param sv0 reference to scan variable 0 - \param sv1 reference to scan variable 1 - \param detindex reference to detector id - \returns file name - */ - static int verifySameFrame(std::string fname, int index, int f_index, int p_index, double sv0, double sv1, int detindex) { \ - int new_index=-1; - int new_f_index=-1; - int new_p_index=-1; - int new_det_index=-1; - double new_sv0=-1; - double new_sv1=-1; - getVariablesFromFileName(fname,new_index, new_f_index, new_p_index, new_sv0, new_sv1, new_det_index); - if(index!=new_index) return 0; - if(f_index!=new_f_index) return 0; - if(p_index!=new_p_index) return 0; - if(sv0!=new_sv0) return 0; - if(sv1!=new_sv1) return 0; - return 1; - } - - - /** static function that returns the name variable from the receiver complete file name prefix - \param fname complete file name prefix - \returns file name - */ - static std::string getNameFromReceiverFilePrefix(std::string fname) { \ - int i; \ - double f; \ - std::string s; \ - s=fname; \ - size_t uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"d%d",&i)) \ - s=fname.substr(0,uscore); \ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"p%d",&i)) \ - s=fname.substr(0,uscore); \ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"s%lf",&f)) \ - s=fname.substr(0,uscore); \ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"S%lf",&f)) \ - s=fname.substr(0,uscore); \ - - - return s; \ - }; - - - - - /** static function that returns the entire filename ithout file name prefix, detector index or extension - This will be concatenated with all the other detector file names for the gui - \param fname complete file name - \returns file name without file name prefix, detector index or extension - */ - static std::string getReceiverFileNameToConcatenate(std::string fname) { \ - int i;double f; \ - std::string s=fname; \ - if(fname.empty()) return fname; \ - size_t dot=s.find("."); - size_t uscore=s.rfind("_"); \ - - if (uscore==std::string::npos) return "??"; \ - if (sscanf(s.substr(uscore+1,s.size()-uscore-1).c_str(),"%d",&i)) \ - s=fname.substr(0,uscore); \ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"f%d",&i)) \ - s=fname.substr(0,uscore); \ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"d%d",&i)) \ - s=fname.substr(0,uscore); \ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"p%d",&i)) \ - s=fname.substr(0,uscore); \ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"s%lf",&f)) \ - s=fname.substr(0,uscore); \ - uscore=s.rfind("_"); \ - if (sscanf( s.substr(uscore+1,s.size()-uscore-1).c_str(),"S%lf",&f)) \ - s=fname.substr(0,uscore); \ - return(fname.substr(s.size(),dot-s.size()));\ - \ - }; - - - - - /** - - writes a data file - \param fname of the file to be written - \param nch number of channels to be written - \param data array of data values - \param err array of arrors on the data. If NULL no errors will be written - \param ang array of angular values. If NULL data will be in the form chan-val(-err) otherwise ang-val(-err) - \param dataformat format of the data: can be 'i' integer or 'f' double - \returns OK or FAIL if it could not write the file or data=NULL - - */ - - static int writeDataFile(std::string fname, int nch, double *data, double *err=NULL, double *ang=NULL, char dataformat='f'){ \ - std::ofstream outfile; \ - if (data==NULL) { \ - cout << "No data to write!" << endl; \ - return slsDetectorDefs::FAIL; \ - } \ - outfile.open (fname.c_str(),std::ios_base::out); \ - if (outfile.is_open()) { \ - writeDataFile(outfile, nch, data, err, ang, dataformat, 0); \ - outfile.close(); \ - return slsDetectorDefs::OK; \ - } else { \ - std::cout<< "Could not open file " << fname << "for writing"<< std::endl; \ - return slsDetectorDefs::FAIL; \ - } \ - }; - - - - - /** - writes a data file - \param outfile output file stream - \param nch number of channels to be written - \param data array of data values - \param err array of arrors on the data. If NULL no errors will be written - \param ang array of angular values. If NULL data will be in the form chan-val(-err) otherwise ang-val(-err) - \param dataformat format of the data: can be 'i' integer or 'f' double (default) - \param offset start channel number - \returns OK or FAIL if it could not write the file or data=NULL - */ - static int writeDataFile(std::ofstream &outfile, int nch, double *data, double *err=NULL, double *ang=NULL, char dataformat='f', int offset=0){ - int idata; \ - if (data==NULL || nch==0) { \ - cout << "No data to write!" << endl; \ - return slsDetectorDefs::FAIL; \ - } \ - for (int ichan=0; ichan> ichan >> fdata; \ - if (ssstr.fail() || ssstr.bad()) { \ - interrupt=1; \ - break; \ - } \ - ich=iline; \ - if (ichan> fang >> fdata; \ - ich=iline; \ - } \ - if (ssstr.fail() || ssstr.bad()) { \ - interrupt=1; \ - break; \ - } \ - if (err) \ - ssstr >> ferr; \ - if (ssstr.fail() || ssstr.bad()) { \ - interrupt=1; \ - break; \ - } \ - if (ich=nch) { \ - interrupt=1; \ - break; \ - } \ - } \ - return iline; \ - }; - - - /** - reads a raw data file - \param fname of the file to be read - \param data array of data values - \param nch number of channels - \returns OK or FAIL if it could not read the file or data=NULL - */ - static int readDataFile(std::string fname, int *data, int nch) { \ - std::ifstream infile; \ - int iline=0; \ - std::string str; \ - infile.open(fname.c_str(), std::ios_base::in); \ - if (infile.is_open()) { \ - iline=readDataFile(infile, data, nch, 0); \ - infile.close(); \ - } else { \ - std::cout<< "Could not read file " << fname << std::endl; \ - return -1; \ - } \ - return iline; \ - }; - - - /** - reads a raw data file - \param infile input file stream - \param data array of data values - \param nch number of channels - \param offset start channel value - \returns OK or FAIL if it could not read the file or data=NULL - */ - static int readDataFile(std::ifstream &infile, int *data, int nch, int offset) { \ - int ichan, idata, iline=0; \ - int interrupt=0; \ - std::string str; \ - while (infile.good() and interrupt==0) { \ - getline(infile,str); \ - std::istringstream ssstr(str); \ - ssstr >> ichan >> idata; \ - if (ssstr.fail() || ssstr.bad()) { \ - interrupt=1; \ - break; \ - } \ - if (iline=offset) { \ - data[iline]=idata; \ - iline++; \ - } \ - } else { \ - interrupt=1; \ - break; \ - } \ - } \ - return iline; \ - }; - - /** - reads a short int rawdata file - \param name of the file to be read - \param data array of data values - \param nch number of channels - \returns OK or FAIL if it could not read the file or data=NULL - */ - static int readDataFile(std::string fname, short int *data, int nch){ \ - std::ifstream infile; \ - int iline=0; \ - std::string str; \ - infile.open(fname.c_str(), std::ios_base::in); \ - if (infile.is_open()) { \ - iline=readDataFile(infile, data, nch, 0); \ - infile.close(); \ - } else { \ - std::cout<< "Could not read file " << fname << std::endl; \ - return -1; \ - } \ - return iline; \ - }; - - /** - reads a short int raw data file - \param infile input file stream - \param data array of data values - \param nch number of channels - \param offset start channel value - \returns OK or FAIL if it could not read the file or data=NULL - */ - static int readDataFile(std::ifstream &infile, short int *data, int nch, int offset) { \ - int ichan, iline=0; \ - short int idata; \ - int interrupt=0; \ - std::string str; \ - while (infile.good() and interrupt==0) { \ - getline(infile,str); \ - std::istringstream ssstr(str); \ - ssstr >> ichan >> idata; \ - if (ssstr.fail() || ssstr.bad()) { \ - interrupt=1; \ - break; \ - } \ - if (iline=offset) { \ - data[iline]=idata; \ - iline++; \ - } \ - } else { \ - interrupt=1; \ - break; \ - } \ - return iline; \ - }; \ - return iline; \ - }; -}; - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/movingStat.h b/slsDetectorSoftware/slsDetectorAnalysis/movingStat.h deleted file mode 100644 index f81fab696..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/movingStat.h +++ /dev/null @@ -1,147 +0,0 @@ - /********************************************//** - * @file movingStat.h - * @short handles pedestal data and moves accordingly - ***********************************************/ -#ifndef MOVINGSTAT_H -#define MOVINGSTAT_H - -//#include "sls_detector_defs.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -; - - -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; - - -/** - @short class handling pedestal data and moves according to data - */ - -class movingStat{ - -public: - /** - * Constructor - */ - movingStat() : n(0), m_n(0), m_oldM(0), m_newM(0), m_oldM2(0), m_newM2(0){} - - /** - * Clear number of data values - */ - inline void Clear(){ - m_n = 0; - } - - /** - * Set Pedestal - */ - inline void SetN(int i) {n=i;}; - - /** - * Get Pedestal - */ - inline int GetN() {return n;}; - - /** - * Calculate Pedestal - */ - inline void Calc(double x) { - if (m_n 0) ? m_newM/m_n : 0.0; - } - - /** - * Get mean 2 - */ - inline double M2() const{ - return ( (m_n > 1) ? m_newM2/m_n : 0.0 ); - } - - /** - * Get variance - */ - inline double Variance() const{ - return ( (m_n > 1) ? (M2()-Mean()*Mean()) : 0.0 ); - } - - /** - * Get standard deviation - */ - inline double StandardDeviation() const{ - return ( (Variance() > 0) ? sqrt( Variance() ) : -1 ); - } - -private: - /** pedestal */ - int n; - /** number of data values */ - int m_n; - - /** old and new mean */ - double m_oldM, m_newM, m_oldM2, m_newM2; -}; - - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.cpp b/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.cpp deleted file mode 100644 index 86f9faaf8..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.cpp +++ /dev/null @@ -1,901 +0,0 @@ -#include "postProcessing.h" -#include "postProcessingFuncs.h" -#include "angleConversionConstant.h" -#ifdef VERBOSE -#include "usersFunctions.h" -#elif EXTPP -#include "usersFunctions.h" -#endif -#include - -using namespace std; -//#define VERBOSE - -static void* startProcessData(void *n){ - postProcessing *myDet=(postProcessing*)n; - myDet->processData(1); - pthread_exit(NULL); - -}; - -static void* startProcessDataNoDelete(void *n){ - postProcessing *myDet=(postProcessing*)n; - myDet->processData(0); - pthread_exit(NULL); - -}; - - -int postProcessing::kbhit(){ - struct timeval tv; - fd_set fds; - tv.tv_sec = 0; - tv.tv_usec = 0; - FD_ZERO(&fds); - FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0 - select(STDIN_FILENO+1, &fds, NULL, NULL, &tv); - return FD_ISSET(STDIN_FILENO, &fds); -} - - -postProcessing::postProcessing(): expTime(NULL), badChannelMask(NULL), ang(NULL), val(NULL), err(NULL), numberOfChannels(0) { - pthread_mutex_t mp1 = PTHREAD_MUTEX_INITIALIZER; - mp=mp1; - pthread_mutex_init(&mp, NULL); - mg=mp1; - pthread_mutex_init(&mg, NULL); - ms=mp1; - pthread_mutex_init(&ms, NULL); - - //cout << "reg callback "<< endl; - dataReady = 0; - pCallbackArg = 0; - //cout << "done "<< endl; - rawDataReady = 0; - pRawDataArg = 0; - - - //#ifdef VERBOSE - // registerDataCallback(&defaultDataReadyFunc, NULL); - //#endif -#ifdef EXTPP - registerRawDataCallback(&defaultRawDataReadyFunc, NULL); -#endif - - ppFun=new postProcessingFuncs(); - -} - - - - - -postProcessing::~postProcessing(){ - delete ppFun; -}; - - - - - - - - -void postProcessing::processFrame(int *myData, int delflag, int jctb) { - - string fname; - int nn; - //double *fdata=NULL; - -#ifdef VERBOSE - cout << "start processing"<< endl; -#endif - - incrementProgress(); - -#ifdef VERBOSE - cout << "prog incremented"<< endl; -#endif - - /** decode data */ - - // cout << "decode 0"<< endl; - // if (getDetectorsType()==MYTHEN) { - - - // for (int ib=0; ib<1000; ib++) - // cout << ((*(((u_int64_t*)myData)+ib))>>17&1) ; - // cout << endl; - - - fdata=decodeData(myData,nn, fdata); - - //#ifdef VERBOSE - // cout << "decode 1"<< endl; - //#endif - // } else - // fdata=NULL; - if (rawDataReady) { -#ifdef VERBOSE - cout << "decoded data size is "<=0){ - if (getDetectorsType()==MYTHEN) - incrementFrameIndex(1); - else if((currentFrameIndex%getFramesPerFile())==0) - incrementFrameIndex(getFramesPerFile()); - } - - - - - if (fdata) - delete [] fdata; - fdata=NULL; - - - // if (jctb==0) { - delete [] myData; - myData=NULL; - -#ifdef VERBOSE - cout << "Pop data queue " << *fileIndex << endl; -#endif - - popDataQueue(); //remove the data from the queue - -#ifdef VERBOSE - cout << "Data queue popped" << endl; -#endif - - -#ifdef VERBOSE - cout << "process frame returning " << endl; -#endif - // } - -} - - - - -void postProcessing::doProcessing(double *lfdata, int delflag, string fname) { - - #ifdef VERBOSE - cout << "??????????????????????????????????????????? do processing - data size is " << arraySize << endl; - #endif - - - int np; - -#ifdef VERBOSE - cout << "arrays allocated " << endl; -#endif - int npos=getNumberOfPositions(); - - string ext=".dat"; - -#ifdef VERBOSE - cout << "npos is "<< npos << endl; -#endif - - double t=0; - - if (expTime) - t=(*expTime)*1E-9; - else - cout << "no pointer to exptime" << endl; -#ifdef VERBOSE - cout << "exptime is "<< t << endl; -#endif - - if (GetCurrentPositionIndex()<=1 || npos<2) { -#ifdef VERBOSE - cout << "init dataset" << endl; -#endif - - - if (*correctionMask&(1<< ANGULAR_CONVERSION)) - ang=new double[arraySize]; - else - ang=NULL; - - val=new double[arraySize]; - err=new double[arraySize]; - - initDataset(0); - } - -#ifdef VERBOSE - cout << "add frame" << endl; -#endif - - /**ot them -start processing -prog incremented -decode -fname is //run_f0_0 -??????????????????????????????????????????? do processing - data size is 30720 -arrays allocated -npos is 0 -exptime is 10.00 -init dataset -add frame -data queue size lock -data queue size unlock - **/ - - addFrame(lfdata,currentPosition, currentI0, t, fname, 0); - // cout << "++++++++++++++++++++" << GetCurrentPositionIndex() << " " << npos << " " << positionFinished() << " " << dataQueueSize() << endl; - if ((GetCurrentPositionIndex()>=npos && dataQueueSize()) || npos<2) { - //&& - - while(positionFinished()==0 && npos>1) { - ; - } -#ifdef VERBOSE - cout << "finalize dataset" << endl; -#endif - - finalizeDataset(ang, val, err, np); - //if (npos<2) { - IncrementPositionIndex(); - - pthread_mutex_lock(&mp); - fname=createFileName(); - pthread_mutex_unlock(&mp); - //} - - if((*correctionMask)&(1<0) { - - int *badChansList=new int[nbad]; - #ifdef VERBOSE - cout << "get badch array " << nbad << endl; - #endif - getBadChannelCorrection(badChansList); - #ifdef VERBOSE - cout << "done " << nbad << endl; - #endif - - if (badChannelMask) - delete [] badChannelMask; - - -#ifdef VERBOSE - cout << " nchans " << getTotalNumberOfChannels() << endl; -#endif - - badChannelMask=new int[getTotalNumberOfChannels()]; - -#ifdef VERBOSE - cout << " pointer to bad channel mask is " << badChannelMask << endl; -#endif - for (int ichan=0; ichan=0 ) { - if (badChannelMask[badChansList[ichan]]==0) { - badChannelMask[badChansList[ichan]]=1; - // cout << "bad: " << ichan << " " << badChansList[ichan] << endl; - } else - nbad--; - } - } - delete [] badChansList; - - } else { - if (badChannelMask) { -#ifdef VERBOSE - cout << "deleting bad channel mask beacuse number of bad channels is 0" << endl; -#endif - - delete [] badChannelMask; - badChannelMask=NULL; - } - } - - } else { -#ifdef VERBOSE - cout << "bad channel correction is disabled " << nbad << endl; -#endif - if (badChannelMask) { -#ifdef VERBOSE - cout << "deleting bad channel mask beacuse no bad channel correction is selected" << endl; -#endif - delete [] badChannelMask; - badChannelMask=NULL; - } - } - -#ifdef VERBOSE - cout << "number of bad channels is " << nbad << endl; -#endif - return nbad; - -} - - - - - - -void* postProcessing::processData(int delflag) { - if(setReceiverOnline()==OFFLINE_FLAG){ - -#ifdef VERBOSE - std::cout<< " ??????????????????????????????????????????? processing data - threaded mode " << *threadedProcessing << endl; -#endif - - - - - queuesize=dataQueueSize(); - - - int *myData; - int dum=1; -// int nf=1, ii, nch; -// int jctb=0; - - -// if (getDetectorsType()==JUNGFRAUCTB) { -// nch=getTotalNumberOfChannels(); -// nf= getDataBytes()/(nch*2); -// cout << "WILL PROCESS " << nf << "SAMPLES AND " << nch <<"CHANNELS PER FRAME!" << endl; -// jctb=1; -// }// else -// // cout << "NOOT A JCTB" << endl; - - fdata=NULL; - - while(dum | *threadedProcessing) { // ???????????????????????? - /* IF THERE ARE DATA PROCESS THEM*/ - // cout << "loop" << endl; - while((queuesize=dataQueueSize())>0) { - /** Pop data queue */ - #ifdef VERBOSE - cout << "data found"<< endl<r_conversion; - angOff[im]=p->offset; - angCenter[im]=p->center; - -#ifdef VERBOSE - cout << im << " " << angCenter[im] << " " << angRad[im] << " " << angOff[im] << endl; -#endif - - - } - sx=getAngularConversionParameter(SAMPLE_X); - sy=getAngularConversionParameter(SAMPLE_Y); - - } - - -#ifdef VERBOSE - cout << "init dataset" << endl; -#endif - // cout << "pp bad channel mask " << badChannelMask << endl; - fillBadChannelMask(); - // cout << "pp bad channel mask " << badChannelMask << endl; - - //cout << "EEEEEEEEEEEEEEEEEEEE init dataset " << endl; - ppFun->initDataset(&nmod,chPM,mM,badChannelMask, ffcoeff, fferr, &tdead, &angdir, angRad, angOff, angCenter, &to, &bs, &sx, &sy); - -#ifdef VERBOSE - cout << "done" << endl; -#endif - - delete [] chPM; - delete [] mM; - if (ffcoeff != NULL) delete [] ffcoeff; - if (fferr != NULL) delete [] fferr; - if (angRad != NULL) delete [] angRad; - if (angOff != NULL) delete [] angOff; - if (angCenter != NULL) delete [] angCenter; - - - if (*correctionMask&(1<< ANGULAR_CONVERSION)) { - arraySize=getNumberOfAngularBins(); - if (arraySize<=0) - arraySize=totch; - } else { - arraySize=totch; - } - - numberOfChannels=totch; - - queuesize=dataQueueSize(); - - // resetFinalDataQueue(); - resetDataQueue(); - - - } else { - - // cout << "EEEEEEEEEEEEEEEEEEEE init dataset XXXX " << endl; - - ppFun->initDataset(); - - - } - -} - - - - - - -void postProcessing::addFrame(double *data, double pos, double i0, double t, string fname, double var) { - // cout << "EEEEEEEEEEEEEEEEEEEE add frame " << pos << " " << i0 << endl; - - if (*correctionMask&(1<< I0_NORMALIZATION)) - ppFun->addFrame(data, &pos, &i0, &t, fname.c_str(), &var); - else - ppFun->addFrame(data, &pos,NULL, &t, fname.c_str(), &var); - - - -} - -void postProcessing::finalizeDataset(double *a, double *v, double *e, int &np) { - - // cout << "EEEEEEEEEEEEEEEEEEEE finalize dataset " << endl; - ppFun->finalizeDataset(a, v, e, &np); - -} - - - - - - - - - - - - - - - - - -void postProcessing::startThread(int delflag) { - - /////////////////////////////////// Initialize dataset - - //resetDataQueue(); - - setTotalProgress(); - - initDataset(1); - - /////////////////////////////////// Start thread //////////////////////////////////////////////////////// -#ifdef VERBOSE - cout << "start thread stuff" << endl; -#endif - - pthread_attr_t tattr; - int ret; - sched_param param, mparam; - int policy= SCHED_OTHER; - - // set the priority; others are unchanged - //newprio = 30; - mparam.sched_priority =1; - param.sched_priority =1; - - - /* Initialize and set thread detached attribute */ - pthread_attr_init(&tattr); - pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_JOINABLE); - - - - // param.sched_priority = 5; - // scheduling parameters of main thread - ret = pthread_setschedparam(pthread_self(), policy, &mparam); - - //#ifdef VERBOSE - // printf("current priority is %d\n",param.sched_priority); - //#endif - if (delflag) - ret = pthread_create(&dataProcessingThread, &tattr,startProcessData, (void*)this); - else - ret = pthread_create(&dataProcessingThread, &tattr,startProcessDataNoDelete, (void*)this); - - if (ret) - printf("ret %d\n", ret); - - pthread_attr_destroy(&tattr); - - // scheduling parameters of target thread - ret = pthread_setschedparam(dataProcessingThread, policy, ¶m); - -} - - - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.h b/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.h deleted file mode 100644 index 7903688dd..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/postProcessing.h +++ /dev/null @@ -1,385 +0,0 @@ -#ifndef POSTPROCESSING_H -#define POSTPROCESSING_H - - -#include "detectorData.h" -#include "slsDetectorBase.h" -#include "angularConversion.h" -#include "badChannelCorrections.h" -#include "fileIO.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class postProcessingFuncs; - - -// - -#define MAX_BADCHANS 20000 - - -#define defaultTDead {170,90,750} /**< should be changed in order to have it separate for the different detector types */ - - -/** - @short methods for data postprocessing - - (including thread for writing data files and plotting in parallel with the acquisition) -*/ - -class postProcessing : public angularConversion, public fileIO, public badChannelCorrections { - -//public virtual angularConversion, public virtual fileIO { - - public: - postProcessing(); - virtual ~postProcessing(); - - - - - /** - get bad channels correction - \param bad pointer to array that if bad!=NULL will be filled with the bad channel list - \returns 0 if bad channel disabled or no bad channels, >0 otherwise - */ - virtual int getBadChannelCorrection(int *bad=NULL)=0; - - - /** - get flat field corrections - \param corr if !=NULL will be filled with the correction coefficients - \param ecorr if !=NULL will be filled with the correction coefficients errors - \returns 0 if ff correction disabled, >0 otherwise - */ - virtual int getFlatFieldCorrection(double *corr=NULL, double *ecorr=NULL)=0; - - /** - set flat field corrections - \param corr if !=NULL the flat field corrections will be filled with corr (NULL usets ff corrections) - \param ecorr if !=NULL the flat field correction errors will be filled with ecorr (1 otherwise) - \returns 0 if ff correction disabled, >0 otherwise - */ - virtual int setFlatFieldCorrection(double *corr, double *ecorr=NULL)=0; - - /** - set bad channels correction - \param fname file with bad channel list ("" disable) - \returns 0 if bad channel disabled, >0 otherwise - */ - virtual int setBadChannelCorrection(std::string fname="")=0; - - - /** - set bad channels correction - \param fname file with bad channel list ("" disable) - \param nbad reference to number of bad channels - \param badlist array of badchannels - \returns 0 if bad channel disabled, >0 otherwise - */ - virtual int setBadChannelCorrection(std::string fname, int &nbad, int *badlist, int off=0)=0; - using badChannelCorrections::setBadChannelCorrection; - - /** - set bad channels correction - \param nch number of bad channels - \param chs array of channels - \param ff 0 if normal bad channels, 1 if ff bad channels - \returns 0 if bad channel disabled, >0 otherwise - */ - virtual int setBadChannelCorrection(int nch, int *chs, int ff=0)=0; - - - - int enableWriteToFileMask(int i=-1) {if (i>0) ((*correctionMask)|=(1<>WRITE_FILE) ;}; - - int enableOverwriteMask(int i=-1) {if (i>0) ((*correctionMask)|=(1<>OVERWRITE_FILE) ;}; - - int setAngularCorrectionMask(int i=-1){if (i==0) (*correctionMask)&=~(1<< ANGULAR_CONVERSION); if (i>0) (*correctionMask)|=(1<< ANGULAR_CONVERSION); return (((*correctionMask)&(1<< ANGULAR_CONVERSION))>>ANGULAR_CONVERSION);}; - - - - int enableAngularConversion(int i=-1) {if (i>0) return setAngularConversionFile("default"); if (i==0) return setAngularConversionFile(""); return setAngularCorrectionMask();}; - - - int enableBadChannelCorrection(int i=-1) {if (i>0) return setBadChannelCorrection("default"); if (i==0) return setBadChannelCorrection(""); return (((*correctionMask)&(1<< DISCARD_BAD_CHANNELS))>>DISCARD_BAD_CHANNELS);}; - - - - - /** returns the bad channel list file */ - std::string getBadChannelCorrectionFile() {if ((*correctionMask)&(1<< DISCARD_BAD_CHANNELS)) return std::string(badChanFile); else return std::string("none");}; - - - /** - get flat field corrections file directory - \returns flat field correction file directory - */ - std::string getFlatFieldCorrectionDir(){return std::string(flatFieldDir);}; - /** - set flat field corrections file directory - \param flat field correction file directory - \returns flat field correction file directory - */ - std::string setFlatFieldCorrectionDir(std::string dir){strcpy(flatFieldDir,dir.c_str()); return std::string(flatFieldDir);}; - - /** - get flat field corrections file name - \returns flat field correction file name - */ - std::string getFlatFieldCorrectionFile(){ if ((*correctionMask)&(1<=0) *threadedProcessing=b; return *threadedProcessing;}; - - - - - /** processes the data - \param delflag 0 leaves the data in the final data queue - \returns nothing - - */ - void *processData(int delflag); - - /** processes the data - \param delflag 0 leaves the data in the final data queue - \returns nothing - - */ - void processFrame(int* myData, int delflag, int jctb=0); - - /** processes the data - \param delflag 0 leaves the data in the final data queue - \returns nothing - - */ - void doProcessing(double* myData, int delflag, std::string fname); - - - /** - pops the data from the data queue - \returns pointer to the popped data or NULL if the queue is empty. - \sa dataQueue - */ - int* popDataQueue(); - - int* dataQueueFront(); - - int dataQueueSize(); - -/* /\** */ -/* pops the data from thepostprocessed data queue */ -/* \returns pointer to the popped data or NULL if the queue is empty. */ -/* \sa finalDataQueue */ -/* *\/ */ -/* detectorData* popFinalDataQueue(); */ - - - int checkJoinThread(); - void setJoinThread(int v); - - - /** - resets the raw data queue - \sa dataQueue - */ - void resetDataQueue(); - -/* /\** */ -/* resets the postprocessed data queue */ -/* \sa finalDataQueue */ -/* *\/ */ -/* void resetFinalDataQueue(); */ - - - - - - int fillBadChannelMask(); - - - - - virtual int rateCorrect(double*, double*, double*, double*)=0; - virtual int flatFieldCorrect(double*, double*, double*, double*)=0; - - - virtual int fillModuleMask(int *mM)=0; - - virtual int getNMods()=0; - - - - int GetCurrentPositionIndex(){ pthread_mutex_lock(&mp); int retval=getCurrentPositionIndex(); pthread_mutex_unlock(&mp); return retval;}; - void IncrementPositionIndex(){ pthread_mutex_lock(&mp); incrementPositionIndex(); pthread_mutex_unlock(&mp);}; - - void IncrementFileIndex(){ pthread_mutex_lock(&mp); incrementFileIndex(); pthread_mutex_unlock(&mp); }; - int GetFileIndex(){ pthread_mutex_lock(&mp); int i=*fileIndex; pthread_mutex_unlock(&mp); return i;}; - - void ResetPositionIndex(){pthread_mutex_lock(&mp); resetPositionIndex(); pthread_mutex_unlock(&mp);}; - - - void registerDataCallback(int( *userCallback)(detectorData*, int, int, void*), void *pArg) { \ - dataReady = userCallback; \ - pCallbackArg = pArg; \ - if (setReceiverOnline() == slsDetectorDefs::ONLINE_FLAG) { \ - enableDataStreamingToClient(1); \ - enableDataStreamingFromReceiver(1);}}; \ - - - void registerRawDataCallback(int( *userCallback)(double*, int, void*), void *pArg) {rawDataReady = userCallback; pRawDataArg = pArg;}; - - virtual double getRateCorrectionTau()=0; - - - int positionFinished(int v=-1){pthread_mutex_lock(&mp); if (v>=0) posfinished=v; int retval=posfinished; pthread_mutex_unlock(&mp); return retval;}; - - double getCurrentPosition() {double p; pthread_mutex_lock(&mp); p=currentPosition; pthread_mutex_unlock(&mp); return p;}; - double setCurrentPosition(double v) { pthread_mutex_lock(&mp); currentPosition=v; pthread_mutex_unlock(&mp); return currentPosition;}; - - - - - void initDataset(int refresh); - void addFrame(double *data, double pos, double i0, double t, std::string fname, double var); - void finalizeDataset(double *a, double *v, double *e, int &np); - - virtual detectorType getDetectorsType(int pos=-1)=0; - - protected: - - int *threadedProcessing; - - int *correctionMask; - - char *flatFieldDir; - char *flatFieldFile; - - int64_t *expTime; - - /** mutex to synchronize main and data processing threads */ - pthread_mutex_t mp; - - - /** mutex to synchronizedata processing and plotting threads */ - pthread_mutex_t mg; - - /** mutex to synchronize slsdetector threads */ - pthread_mutex_t ms; - - /** sets when the acquisition is finished */ - int jointhread; - - /** sets when the position is finished */ - int posfinished; - - /** - data queue - */ - std::queue dataQueue; - /** - queue containing the postprocessed data - */ - std::queue finalDataQueue; - - /** data queue size */ - int queuesize; - - /** queue mutex */ - sem_t sem_queue; - /** set when detector finishes acquiring */ - int acquiringDone; - - - /** - start data processing thread - */ - void startThread(int delflag=1); // - /** the data processing thread */ - - pthread_t dataProcessingThread; - - - - /** pointer to bad channel mask 0 is channel is good 1 if it is bad \sa fillBadChannelMask() */ - int *badChannelMask; - - - - - /** - I0 measured - */ - double currentI0; - - - int arraySize; - - - - double *fdata; - int (*dataReady)(detectorData*,int, int, void*); - void *pCallbackArg; - detectorData *thisData; - - private: - int kbhit(void); - - // double *fdata; - // int (*dataReady)(detectorData*,int, int,void*); - // void *pCallbackArg; - - int (*rawDataReady)(double*,int,void*); - void *pRawDataArg; - - - postProcessingFuncs *ppFun; - //detectorData *thisData; - - - double *ang; - double *val; - double *err; - - int numberOfChannels; - - - -}; - - -/* static void* startProcessData(void *n){\ */ -/* postProcessing *myDet=(postProcessing*)n;\ */ -/* myDet->processData(1);\ */ -/* pthread_exit(NULL);\ */ - -/* }; */ - -/* static void* startProcessDataNoDelete(void *n){\ */ -/* postProcessing *myDet=(postProcessing*)n;\ */ -/* myDet->processData(0);\ */ -/* pthread_exit(NULL);\ */ - -/* }; */ - - - - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/postProcessingFileIO_Standalone.cpp b/slsDetectorSoftware/slsDetectorAnalysis/postProcessingFileIO_Standalone.cpp deleted file mode 100644 index 275003a6c..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/postProcessingFileIO_Standalone.cpp +++ /dev/null @@ -1,602 +0,0 @@ -#include "postProcessingFileIO_Standalone.h" -#include "usersFunctions.h" -//#include "externPostProcessing.h" - -postProcessing::postProcessing(){ - - pthread_mutex_t mp1 = PTHREAD_MUTEX_INITIALIZER; - mp=mp1; - pthread_mutex_init(&mp, NULL); - mg=mp1; - pthread_mutex_init(&mg, NULL); - //cout << "reg callback "<< endl; - dataReady = 0; - pCallbackArg = 0; - registerDataCallback(&defaultDataReadyFunc, NULL); - //cout << "done "<< endl; - angConv=new angularConversion(numberOfPositions,detPositions,binSize, fineOffset, globalOffset); - IOfile= new fileIO(); - - //registerCallBackGetChansPerMod(&getChannelPerMod,this); - registerCallBackGetNumberofChannel(&defaultGetTotalNumberofChannels,this); - //registerAngularConversionCallback(&defaultAngularConversion,this); -} - - - - - - -int postProcessing::flatFieldCorrect(double datain, double errin, double &dataout, double &errout, double ffcoefficient, double fferr){ - double e; - - dataout=datain*ffcoefficient; - - if (errin==0 && datain>=0) - e=sqrt(datain); - else - e=errin; - - if (dataout>0) - errout=sqrt(e*ffcoefficient*e*ffcoefficient+datain*fferr*datain*fferr); - else - errout=1.0; - - return 0; -}; - - - int postProcessing::rateCorrect(double datain, double errin, double &dataout, double &errout, double tau, double t){ - - // double data; - double e; - - dataout=(datain*exp(tau*datain/t)); - - if (errin==0 && datain>=0) - e=sqrt(datain); - else - e=errin; - - if (dataout>0) - errout=e*dataout*sqrt((1/(datain*datain)+tau*tau/(t*t))); - else - errout=1.; - return 0; - -}; - - - - - -int postProcessing::setBadChannelCorrection(ifstream &infile, int &nbad, int *badlist, int moff){ - - int interrupt=0; - int ich; - int chmin,chmax; - string str; - - - - nbad=0; - while (infile.good() and interrupt==0) { - getline(infile,str); -#ifdef VERBOSE - std::cout << str << std::endl; -#endif - istringstream ssstr; - ssstr.str(str); - if (ssstr.bad() || ssstr.fail() || infile.eof()) { - interrupt=1; - break; - } - if (str.find('-')!=string::npos) { - ssstr >> chmin ; - ssstr.str(str.substr(str.find('-')+1,str.size())); - ssstr >> chmax; -#ifdef VERBOSE - std::cout << "channels between"<< chmin << " and " << chmax << std::endl; -#endif - for (ich=chmin; ich<=chmax; ich++) { - if (nbad> ich; -#ifdef VERBOSE - std::cout << "channel "<< ich << std::endl; -#endif - if (nbadcreateFileName(getActionMask(),getCurrentScanVariable(0),getScanPrecision(0),getCurrentScanVariable(1),getScanPrecision(1),getCurrentPositionIndex(),getNumberOfPositions()); - -//Checking for write flag - if(*correctionMask&(1<writeDataFile (fname+string(".raw"),fdata, NULL, NULL, 'i'); - - } - - doProcessing(fdata,delflag, fname); - - delete [] myData; - myData=NULL; - fdata=NULL; - -#ifdef VERBOSE - cout << "Pop data queue " << *fileIndex << endl; -#endif - - pthread_mutex_lock(&mp); - dataQueue.pop(); //remove the data from the queue - queuesize=dataQueue.size(); - pthread_mutex_unlock(&mp); - - -} - - - - -void postProcessing::doProcessing(double *lfdata, int delflag, string fname) { - - -// /** write raw data file */ -// if (*correctionMask==0 && delflag==1) { -// // delete [] fdata; -// ; -// } else { - - - - double *rcdata=NULL, *rcerr=NULL; - double *ffcdata=NULL, *ffcerr=NULL; - double *ang=NULL; - // int imod; - int np; - //string fname; - detectorData *thisData; - - - string ext=".dat"; - // fname=createFileName(); - - /** rate correction */ - if (*correctionMask&(1<writeDataFile (fname+ext, ffcdata, ffcerr,ang);} - } - - if (*correctionMask&(1<< ANGULAR_CONVERSION) && getNumberOfPositions()>0) { -#ifdef VERBOSE - cout << "**************Current position index is " << getCurrentPositionIndex() << endl; -#endif - // if (*numberOfPositions>0) {setTotalNumberOfChannels - if (getCurrentPositionIndex()<=1) { - -#ifdef VERBOSE - cout << "reset merging " << endl; -#endif - angConv->resetMerging(); - } - -#ifdef VERBOSE - cout << "add to merging "<< getCurrentPositionIndex() << endl; -#endif - - angConv->addToMerging(ang, ffcdata, ffcerr, badChannelMask ); - -#ifdef VERBOSE - cout << getCurrentPositionIndex() << " " << getNumberOfPositions() << endl; - -#endif - - - // cout << "lock 1" << endl; - pthread_mutex_lock(&mp); - if ((getCurrentPositionIndex()>=getNumberOfPositions() && posfinished==1 && queuesize==1)) { - -#ifdef VERBOSE - cout << "finalize merging " << getCurrentPositionIndex()<< endl; -#endif - np=angConv->finalizeMerging(); - /** file writing */ - angConv->incrementPositionIndex(); - // cout << "unlock 1" << endl; - pthread_mutex_unlock(&mp); - - - fname=IOfile->createFileName(getActionMask(),getCurrentScanVariable(0),getScanPrecision(0),getCurrentScanVariable(1),getScanPrecision(1),getCurrentPositionIndex(),getNumberOfPositions()); - -#ifdef VERBOSE - cout << "writing merged data file" << endl; -#endif - if(*correctionMask&(1<writeDataFile (fname+ext,np,angConv->getMergedCounts(), angConv->getMergedErrors(), angConv->getMergedPositions(),'f');} -#ifdef VERBOSE - cout << " done" << endl; -#endif - - - -// if (delflag) { -// deleteMerging(); -// } else { - thisData=new detectorData(angConv->getMergedCounts(),angConv->getMergedErrors(),angConv->getMergedPositions(),getCurrentProgress(),(fname+ext).c_str(),np); - - // // cout << "lock 2" << endl; -// pthread_mutex_lock(&mg); -// finalDataQueue.push(thisData); -// // cout << "unlock 2" << endl; - -// pthread_mutex_unlock(&mg); - - if (dataReady) { - - dataReady(thisData, pCallbackArg); - delete thisData; - } - -// } - // cout << "lock 3" << endl; - pthread_mutex_lock(&mp); - } - // cout << "unlock 3" << endl; - pthread_mutex_unlock(&mp); - - if (ffcdata) - delete [] ffcdata; - - ffcdata=NULL; - - if (ffcerr) - delete [] ffcerr; - ffcerr=NULL; - - if (ang) - delete [] ang; - ang=NULL; - - } else { -// if (delflag) { -// if (ffcdata) -// delete [] ffcdata; -// if (ffcerr) -// delete [] ffcerr; -// if ( ang) -// delete [] ang; -// } else { - thisData=new detectorData(ffcdata,ffcerr,NULL,getCurrentProgress(),(fname+ext).c_str(),getTotalNumberOfChannels()); - - - if (dataReady) { - dataReady(thisData, pCallbackArg); - delete thisData; - } -// pthread_mutex_lock(&mg); -// finalDataQueue.push(thisData); - - -// pthread_mutex_unlock(&mg); -// } - } - //} - - if(*correctionMask&(1<incrementFileIndex();} -#ifdef VERBOSE - cout << "fdata is " << fdata << endl; -#endif - -} - - - - - -int postProcessing::fillBadChannelMask() { - - int nbad=0; - - if (*correctionMask&(1<< DISCARD_BAD_CHANNELS)) { - nbad=getBadChannelCorrection(); -#ifdef VERBOSE - cout << "number of bad channels is " << nbad << endl; -#endif - if (nbad>0) { - - int *badChansList=new int[nbad]; - getBadChannelCorrection(badChansList); - - if (badChannelMask) - delete [] badChannelMask; - badChannelMask=new int[getTotalNumberOfChannels()]; - -#ifdef VERBOSE - cout << " pointer to bad channel mask is " << badChannelMask << endl; -#endif - for (int ichan=0; ichan=0 ) { - if (badChannelMask[badChansList[ichan]]==0) - nbad++; - badChannelMask[badChansList[ichan]]=1; - - } - } - delete [] badChansList; - - } else { - if (badChannelMask) { -#ifdef VERBOSE - cout << "deleting bad channel mask beacuse number of bad channels is 0" << endl; -#endif - - delete [] badChannelMask; - badChannelMask=NULL; - } - } - - } else { -#ifdef VERBOSE - cout << "bad channel correction is disabled " << nbad << endl; -#endif - if (badChannelMask) { -#ifdef VERBOSE - cout << "deleting bad channel mask beacuse no bad channel correction is selected" << endl; -#endif - delete [] badChannelMask; - badChannelMask=NULL; - } - } - -#ifdef VERBOSE - cout << "number of bad channels is " << nbad << endl; -#endif - return nbad; - -} - - - - - - -void* postProcessing::processData(int delflag) { - - -#ifdef VERBOSE - std::cout<< " processing data - threaded mode " << *threadedProcessing << endl; -#endif - - - angConv->setTotalNumberOfChannels(getTotalNumberOfChannels()); - IOfile->setTotalNumberofChannels(getTotalNumberOfChannels()); - setTotalProgress(); - pthread_mutex_lock(&mp); - queuesize=dataQueue.size(); - pthread_mutex_unlock(&mp); - - int *myData; - int dum=1; - - fdata=NULL; - - - while(dum | *threadedProcessing) { // ???????????????????????? - - - /* IF THERE ARE DATA PROCESS THEM*/ - pthread_mutex_lock(&mp); - while((queuesize=dataQueue.size())>0) { - /** Pop data queue */ - myData=dataQueue.front(); // get the data from the queue - pthread_mutex_unlock(&mp); - - if (myData) { - processFrame(myData,delflag); - //usleep(1000); - } - pthread_mutex_lock(&mp); - - } - pthread_mutex_unlock(&mp); - - /* IF THERE ARE NO DATA look if acquisition is finished */ - pthread_mutex_lock(&mp); - if (jointhread) { - if (dataQueue.size()==0) { - pthread_mutex_unlock(&mp); - break; - } - pthread_mutex_unlock(&mp); - } else { - pthread_mutex_unlock(&mp); - } - dum=0; - } - - if (fdata) { -#ifdef VERBOSE - cout << "delete fdata" << endl; -#endif - delete [] fdata; -#ifdef VERBOSE - cout << "done " << endl; -#endif - } - return 0; -} - - -int* postProcessing::popDataQueue() { - int *retval=NULL; - if( !dataQueue.empty() ) { - retval=dataQueue.front(); - dataQueue.pop(); - } - return retval; -} - -detectorData* postProcessing::popFinalDataQueue() { - detectorData *retval=NULL; - pthread_mutex_unlock(&mg); - if( !finalDataQueue.empty() ) { - retval=finalDataQueue.front(); - finalDataQueue.pop(); - } - pthread_mutex_unlock(&mg); - return retval; -} - -void postProcessing::resetDataQueue() { - int *retval=NULL; - while( !dataQueue.empty() ) { - retval=dataQueue.front(); - dataQueue.pop(); - delete [] retval; - } - -} - -void postProcessing::resetFinalDataQueue() { - detectorData *retval=NULL; - pthread_mutex_lock(&mg); - while( !finalDataQueue.empty() ) { - retval=finalDataQueue.front(); - finalDataQueue.pop(); - delete retval; - } - pthread_mutex_unlock(&mg); -} - - -void postProcessing::startThread(int delflag) { - pthread_attr_t tattr; - int ret; - sched_param param, mparam; - int policy= SCHED_OTHER; - - - // set the priority; others are unchanged - //newprio = 30; - mparam.sched_priority =1; - param.sched_priority =1; - - - /* Initialize and set thread detached attribute */ - pthread_attr_init(&tattr); - pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_JOINABLE); - - - - // param.sched_priority = 5; - // scheduling parameters of main thread - ret = pthread_setschedparam(pthread_self(), policy, &mparam); - //#ifdef VERBOSE - // printf("current priority is %d\n",param.sched_priority); - //#endif - if (delflag) - ret = pthread_create(&dataProcessingThread, &tattr,startProcessData, (void*)this); - else - ret = pthread_create(&dataProcessingThread, &tattr,startProcessDataNoDelete, (void*)this); - - pthread_attr_destroy(&tattr); - // scheduling parameters of target thread - ret = pthread_setschedparam(dataProcessingThread, policy, ¶m); - -} - - - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/postProcessingFileIO_Standalone.h b/slsDetectorSoftware/slsDetectorAnalysis/postProcessingFileIO_Standalone.h deleted file mode 100644 index 7edfddc0b..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/postProcessingFileIO_Standalone.h +++ /dev/null @@ -1,391 +0,0 @@ -#ifndef POSTPROCESSING_H -#define POSTPROCESSING_H - - -#include "detectorData.h" -#include "sls_detector_defs.h" -#include "slsDetectorBase_Standalone.h" -#include "slsDetectorUsers.h" -#include "FileIO_Standalone.h" -#include "AngularConversion_Standalone.h" -//#include "externPostProcessing.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - - -class angularConversion; -class fileIO; - -; - -#define MAX_BADCHANS 2000 - - -#define defaultTDead {170,90,750} /**< should be changed in order to have it separate for the different detector types */ - - -/** - @short methods for data postprocessing - - (including thread for writing data files and plotting in parallel with the acquisition) -*/ - -class postProcessing : public virtual slsDetectorBase1 { - - -//: public angularConversion, public fileIO - - public: - postProcessing(); - virtual ~postProcessing(){}; - - - - /** - get bad channels correction - \param bad pointer to array that if bad!=NULL will be filled with the bad channel list - \returns 0 if bad channel disabled or no bad channels, >0 otherwise - */ - virtual int getBadChannelCorrection(int *bad=NULL)=0; - - - /** - get flat field corrections - \param corr if !=NULL will be filled with the correction coefficients - \param ecorr if !=NULL will be filled with the correction coefficients errors - \returns 0 if ff correction disabled, >0 otherwise - */ - virtual int getFlatFieldCorrection(double *corr=NULL, double *ecorr=NULL)=0; - - /** - set flat field corrections - \param corr if !=NULL the flat field corrections will be filled with corr (NULL usets ff corrections) - \param ecorr if !=NULL the flat field correction errors will be filled with ecorr (1 otherwise) - \returns 0 if ff correction disabled, >0 otherwise - */ - virtual int setFlatFieldCorrection(double *corr, double *ecorr=NULL)=0; - - /** - set bad channels correction - \param fname file with bad channel list ("" disable) - \returns 0 if bad channel disabled, >0 otherwise - */ - virtual int setBadChannelCorrection(string fname="")=0; - - static int setBadChannelCorrection(ifstream &infile, int &nbad, int *badlist, int moff=0); - /** - set bad channels correction - \param fname file with bad channel list ("" disable) - \param nbad reference to number of bad channels - \param badlist array of badchannels - \returns 0 if bad channel disabled, >0 otherwise - */ - virtual int setBadChannelCorrection(string fname, int &nbad, int *badlist, int off=0)=0; - - - /** - set bad channels correction - \param nch number of bad channels - \param chs array of channels - \param ff 0 if normal bad channels, 1 if ff bad channels - \returns 0 if bad channel disabled, >0 otherwise - */ - virtual int setBadChannelCorrection(int nch, int *chs, int ff=0)=0; - - /** - flat field correct data - \param datain data - \param errin error on data (if<=0 will default to sqrt(datain) - \param dataout corrected data - \param errout error on corrected data - \param ffcoefficient flat field correction coefficient - \param fferr erro on ffcoefficient - \returns 0 - */ - static int flatFieldCorrect(double datain, double errin, double &dataout, double &errout, double ffcoefficient, double fferr); - - /** - rate correct data - \param datain data - \param errin error on data (if<=0 will default to sqrt(datain) - \param dataout corrected data - \param errout error on corrected data - \param tau dead time 9in ns) - \param t acquisition time (in ns) - \returns 0 - */ - static int rateCorrect(double datain, double errin, double &dataout, double &errout, double tau, double t); - - - int enableWriteToFile(int i=-1) {if (i>0) ((*correctionMask)|=(1<0) (*correctionMask)|=(1<< ANGULAR_CONVERSION); return ((*correctionMask)&(1<< ANGULAR_CONVERSION));}; - - - - int enableAngularConversion(int i=-1) {if (i>0) return setAngularConversionFile("default"); if (i==0) return setAngularConversionFile(""); return setAngularCorrectionMask();}; - - - int enableBadChannelCorrection(int i=-1) {if (i>0) return setBadChannelCorrection("default"); if (i==0) return setBadChannelCorrection(""); return ((*correctionMask)&(1<< DISCARD_BAD_CHANNELS));}; - - - - - /** returns the bad channel list file */ - string getBadChannelCorrectionFile() {if ((*correctionMask)&(1<< DISCARD_BAD_CHANNELS)) return string(badChanFile); else return string("none");}; - - - /** - get flat field corrections file directory - \returns flat field correction file directory - */ - string getFlatFieldCorrectionDir(){return string(flatFieldDir);}; - /** - set flat field corrections file directory - \param flat field correction file directory - \returns flat field correction file directory - */ - string setFlatFieldCorrectionDir(string dir){strcpy(flatFieldDir,dir.c_str()); return string(flatFieldDir);}; - - /** - get flat field corrections file name - \returns flat field correction file name - */ - string getFlatFieldCorrectionFile(){ if ((*correctionMask)&(1<=0) *threadedProcessing=b; return *threadedProcessing;}; - - - - - /** processes the data - \param delflag 0 leaves the data in the final data queue - \returns nothing - - */ - void *processData(int delflag); - - /** processes the data - \param delflag 0 leaves the data in the final data queue - \returns nothing - - */ - void processFrame(int* myData, int delflag); - - /** processes the data - \param delflag 0 leaves the data in the final data queue - \returns nothing - - */ - void doProcessing(double* myData, int delflag, string fname); - - - /** - pops the data from the data queue - \returns pointer to the popped data or NULL if the queue is empty. - \sa dataQueue - */ - int* popDataQueue(); - - /** - pops the data from thepostprocessed data queue - \returns pointer to the popped data or NULL if the queue is empty. - \sa finalDataQueue - */ - detectorData* popFinalDataQueue(); - - - /** - resets the raw data queue - \sa dataQueue - */ - void resetDataQueue(); - - /** - resets the postprocessed data queue - \sa finalDataQueue - */ - void resetFinalDataQueue(); - - - - - - int fillBadChannelMask(); - - - - - virtual int rateCorrect(double*, double*, double*, double*)=0; - virtual int flatFieldCorrect(double*, double*, double*, double*)=0; - - - - - - //void registerAngularConversionCallback(int (*sAngularConversion)(int & ,angleConversionConstant* ,void *), void *arg){seAngularConversion=sAngularConversion; pAngular= arg; }; - - void registerDataCallback(int( *userCallback)(detectorData*, void*), void *pArg) {dataReady = userCallback; pCallbackArg = pArg;}; - - void registerCallBackGetNumberofChannel(int (*func)(int, void *),void *arg){ getNoChannel=func;pNumberofChannel=arg;}; - - - - /** - sets the angular conversion file - \param fname file to read - \returns angular conversion flag - */ - - int setAngularConversionFile(string fname); - - //static int defaultAngularConversion(int &direc, angleConversionConstant *angoff,void *p=NULL){ return ((postProcessing *)p)->getAngularConversion( direc,angleConversionConstant *angoff=NULL);}; - /** - returns the angular conversion file - */ - string getAngularConversionFile(){if (setAngularCorrectionMask()) return string(angConvFile); else return string("none");}; - - //static int setAngularConversion(); - - static int defaultGetTotalNumberofChannels (int nChannel, void *p=NULL){ if(nChannel>=0){ return ((postProcessing*)p)->getTotalNumberOfChannels();} else return -1;}; - - protected: - - int *threadedProcessing; - - int *correctionMask; - - char *flatFieldDir; - char *flatFieldFile; - - char *badChanFile; - int *nBadChans; - int *badChansList; - int *nBadFF; - int *badFFList; - int *direction; - - /** pointer to angular conversion file name*/ - char *angConvFile; - - - /** mutex to synchronize main and data processing threads */ - pthread_mutex_t mp; - - - /** mutex to synchronizedata processing and plotting threads */ - pthread_mutex_t mg; - - /** sets when the acquisition is finished */ - int jointhread; - - /** sets when the position is finished */ - int posfinished; - - /** - data queue - */ - queue dataQueue; - /** - queue containing the postprocessed data - */ - queue finalDataQueue; - - - /** data queue size */ - int queuesize; - - - - - /** - start data processing thread - */ - void startThread(int delflag=1); // - /** the data processing thread */ - - pthread_t dataProcessingThread; - - - - /** pointer to bad channel mask 0 is channel is good 1 if it is bad \sa fillBadChannelMask() */ - int *badChannelMask; - - - - - /** - I0 measured - */ - double currentI0; - - double *fdata; - - int (*seAngularConversion)(int & ,angleConversionConstant* ,void*); - int (*getNoChannel)(int ,void*); - int (*dataReady)(detectorData*,void*); - void *pCallbackArg, *pChpermod,*pNumberofChannel,*pAngular; - - - - private: - - angularConversion *angConv; - fileIO *IOfile; - - /** pointer to beamlien fine offset*/ - double *fineOffset; - /** pointer to beamlien global offset*/ - double *globalOffset; - /** pointer to number of positions for the acquisition*/ - int *numberOfPositions; - - /** pointer to the detector positions for the acquisition*/ - double *detPositions; - - angleConversionConstant angcc[MAXMODS*MAXDET]; - - - /** pointer to angular bin size*/ - double *binSize; - - -}; - - -static void* startProcessData(void *n){\ - postProcessing *myDet=(postProcessing*)n;\ - myDet->processData(1);\ - pthread_exit(NULL);\ - -}; - -static void* startProcessDataNoDelete(void *n){\ - postProcessing *myDet=(postProcessing*)n;\ - myDet->processData(0);\ - pthread_exit(NULL);\ - -}; - - - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/postProcessingFuncs.cpp b/slsDetectorSoftware/slsDetectorAnalysis/postProcessingFuncs.cpp deleted file mode 100644 index a6845c8d6..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/postProcessingFuncs.cpp +++ /dev/null @@ -1,566 +0,0 @@ -#include "postProcessingFuncs.h" -#include "angleConversionConstant.h" -using namespace std; -//#define VERBOSE - -postProcessingFuncs::postProcessingFuncs(int *nModules,int *chPerMod,int modMask[],int badCh[], double ffcoeff[], double fferr[], double* t, int *dir, double angRadius[], double angOffset[], double angCentre[], double* to, double* bs, double *sX, double *sY): - nMods(0), chansPerMod(NULL), moduleMask(NULL), badChannelMask(NULL), ffCoeff(NULL), ffErr(NULL), tDead(0), angDir(1), angConv(NULL), totalOffset(0), binSize(0), sampleX(0), sampleY(0), totalChans(0), nBins(0), mp(NULL), mv(NULL), me(NULL), mm(NULL) -{ - initDataset(nModules, chPerMod,modMask,badCh, ffcoeff, fferr, t, dir, angRadius, angOffset, angCentre, to, bs, sX, sY); - -} - -int postProcessingFuncs::initDataset() { - - // cout << "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA init dataset " << endl; - - if (nBins) { - mp=new double[nBins]; - mv=new double[nBins]; - me=new double[nBins]; - mm=new int[nBins]; - resetMerging(mp,mv,me,mm, nBins); - // cout << "nbins " << nBins << endl; - } else { - mv=new double[totalChans]; - me=new double[totalChans]; - // cout << "nchans " << totalChans << endl; - } - totalI0=0; - - return 0; - -} - -int postProcessingFuncs::finalizeDataset(double *ang, double *val, double *err, int *np) { - - // cout << "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA finalize dataset " << endl; - - if (nBins) - *np=finalizeMerging(mp,mv,me,mm,nBins); - else - *np=totalChans; - - - - if (totalI0<=0) - totalI0=1.; - - - for (int ip=0; ip<(*np); ip++) { - - if (ang) - if (mp) - ang[ip]=mp[ip]; - - if (mv) - val[ip]=mv[ip]*totalI0; - - if (me) - err[ip]=me[ip]*totalI0; - - } - - - // cout << "delete mp " <chlast) { - // cout << *pos << " " << moduleMask[imod] << endl; - imod++; - ch0=chlast+1; - nchmod=chansPerMod[imod]; - chlast=ch0+nchmod-1; - } - - vin=data[ich]; - ein=0; - vout=data[ich]; - if (vout>=0) - eout=sqrt(vout); - else - eout=0; - - - if (tDead) { - //#ifdef VERBOSE - // cout << "ppFuncs ratecorrect" << endl; - //#endif - rateCorrect(vin, ein, vout, eout, tDead, *expTime); - vin=vout; - ein=eout; - } - //ffcorrect - - if (ffCoeff) { - //#ifdef VERBOSE - // cout << "ppFuncs ffcorrect" << endl; - //#endif - if (ffErr) - e=ffErr[ich]; - else - e=0; - flatFieldCorrect(vin, ein, vout, eout, ffCoeff[ich], e); - } - - - //i0correct - if (i0>0) { - //#ifdef VERBOSE - // cout << "ppFuncs i0 norm" << endl; - //#endif - vout/=i0; - eout/=i0; - } - - if (badChannelMask) { - //#ifdef VERBOSE - // cout << "ppFuncs badchans" << endl; - //#endif - if (badChannelMask[ich]) { - // cout << "------------------ Discarding channel " << ich << endl; - continue; - } - } - if (nBins) { - //angconv - -// #ifdef VERBOSE -// cout << "ppFuncs angconv" << endl; -// #endif -// //check module mask?!?!?!? - - - p1=convertAngle(*pos,ich-ch0,angConv[imod],moduleMask[imod],totalOffset,0,angDir); - -// #ifdef VERBOSE -// cout << "************************** ppFuncs merge" << endl; -// #endif - addPointToMerging(p1,vout,eout,mp,mv,me,mm, binSize, nBins); - - - } else { -#ifdef VERBOSE - cout << "ppFuncs merge" << endl; -#endif - //mp[ich]=ich; - mv[ich]+=vout; - me[ich]+=eout*eout; - } - } - return 0; -} - - - - - -int postProcessingFuncs::initDataset(int *nModules,int *chPerMod,int modMask[],int badCh[], double ffcoeff[], double fferr[], double* t, int *dir, double angRadius[], double angOffset[], double angCenter[], double* to, double* bs, double *sX, double *sY) { - - // cout << "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA init dataset XXXXXX " << endl; - //#ifdef VERBOSE - // cout << "delete pointers " << endl; - //#endif - - deletePointers(); - - - //#ifdef VERBOSE - // cout << "nmod " << endl; - //#endif - - if (nModules) - nMods=*nModules; - else - nMods=0; - - - //#ifdef VERBOSE - //cout << nMods << endl; - //#endif -#ifdef VERBOSE - cout << "tdead " << endl; -#endif - - if (t) - tDead=*t; - else - tDead=0; - -#ifdef VERBOSE - cout << tDead << endl; -#endif -#ifdef VERBOSE - cout << "toffset " << endl; -#endif - - if (to) - totalOffset=*to; - else - totalOffset=0; -#ifdef VERBOSE - cout << totalOffset << endl; -#endif - - - //#ifdef VERBOSE - // cout << "binsize " << endl; - //#endif - if (bs) - binSize=*bs; - else - binSize=0; - - - //#ifdef VERBOSE - // cout << binSize << endl; - //#endif -#ifdef VERBOSE - cout << "samplex " << endl; -#endif - if (sX) - sampleX=*sX; - else - sampleX=0; - -#ifdef VERBOSE - cout << sampleX << endl; -#endif -#ifdef VERBOSE - cout << "sampley " << endl; -#endif - if (sY) - sampleY=*sY; - else - sampleY=0; - -#ifdef VERBOSE - cout << sampleY << endl; -#endif - //#ifdef VERBOSE - // cout << "angdir " << endl; - //#endif - if (dir) - angDir=*dir; - else - angDir=1; - - //#ifdef VERBOSE - // cout << angDir << endl; - //#endif - totalChans=0; - - - if (nMods) - chansPerMod=new int [nMods]; - - if (nMods) - moduleMask=new int [nMods]; - - nBins=0; - if (angRadius && angOffset && angCenter && (binSize>0)) { - // cout << "??????? creating angConv"<< endl; - if (nMods) - angConv=new angleConversionConstant*[nMods]; - nBins=(int)(360./binSize)+1; - } - //#ifdef VERBOSE - //cout << "nBins " << nBins << endl; - //#endif - for (int im=0; im=0) - e=sqrt(datain); - else - e=errin; - - if (dataout>0) - errout=sqrt(e*ffcoefficient*e*ffcoefficient+datain*fferr*datain*fferr); - else - errout=1.0; - - return 0; -}; - - - int postProcessingFuncs::rateCorrect(double datain, double errin, double &dataout, double &errout, double tau, double t){ - - // double data; - double e; - - dataout=(datain*exp(tau*datain/t)); - - if (errin==0 && datain>=0) - e=sqrt(datain); - else - e=errin; - - if (dataout>0) - errout=e*dataout*sqrt((1/(datain*datain)+tau*tau/(t*t))); - else - errout=1.; - return 0; - -}; - - -int postProcessingFuncs::calculateFlatField(int* nModules, int *chPerMod, int *moduleMask, int *badChannelMask, double *ffData, double *ffCoeff, double *ffErr) { - int nmed=0, im=0; - double *xmed; - - // cout << "Claculate flat field " << endl; - - if (chPerMod==NULL) - return -1; - // if (moduleMask==NULL) - // return -1; - if (ffData==NULL) - return -1; - - if (ffErr==NULL) - return -1; - - - // cout << *nModules << " pp chpm0 " << chPerMod[0] << endl; - int totch=0; - int nm= *nModules; - for (int im=0; im0) { - im=0; - while ((imim; i--) - xmed[i]=xmed[i-1]; - - xmed[im]=ffData[ich]; - nmed++; - - } - - - - } - - - if (nmed>1 && xmed[nmed/2]>0) { - //#ifdef VERBOSE - // std::cout<< "Flat field median is " << xmed[nmed/2] << " calculated using "<< nmed << " points" << std::endl; - //#endif - - - // cout << "checking bad channel mask " << endl; - for (int ich=0; ich0) { - ffCoeff[ich]=xmed[nmed/2]/ffData[ich]; - ffErr[ich]=ffCoeff[ich]*sqrt(ffData[ich])/ffData[ich]; - } else { - ffCoeff[ich]=0.; - ffErr[ich]=1.; - } - cout << ich << " " << ffData[ich] << " " << ffCoeff[ich] << endl; - } - - } - cout << "done " << endl; - - delete [] xmed; - xmed=NULL; - - return 0; - -} - - - - - - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/postProcessingFuncs.h b/slsDetectorSoftware/slsDetectorAnalysis/postProcessingFuncs.h deleted file mode 100644 index 5851c001f..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/postProcessingFuncs.h +++ /dev/null @@ -1,80 +0,0 @@ -#ifndef POSTPROCESSINGFUNCS_H -#define POSTPROCESSINGFUNCS_H - - - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "angularConversionStatic.h" -class angleConversionConstant; - - - - -class postProcessingFuncs : public virtual angularConversionStatic - -{ - - public: - postProcessingFuncs(int *nModules=NULL,int *chPerMod=NULL,int *modMask=NULL,int *badChMask=NULL, double *ffcoeff=NULL, double *fferr=NULL, double* t=NULL, int *dir=NULL, double *angRadius=NULL, double *angOffset=NULL, double *angCentre=NULL, double* to=NULL, double* bs=NULL, double *sX=NULL, double *sY=NULL); - - - ~postProcessingFuncs(); - - - int initDataset(int *nModules,int *chPerMod,int modMask[],int badCh[], double ffcoeff[], double fferr[], double* tDead, int *dir, double angRadius[], double angOffset[], double angCentre[], double* to, double* bs, double *sX, double *sY); - - int initDataset(); - - - int finalizeDataset(double ang[], double val[], double err[], int *np); - - int addFrame(double data[], double *pos, double *IO, double *expTime, const char *filename, double *var=0); - - static int calculateFlatField(int* nModules, int *chPerMod, int moduleMask[], int badChannelMask[], double ffData[], double ffCoeff[], double ffErr[]); - - static int flatFieldCorrect(double datain, double errin, double &dataout, double &errout, double ffcoefficient, double fferr); - - - static int rateCorrect(double datain, double errin, double &dataout, double &errout, double tau, double t); - - private: - void deletePointers(); - - - int nMods; - int *chansPerMod; - int *moduleMask; - int *badChannelMask; - double *ffCoeff; - double *ffErr; - double tDead; - int angDir; - angleConversionConstant **angConv; - double totalOffset; - double binSize; - double sampleX; - double sampleY; - int totalChans; - - int nBins; - - double totalI0; - - - double *mp, *mv,*me; - int *mm; - -}; - - -#endif //POSTPROCESSINGFUNCS_H diff --git a/slsDetectorSoftware/slsDetectorAnalysis/postProcessing_Standalone.cpp b/slsDetectorSoftware/slsDetectorAnalysis/postProcessing_Standalone.cpp deleted file mode 100644 index 185d811ad..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/postProcessing_Standalone.cpp +++ /dev/null @@ -1,593 +0,0 @@ -#include "postProcessing.h" -#include "usersFunctions.h" -//#include "angularConversion.h" - -//#include "AngularConversion_Standalone.h" - -postProcessing::postProcessing(){ - pthread_mutex_t mp1 = PTHREAD_MUTEX_INITIALIZER; - mp=mp1; - pthread_mutex_init(&mp, NULL); - mg=mp1; - pthread_mutex_init(&mg, NULL); - //cout << "reg callback "<< endl; - dataReady = 0; - pCallbackArg = 0; - registerDataCallback(&defaultDataReadyFunc, NULL); - //tregisterCallBackGetChansPerMod(&defaultGetChansPerMod,NULL); - //cout << "done "<< endl; - angConv=new angularConversion(numberOfPositions,detPositions,binSize, fineOffset, globalOffset); -} - - - - - - -int postProcessing::flatFieldCorrect(double datain, double errin, double &dataout, double &errout, double ffcoefficient, double fferr){ - double e; - - dataout=datain*ffcoefficient; - - if (errin==0 && datain>=0) - e=sqrt(datain); - else - e=errin; - - if (dataout>0) - errout=sqrt(e*ffcoefficient*e*ffcoefficient+datain*fferr*datain*fferr); - else - errout=1.0; - - return 0; -}; - - - int postProcessing::rateCorrect(double datain, double errin, double &dataout, double &errout, double tau, double t){ - - // double data; - double e; - - dataout=(datain*exp(tau*datain/t)); - - if (errin==0 && datain>=0) - e=sqrt(datain); - else - e=errin; - - if (dataout>0) - errout=e*dataout*sqrt((1/(datain*datain)+tau*tau/(t*t))); - else - errout=1.; - return 0; - -}; - - - - - -int postProcessing::setBadChannelCorrection(ifstream &infile, int &nbad, int *badlist, int moff){ - - int interrupt=0; - int ich; - int chmin,chmax; - string str; - - - - nbad=0; - while (infile.good() and interrupt==0) { - getline(infile,str); -#ifdef VERBOSE - std::cout << str << std::endl; -#endif - istringstream ssstr; - ssstr.str(str); - if (ssstr.bad() || ssstr.fail() || infile.eof()) { - interrupt=1; - break; - } - if (str.find('-')!=string::npos) { - ssstr >> chmin ; - ssstr.str(str.substr(str.find('-')+1,str.size())); - ssstr >> chmax; -#ifdef VERBOSE - std::cout << "channels between"<< chmin << " and " << chmax << std::endl; -#endif - for (ich=chmin; ich<=chmax; ich++) { - if (nbad> ich; -#ifdef VERBOSE - std::cout << "channel "<< ich << std::endl; -#endif - if (nbad0) { -#ifdef VERBOSE - cout << "**************Current position index is " << getCurrentPositionIndex() << endl; -#endif - // if (*numberOfPositions>0) { - if (getCurrentPositionIndex()<=1) { - -#ifdef VERBOSE - cout << "reset merging " << endl; -#endif - angConv->resetMerging(); - } - -#ifdef VERBOSE - cout << "add to merging "<< getCurrentPositionIndex() << endl; -#endif - - angConv->addToMerging(ang, ffcdata, ffcerr, badChannelMask ); - -#ifdef VERBOSE - cout << getCurrentPositionIndex() << " " << getNumberOfPositions() << endl; - -#endif - - - // cout << "lock 1" << endl; - pthread_mutex_lock(&mp); - if ((getCurrentPositionIndex()>=getNumberOfPositions() && posfinished==1 && queuesize==1)) { - -#ifdef VERBOSE - cout << "finalize merging " << getCurrentPositionIndex()<< endl; -#endif - np=angConv->finalizeMerging(); - /** file writing */ - angConv->incrementPositionIndex(); - // cout << "unlock 1" << endl; - pthread_mutex_unlock(&mp); - - - fname=createFileName(); - -#ifdef VERBOSE - cout << "writing merged data file" << endl; -#endif - writeDataFile (fname+ext,np,angConv->getMergedCounts(), angConv->getMergedErrors(), angConv->getMergedPositions(),'f'); -#ifdef VERBOSE - cout << " done" << endl; -#endif - - - -// if (delflag) { -// deleteMerging(); -// } else { - thisData=new detectorData(angConv->getMergedCounts(),angConv->getMergedErrors(),angConv->getMergedPositions(),getCurrentProgress(),(fname+ext).c_str(),np); - - // // cout << "lock 2" << endl; -// pthread_mutex_lock(&mg); -// finalDataQueue.push(thisData); -// // cout << "unlock 2" << endl; - -// pthread_mutex_unlock(&mg); - - if (dataReady) { - - dataReady(thisData, pCallbackArg); - delete thisData; - } - -// } - // cout << "lock 3" << endl; - pthread_mutex_lock(&mp); - } - // cout << "unlock 3" << endl; - pthread_mutex_unlock(&mp); - - if (ffcdata) - delete [] ffcdata; - - ffcdata=NULL; - - if (ffcerr) - delete [] ffcerr; - ffcerr=NULL; - - if (ang) - delete [] ang; - ang=NULL; - - } else { -// if (delflag) { -// if (ffcdata) -// delete [] ffcdata; -// if (ffcerr) -// delete [] ffcerr; -// if ( ang) -// delete [] ang; -// } else { - thisData=new detectorData(ffcdata,ffcerr,NULL,getCurrentProgress(),(fname+ext).c_str(),getTotalNumberOfChannels()); - - - if (dataReady) { - dataReady(thisData, pCallbackArg); - delete thisData; - } -// pthread_mutex_lock(&mg); -// finalDataQueue.push(thisData); - - -// pthread_mutex_unlock(&mg); -// } - } - //} - - incrementFileIndex(); -#ifdef VERBOSE - cout << "fdata is " << fdata << endl; -#endif - -} - - - - - -int postProcessing::fillBadChannelMask() { - - int nbad=0; - - if (*correctionMask&(1<< DISCARD_BAD_CHANNELS)) { - nbad=getBadChannelCorrection(); -#ifdef VERBOSE - cout << "number of bad channels is " << nbad << endl; -#endif - if (nbad>0) { - - int *badChansList=new int[nbad]; - getBadChannelCorrection(badChansList); - - if (badChannelMask) - delete [] badChannelMask; - badChannelMask=new int[getTotalNumberOfChannels()]; - -#ifdef VERBOSE - cout << " pointer to bad channel mask is " << badChannelMask << endl; -#endif - for (int ichan=0; ichan=0 ) { - if (badChannelMask[badChansList[ichan]]==0) - nbad++; - badChannelMask[badChansList[ichan]]=1; - - } - } - delete [] badChansList; - - } else { - if (badChannelMask) { -#ifdef VERBOSE - cout << "deleting bad channel mask beacuse number of bad channels is 0" << endl; -#endif - - delete [] badChannelMask; - badChannelMask=NULL; - } - } - - } else { -#ifdef VERBOSE - cout << "bad channel correction is disabled " << nbad << endl; -#endif - if (badChannelMask) { -#ifdef VERBOSE - cout << "deleting bad channel mask beacuse no bad channel correction is selected" << endl; -#endif - delete [] badChannelMask; - badChannelMask=NULL; - } - } - -#ifdef VERBOSE - cout << "number of bad channels is " << nbad << endl; -#endif - return nbad; - -} - - - - - - -void* postProcessing::processData(int delflag) { - - -#ifdef VERBOSE - std::cout<< " processing data - threaded mode " << *threadedProcessing << endl; -#endif - - - angConv->setTotalNumberOfChannels(getTotalNumberOfChannels()); - setTotalProgress(); - pthread_mutex_lock(&mp); - queuesize=dataQueue.size(); - pthread_mutex_unlock(&mp); - - int *myData; - int dum=1; - - fdata=NULL; - - - while(dum | *threadedProcessing) { // ???????????????????????? - - - /* IF THERE ARE DATA PROCESS THEM*/ - pthread_mutex_lock(&mp); - while((queuesize=dataQueue.size())>0) { - /** Pop data queue */ - myData=dataQueue.front(); // get the data from the queue - pthread_mutex_unlock(&mp); - - if (myData) { - processFrame(myData,delflag); - //usleep(1000); - } - pthread_mutex_lock(&mp); - - } - pthread_mutex_unlock(&mp); - - /* IF THERE ARE NO DATA look if acquisition is finished */ - pthread_mutex_lock(&mp); - if (jointhread) { - if (dataQueue.size()==0) { - pthread_mutex_unlock(&mp); - break; - } - pthread_mutex_unlock(&mp); - } else { - pthread_mutex_unlock(&mp); - } - dum=0; - } - - if (fdata) { -#ifdef VERBOSE - cout << "delete fdata" << endl; -#endif - delete [] fdata; -#ifdef VERBOSE - cout << "done " << endl; -#endif - } - return 0; -} - - -int* postProcessing::popDataQueue() { - int *retval=NULL; - if( !dataQueue.empty() ) { - retval=dataQueue.front(); - dataQueue.pop(); - } - return retval; -} - -detectorData* postProcessing::popFinalDataQueue() { - detectorData *retval=NULL; - pthread_mutex_unlock(&mg); - if( !finalDataQueue.empty() ) { - retval=finalDataQueue.front(); - finalDataQueue.pop(); - } - pthread_mutex_unlock(&mg); - return retval; -} - -void postProcessing::resetDataQueue() { - int *retval=NULL; - while( !dataQueue.empty() ) { - retval=dataQueue.front(); - dataQueue.pop(); - delete [] retval; - } - -} - -void postProcessing::resetFinalDataQueue() { - detectorData *retval=NULL; - pthread_mutex_lock(&mg); - while( !finalDataQueue.empty() ) { - retval=finalDataQueue.front(); - finalDataQueue.pop(); - delete retval; - } - pthread_mutex_unlock(&mg); -} - - -void postProcessing::startThread(int delflag) { - pthread_attr_t tattr; - int ret; - sched_param param, mparam; - int policy= SCHED_OTHER; - - - // set the priority; others are unchanged - //newprio = 30; - mparam.sched_priority =1; - param.sched_priority =1; - - - /* Initialize and set thread detached attribute */ - pthread_attr_init(&tattr); - pthread_attr_setdetachstate(&tattr, PTHREAD_CREATE_JOINABLE); - - - - // param.sched_priority = 5; - // scheduling parameters of main thread - ret = pthread_setschedparam(pthread_self(), policy, &mparam); - //#ifdef VERBOSE - // printf("current priority is %d\n",param.sched_priority); - //#endif - if (delflag) - ret = pthread_create(&dataProcessingThread, &tattr,startProcessData, (void*)this); - else - ret = pthread_create(&dataProcessingThread, &tattr,startProcessDataNoDelete, (void*)this); - - pthread_attr_destroy(&tattr); - // scheduling parameters of target thread - ret = pthread_setschedparam(dataProcessingThread, policy, ¶m); - -} - - - diff --git a/slsDetectorSoftware/slsDetectorAnalysis/postProcessing_Standalone.h b/slsDetectorSoftware/slsDetectorAnalysis/postProcessing_Standalone.h deleted file mode 100644 index 213ed6de4..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/postProcessing_Standalone.h +++ /dev/null @@ -1,367 +0,0 @@ -#ifndef POSTPROCESSING_H -#define POSTPROCESSING_H - - -#include "detectorData.h" -#include "fileIO.h" -#include - -#include -#include -#include -#include -#include -#include -#include -#include - - -class angularConversion; - -; - -#define MAX_BADCHANS 2000 - - -#define defaultTDead {170,90,750} /**< should be changed in order to have it separate for the different detector types */ - - -/** - @short methods for data postprocessing - - (including thread for writing data files and plotting in parallel with the acquisition) -*/ - -class postProcessing : public virtual fileIO { - - -//: public angularConversion, public fileIO - - public: - postProcessing(); - virtual ~postProcessing(){}; - - - - - /** - get bad channels correction - \param bad pointer to array that if bad!=NULL will be filled with the bad channel list - \returns 0 if bad channel disabled or no bad channels, >0 otherwise - */ - virtual int getBadChannelCorrection(int *bad=NULL)=0; - - - /** - get flat field corrections - \param corr if !=NULL will be filled with the correction coefficients - \param ecorr if !=NULL will be filled with the correction coefficients errors - \returns 0 if ff correction disabled, >0 otherwise - */ - virtual int getFlatFieldCorrection(float *corr=NULL, float *ecorr=NULL)=0; - - /** - set flat field corrections - \param corr if !=NULL the flat field corrections will be filled with corr (NULL usets ff corrections) - \param ecorr if !=NULL the flat field correction errors will be filled with ecorr (1 otherwise) - \returns 0 if ff correction disabled, >0 otherwise - */ - virtual int setFlatFieldCorrection(float *corr, float *ecorr=NULL)=0; - - /** - set bad channels correction - \param fname file with bad channel list ("" disable) - \returns 0 if bad channel disabled, >0 otherwise - */ - virtual int setBadChannelCorrection(string fname="")=0; - - static int setBadChannelCorrection(ifstream &infile, int &nbad, int *badlist, int moff=0); - /** - set bad channels correction - \param fname file with bad channel list ("" disable) - -ff - \param nbad reference to number of bad channels - \param badlist array of badchannels - \returns 0 if bad channel disabled, >0 otherwise - */ - virtual int setBadChannelCorrection(string fname, int &nbad, int *badlist, int off=0)=0; - - - /** - set bad channels correction - \param nch number of bad channels - \param chs array of channels - \param ff 0 if normal bad channels, 1 if ff bad channels - \returns 0 if bad channel disabled, >0 otherwise - */ - virtual int setBadChannelCorrection(int nch, int *chs, int ff=0)=0; - - /** - flat field correct data - \param datain data - \param errin error on data (if<=0 will default to sqrt(datain) - \param dataout corrected data - \param errout error on corrected data - \param ffcoefficient flat field correction coefficient - \param fferr erro on ffcoefficient - \returns 0 - */ - static int flatFieldCorrect(float datain, float errin, float &dataout, float &errout, float ffcoefficient, float fferr); - - /** - rate correct data - \param datain data - \param errin error on data (if<=0 will default to sqrt(datain) - \param dataout corrected data - \param errout error on corrected data - \param tau dead time 9in ns) - \param t acquisition time (in ns) - \returns 0 - */ - static int rateCorrect(float datain, float errin, float &dataout, float &errout, float tau, float t); - - - int enableWriteToFile(int i=-1) {if (i>0) ((*correctionMask)|=(1<0) (*correctionMask)|=(1<< ANGULAR_CONVERSION); return ((*correctionMask)&(1<< ANGULAR_CONVERSION));}; - - - - int enableAngularConversion(int i=-1) {if (i>0) return setAngularConversionFile("default"); if (i==0) return setAngularConversionFile(""); return setAngularCorrectionMask();}; - - - int enableBadChannelCorrection(int i=-1) {if (i>0) return setBadChannelCorrection("default"); if (i==0) return setBadChannelCorrection(""); return ((*correctionMask)&(1<< DISCARD_BAD_CHANNELS));}; - - - - - /** returns the bad channel list file */ - string getBadChannelCorrectionFile() {if ((*correctionMask)&(1<< DISCARD_BAD_CHANNELS)) return string(badChanFile); else return string("none");}; - - - /** - get flat field corrections file directory - \returns flat field correction file directory - */ - string getFlatFieldCorrectionDir(){return string(flatFieldDir);}; - /** - set flat field corrections file directory - \param flat field correction file directory - \returns flat field correction file directory - */ - string setFlatFieldCorrectionDir(string dir){strcpy(flatFieldDir,dir.c_str()); return string(flatFieldDir);}; - - /** - get flat field corrections file name - \returns flat field correction file name - */ - string getFlatFieldCorrectionFile(){ if ((*correctionMask)&(1<=0) *threadedProcessing=b; return *threadedProcessing;}; - - - - - /** processes the data - \param delflag 0 leaves the data in the final data queue - \returns nothing - - */ - void *processData(int delflag); - - /** processes the data - \param delflag 0 leaves the data in the final data queue - \returns nothing - - */ - void processFrame(int* myData, int delflag); - - /** processes the data - \param delflag 0 leaves the data in the final data queue - \returns nothing - - */ - void doProcessing(float* myData, int delflag, string fname); - - - /** - pops the data from the data queue - \returns pointer to the popped data or NULL if the queue is empty. - \sa dataQueue - */ - int* popDataQueue(); - - /** - pops the data from thepostprocessed data queue - \returns pointer to the popped data or NULL if the queue is empty. - \sa finalDataQueue - */ - detectorData* popFinalDataQueue(); - - - /** - resets the raw data queue - \sa dataQueue - */ - void resetDataQueue(); - - /** - resets the postprocessed data queue - \sa finalDataQueue - */ - void resetFinalDataQueue(); - - - - - - int fillBadChannelMask(); - - - - - virtual int rateCorrect(float*, float*, float*, float*)=0; - virtual int flatFieldCorrect(float*, float*, float*, float*)=0; - - - - - - - - void registerDataCallback(int( *userCallback)(detectorData*, void*), void *pArg) {dataReady = userCallback; pCallbackArg = pArg;}; - //void registerCallBackGetChansPerMod(int (*func)(int, void *),void *arg){ getChansPerMod=func;pChpermod=arg;} - - - - /** - sets the angular conversion file - \param fname file to read - \returns angular conversion flag - */ - - int setAngularConversionFile(string fname); - - - /** - returns the angular conversion file - */ - string getAngularConversionFile(){if (setAngularCorrectionMask()) return string(angConvFile); else return string("none");}; - - - - protected: - - int *threadedProcessing; - - int *correctionMask; - - char *flatFieldDir; - char *flatFieldFile; - - char *badChanFile; - int *nBadChans; - int *badChansList; - int *nBadFF; - int *badFFList; - - /** pointer to angular conversion file name*/ - char *angConvFile; - - - /** mutex to synchronize main and data processing threads */ - pthread_mutex_t mp; - - - /** mutex to synchronizedata processing and plotting threads */ - pthread_mutex_t mg; - - /** sets when the acquisition is finished */ - int jointhread; - - /** sets when the position is finished */ - int posfinished; - - /** - data queue - */ - queue dataQueue; - /** - queue containing the postprocessed data - */ - queue finalDataQueue; - - - /** data queue size */ - int queuesize; - - - - - /** - start data processing thread - */ - void startThread(int delflag=1); // - /** the data processing thread */ - - pthread_t dataProcessingThread; - - - - /** pointer to bad channel mask 0 is channel is good 1 if it is bad \sa fillBadChannelMask() */ - int *badChannelMask; - - - - - /** - I0 measured - */ - float currentI0; - - float *fdata; - - - //int (*getChansPerMod)(int, void*); - - - int (*dataReady)(detectorData*,void*); - void *pCallbackArg, *pChpermod; - - - - private: - angularConversion *angConv; - - -}; - - -static void* startProcessData(void *n){\ - postProcessing *myDet=(postProcessing*)n;\ - myDet->processData(1);\ - pthread_exit(NULL);\ - -}; - -static void* startProcessDataNoDelete(void *n){\ - postProcessing *myDet=(postProcessing*)n;\ - myDet->processData(0);\ - pthread_exit(NULL);\ - -}; - - - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/runningStat.h b/slsDetectorSoftware/slsDetectorAnalysis/runningStat.h deleted file mode 100644 index 98ab7986f..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/runningStat.h +++ /dev/null @@ -1,92 +0,0 @@ - /********************************************//** - * @file runningStat.h - * @short handles pedestal data and doesnt move - ***********************************************/ -#ifndef RUNNINGSTAT_H -#define RUNNINGSTAT_H - -#include - -//#include "sls_detector_defs.h" -#include -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; - -/** - @short class handling pedestal data that is static - */ - -class runningStat{ - -public: - /** - * Constructor - */ - runningStat() : m_n(0),m_oldM(0),m_newM(0),m_oldS(0),m_newS(0) {} - - /** - * Clear number of data values - */ - void Clear(){ - m_n = 0; - } - - /** - * Push Pedestal - */ - void Push(double x){ - m_n++; - - // See Knuth TAOCP vol 2, 3rd edition, page 232 - if (m_n == 1){ - m_oldM = m_newM = x; - m_oldS = 0.0; - }else{ - m_newM = m_oldM + (x - m_oldM)/m_n; - m_newS = m_oldS + (x - m_oldM)*(x - m_newM); - - // set up for next iteration - m_oldM = m_newM; - m_oldS = m_newS; - } - } - - /** - * Get number of data values - */ - int NumDataValues() const{ - return m_n; - } - - /** - * Get mean - */ - double Mean() const{ - return (m_n > 0) ? m_newM : 0.0; - } - - /** - * Get variance - */ - double Variance() const{ - return ( (m_n > 1) ? m_newS/(m_n - 1) : 0.0 ); - } - - /** - * Get standard deviation - */ - double StandardDeviation() const{ - return sqrt( Variance() ); - } - -private: - /** number of data values */ - int m_n; - - /** old and new mean */ - double m_oldM, m_newM, m_oldS, m_newS; - -}; - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/singlePhotonFilter.cpp b/slsDetectorSoftware/slsDetectorAnalysis/singlePhotonFilter.cpp deleted file mode 100644 index ee9dc95e7..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/singlePhotonFilter.cpp +++ /dev/null @@ -1,678 +0,0 @@ - /********************************************//** - * @file singlePhotonFilter.cpp - * @short single photon filter using trees - ***********************************************/ -#include "singlePhotonFilter.h" -#include - - -#define FILE_BUF_SIZE (16*1024*1024) //16mb -#define HEADER_SIZE_NUM_FRAMES 2 -#define HEADER_SIZE_NUM_PACKETS 1 - - -singlePhotonFilter::singlePhotonFilter(int nx, int ny, - int fmask, int pmask, int foffset, int poffset, int pperf, int iValue, - int16_t *m, int16_t *s, CircularFifo* f, int d, int* tfcaught, int* fcaught,uint32_t* cframenum): -#ifdef MYROOT1 - myTree(NULL), -#else - - nHitsPerFile(0), - nTotalHits(0), -#endif - myFile(NULL), - nHitsPerFrame(0), - nChannelsX(nx), - nChannelsY(ny), - nClusterX(CLUSTER_SIZE), - nClusterY(CLUSTER_SIZE), - map(m), - dataSize(d), - mask(s), - nped(DEFAULT_NUM_PEDESTAL), - nsigma(DEFAULT_SIGMA), - nbackground(DEFAULT_BACKGROUND), - outcorr(DEFAULT_CORRECTION), - fnum(0), - pnum(0), - ptot(0), - f0(0), - frame_index_mask(fmask), - packet_index_mask(pmask), - frame_index_offset(foffset), - packet_index_offset(poffset), - packets_per_frame(pperf), - incrementValue(iValue), - firstTime(true), - ret(0), - pIndex(0), - fIndex(0), - thread_started(0), - threads_mask(0x0), - currentThread(-1), - thisThreadIndex(-1), - fileIndex(0), - fifo(f), - totalFramesCaught(tfcaught), - framesCaught(fcaught), - currentframenum(cframenum), - freeFifoCallBack(NULL), - pFreeFifo(NULL){ - //cluster - if (nChannelsX) - nClusterX = 1; - -#ifndef MYROOT1 - //photonHitList=(single_photon_hit**) (new int*[nChannelsX*nChannelsY/(nClusterX*nClusterY)*1000]); - photonHitList=new single_photon_hit*[nChannelsX*nChannelsY/(nClusterX*nClusterY)*1000]; - for (int ii=0; iidata = new double[nClusterX*nClusterY]; - myPhotonHit->x = 0; - myPhotonHit->y = 0; - myPhotonHit->rms = 0; - myPhotonHit->ped = 0; - myPhotonHit->iframe = -1; - - for(int i=0;i < NUM_THREADS; i++){ - /*smp[i] = NULL;*/ - mem0[i]=NULL; - } - numFramesAlloted = new int[NUM_THREADS]; - - strcpy(savefilename,""); - strcpy(filePath,""); - strcpy(fileName,"run"); - - pthread_mutex_init(&write_mutex,NULL); - pthread_mutex_init(&running_mutex,NULL); - pthread_mutex_init(&frnum_mutex,NULL); - - - -} - - -singlePhotonFilter::~singlePhotonFilter(){ - enableCompression(false); - if(numFramesAlloted) delete [] numFramesAlloted; - writeToFile(); - closeFile(); - if(myFile) delete myFile; - if(mask) delete mask; - if(stat) delete stat; - if(nHitStat) delete nHitStat; - /*if(smp) delete []smp;*/ - if(mem0) delete [] mem0; - if(fifo) delete fifo; -} - - - - - - -int singlePhotonFilter::enableCompression(bool enable){ -//#ifdef VERBOSE - cout << "Compression set to " << enable; -#ifdef MYROOT1 - cout << " with root" << endl; -#else - cout << " without root" << endl; -#endif -//#endif - if(enable){ - threads_mask = 0x0; - currentThread = -1; - - for(int i=0; ifindHits(); - return this_pointer; -} - - - -int singlePhotonFilter::initTree(){ -#ifdef MYROOT1 - writeToFile(); - closeFile(); - sprintf(savefilename, "%s/%s_%d_.root", filePath,fileName,fileIndex); - - //file - myFile = new TFile(savefilename, "RECREATE"); /** later return error if it exists */ - cout<<"File created: "<Branch("iframe",&myPhotonHit->iframe,"iframe/I"); - myTree->Branch("x",&myPhotonHit->x,"x/I"); - myTree->Branch("y",&myPhotonHit->y,"y/I"); - myTree->Branch("data",myPhotonHit->data,cdata); - myTree->Branch("pedestal",&myPhotonHit->ped,"pedestal/D"); - myTree->Branch("rms",&myPhotonHit->rms,"rms/D"); -#else - - writeToFile(); - closeFile(); - sprintf(savefilename, "%s/%s_f%012d_%d.raw", filePath,fileName,nTotalHits,fileIndex); - myFile = fopen(savefilename, "w"); - setvbuf(myFile,NULL,_IOFBF,FILE_BUF_SIZE); - cout<<"File created: "<Write(); - nHitsPerFrame = 0; - return OK; - }else - cout << "ERROR: Could not write to " << nHitsPerFrame << " hits to file as file or tree doesnt exist" << endl; -#else - if(myFile){ - int ii; - /*cout<<"writing "<< nHitsPerFrame << " hits to file" << endl;*/ - for (ii=0; iiwrite(myFile); - // delete photonHitList[ii]; - } - // delete photonHitList[ii]; - // photonHitList[0]=new single_photon_hit(nClusterX,nClusterY); - - // fwrite((void*)(photonHitList), 1, sizeof(single_photon_hit)*nHitsPerFrame, myFile); - /*framesInFile += nHitsPerFrame;*/ - nHitsPerFrame = 0; - //cout<<"Exiting writeToFile"<GetCurrentFile(); - myFile->Close(); - myFile = NULL;//delete myFile; - } - myTree = NULL;//delete myTree; - } -#else - if(myFile) - fclose(myFile); - myFile = NULL; -#endif - return OK; -} - - - - - -void singlePhotonFilter::setupAcquisitionParameters(char *outfpath, char* outfname, int outfIndex){ - fileIndex = outfIndex; - strcpy(filePath,outfpath); - strcpy(fileName,outfname); - - fnum = 0; pnum = 0; ptot = 0; f0 = 0; firstTime = true; currentThread = -1; - *framesCaught = 0; - *currentframenum = 0; - - //initialize - for (int ir=0; irClear(); - nHitStat->SetN(nbackground); -#ifndef MYROOT1 - nTotalHits = 0; -#endif -} - - -/* - rets -case 0: waiting for next packet of new frame -case 1: finished with full frame, - start new frame -case -1: last packet of current frame, - invalidate remaining packets, - start new frame -case -2: first packet of new frame, - invalidate remaining packets, - check buffer needs to be pushed, - start new frame with the current packet, - then ret = 0 -case -3: last packet of new frame, - invalidate remaining packets, - check buffer needs to be pushed, - start new frame with current packet, - then ret = -1 (invalidate remaining packets and start a new frame) - */ -int singlePhotonFilter::verifyFrame(char *inData){ - ret = 0; - pIndex = 0; - fIndex = 0; - fIndex = (((uint32_t)(*((uint32_t*)inData)))& frame_index_mask) >> frame_index_offset; - pIndex = (((uint32_t)(*((uint32_t*)inData)))& packet_index_mask) >> packet_index_offset; - - //check validity of packet index - if ((pIndex < 0) && (pIndex >= packets_per_frame)){ - cout << "cannot decode packet index:" << pIndex << endl; - //its already dealt with cuz this frame will be discarded in the end - } - pIndex += incrementValue; - - //for moench, put first packet last - if (pIndex == 0) - pIndex = packets_per_frame; -//#ifdef VERYVERBOSE - cout<<"fi:"<>frame_index_offset); - //progress - if((clusteriframe + PROGRESS_INCREMENT) > *currentframenum){ - pthread_mutex_lock(&frnum_mutex); - *currentframenum = clusteriframe; - pthread_mutex_unlock(&frnum_mutex); - /*cout<<"currentframenum:"<data; - - //for each pixel - for (ir=0; ir= (dataSize))){ - cout << "Bad Channel Mapping index: " << map[currentIndex] << endl; - continue; - } - - //if frame within pedestal number - if (clusteriframe < nped){ - stat[currentIndex].Calc((double)(mask[currentIndex] ^ myData[map[currentIndex]])); - // frame outside pedestal number - }else{ - - dum = 1; - tot = 0; - clusterrms = stat[currentIndex].StandardDeviation();//-1 - clusterped = stat[currentIndex].Mean();//0 - sigmarms = clusterrms * nsigma; - - - clusterData[clusterCenterPixel] = ((double)(mask[currentIndex] ^ myData[map[currentIndex]])) - clusterped; - for (r=-deltaX; r <= deltaX; ++r ){ - if (((ir+r) < 0) || ((ir+r) >= nChannelsX)) - continue; - for(c=-1; c <= 1; ++c){ - if (((ic+c) < 0) || ((ic+c) >= nChannelsY)) - continue; - - - pixelIndex = currentIndex + (r*nChannelsY+c); - - if ((map[pixelIndex] < 0) || (map[pixelIndex] >= dataSize)){ - cout << "Bad Channel Mapping index: " << map[pixelIndex] << endl; - continue; - } - - clusterIndex = pixelIndex-(currentIndex - deltaX * nChannelsY - 1); - clusterData[clusterIndex] = ((double)(mask[pixelIndex] ^ myData[map[pixelIndex]])) - stat[pixelIndex].Mean(); - tot += clusterData[clusterIndex]; - //discard negative events - if (clusterData[clusterIndex] > clusterData[clusterCenterPixel]) - dum = 2; - - } - - } - - - if (tot < sqrtCluster * sigmarms) - dum = 0; - //discard events (for pedestal) where sum of the neighbours is too large. - if (clusterData[clusterCenterPixel] < sigmarms && dum != 0) - dum = 3; - //Appriximated running average - if (clusterData[clusterCenterPixel] > -sigmarms && - clusterData[clusterCenterPixel] < sigmarms && - dum == 0){ - stat[currentIndex].Calc((double)(mask[currentIndex]^myData[map[currentIndex]])); - } - // this is an event and we are in the center - else if (dum == 1){ - pthread_mutex_lock(&write_mutex); -#ifdef MYROOT1 - myTree->Fill(); -#else - for (int ix=0; ixdata[ix] = clusterData[ix]; - - photonHitList[nHitsPerFrame]->x = ic; - photonHitList[nHitsPerFrame]->y = ir; - photonHitList[nHitsPerFrame]->rms = clusterrms; - photonHitList[nHitsPerFrame]->ped = clusterped; - photonHitList[nHitsPerFrame]->iframe = clusteriframe; - //hit.write(myFile); - - nHitsPerFrame++; - - // cout << nHitsPerFrame << " " << nChannelsX*nChannelsY/(nClusterX*nClusterY)*1000 << endl; - - // photonHitList[nHitsPerFrame]=new single_photon_hit(nClusterX,nClusterY); - // cout << "done" << endl; - nHitsPerFile++; - nTotalHits++; - if(nHitsPerFile >= MAX_HITS_PER_FILE-1) - initTree(); -#endif - pthread_mutex_unlock(&write_mutex); - } - - } - } - } - }else{ - //cout<< "did no receiver fulll frame"<Calc((double)nHitsPerFrame); - //write for each frame, not packet - - pthread_mutex_lock(&write_mutex); - cout << "write to file " << nHitsPerFrame << endl; - writeToFile(); - pthread_mutex_unlock(&write_mutex); - - //increment offset - isData += dataSize; - - /* - if ((clusteriframe%1000 == 0) && (clusteriframe != 0) ){ - cout << dec << "Frame: " << clusteriframe << " Hit Avg over last frames: " << - nHitStat->Mean() << " .. "<StandardDeviation() << endl; - cout<<"writing "<< nHitsPerFrame << " hits to file" << endl; - } - */ - } - - pthread_mutex_lock(&write_mutex); - if(freeFifoCallBack) - freeFifoCallBack(freeData,pFreeFifo); - //fifo->push(freeData);//fifo->push(isData); - pthread_mutex_unlock(&write_mutex); - - //thread not running - pthread_mutex_lock(&running_mutex); - threads_mask^=(1<=25000) { - cout<<"*****************problem: "<<((theData-listmem0)/4096)<<" :"< -#include -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "circularFifo.h" -#include "runningStat.h" -#include "movingStat.h" -#include "single_photon_hit.h" - - - -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; -#define MAX_STR_LENGTH 1000 - -/** - return values -*/ -enum { - OK, /**< function succeeded */ - FAIL /**< function failed */ -}; - - -/** - @short class handling trees and its data file - */ - -class singlePhotonFilter{ -public: - /** - * Constructor - * @param nx Number of Channels in X direction - * @param ny Number of Channels in Y direction - * @param fmask frame index mask - * @param pmask packet index mask - * @param foffset frame index offset - * @param poffset packet index offset - * @param pperf packets per frame - * @param iValue increment value (only for gotthard to increment index to have matching frame number) - * @param m Map to data without headers - * @param s mask as to which adcs are inverted - * @param f circular fifo buffer, which needs to be freed - * @param d Size of data with the headers - * @param tfcaught pointer to total frames caught- needs updation for client - * @param fcaught pointer to frames caught - needs updation for client - * @param cframenum pointer to currentframe num- needs updation for progress for gui - */ - singlePhotonFilter( - int nx, - int ny, - int fmask, - int pmask, - int foffset, - int poffset, - int pperf, - int iValue, - int16_t *m, - int16_t *s, - CircularFifo* f, - int d, - int* tfcaught, - int* fcaught, - uint32_t* cframenum); - - /** virtual destructor */ - virtual ~singlePhotonFilter(); - -#ifdef MYROOT1 - /** - * returns tree - */ - TTree *getTree(){ return myTree; }; -#endif - - /** - * Returns packets per frame - */ - int getPacketsPerFrame(){ return packets_per_frame;}; - - /** - * returns struct - */ - single_photon_hit* getStructure(){ return myPhotonHit; }; - - /** Set number of frames to calculate pedestal at beginning */ - void setNPed(int n){ nped = n; }; - - /** Get number of frames to calculate pedestal at beginning */ - int getNPed(){return nped;}; - - /** Set Distance from pedestal to detect a hit */ - void setNSigma(int n){ nsigma = n; }; - - /** Get Distance from pedestal to detect a hit */ - int getNSigma(){return nsigma;}; - - /** Set background */ - void setNBackground(int n){ nbackground = n; }; - - /** Get background */ - int getNBackground(){return nbackground;}; - - /** Set correction */ - void setOutCorr(double d){ outcorr = d; }; - - /** Get correction */ - double getOutCorr(){return outcorr;}; - - /** - * Construct a tree, populate struct for the single photon hit and provide all the masks and offsets - * @param outdir Output file directory/Output file name - * returns OK if successful, else FAIL - - */ - int initTree(); - - /** - * Writes tree/struct to file - * returns OK if successful, else FAIL - */ - int writeToFile(); - - /** - * Closes file - * returns OK if successful, else FAIL - */ - int closeFile(); - - /** - * Reset Indices before starting acquisition - */ - void setupAcquisitionParameters(char *outfpath, char* outfname, int outfIndex); - - /** reconstruct the frame with all the right packets - * @param inData the data from socket to be verified - * returns - * 0: waiting for next packet of new frame - * 1: finished with full frame, - * start new frame - * -1: last packet of current frame, - * invalidate remaining packets, - * start new frame - * -2: first packet of new frame, - * invalidate remaining packets, - * check buffer needs to be pushed, - * start new frame with the current packet, - * then ret = 0 - * -3: last packet of new frame, - * invalidate remaining packets, - * check buffer needs to be pushed, - * start new frame with current packet, - * then ret = -1 (invalidate remaining packets and start a new frame) - */ - int verifyFrame(char *inData); - - /** - * Find Hits frame by frame and save it in file/tree - */ - void findHits(); - - /** Enable or disable compression - * @param enable true to enable compression and false to disable - * returns OK for success or FAIL for failure, incase threads fail to start - * */ - int enableCompression(bool enable); - - /** create threads for compression - * @param this_pointer obejct of this class - * */ - static void* createThreads(void *this_pointer); - - /** assignjobs to each thread - * @param thisData a bunch of frames - * @param numThisData number of frames - * */ - void assignJobsForThread(char *thisData, int numThisData); - - /** Checks if all the threads are done processing - * @param returns 1 for jobs done and 0 for jobs not done - * */ - int checkIfJobsDone(); - - /** - * call back to free fifo - * call back arguments are - * fbuffer buffer address to be freed - */ - void registerCallBackFreeFifo(void (*func)(char*, void*),void *arg){freeFifoCallBack=func; pFreeFifo=arg;}; - - - -private: - -#ifdef MYROOT1 - /** Tree where the hits are stored */ - TTree *myTree; - - /** File where the tree is saved */ - TFile *myFile; -#else - FILE *myFile; - - /** pointer to array of structs when only using files */ - //single_photon_hit* photonHitList; - single_photon_hit ** photonHitList; - - /** Number of Hits per file */ - int nHitsPerFile; - - /** Total Number of Hits Per Acquisition */ - int nTotalHits; -#endif - - /** Number of Hits per frame*/ - int nHitsPerFrame; - - /** Maximum Number of hits written to file */ - const static int MAX_HITS_PER_FILE = 2000000; - - /** Number of Channels in X direction */ - int nChannelsX; - - /** Number of Channels in Y direction */ - int nChannelsY; - - /** Cluster size in X direction */ - int nClusterX; - - /** Cluster size in Y direction */ - int nClusterY; - - /** map to the data without headers */ - int16_t *map; - - /** Size of data with headers */ - int dataSize; - - /** mask as to which adcs are inverted */ - int16_t *mask; - - /** movingStat object */ - movingStat *stat; - - movingStat *nHitStat; - - /** single Photon Hit structure */ - single_photon_hit* myPhotonHit; - - /** Cluster size */ - const static int CLUSTER_SIZE = 3; - - /** Default Number of frames at the beginning to calculate pedestal */ - const static int DEFAULT_NUM_PEDESTAL = 500; - - /** Default Distance from pedestal to detect a hit */ - const static int DEFAULT_SIGMA = 5; - - /** Default Background */ - const static int DEFAULT_BACKGROUND = 1000; - - /** Default Correction Percentage */ - const static double DEFAULT_CORRECTION = 1.0; - - /** Number of frames at the beginning to calculate pedestal */ - int nped; - - /** Distance from pedestal to detect a hit */ - int nsigma; - - /** background */ - int nbackground; - - /** correction */ - double outcorr; - - /** previous frame index */ - unsigned int fnum; - - /** previous packet index */ - unsigned int pnum; - - /** total packets received */ - unsigned int ptot; - - /** first frame number */ - unsigned int f0; - - /** frame index mask */ - int frame_index_mask; - - /** packet index mask */ - int packet_index_mask; - - /** frame index offset */ - int frame_index_offset; - - /** packet index offset */ - int packet_index_offset; - - /** number of packets per frame */ - int packets_per_frame; - - /** increment value for index for gotthard */ - int incrementValue; - - /** first packet */ - bool firstTime; - - /** return status */ - int ret; - - /** current packet index */ - int pIndex; - - /** current frame index */ - int fIndex; - - /** thread related variables */ - static const int NUM_THREADS = 15; - pthread_t find_hits_thread[NUM_THREADS]; - volatile int thread_started; - volatile int threads_mask; - pthread_mutex_t write_mutex; - pthread_mutex_t running_mutex; - pthread_mutex_t frnum_mutex; - - static const int PROGRESS_INCREMENT = 100; - /** current thread the job being allotted to */ - int currentThread; - - /** current index alloted for each thread */ - int thisThreadIndex; - - /** semaphore to synchronize between different jobs on same thread */ - sem_t smp[NUM_THREADS]; - - /** starting memory of data for different threads */ - char* mem0[NUM_THREADS]; - - /** number of frames alloted for each thread to process */ - int* numFramesAlloted; - - - - /** final file name */ - char savefilename[MAX_STR_LENGTH]; - - /** file path */ - char filePath[MAX_STR_LENGTH]; - - /** file prefix */ - char fileName[MAX_STR_LENGTH]; - - /** file acquisition index */ - int fileIndex; - - - /** 0 for 1d and 1 for 2d */ - int deltaX; - - /** index of center of cluster for 1d and for 2d*/ - int clusterCenterPixel; - - /** squareroot of cluster */ - double sqrtCluster; - - /** circular fifo buffer to be freed */ - CircularFifo* fifo; - - /**total frames caught */ - int* totalFramesCaught; - - /** frames caught */ - int* framesCaught; - - /** current frame number */ - uint32_t* currentframenum; - - /** call back function */ - void (*freeFifoCallBack)(char*, void*); - - /** call back arguments */ - void *pFreeFifo; -}; - - - - -#endif diff --git a/slsDetectorSoftware/slsDetectorAnalysis/single_photon_hit.h b/slsDetectorSoftware/slsDetectorAnalysis/single_photon_hit.h deleted file mode 100644 index 278c9f691..000000000 --- a/slsDetectorSoftware/slsDetectorAnalysis/single_photon_hit.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef SINGLE_PHOTON_HIT_H -#define SINGLE_PHOTON_HIT_h - -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; - -/* /\** */ -/* @short structure for a single photon hit */ -/* *\/ */ -/* typedef struct{ */ -/* double* data; /\**< data size *\/ */ -/* int x; /\**< x-coordinate of the center of hit *\/ */ -/* int y; /\**< x-coordinate of the center of hit *\/ */ -/* double rms; /\**< noise of central pixel *\/ */ -/* double ped; /\**< pedestal of the central pixel *\/ */ -/* int iframe; /\**< frame number *\/ */ -/* }single_photon_hit; */ - - -class single_photon_hit { - - public: - single_photon_hit(int nx, int ny=1): dx(nx), dy(ny) {data=new double[dx*dy];}; - ~single_photon_hit(){delete [] data;}; - void write(FILE *myFile) {fwrite((void*)this, 1, 3*sizeof(int)+2*sizeof(double), myFile); fwrite((void*)data, 1, dx*dy*sizeof(double), myFile);}; - void read(FILE *myFile) {fread((void*)this, 1, 3*sizeof(int)+2*sizeof(double), myFile); fread((void*)data, 1, dx*dy*sizeof(double), myFile);}; - void set_data(double v, int ix, int iy=0){data[(iy+dy/2)*dx+ix+dx/2]=v;}; - double get_data(int ix, int iy=0){return data[(iy+dy/2)*dx+ix+dx/2];}; - - - int x; /**< x-coordinate of the center of hit */ - int y; /**< x-coordinate of the center of hit */ - double rms; /**< noise of central pixel */ - double ped; /**< pedestal of the central pixel */ - int iframe; /**< frame number */ - double *data; /**< data size */ - const int dx; - const int dy; -}; - - - -#endif diff --git a/slsDetectorSoftware/slsDetectorClient/CMakeLists.txt b/slsDetectorSoftware/slsDetectorClient/CMakeLists.txt deleted file mode 100644 index aa65dcf79..000000000 --- a/slsDetectorSoftware/slsDetectorClient/CMakeLists.txt +++ /dev/null @@ -1,71 +0,0 @@ -set(SOURCES - sls_detector_client.cpp -) - -include_directories( - ../commonFiles - ../multiSlsDetector - ../slsDetector - ../slsDetectorAnalysis - ../slsReceiverInterface - ../usersFunctions - ../MySocketTCP -) - -add_executable(sls_detector_get - ${SOURCES} -) -target_link_libraries(sls_detector_get - slsDetectorShared - pthread - zmq - rt -) -set_target_properties(sls_detector_get PROPERTIES - RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin - COMPILE_DEFINITIONS GET=1 -) - -add_executable(sls_detector_put - ${SOURCES} -) -target_link_libraries(sls_detector_put - slsDetectorShared - pthread - zmq - rt -) -set_target_properties(sls_detector_put PROPERTIES - RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin - COMPILE_DEFINITIONS PUT=1 -) - -add_executable(sls_detector_acquire - ${SOURCES} -) -target_link_libraries(sls_detector_acquire - slsDetectorShared - pthread - zmq - rt -) -set_target_properties(sls_detector_acquire PROPERTIES - RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin - COMPILE_DEFINITIONS READOUT=1 -) - -add_executable(sls_detector_help - ${SOURCES} -) -target_link_libraries(sls_detector_help - slsDetectorShared - pthread - zmq - rt -) -set_target_properties(sls_detector_help PROPERTIES - RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin - COMPILE_DEFINITIONS HELP=1 -) - -install(TARGETS sls_detector_put sls_detector_get sls_detector_acquire sls_detector_help DESTINATION bin) diff --git a/slsDetectorSoftware/slsDetectorClient/Makefile b/slsDetectorSoftware/slsDetectorClient/Makefile deleted file mode 100644 index 9c26be641..000000000 --- a/slsDetectorSoftware/slsDetectorClient/Makefile +++ /dev/null @@ -1,111 +0,0 @@ -include ../../Makefile.include - -CFLAGS= -DC_ONLY -#FLAGS=-DVERBOSE -#ASM=$(shell echo "/lib/modules/`uname -r`/build/include") - -INCLUDES?= -I../commonFiles -I../slsDetector -I ../MySocketTCP -I../usersFunctions -I../multiSlsDetector -I../slsDetectorAnalysis -I../slsReceiverInterface -I ../../slsReceiverSoftware/include -I$(shell echo "/lib/modules/`uname -r`/build/include") -DESTDIR ?= ../../bin -BIN=$(DESTDIR) -LIBS?= -L$(DESTDIR) -lSlsDetector -LIBRARYDIR?=../ -LDFLAG= -L/usr/lib64/ -pthread -DOCDIR ?= $(PWD)/docs -SRC_CLNT=sls_detector_client.cpp - - -$(info ) -$(info #######################################) -$(info # In slsDetectorclient Makefile #) -$(info #######################################) -$(info ) - -all: clients - -nonstatic: clients - -clients: builddir lib $(DESTDIR)/sls_detector_put $(DESTDIR)/sls_detector_get $(DESTDIR)/sls_detector_acquire $(DESTDIR)/sls_detector_help - -static_clients: builddir lib $(DESTDIR)/ssls_detector_put $(DESTDIR)/ssls_detector_get $(DESTDIR)/ssls_detector_acquire $(DESTDIR)/ssls_detector_help - -builddir: -# echo $(LIBS) -# echo $(LDFLAG) - mkdir -p $(BIN) - -lib: -# echo $(LIBDIR) - cd $(LIBRARYDIR) && $(MAKE) DESTDIR=$(DESTDIR) TABSPACE='$(TABSPACE)' - @echo "" - @echo "#######################################" - @echo "# Back in slsDetectorClient Makefile #" - @echo "#######################################" - @echo "" - -$(DESTDIR)/ssls_detector_put: $(SRC_CLNT) $(DESTDIR)/libSlsDetector.so $(DESTDIR)/libSlsDetector.a - $(call colorecho,"#######################################") - $(call colorecho,"# Compiling ssls_detector_put #") - $(call colorecho,"#######################################") - $(CXX) -static -o $(BIN)/ssls_detector_put $(SRC_CLNT) $(FLAGS) $(INCLUDES) -DPUT $(LIBS) $(LDFLAG) - -$(DESTDIR)/ssls_detector_get: $(SRC_CLNT) $(DESTDIR)/libSlsDetector.so $(DESTDIR)/libSlsDetector.a - $(call colorecho,"#######################################") - $(call colorecho,"# Compiling ssls_detector_get #") - $(call colorecho,"#######################################") - $(CXX) -static -o $(BIN)/ssls_detector_get $(SRC_CLNT) $(FLAGS) $(INCLUDES) -DGET $(LIBS) $(LDFLAG) - -$(DESTDIR)/ssls_detector_acquire: $(SRC_CLNT) $(DESTDIR)/libSlsDetector.so $(DESTDIR)/libSlsDetector.a - $(call colorecho,"#######################################") - $(call colorecho,"# Compiling ssls_detector_acquire #") - $(call colorecho,"#######################################") - $(CXX) -static -o $(BIN)/ssls_detector_acquire $(SRC_CLNT) $(FLAGS) $(INCLUDES) -DREADOUT $(LIBS) $(LDFLAG) - -$(DESTDIR)/ssls_detector_help: $(SRC_CLNT) $(DESTDIR)/libSlsDetector.so $(DESTDIR)/libSlsDetector.a - $(call colorecho,"#######################################") - $(call colorecho,"# Compiling ssls_detector_help #") - $(call colorecho,"#######################################") - $(CXX) -static -o $(BIN)/ssls_detector_help $(SRC_CLNT) $(FLAGS) $(INCLUDES) -DHELP $(LIBS) $(LDFLAG) - - - -$(DESTDIR)/sls_detector_put: $(SRC_CLNT) $(DESTDIR)/libSlsDetector.so $(DESTDIR)/libSlsDetector.a - $(call colorecho,"#######################################") - $(call colorecho,"# Compiling sls_detector_put #") - $(call colorecho,"#######################################") - $(CXX) -o $(BIN)/sls_detector_put $(SRC_CLNT) $(FLAGS) $(INCLUDES) -DPUT $(LIBS) $(LDFLAG) - $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) - -$(DESTDIR)/sls_detector_get: $(SRC_CLNT) $(DESTDIR)/libSlsDetector.so $(DESTDIR)/libSlsDetector.a - $(call colorecho,"#######################################") - $(call colorecho,"# Compiling sls_detector_get #") - $(call colorecho,"#######################################") - $(CXX) -o $(BIN)/sls_detector_get $(SRC_CLNT) $(FLAGS) $(INCLUDES) -DGET $(LIBS) $(LDFLAG) - $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) - -$(DESTDIR)/sls_detector_acquire: $(SRC_CLNT) $(DESTDIR)/libSlsDetector.so $(DESTDIR)/libSlsDetector.a - $(call colorecho,"#######################################") - $(call colorecho,"# Compiling sls_detector_acquire #") - $(call colorecho,"#######################################") - $(CXX) -o $(BIN)/sls_detector_acquire $(SRC_CLNT) $(FLAGS) $(INCLUDES) -DREADOUT $(LIBS) $(LDFLAG) - $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) - -$(DESTDIR)/sls_detector_help: $(SRC_CLNT) $(DESTDIR)/libSlsDetector.so $(DESTDIR)/libSlsDetector.a - $(call colorecho,"#######################################") - $(call colorecho,"# Compiling sls_detector_help #") - $(call colorecho,"#######################################") - $(CXX) -o $(BIN)/sls_detector_help $(SRC_CLNT) $(FLAGS) $(INCLUDES) -DHELP $(LIBS) $(LDFLAG) - $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) - - -doc: - cd manual && make DESTDIR=$(DOCDIR) - -htmldoc: - cd manual && make html DESTDIR=$(DOCDIR) - -clean: -# cd manual && make clean - rm -rf $(BIN)/sls_detector_put $(BIN)/sls_detector_get $(BIN)/sls_detector_acquire $(BIN)/sls_detector_help $(BIN)/gui_client - -install: clients - diff --git a/slsDetectorSoftware/slsDetectorClient/Makefile.x04sa b/slsDetectorSoftware/slsDetectorClient/Makefile.x04sa deleted file mode 100644 index af02ea176..000000000 --- a/slsDetectorSoftware/slsDetectorClient/Makefile.x04sa +++ /dev/null @@ -1,54 +0,0 @@ -CFLAGS= -DC_ONLY -FLAGS=-DVERBOSE -INCLUDES= -I../slsDetectorSoftware/commonFiles -I../slsDetectorSoftware/slsDetector -I ../slsDetectorSoftware/MySocketTCP -I../slsDetectorSoftware/usersFunctions -I../slsDetectorSoftware/multiSlsDetector -I../slsDetectorSoftware/slsDetectorAnalysis -LIBS= -L../slsDetectorSoftware/ -LDFLAG= -lSlsDetector -pthread - -EPICSFLAGS=-DEPICS -I/usr/local/epics/base/include/ -I /usr/local/epics/base/include/os/Linux/ -L /usr/local/epics/base/lib/SL5-x86/ -Wl,-R/usr/local/epics/base/lib/SL5-x86 -lca -lCom - -BIN=bin - -SRC_CLNT=sls_detector_client.cpp - -clients: sls_detector_put sls_detector_get sls_detector_acquire sls_detector_help - -all: lib clients - -lib: - cd ../slsDetectorSoftware && $(MAKE) lib - - - -sls_detector_put: $(SRC_CLNT) - mkdir -p $(BIN) - $(CXX) -o $(BIN)/sls_detector_put $(SRC_CLNT) $(FLAGS) $(INCLUDES) -DPUT $(LIBS) $(LDFLAG) $(EPICSFLAGS) - -sls_detector_get: $(SRC_CLNT) - mkdir -p $(BIN) - $(CXX) -o $(BIN)/sls_detector_get $(SRC_CLNT) $(FLAGS) $(INCLUDES) -DGET $(LIBS) $(LDFLAG) $(EPICSFLAGS) - -sls_detector_acquire: $(SRC_CLNT) - mkdir -p $(BIN) - $(CXX) -o $(BIN)/sls_detector_acquire $(SRC_CLNT) $(FLAGS) $(INCLUDES) -DREADOUT $(LIBS) $(LDFLAG) $(EPICSFLAGS) - -sls_detector_help: $(SRC_CLNT) - mkdir -p $(BIN) - $(CXX) -o $(BIN)/sls_detector_help $(SRC_CLNT) $(FLAGS) $(INCLUDES) -DHELP $(LIBS) $(LDFLAG) $(EPICSFLAGS) - - -clean: - rm -rf $(BIN)/sls_detector_* - - - - - -install_sls_detector: all - $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) - cp -P $(BIN)/sls_detector_put $(DESTDIR) - cp -P $(BIN)/sls_detector_get $(DESTDIR) - cp -P $(BIN)/sls_detector_acquire $(DESTDIR) - cp -P $(BIN)/sls_detector_help $(DESTDIR) - - - diff --git a/slsDetectorSoftware/slsDetectorClient/sls_detector_client.cpp b/slsDetectorSoftware/slsDetectorClient/sls_detector_client.cpp deleted file mode 100644 index d0525f9a6..000000000 --- a/slsDetectorSoftware/slsDetectorClient/sls_detector_client.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include "multiSlsDetectorClient.h" -#include "gitInfoLib.h" - - -#include -using namespace std; - -int main(int argc, char *argv[]) - -{ - for (int i = 1; i < argc; ++i ) { - if (!(strcmp (argv[i],"--version")) || !(strcmp (argv[i],"-v"))) { - int64_t tempval = GITDATE; - cout << argv[0] << " " << GITBRANCH << " (0x" << hex << tempval << ")" << endl; - return 0; - } - } - -#ifdef PUT - int action=slsDetectorDefs::PUT_ACTION; -#endif - -#ifdef GET - int action=slsDetectorDefs::GET_ACTION; -#endif - - -#ifdef READOUT - int action=slsDetectorDefs::READOUT_ACTION; -#endif - - -#ifdef HELP - int action=slsDetectorDefs::HELP_ACTION; -#endif - - multiSlsDetectorClient *cl; - if (argc>1) - cl=new multiSlsDetectorClient(argc-1, argv+1, action); - else - cl=new multiSlsDetectorClient(argc-1, argv, action); - - delete cl; -} - - diff --git a/slsDetectorSoftware/slsDetectorServer/AD9257.h b/slsDetectorSoftware/slsDetectorServer/AD9257.h deleted file mode 100755 index a716af64c..000000000 --- a/slsDetectorSoftware/slsDetectorServer/AD9257.h +++ /dev/null @@ -1,141 +0,0 @@ -#ifndef AD9257_H -#define AD9257_H - -#include "ansi.h" - -#include "commonServerFunctions.h" -#include - -/* AD9257 ADC DEFINES */ -#define AD9257_ADC_NUMBITS (24) - -#define AD9257_DEV_IND_2_REG (0x04) -#define AD9257_CHAN_H_OFST (0) -#define AD9257_CHAN_H_MSK (0x00000001 << AD9257_CHAN_H_OFST) -#define AD9257_CHAN_G_OFST (1) -#define AD9257_CHAN_G_MSK (0x00000001 << AD9257_CHAN_G_OFST) -#define AD9257_CHAN_F_OFST (2) -#define AD9257_CHAN_F_MSK (0x00000001 << AD9257_CHAN_F_OFST) -#define AD9257_CHAN_E_OFST (3) -#define AD9257_CHAN_E_MSK (0x00000001 << AD9257_CHAN_E_OFST) - -#define AD9257_DEV_IND_1_REG (0x05) -#define AD9257_CHAN_D_OFST (0) -#define AD9257_CHAN_D_MSK (0x00000001 << AD9257_CHAN_D_OFST) -#define AD9257_CHAN_C_OFST (1) -#define AD9257_CHAN_C_MSK (0x00000001 << AD9257_CHAN_C_OFST) -#define AD9257_CHAN_B_OFST (2) -#define AD9257_CHAN_B_MSK (0x00000001 << AD9257_CHAN_B_OFST) -#define AD9257_CHAN_A_OFST (3) -#define AD9257_CHAN_A_MSK (0x00000001 << AD9257_CHAN_A_OFST) -#define AD9257_CLK_CH_DCO_OFST (4) -#define AD9257_CLK_CH_DCO_MSK (0x00000001 << AD9257_CLK_CH_DCO_OFST) -#define AD9257_CLK_CH_IFCO_OFST (5) -#define AD9257_CLK_CH_IFCO_MSK (0x00000001 << AD9257_CLK_CH_IFCO_OFST) - -#define AD9257_POWER_MODE_REG (0x08) -#define AD9257_POWER_INTERNAL_OFST (0) -#define AD9257_POWER_INTERNAL_MSK (0x00000003 << AD9257_POWER_INTERNAL_OFST) -#define AD9257_INT_RESET_VAL (0x3) -#define AD9257_INT_CHIP_RUN_VAL (0x0) -#define AD9257_POWER_EXTERNAL_OFST (5) -#define AD9257_POWER_EXTERNAL_MSK (0x00000001 << AD9257_POWER_EXTERNAL_OFST) -#define AD9257_EXT_FULL_POWER_VAL (0x0) -#define AD9257_EXT_STANDBY_VAL (0x1) - -#define AD9257_OUT_MODE_REG (0x14) -#define AD9257_OUT_FORMAT_OFST (0) -#define AD9257_OUT_FORMAT_MSK (0x00000001 << AD9257_OUT_FORMAT_OFST) -#define AD9257_OUT_BINARY_OFST_VAL (0) -#define AD9257_OUT_TWOS_COMPL_VAL (1) -#define AD9257_OUT_LVDS_OPT_OFST (6) -#define AD9257_OUT_LVDS_OPT_MSK (0x00000001 << AD9257_OUT_LVDS_OPT_OFST) -#define AD9257_OUT_LVDS_ANSI_VAL (0) -#define AD9257_OUT_LVDS_IEEE_VAL (1) - -#define AD9257_OUT_PHASE_REG (0x16) -#define AD9257_OUT_CLK_OFST (0) -#define AD9257_OUT_CLK_MSK (0x0000000F << AD9257_OUT_CLK_OFST) -#define AD9257_OUT_CLK_60_VAL (0x1) -#define AD9257_IN_CLK_OFST (4) -#define AD9257_IN_CLK_MSK (0x00000007 << AD9257_IN_CLK_OFST) -#define AD9257_IN_CLK_0_VAL (0x0) - -#define AD9257_VREF_REG (0x18) -#define AD9257_VREF_OFST (0) -#define AD9257_VREF_MSK (0x00000003 << AD9257_VREF_OFST) -#define AD9257_VREF_1_33_VAL (0x2) - -#define AD9257_TEST_MODE_REG (0x0D) -#define AD9257_OUT_TEST_OFST (0) -#define AD9257_OUT_TEST_MSK (0x0000000F << AD9257_OUT_TEST_OFST) -#define AD9257_NONE_VAL (0x0) -#define AD9257_MIXED_BIT_FREQ_VAL (0xC) -#define AD9257_TEST_RESET_SHORT_GEN (4) -#define AD9257_TEST_RESET_LONG_GEN (5) -#define AD9257_USER_IN_MODE_OFST (6) -#define AD9257_USER_IN_MODE_MSK (0x00000003 << AD9257_USER_IN_MODE_OFST) - - -void setAdc(int addr, int val) { - - u_int32_t codata; - codata = val + (addr << 8); - printf(" Setting ADC SPI Register. Wrote 0x%04x at 0x%04x\n", val, addr); - serializeToSPI(ADC_SPI_REG, codata, ADC_SERIAL_CS_OUT_MSK, AD9257_ADC_NUMBITS, - ADC_SERIAL_CLK_OUT_MSK, ADC_SERIAL_DATA_OUT_MSK, ADC_SERIAL_DATA_OUT_OFST); -} - -void prepareADC(){ - printf("\n\nPreparing ADC ... \n"); - - //power mode reset - printf("power mode reset:\n"); - setAdc(AD9257_POWER_MODE_REG, - (AD9257_INT_RESET_VAL << AD9257_POWER_INTERNAL_OFST) & AD9257_POWER_INTERNAL_MSK); - - //power mode chip run - printf("power mode chip run:\n"); - setAdc(AD9257_POWER_MODE_REG, - (AD9257_INT_CHIP_RUN_VAL << AD9257_POWER_INTERNAL_OFST) & AD9257_POWER_INTERNAL_MSK); - - //output clock phase - printf("output clock phase:\n"); - setAdc(AD9257_OUT_PHASE_REG, - (AD9257_OUT_CLK_60_VAL << AD9257_OUT_CLK_OFST) & AD9257_OUT_CLK_MSK); - - // lvds-iee reduced , binary offset - printf("lvds-iee reduced, binary offset:\n"); - setAdc(AD9257_OUT_MODE_REG, - (AD9257_OUT_LVDS_IEEE_VAL << AD9257_OUT_LVDS_OPT_OFST) & AD9257_OUT_LVDS_OPT_MSK); - - // all devices on chip to receive next command - printf("all devices on chip to receive next command:\n"); - setAdc(AD9257_DEV_IND_2_REG, - AD9257_CHAN_H_MSK | AD9257_CHAN_G_MSK | AD9257_CHAN_F_MSK | AD9257_CHAN_E_MSK); - setAdc(AD9257_DEV_IND_1_REG, - AD9257_CHAN_D_MSK | AD9257_CHAN_C_MSK | AD9257_CHAN_B_MSK | AD9257_CHAN_A_MSK | - AD9257_CLK_CH_DCO_MSK | AD9257_CLK_CH_IFCO_MSK); - - // vref 1.33 - printf("vref 1.33:\n"); - setAdc(AD9257_VREF_REG, - (AD9257_VREF_1_33_VAL << AD9257_VREF_OFST) & AD9257_VREF_MSK); - - // no test mode - printf("no test mode:\n"); - setAdc(AD9257_TEST_MODE_REG, - (AD9257_NONE_VAL << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK); - -#ifdef TESTADC - printf("***************************************** *******\n"); - printf("******* PUTTING ADC IN TEST MODE!!!!!!!!! *******\n"); - printf("***************************************** *******\n"); - // mixed bit frequency test mode - printf("mixed bit frequency test mode:\n"); - setAdc(AD9257_TEST_MODE_REG, - (AD9257_MIXED_BIT_FREQ_VAL << AD9257_OUT_TEST_OFST) & AD9257_OUT_TEST_MSK); -#endif -} - -#endif //AD9257_H diff --git a/slsDetectorSoftware/slsDetectorServer/Makefile b/slsDetectorSoftware/slsDetectorServer/Makefile deleted file mode 100644 index 8c3ee8d97..000000000 --- a/slsDetectorSoftware/slsDetectorServer/Makefile +++ /dev/null @@ -1,26 +0,0 @@ -CC = gcc -CLAGS += -Wall -DVIRTUAL -DDACS_INT -DGENERICD # -DSLS_DETECTOR_FUNCTION_LIST -LDLIBS += -lm - -PROGS = genericDetectorServer -DESTDIR ?= bin -INSTMODE = 0777 - -SRC_CLNT = slsDetectorServer.c slsDetectorServer_funcs.c communication_funcs.c slsDetectorFunctionList.c -OBJS = $(SRC_CLNT:.cpp=.o) - - - -all: clean $(PROGS) - -boot: $(OBJS) - -$(PROGS): - echo $(OBJS) - mkdir -p $(DESTDIR) - $(CC) $(SRC_CLNT) $(CLAGS) $(LDLIBS) -o $@ - mv $(PROGS) $(DESTDIR) - - -clean: - rm -rf $(DESTDIR)/$(PROGS) *.o diff --git a/slsDetectorSoftware/slsDetectorServer/commonServerFunctions.h b/slsDetectorSoftware/slsDetectorServer/commonServerFunctions.h deleted file mode 100755 index 55d30b8c4..000000000 --- a/slsDetectorSoftware/slsDetectorServer/commonServerFunctions.h +++ /dev/null @@ -1,73 +0,0 @@ -#ifndef COMMON_SERVER_FUNCTIONS_H -#define COMMON_SERVER_FUNCTIONS_H - -#ifndef GOTTHARDD //gotthard already had bus_w etc defined in its firmware_funcs.c (not yet made with common files) -#include "blackfin.h" -#endif - -/* global variables */ - -void SPIChipSelect (u_int32_t* valw, u_int32_t addr, u_int32_t csmask) { - - // start point - (*valw) = 0xffffffff; // old board compatibility (not using specific bits) - bus_w (addr, (*valw)); - - // chip sel bar down - (*valw) &= ~csmask; /* todo with test: done a bit different, not with previous value */ - bus_w (addr, (*valw)); -} - - -void SPIChipDeselect (u_int32_t* valw, u_int32_t addr, u_int32_t csmask, u_int32_t clkmask) { - // chip sel bar up - (*valw) |= csmask; /* todo with test: not done for spi */ - bus_w (addr, (*valw)); - - //clk down - (*valw) &= ~clkmask; - bus_w (addr, (*valw)); - - // stop point = start point of course - (*valw) = 0xffffffff; // old board compatibility (not using specific bits) - bus_w (addr, (*valw)); -} - -void sendDataToSPI (u_int32_t* valw, u_int32_t addr, u_int32_t val, int numbitstosend, u_int32_t clkmask, u_int32_t digoutmask, int digofset) { - int i = 0; - for (i = 0; i < numbitstosend; ++i) { - - // clk down - (*valw) &= ~clkmask; - bus_w (addr, (*valw)); - - // write data (i) - (*valw) = (((*valw) & ~digoutmask) + // unset bit - (((val >> (numbitstosend - 1 - i)) & 0x1) << digofset)); // each bit from val starting from msb - bus_w (addr, (*valw)); - - // clk up - (*valw) |= clkmask ; - bus_w (addr, (*valw)); - } -} - - -void serializeToSPI(u_int32_t addr, u_int32_t val, u_int32_t csmask, int numbitstosend, u_int32_t clkmask, u_int32_t digoutmask, int digofset) { -#ifdef VERBOSE - if (numbitstosend == 16) - printf("Writing to SPI Register: 0x%04x\n",val); - else - printf("Writing to SPI Register: 0x%08x\n", val); -#endif - - u_int32_t valw; - - SPIChipSelect (&valw, addr, csmask); - - sendDataToSPI(&valw, addr, val, numbitstosend, clkmask, digoutmask, digofset); - - SPIChipDeselect(&valw, addr, csmask, clkmask); -} - -#endif //COMMON_SERVER_FUNCTIONS_H diff --git a/slsDetectorSoftware/slsDetectorServer/communication_funcs.c b/slsDetectorSoftware/slsDetectorServer/communication_funcs.c deleted file mode 120000 index 87a4f95d1..000000000 --- a/slsDetectorSoftware/slsDetectorServer/communication_funcs.c +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.c \ No newline at end of file diff --git a/slsDetectorSoftware/slsDetectorServer/communication_funcs.h b/slsDetectorSoftware/slsDetectorServer/communication_funcs.h deleted file mode 120000 index f220903b2..000000000 --- a/slsDetectorSoftware/slsDetectorServer/communication_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/communication_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetectorFunctionList.c b/slsDetectorSoftware/slsDetectorServer/slsDetectorFunctionList.c deleted file mode 100644 index c28ab462d..000000000 --- a/slsDetectorSoftware/slsDetectorServer/slsDetectorFunctionList.c +++ /dev/null @@ -1,838 +0,0 @@ -#ifdef SLS_DETECTOR_FUNCTION_LIST - -#include "slsDetectorFunctionList.h" -#include "slsDetectorServer_defs.h" - -#include -#include - - -const int nChans=NCHAN; -const int nChips=NCHIP; -const int nDacs=NDAC; -const int nAdcs=NADC; -const int allSelected=-2; -const int noneSelected=-1; - -sls_detector_module *detectorModules=NULL; -int *detectorChips=NULL; -int *detectorChans=NULL; -dacs_t *detectorDacs=NULL; -dacs_t *detectorAdcs=NULL; - -int nModY = NMAXMOD; -int nModX = NMAXMOD; -int dynamicRange= DYNAMIC_RANGE; -int dataBytes = NMAXMOD*NCHIP*NCHAN*2; -int masterMode = NO_MASTER; -int syncMode = NO_SYNCHRONIZATION; -int timingMode = AUTO_TIMING; - - - -enum detectorSettings thisSettings; -int sChan, sChip, sMod, sDac, sAdc; -int nModBoard; -extern int dataBytes; - - -int initializeDetectorStructure(){ - - int imod; - int n=getNModBoard(X)*getNModBoard(Y); -#ifdef VERBOSE - printf("Board is for %d modules\n",n); -#endif - detectorModules=malloc(n*sizeof(sls_detector_module)); - detectorChips=malloc(n*NCHIP*sizeof(int)); - detectorChans=malloc(n*NCHIP*NCHAN*sizeof(int)); - detectorDacs=malloc(n*NDAC*sizeof(int)); - detectorAdcs=malloc(n*NADC*sizeof(int)); -#ifdef VERBOSE - printf("modules from 0x%x to 0x%x\n",(unsigned int)(detectorModules), (unsigned int)(detectorModules+n)); - printf("chips from 0x%x to 0x%x\n",(unsigned int)(detectorChips), (unsigned int)(detectorChips+n*NCHIP)); - printf("chans from 0x%x to 0x%x\n",(unsigned int)(detectorChans), (unsigned int)(detectorChans+n*NCHIP*NCHAN)); - printf("dacs from 0x%x to 0x%x\n",(unsigned int)(detectorDacs), (unsigned int)(detectorDacs+n*NDAC)); - printf("adcs from 0x%x to 0x%x\n",(unsigned int)(detectorAdcs), (unsigned int)(detectorAdcs+n*NADC)); -#endif - for (imod=0; imoddacs=detectorDacs+imod*NDAC; - (detectorModules+imod)->adcs=detectorAdcs+imod*NADC; - (detectorModules+imod)->chipregs=detectorChips+imod*NCHIP; - (detectorModules+imod)->chanregs=detectorChans+imod*NCHIP*NCHAN; - (detectorModules+imod)->ndac=NDAC; - (detectorModules+imod)->nadc=NADC; - (detectorModules+imod)->nchip=NCHIP; - (detectorModules+imod)->nchan=NCHIP*NCHAN; - (detectorModules+imod)->module=imod; - (detectorModules+imod)->gain=0; - (detectorModules+imod)->offset=0; - (detectorModules+imod)->reg=0; - /* initialize registers, dacs, retrieve sn, adc values etc */ - } - thisSettings=UNINITIALIZED; - sChan=noneSelected; - sChip=noneSelected; - sMod=noneSelected; - sDac=noneSelected; - sAdc=noneSelected; - - return OK; -} - - - - - - -int setupDetector(){ - //testFpga(); - //testRAM(); - - //setSettings(GET_SETTINGS,-1); - //setFrames(1); - //setTrains(1); - //setExposureTime(1e6); - //setPeriod(1e9); - //setDelay(0); - //setGates(0); - - //setTiming(GET_EXTERNAL_COMMUNICATION_MODE); - //setMaster(GET_MASTER); - //setSynchronization(GET_SYNCHRONIZATION_MODE); - return OK; -} - - - - -int setNMod(int nm, enum dimension dim){ - return 1; -} - - - -int getNModBoard(enum dimension arg){ - return 1; -} - - - - - - - - -int64_t getModuleId(enum idMode arg, int imod){ - //DETECTOR_SERIAL_NUMBER - //DETECTOR_FIRMWARE_VERSION - return 0; -} - - - - -int64_t getDetectorId(enum idMode arg){ - //DETECTOR_SOFTWARE_VERSION defined in slsDetector_defs.h? - return 0; -} - - - - - -int moduleTest( enum digitalTestMode arg, int imod){ - //template testShiftIn from mcb_funcs.c - - //CHIP_TEST - //testShiftIn - //testShiftOut - //testShiftStSel - //testDataInOutMux - //testExtPulseMux - //testOutMux - //testFpgaMux - - return OK; -} - - - - - -int detectorTest( enum digitalTestMode arg){ - //templates from firmware_funcs.c - - //DETECTOR_FIRMWARE_TEST:testFpga() - //DETECTOR_MEMORY_TEST:testRAM() - //DETECTOR_BUS_TEST:testBus() - //DETECTOR_SOFTWARE_TEST:testFpga() - return OK; -} - - - - - - -double setDAC(enum dacIndex ind, double val, int imod){ - //template initDACbyIndexDACU from mcb_funcs.c - - //check that slsDetectorServer_funcs.c set_dac() has all the specific dac enums - //set dac and write to a register in fpga to remember dac value when server restarts - return 0; -} - - - -double getADC(enum dacIndex ind, int imod){ - //get adc value - return 0; -} - - - - -int setChannel(sls_detector_channel myChan){ - //template initChannelByNumber() from mcb_funcs.c - - return myChan.reg; -} - - -int getChannel(sls_detector_channel *myChan){ - //template getChannelbyNumber() from mcb_funcs.c - return FAIL; -} - - - -int setChip(sls_detector_chip myChip){ - //template initChipbyNumber() from mcb_funcs.c - return myChip.reg; -} - - -int getChip(sls_detector_chip *myChip){ - //template getChipbyNumber() from mcb_funcs.c - return FAIL; -} - -int setModule(sls_detector_module myChan){ - //template initModulebyNumber() from mcb_funcs.c - return OK; -} - -int getModule(sls_detector_module *myChan){ - //template getModulebyNumber() from mcb_funcs.c - return FAIL; -} - -int getThresholdEnergy(int imod){ - //template getThresholdEnergy() from mcb_funcs.c - //depending on settings - return FAIL; -} - - -int setThresholdEnergy(int thr, int imod){ - //template getThresholdEnergy() from mcb_funcs.c - //depending on settings - return FAIL; -} - - - -enum detectorSettings setSettings(enum detectorSettings sett, int imod){ - //template setSettings() from mcb_funcs.c - //reads the dac registers from fpga to confirm which settings, if weird, undefined - - return OK; -} - -int startStateMachine(){ - //template startStateMachine() from firmware_funcs.c - /* - fifoReset(); - now_ptr=(char*)ram_values; - //send start acquisition to fpga - */ - return FAIL; -} - - -int stopStateMachine(){ - //template stopStateMachine() from firmware_funcs.c - // send stop to fpga - //if status = busy after 500us, return FAIL - return FAIL; -} - - -int startReadOut(){ - //template startReadOut() from firmware_funcs.c - //send fpga start readout - return FAIL; -} - - -enum runStatus getRunStatus(){ - //template runState() from firmware_funcs.c - //get status from fpga - return ERROR; -} - - -char *readFrame(int *ret, char *mess){ - //template fifo_read_event() from firmware_funcs.c - //checks if state machine running and if fifo has data(look_at_me_reg) and accordingly reads frame - // memcpy(now_ptr, values, dataBytes); - //returns ptr to values - return NULL; -} - - -int64_t setTimer(enum timerIndex ind, int64_t val){ - //template setDelay() from firmware_funcs.c - //writes to reg - //FRAME_NUMBER - //ACQUISITION_TIME - //FRAME_PERIOD - //DELAY_AFTER_TRIGGER - //GATES_NUMBER - //PROBES_NUMBER - //CYCLES_NUMBER - return 0; -} - - -int64_t getTimeLeft(enum timerIndex ind){ - //template getDelay() from firmware_funcs.c - //reads from reg - //FRAME_NUMBER - //ACQUISITION_TIME - //FRAME_PERIOD - //DELAY_AFTER_TRIGGER - //GATES_NUMBER - //PROBES_NUMBER - //CYCLES_NUMBER - return -1; -} - - -int setDynamicRange(int dr){ - //template setDynamicRange() from firmware_funcs.c - return 0; -} - - -enum readOutFlags setReadOutFlags(enum readOutFlags val){ - //template setStoreInRAM from firmware_funcs.c - return -1; -} - - - - -int setROI(int n, ROI arg[], int *retvalsize, int *ret){ - return FAIL; -} - - - -int setSpeed(enum speedVariable arg, int val){ - //template setClockDivider() from firmware_funcs.c - //CLOCK_DIVIDER - //WAIT_STATES - //SET_SIGNAL_LENGTH - //TOT_CLOCK_DIVIDER - //TOT_DUTY_CYCLE - - //returns eg getClockDivider from firmware_funcs.c - return 0; -} - - - -int executeTrimming(enum trimMode mode, int par1, int par2, int imod){ - // template trim_with_noise from trimming_funcs.c - return FAIL; -} - - - - -int configureMAC(int ipad, long long int imacadd, long long int iservermacadd, int dtb){ - //detector specific. - return FAIL; -} - - -int loadImage(enum imageType index, char *imageVals){ - //detector specific. - return FAIL; -} - - -int readCounterBlock(int startACQ, char *counterVals){ - //detector specific. - return FAIL; -} - -int resetCounterBlock(int startACQ){ - //detector specific. - return FAIL; -} - -int startReceiver(int d){ - - return 0; -} - -int calibratePedestal(int frames){ - - return 0; -} - -int calculateDataBytes(){ - return 0; -} - -int getTotalNumberOfChannels(){return 0;} -int getTotalNumberOfChips(){return 0;} -int getTotalNumberOfModules(){return 0;} -int getNumberOfChannelsPerChip(){return 0;} -int getNumberOfChannelsPerModule(){return 0;} -int getNumberOfChipsPerModule(){return 0;} -int getNumberOfDACsPerModule(){return 0;} -int getNumberOfADCsPerModule(){return 0;} - - - - - - - -enum externalSignalFlag getExtSignal(int signalindex){ - //template getExtSignal from firmware_funcs.c - //return signals[signalindex]; - return -1; -} - - - - - -enum externalSignalFlag setExtSignal(int signalindex, enum externalSignalFlag flag){ - //template setExtSignal from firmware_funcs.c - - //in short..sets signals array, checks if agrees with timing mode, writes to fpga reg, calls synchronization and then settiming - /* - if (signalindex>=0 && signalindex<4) { - signals[signalindex]=flag; -#ifdef VERBOSE - printf("settings signal variable number %d to value %04x\n", signalindex, signals[signalindex]); -#endif - // if output signal, set it! - switch (flag) { - case GATE_IN_ACTIVE_HIGH: - case GATE_IN_ACTIVE_LOW: - if (timingMode==GATE_FIX_NUMBER || timingMode==GATE_WITH_START_TRIGGER)//timingMode = AUTO_TIMING by default and is set in setTiming() - setFPGASignal(signalindex,flag); //not implemented here, checks if flag within limits and writes to fpga reg - else - setFPGASignal(signalindex,SIGNAL_OFF); - break; - case TRIGGER_IN_RISING_EDGE: - case TRIGGER_IN_FALLING_EDGE: - if (timingMode==TRIGGER_EXPOSURE || timingMode==GATE_WITH_START_TRIGGER) - setFPGASignal(signalindex,flag); - else - setFPGASignal(signalindex,SIGNAL_OFF); - break; - case RO_TRIGGER_IN_RISING_EDGE: - case RO_TRIGGER_IN_FALLING_EDGE: - if (timingMode==BURST_TRIGGER) - setFPGASignal(signalindex,flag); - else - setFPGASignal(signalindex,SIGNAL_OFF); - break; - case MASTER_SLAVE_SYNCHRONIZATION: - setSynchronization(syncMode);//syncmode = NO_SYNCHRONIZATION by default and set with this function - break; - default: - setFPGASignal(signalindex,mode); - } - - setTiming(GET_EXTERNAL_COMMUNICATION_MODE); - } - */ - return getExtSignal(signalindex); -} - - - - - - -enum externalCommunicationMode setTiming( enum externalCommunicationMode arg){ - //template setTiming from firmware_funcs.c - //template getFPGASignal from firmware_funcs.c - - - //getFPGASignal(signalindex) used later on in this fucntion - //gets flag from fpga reg, checks if flag within limits, - //if( flag=SIGNAL_OFF and signals[signalindex]==MASTER_SLAVE_SYNCHRONIZATION), return -1, (ensures masterslaveflag !=off now) - //else return flag - - int ret=GET_EXTERNAL_COMMUNICATION_MODE; - //sets timingmode variable - //ensures that the signals are in acceptance with timing mode and according sets the timing mode - /* - int g=-1, t=-1, rot=-1; - - int i; - - switch (ti) { - case AUTO_TIMING: - timingMode=ti; - // disable all gates/triggers in except if used for master/slave synchronization - for (i=0; i<4; i++) { - if (getFPGASignal(i)>0 && getFPGASignal(i)=0 && t>=0 && rot<0) { - ret=GATE_WITH_START_TRIGGER; - } else if (g<0 && t>=0 && rot<0) { - ret=TRIGGER_EXPOSURE; - } else if (g>=0 && t<0 && rot<0) { - ret=GATE_FIX_NUMBER; - } else if (g<0 && t<0 && rot>0) { - ret=TRIGGER_READOUT; - } else if (g<0 && t<0 && rot<0) { - ret=AUTO_TIMING; - } - - */ - return ret; -} - - - -enum masterFlags setMaster(enum masterFlags arg){ - //template setMaster from firmware_funcs.c - /* - int i; - switch(f) { - case NO_MASTER: - // switch of gates or triggers - masterMode=NO_MASTER; - for (i=0; i<4; i++) { - if (signals[i]==MASTER_SLAVE_SYNCHRONIZATION) { - setFPGASignal(i,SIGNAL_OFF); - } - } - break; - case IS_MASTER: - // configure gate or trigger out - masterMode=IS_MASTER; - for (i=0; i<4; i++) { - if (signals[i]==MASTER_SLAVE_SYNCHRONIZATION) { - switch (syncMode) { - case NO_SYNCHRONIZATION: - setFPGASignal(i,SIGNAL_OFF); - break; - case MASTER_GATES: - setFPGASignal(i,GATE_OUT_ACTIVE_HIGH); - break; - case MASTER_TRIGGERS: - setFPGASignal(i,TRIGGER_OUT_RISING_EDGE); - break; - case SLAVE_STARTS_WHEN_MASTER_STOPS: - setFPGASignal(i,RO_TRIGGER_OUT_RISING_EDGE); - break; - default: - ; - } - } - } - break; - case IS_SLAVE: - // configure gate or trigger in - masterMode=IS_SLAVE; - for (i=0; i<4; i++) { - if (signals[i]==MASTER_SLAVE_SYNCHRONIZATION) { - switch (syncMode) { - case NO_SYNCHRONIZATION: - setFPGASignal(i,SIGNAL_OFF); - break; - case MASTER_GATES: - setFPGASignal(i,GATE_IN_ACTIVE_HIGH); - break; - case MASTER_TRIGGERS: - setFPGASignal(i,TRIGGER_IN_RISING_EDGE); - break; - case SLAVE_STARTS_WHEN_MASTER_STOPS: - setFPGASignal(i,TRIGGER_IN_RISING_EDGE); - break; - default: - ; - } - } - } - break; - default: - //do nothing - ; - } - - switch(masterMode) { - case NO_MASTER: - return NO_MASTER; - - - case IS_MASTER: - for (i=0; i<4; i++) { - if (signals[i]==MASTER_SLAVE_SYNCHRONIZATION) { - switch (syncMode) { - case NO_SYNCHRONIZATION: - return IS_MASTER; - case MASTER_GATES: - if (getFPGASignal(i)==GATE_OUT_ACTIVE_HIGH) - return IS_MASTER; - else - return NO_MASTER; - case MASTER_TRIGGERS: - if (getFPGASignal(i)==TRIGGER_OUT_RISING_EDGE) - return IS_MASTER; - else - return NO_MASTER; - case SLAVE_STARTS_WHEN_MASTER_STOPS: - if (getFPGASignal(i)==RO_TRIGGER_OUT_RISING_EDGE) - return IS_MASTER; - else - return NO_MASTER; - default: - return NO_MASTER; - } - - } - } - - case IS_SLAVE: - for (i=0; i<4; i++) { - if (signals[i]==MASTER_SLAVE_SYNCHRONIZATION) { - switch (syncMode) { - case NO_SYNCHRONIZATION: - return IS_SLAVE; - case MASTER_GATES: - if (getFPGASignal(i)==GATE_IN_ACTIVE_HIGH) - return IS_SLAVE; - else - return NO_MASTER; - case MASTER_TRIGGERS: - case SLAVE_STARTS_WHEN_MASTER_STOPS: - if (getFPGASignal(i)==TRIGGER_IN_RISING_EDGE) - return IS_SLAVE; - else - return NO_MASTER; - default: - return NO_MASTER; - } - - } - } - - } - */ - - return NO_MASTER; -} - - - -enum synchronizationMode setSynchronization(enum synchronizationMode arg){ - /* - int i; - - switch(s) { - case NO_SYNCHRONIZATION: - syncMode=NO_SYNCHRONIZATION; - for (i=0; i<4; i++) { - if (signals[i]==MASTER_SLAVE_SYNCHRONIZATION) { - setFPGASignal(i,SIGNAL_OFF); - } - } - break; - // disable external signals? - case MASTER_GATES: - // configure gate in or out - syncMode=MASTER_GATES; - for (i=0; i<4; i++) { - if (signals[i]==MASTER_SLAVE_SYNCHRONIZATION) { - if (masterMode==IS_MASTER) - setFPGASignal(i,GATE_OUT_ACTIVE_HIGH); - else if (masterMode==IS_SLAVE) - setFPGASignal(i,GATE_IN_ACTIVE_HIGH); - } - } - - break; - case MASTER_TRIGGERS: - // configure trigger in or out - syncMode=MASTER_TRIGGERS; - for (i=0; i<4; i++) { - if (signals[i]==MASTER_SLAVE_SYNCHRONIZATION) { - if (masterMode==IS_MASTER) - setFPGASignal(i,TRIGGER_OUT_RISING_EDGE); - else if (masterMode==IS_SLAVE) - setFPGASignal(i,TRIGGER_IN_RISING_EDGE); - } - } - break; - - - case SLAVE_STARTS_WHEN_MASTER_STOPS: - // configure trigger in or out - syncMode=SLAVE_STARTS_WHEN_MASTER_STOPS; - for (i=0; i<4; i++) { - if (signals[i]==MASTER_SLAVE_SYNCHRONIZATION) { - if (masterMode==IS_MASTER) - setFPGASignal(i,RO_TRIGGER_OUT_RISING_EDGE); - else if (masterMode==IS_SLAVE) - setFPGASignal(i,TRIGGER_IN_RISING_EDGE); - } - } - break; - - - default: - //do nothing - ; - } - - switch (syncMode) { - - case NO_SYNCHRONIZATION: - return NO_SYNCHRONIZATION; - - case MASTER_GATES: - - for (i=0; i<4; i++) { - if (signals[i]==MASTER_SLAVE_SYNCHRONIZATION) { - if (masterMode==IS_MASTER && getFPGASignal(i)==GATE_OUT_ACTIVE_HIGH) - return MASTER_GATES; - else if (masterMode==IS_SLAVE && getFPGASignal(i)==GATE_IN_ACTIVE_HIGH) - return MASTER_GATES; - } - } - return NO_SYNCHRONIZATION; - - case MASTER_TRIGGERS: - for (i=0; i<4; i++) { - if (signals[i]==MASTER_SLAVE_SYNCHRONIZATION) { - if (masterMode==IS_MASTER && getFPGASignal(i)==TRIGGER_OUT_RISING_EDGE) - return MASTER_TRIGGERS; - else if (masterMode==IS_SLAVE && getFPGASignal(i)==TRIGGER_IN_RISING_EDGE) - return MASTER_TRIGGERS; - } - } - return NO_SYNCHRONIZATION; - - case SLAVE_STARTS_WHEN_MASTER_STOPS: - for (i=0; i<4; i++) { - if (signals[i]==MASTER_SLAVE_SYNCHRONIZATION) { - if (masterMode==IS_MASTER && getFPGASignal(i)==RO_TRIGGER_OUT_RISING_EDGE) - return SLAVE_STARTS_WHEN_MASTER_STOPS; - else if (masterMode==IS_SLAVE && getFPGASignal(i)==TRIGGER_IN_RISING_EDGE) - return SLAVE_STARTS_WHEN_MASTER_STOPS; - } - } - return NO_SYNCHRONIZATION; - - default: - return NO_SYNCHRONIZATION; - - } - - - */ - return NO_SYNCHRONIZATION; -} - - - -#endif diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetectorFunctionList.h b/slsDetectorSoftware/slsDetectorServer/slsDetectorFunctionList.h deleted file mode 100644 index b10be6845..000000000 --- a/slsDetectorSoftware/slsDetectorServer/slsDetectorFunctionList.h +++ /dev/null @@ -1,292 +0,0 @@ -#ifdef SLS_DETECTOR_FUNCTION_LIST -#ifndef SLS_DETECTOR_FUNCTION_LIST_H -#define SLS_DETECTOR_FUNCTION_LIST_H - -#include "sls_receiver_defs.h" -#include "slsDetectorServer_defs.h" // DAC_INDEX, ADC_INDEX, also include RegisterDefs.h - -#include -#include // FILE - - -/**************************************************** -This functions are used by the slsDetectroServer_funcs interface. -Here are the definitions, but the actual implementation should be done for each single detector. - -****************************************************/ - - -// basic tests -#if defined(EIGERD) || defined(JUNGFRAUD) || defined(GOTTHARD) -int isFirmwareCheckDone(); -int getFirmwareCheckResult(char** mess); -#endif - -void checkFirmwareCompatibility(int flag); -#if defined(MYTHEN3D) || defined(JUNGFRAUD) -int checkType(); -u_int32_t testFpga(void); -int testBus(void); -#endif - -#if defined(MYTHEND) || defined(JUNGFRAUD) || defined(MYTHEN3D) -int moduleTest( enum digitalTestMode arg, int imod); -#endif -#if defined(MYTHEND) || defined(JUNGFRAUD) -int detectorTest( enum digitalTestMode arg); -#endif - -// Ids -int64_t getDetectorId(enum idMode arg); -u_int64_t getFirmwareVersion(); -#ifdef MYTHEND -int64_t getModuleId(enum idMode arg, int imod); -#elif JUNGFRAUD -u_int64_t getFirmwareAPIVersion(); -u_int16_t getHardwareVersionNumber(); -u_int16_t getHardwareSerialNumber(); -#endif -#ifndef MYTHEN3D -u_int32_t getDetectorNumber(); -#endif -u_int64_t getDetectorMAC(); -u_int32_t getDetectorIP(); - - -// initialization -void initControlServer(); -void initStopServer(); -#ifdef EIGERD -void getModuleConfiguration(); -#endif - -// set up detector -void allocateDetectorStructureMemory(); -void setupDetector(); -#ifdef JUNGFRAUD -int setDefaultDacs(); -#endif - - -// advanced read/write reg -#ifndef EIGERD -extern u_int32_t writeRegister(u_int32_t offset, u_int32_t data); // blackfin.h -extern u_int32_t readRegister(u_int32_t offset); // blackfin.h -#else -uint32_t writeRegister(uint32_t offset, uint32_t data); -uint32_t readRegister(uint32_t offset); -#endif - - -// firmware functions (resets) -#if defined(MYTHEN3D) || defined(JUNGFRAUD) -int powerChip (int on); -void cleanFifos(); -void resetCore(); -void resetPeripheral(); -#endif -#ifdef MYTHEN3D -int getPhase(int i); -int configurePhase(int val, enum CLKINDEX i); -int configureFrequency(int val, int i); -#elif JUNGFRAUD -int autoCompDisable(int on); -int adcPhase(int st); -int getPhase(); -void configureASICTimer(); -#endif - -// parameters - nmod, dr, roi -int setNMod(int nm, enum dimension dim); // mythen specific, but for detector compatibility as a get -int getNModBoard(enum dimension arg); // mythen specific, but for detector compatibility as a get -int setDynamicRange(int dr); -#ifdef GOTTHARD -int setROI(int n, ROI arg[], int *retvalsize, int *ret); -#endif - -// parameters - readout -int setSpeed(enum speedVariable arg, int val); -#if defined(EIGERD) || defined(MYTHEND) -enum readOutFlags setReadOutFlags(enum readOutFlags val); -#endif -#ifdef MYTHEND -int executeTrimming(enum trimMode mode, int par1, int par2, int imod); -#endif - -// parameters - timer -#ifdef JUNGFRAUD -int selectStoragecellStart(int pos); -#endif -int64_t setTimer(enum timerIndex ind, int64_t val); -int64_t getTimeLeft(enum timerIndex ind); - - -// parameters - channel, chip, module, settings -#ifdef MYTHEND -int setChannel(sls_detector_channel myChan); -int getChannel(sls_detector_channel *myChan); -int setChip(sls_detector_chip myChip); -int getChip(sls_detector_chip *myChip); -#endif -#ifdef EIGERD -int setModule(sls_detector_module myMod, int delay); -#else -int setModule(sls_detector_module myMod); -#endif -int getModule(sls_detector_module *myMod); -enum detectorSettings setSettings(enum detectorSettings sett, int imod); -enum detectorSettings getSettings(); - - -// parameters - threshold -#if defined(MYTHEND) || defined(EIGERD) -int getThresholdEnergy(int imod); -int setThresholdEnergy(int ev, int imod); -#endif - -// parameters - dac, adc, hv -#if defined(MYTHEN3D) || defined(JUNGFRAUD) -void serializeToSPI(u_int32_t addr, u_int32_t val, u_int32_t csmask, int numbitstosend, u_int32_t clkmask, u_int32_t digoutmask, int digofset); -void initDac(int dacnum); -int voltageToDac(int value); -int dacToVoltage(unsigned int digital); -#endif -#ifdef MYTHEN3D -int setPower(enum DACINDEX ind, int val); -int powerToDac(int value, int chip); -int dacToPower(int value, int chip); -#endif - -#ifdef JUNGFRAUD -extern void setAdc(int addr, int val); // AD9257.h -#endif - -void setDAC(enum DACINDEX ind, int val, int imod, int mV, int retval[]); -#ifdef MYTHEN3D -int getVLimit(); -void setDacRegister(int dacnum,int dacvalue); -int getDacRegister(int dacnum); -#endif -#ifndef MYTHEN3D -int getADC(enum ADCINDEX ind, int imod); -#endif - -#if !defined(MYTHEN3D) && !defined(MYTHEND) -int setHighVoltage(int val); -#endif - - - -// parameters - timing, extsig -#ifdef MYTHEND -enum externalSignalFlag getExtSignal(int signalindex); -enum externalSignalFlag setExtSignal(int signalindex, enum externalSignalFlag flag); -#endif -enum externalCommunicationMode setTiming( enum externalCommunicationMode arg); - -// configure mac -#ifdef JUNGFRAUD -long int calcChecksum(int sourceip, int destip); -#endif -#if !defined(MYTHEN3D) && !defined(MYTHEND) -int configureMAC(uint32_t destip, uint64_t destmac, uint64_t sourcemac, uint32_t sourceip, uint32_t udpport, uint32_t udpport2, int ival); -#endif -#if defined(JUNGFRAUD) || defined(EIGERD) -int setDetectorPosition(int pos[]); -#endif - - -// very detector specific - -// gotthard specific - image, pedestal -#ifdef GOTTHARDD -int loadImage(enum imageType index, char *imageVals); -int readCounterBlock(int startACQ, char *counterVals); -int resetCounterBlock(int startACQ); -int calibratePedestal(int frames); - -// jungfrau specific - pll, flashing firmware -#elif defined(JUNGFRAUD) || defined(MYTHEN3D) -void resetPLL(); -u_int32_t setPllReconfigReg(u_int32_t reg, u_int32_t val); -void configurePll(); -int setThresholdTemperature(int val); -int setTemperatureControl(int val); -int setTemperatureEvent(int val); -extern void eraseFlash(); // programfpga.h -extern int startWritingFPGAprogram(FILE** filefp); // programfpga.h -extern void stopWritingFPGAprogram(FILE* filefp); // programfpga.h -extern int writeFPGAProgram(char* fpgasrc, size_t fsize, FILE* filefp); // programfpga.h - -// eiger specific - iodelay, 10g, pulse, rate, temp, activate, delay nw parameter -#elif EIGERD -int setIODelay(int val, int imod); -int enableTenGigabitEthernet(int val); -int setCounterBit(int val); -int pulsePixel(int n, int x, int y); -int pulsePixelNMove(int n, int x, int y); -int pulseChip(int n); -int64_t setRateCorrection(int64_t custom_tau_in_nsec); -int getRateCorrectionEnable(); -int getDefaultSettingsTau_in_nsec(); -void setDefaultSettingsTau_in_nsec(int t); -int64_t getCurrentTau(); -void setExternalGating(int enable[]); -int setAllTrimbits(int val); -int getAllTrimbits(); -int getBebFPGATemp(); -int activate(int enable); -#endif -#if defined(JUNGFRAUD) || defined(EIGERD) -int setNetworkParameter(enum NETWORKINDEX mode, int value); -#endif - - - - -// aquisition -#if defined(EIGERD) || defined(GOTTHARD) -int prepareAcquisition(); -#endif -int startStateMachine(); -#ifdef VIRTUAL -void* start_timer(void* arg); -#endif -int stopStateMachine(); -#ifdef EIGERD -int softwareTrigger(); -#endif -#ifndef JUNGFRAUD -int startReadOut(); -#endif -enum runStatus getRunStatus(); -void readFrame(int *ret, char *mess); -#ifdef JUNGFRAUD -u_int32_t runBusy(void); -#endif - - -//common -int copyModule(sls_detector_module *destMod, sls_detector_module *srcMod); -int calculateDataBytes(); -int getTotalNumberOfChannels(); -int getTotalNumberOfChips(); -int getTotalNumberOfModules(); -int getNumberOfChannelsPerModule(); -int getNumberOfChipsPerModule(); -int getNumberOfDACsPerModule(); -int getNumberOfADCsPerModule(); -#ifdef EIGERD -int getNumberOfGainsPerModule(); -int getNumberOfOffsetsPerModule(); -#endif -int getNumberOfChannelsPerChip(); - -// sync -enum masterFlags setMaster(enum masterFlags arg); -enum synchronizationMode setSynchronization(enum synchronizationMode arg); - - - -#endif -#endif diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer.c b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer.c deleted file mode 100755 index fd4b0e443..000000000 --- a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer.c +++ /dev/null @@ -1,138 +0,0 @@ -/* A simple server in the internet domain using TCP - The port number is passed as an argument */ - -#include "sls_detector_defs.h" -#include "slsDetectorServer_defs.h" - -#include "communication_funcs.h" -#include "slsDetectorServer_funcs.h" - -#include -#include -#include -#include - -extern int sockfd; - - -void error(char *msg){ - perror(msg); -} - -int main(int argc, char *argv[]){ - int portno = DEFAULT_PORTNO; - int retval = OK; - int sd, fd; - int debugflag = 0; - int controlserver = 1; - - // if socket crash, ignores SISPIPE, prevents global signal handler - // subsequent read/write to socket gives error - must handle locally - signal(SIGPIPE, SIG_IGN); - - // circumvent the basic tests - { - int i; - for (i = 1; i < argc; ++i) { - if(!strcasecmp(argv[i],"-stopserver")) { - cprintf(BLUE,"Detected stop server\n"); - controlserver = 0; - } - else if(!strcasecmp(argv[i],"-devel")){ - cprintf(BLUE,"Detected developer mode\n"); - debugflag = 1; - } -#ifdef JUNGFRAUD - else if(!strcasecmp(argv[i],"-update")){ - cprintf(BLUE,"Detected update mode\n"); - debugflag = PROGRAMMING_MODE; - } -#endif - else if(strchr(argv[i],'-') != NULL) { - cprintf(RED,"cannot scan program argument %s\n", argv[1]); - return -1; - } - } - } - -#ifdef STOP_SERVER - char cmd[100]; - memset(cmd, 0, 100); -#endif - if (controlserver) { - portno = DEFAULT_PORTNO; - cprintf(BLUE, - "********************************************************\n" - "********* opening control server on port %d **********\n" - "********************************************************\n\n" - , portno); -#ifdef STOP_SERVER - { - int i; - for (i = 0; i < argc; ++i) - sprintf(cmd, "%s %s", cmd, argv[i]); - sprintf(cmd,"%s -stopserver&", cmd); - cprintf(BLUE,"cmd:%s\n", cmd); - system(cmd); - } -#endif - } else { - portno = DEFAULT_PORTNO+1; - cprintf(BLUE, - "********************************************************\n" - "*********** opening stop server on port %d ***********\n" - "********************************************************\n\n" - , portno); - } - - setModeFlag(debugflag); //defined in slsDetectorServer_funcs - init_detector(controlserver); //defined in slsDetectorServer_funcs - - sd=bindSocket(portno); //defined in communication_funcs - sockfd=sd; - if (getServerError(sd)) { //defined in communication_funcs - printf("server error!\n"); - return -1; - } - - /* assign function table */ - function_table(); //defined in slsDetectorServer_funcs -#ifdef VERBOSE - printf("function table assigned \n"); -#endif - - if (controlserver) - printf("\nControl Server Ready...\n\n"); - else - printf("\nStop Server Ready...\n\n"); - - /* waits for connection */ - while(retval!=GOODBYE) { -#ifdef VERBOSE - printf("\n"); -#endif -#ifdef VERY_VERBOSE - printf("Waiting for client call\n"); -#endif - fd=acceptConnection(sockfd); //defined in communication_funcs -#ifdef VERY_VERBOSE - printf("Conenction accepted\n"); -#endif - if (fd>0) { - retval=decode_function(fd); //defined in slsDetectorServer_funcs -#ifdef VERY_VERBOSE - printf("function executed\n"); -#endif - closeConnection(fd); //defined in communication_funcs -#ifdef VERY_VERBOSE - printf("connection closed\n"); -#endif - } - } - - exitServer(sockfd); //defined in communication_funcs - printf("Goodbye!\n"); - - return 0; -} - diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_defs.h b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_defs.h deleted file mode 100644 index 02e45004a..000000000 --- a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_defs.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * slsDetectorServer_defs.h - * - * Created on: Jan 24, 2013 - * Author: l_maliakal_d - */ - -#ifndef SLSDETECTORSERVER_DEFS_H_ -#define SLSDETECTORSERVER_DEFS_H_ - -#include "sls_detector_defs.h" -#include - -/** This is only an example file!!! */ - -/* -#define GOODBYE (-200) -enum DAC_INDEX {examplesdac} - - Hardware Definitions -#define NMAXMOD (1) -#define NMOD (1) -#define NCHAN (256 * 256) -#define NCHIP (4) -#define NADC (0) -#define NDAC (16) -#define NGAIN (0) -#define NOFFSET (0) -*/ - -#endif /* SLSDETECTORSERVER_DEFS_H_ */ diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c b/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c deleted file mode 100755 index 8cd09f2b1..000000000 --- a/slsDetectorSoftware/slsDetectorServer/slsDetectorServer_funcs.c +++ /dev/null @@ -1,5928 +0,0 @@ - -#include "sls_detector_defs.h" -#include "slsDetectorServer_funcs.h" -#include "slsDetectorFunctionList.h" -#include "communication_funcs.h" -#include "slsDetectorServer_defs.h" - -#include -#include -#include - - -// Global variables -extern int lockStatus; -extern char lastClientIP[INET_ADDRSTRLEN]; -extern char thisClientIP[INET_ADDRSTRLEN]; -extern int differentClients; - -//defined in the detector specific Makefile -#ifdef MYTHEND -const enum detectorType myDetectorType=MYTHEN; -#elif GOTTHARDD -const enum detectorType myDetectorType=GOTTHARD; -#elif EIGERD -const enum detectorType myDetectorType=EIGER; -#elif PICASSOD -const enum detectorType myDetectorType=PICASSO; -#elif MOENCHD -const enum detectorType myDetectorType=MOENCH; -#elif JUNGFRAUD -const enum detectorType myDetectorType=JUNGFRAU; -#elif MYTHEN3D -const enum detectorType myDetectorType=MYTHEN3; -#else -const enum detectorType myDetectorType=GENERIC; -#endif - -int sockfd; // (updated in slsDetectorServer) as extern -int (*flist[NUM_DET_FUNCTIONS])(int); -char mess[MAX_STR_LENGTH]; -int dataBytes = 10; -int isControlServer = 0; -int debugflag = 0; -#ifdef EIGERD -uint32_t dhcpipad = 0; -#endif - -/* initialization functions */ - -int printSocketReadError() { - cprintf(BG_RED, "Error reading from socket. Possible socket crash\n"); - return FAIL; -} - -void setModeFlag(int flag) { - debugflag = flag; -} - -void basictests() { -#ifdef SLS_DETECTOR_FUNCTION_LIST - checkFirmwareCompatibility(debugflag); -#endif -} - - -void init_detector(int controlserver) { -#ifdef VIRTUAL - printf("This is a VIRTUAL detector\n"); -#endif - -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (controlserver) { - isControlServer = 1; - basictests(); -#ifdef JUNGFRAUD - if (debugflag != PROGRAMMING_MODE) -#endif - initControlServer(); -#ifdef EIGERD - dhcpipad = getDetectorIP(); -#endif - } - else initStopServer(); -#endif - strcpy(mess,"dummy message"); - strcpy(lastClientIP,"none"); - strcpy(thisClientIP,"none1"); - lockStatus=0; -} - - -int decode_function(int file_des) { - int fnum,n; - int ret=FAIL; -#ifdef VERBOSE - printf( "\nreceive data\n"); -#endif - n = receiveData(file_des,&fnum,sizeof(fnum),INT32); - if (n <= 0) { -#ifdef VERBOSE - printf("ERROR reading from socket %d, %d %d (%s)\n", n, fnum, file_des, getFunctionName((enum detFuncs)fnum)); -#endif - return FAIL; - } -#ifdef VERBOSE - else - printf("size of data received %d\n",n); -#endif - -#ifdef VERBOSE - printf(" calling function fnum=%d, (%s) located at 0x%x\n", fnum, getFunctionName((enum detFuncs)fnum), (unsigned int)flist[fnum]); -#endif -#ifdef JUNGFRAUD - if ((debugflag == PROGRAMMING_MODE) && - ((fnum != F_PROGRAM_FPGA) && (fnum != F_GET_DETECTOR_TYPE) && - (fnum != F_RESET_FPGA) && (fnum != F_UPDATE_CLIENT) && (fnum != F_CHECK_VERSION))) { - sprintf(mess,"This Function %s cannot be executed. ", getFunctionName((enum detFuncs)fnum)); - ret=(M_nofuncMode)(file_des); - } else -#endif - if (fnum<0 || fnum>=NUM_DET_FUNCTIONS) { - cprintf(BG_RED,"Unknown function enum %d\n", fnum); - ret=(M_nofunc)(file_des); - }else - ret=(*flist[fnum])(file_des); - if (ret == FAIL) - cprintf(RED, "Error executing the function = %d (%s)\n", fnum, getFunctionName((enum detFuncs)fnum)); - return ret; -} - - -const char* getFunctionName(enum detFuncs func) { - switch (func) { - case F_EXEC_COMMAND: return "F_EXEC_COMMAND"; - case F_GET_ERROR: return "F_GET_ERROR"; - case F_GET_DETECTOR_TYPE: return "F_GET_DETECTOR_TYPE"; - case F_SET_NUMBER_OF_MODULES: return "F_SET_NUMBER_OF_MODULES"; - case F_GET_MAX_NUMBER_OF_MODULES: return "F_GET_MAX_NUMBER_OF_MODULES"; - case F_SET_EXTERNAL_SIGNAL_FLAG: return "F_SET_EXTERNAL_SIGNAL_FLAG"; - case F_SET_EXTERNAL_COMMUNICATION_MODE: return "F_SET_EXTERNAL_COMMUNICATION_MODE"; - case F_GET_ID: return "F_GET_ID"; - case F_DIGITAL_TEST: return "F_DIGITAL_TEST"; - case F_ANALOG_TEST: return "F_ANALOG_TEST"; - case F_ENABLE_ANALOG_OUT: return "F_ENABLE_ANALOG_OUT"; - case F_CALIBRATION_PULSE: return "F_CALIBRATION_PULSE"; - case F_SET_DAC: return "F_SET_DAC"; - case F_GET_ADC: return "F_GET_ADC"; - case F_WRITE_REGISTER: return "F_WRITE_REGISTER"; - case F_READ_REGISTER: return "F_READ_REGISTER"; - case F_WRITE_MEMORY: return "F_WRITE_MEMORY"; - case F_READ_MEMORY: return "F_READ_MEMORY"; - case F_SET_CHANNEL: return "F_SET_CHANNEL"; - case F_GET_CHANNEL: return "F_GET_CHANNEL"; - case F_SET_ALL_CHANNELS: return "F_SET_ALL_CHANNELS"; - case F_SET_CHIP: return "F_SET_CHIP"; - case F_GET_CHIP: return "F_GET_CHIP"; - case F_SET_ALL_CHIPS: return "F_SET_ALL_CHIPS"; - case F_SET_MODULE: return "F_SET_MODULE"; - case F_GET_MODULE: return "F_GET_MODULE"; - case F_SET_ALL_MODULES: return "F_SET_ALL_MODULES"; - case F_SET_SETTINGS: return "F_SET_SETTINGS"; - case F_GET_THRESHOLD_ENERGY: return "F_GET_THRESHOLD_ENERGY"; - case F_SET_THRESHOLD_ENERGY: return "F_SET_THRESHOLD_ENERGY"; - case F_START_ACQUISITION: return "F_START_ACQUISITION"; - case F_STOP_ACQUISITION: return "F_STOP_ACQUISITION"; - case F_START_READOUT: return "F_START_READOUT"; - case F_GET_RUN_STATUS: return "F_GET_RUN_STATUS"; - case F_START_AND_READ_ALL: return "F_START_AND_READ_ALL"; - case F_READ_FRAME: return "F_READ_FRAME"; - case F_READ_ALL: return "F_READ_ALL"; - case F_SET_TIMER: return "F_SET_TIMER"; - case F_GET_TIME_LEFT: return "F_GET_TIME_LEFT"; - case F_SET_DYNAMIC_RANGE: return "F_SET_DYNAMIC_RANGE"; - case F_SET_READOUT_FLAGS: return "F_SET_READOUT_FLAGS"; - case F_SET_ROI: return "F_SET_ROI"; - case F_SET_SPEED: return "F_SET_SPEED"; - case F_EXECUTE_TRIMMING: return "F_EXECUTE_TRIMMING"; - case F_EXIT_SERVER: return "F_EXIT_SERVER"; - case F_LOCK_SERVER: return "F_LOCK_SERVER"; - case F_GET_LAST_CLIENT_IP: return "F_GET_LAST_CLIENT_IP"; - case F_SET_PORT: return "F_SET_PORT"; - case F_UPDATE_CLIENT: return "F_UPDATE_CLIENT"; - case F_CONFIGURE_MAC: return "F_CONFIGURE_MAC"; - case F_LOAD_IMAGE: return "F_LOAD_IMAGE"; - case F_SET_MASTER: return "F_SET_MASTER"; - case F_SET_SYNCHRONIZATION_MODE: return "F_SET_SYNCHRONIZATION_MODE"; - case F_READ_COUNTER_BLOCK: return "F_READ_COUNTER_BLOCK"; - case F_RESET_COUNTER_BLOCK: return "F_RESET_COUNTER_BLOCK"; - case F_CALIBRATE_PEDESTAL: return "F_CALIBRATE_PEDESTAL"; - case F_ENABLE_TEN_GIGA: return "F_ENABLE_TEN_GIGA"; - case F_SET_ALL_TRIMBITS: return "F_SET_ALL_TRIMBITS"; - case F_SET_CTB_PATTERN: return "F_SET_CTB_PATTERN"; - case F_WRITE_ADC_REG: return "F_WRITE_ADC_REG"; - case F_SET_COUNTER_BIT: return "F_SET_COUNTER_BIT"; - case F_PULSE_PIXEL: return "F_PULSE_PIXEL"; - case F_PULSE_PIXEL_AND_MOVE: return "F_PULSE_PIXEL_AND_MOVE"; - case F_PULSE_CHIP: return "F_PULSE_CHIP"; - case F_SET_RATE_CORRECT: return "F_SET_RATE_CORRECT"; - case F_GET_RATE_CORRECT: return "F_GET_RATE_CORRECT"; - case F_SET_NETWORK_PARAMETER: return "F_SET_NETWORK_PARAMETER"; - case F_PROGRAM_FPGA: return "F_PROGRAM_FPGA"; - case F_RESET_FPGA: return "F_RESET_FPGA"; - case F_POWER_CHIP: return "F_POWER_CHIP"; - case F_ACTIVATE: return "F_ACTIVATE"; - case F_PREPARE_ACQUISITION: return "F_PREPARE_ACQUISITION"; - case F_CLEANUP_ACQUISITION: return "F_CLEANUP_ACQUISITION"; - case F_THRESHOLD_TEMP: return "F_THRESHOLD_TEMP"; - case F_TEMP_CONTROL: return "F_TEMP_CONTROL"; - case F_TEMP_EVENT: return "F_TEMP_EVENT"; - case F_AUTO_COMP_DISABLE: return "F_AUTO_COMP_DISABLE"; - case F_STORAGE_CELL_START: return "F_STORAGE_CELL_START"; - case F_CHECK_VERSION: return "F_CHECK_VERSION"; - case F_SOFTWARE_TRIGGER: return "F_SOFTWARE_TRIGGER"; - - default: return "Unknown Function"; - } -} - -void function_table() { - flist[F_EXEC_COMMAND] = &exec_command; - flist[F_GET_ERROR] = &get_error; - flist[F_GET_DETECTOR_TYPE] = &get_detector_type; - flist[F_SET_NUMBER_OF_MODULES] = &set_number_of_modules; - flist[F_GET_MAX_NUMBER_OF_MODULES] = &get_max_number_of_modules; - flist[F_SET_EXTERNAL_SIGNAL_FLAG] = &set_external_signal_flag; - flist[F_SET_EXTERNAL_COMMUNICATION_MODE] = &set_external_communication_mode; - flist[F_GET_ID] = &get_id; - flist[F_DIGITAL_TEST] = &digital_test; - flist[F_ANALOG_TEST] = &analog_test; - flist[F_ENABLE_ANALOG_OUT] = &enable_analog_out; - flist[F_CALIBRATION_PULSE] = &calibration_pulse; - flist[F_SET_DAC] = &set_dac; - flist[F_GET_ADC] = &get_adc; - flist[F_WRITE_REGISTER] = &write_register; - flist[F_READ_REGISTER] = &read_register; - flist[F_WRITE_MEMORY] = &write_memory; - flist[F_READ_MEMORY] = &read_memory; - flist[F_SET_CHANNEL] = &set_channel; - flist[F_GET_CHANNEL] = &get_channel; - flist[F_SET_ALL_CHANNELS] = &set_all_channels; - flist[F_SET_CHIP] = &set_chip; - flist[F_GET_CHIP] = &get_chip; - flist[F_SET_ALL_CHIPS] = &set_all_chips; - flist[F_SET_MODULE] = &set_module; - flist[F_GET_MODULE] = &get_module; - flist[F_SET_ALL_MODULES] = &set_all_modules; - flist[F_SET_SETTINGS] = &set_settings; - flist[F_GET_THRESHOLD_ENERGY] = &get_threshold_energy; - flist[F_SET_THRESHOLD_ENERGY] = &set_threshold_energy; - flist[F_START_ACQUISITION] = &start_acquisition; - flist[F_STOP_ACQUISITION] = &stop_acquisition; - flist[F_START_READOUT] = &start_readout; - flist[F_GET_RUN_STATUS] = &get_run_status; - flist[F_START_AND_READ_ALL] = &start_and_read_all; - flist[F_READ_FRAME] = &read_frame; - flist[F_READ_ALL] = &read_all; - flist[F_SET_TIMER] = &set_timer; - flist[F_GET_TIME_LEFT] = &get_time_left; - flist[F_SET_DYNAMIC_RANGE] = &set_dynamic_range; - flist[F_SET_READOUT_FLAGS] = &set_readout_flags; - flist[F_SET_ROI] = &set_roi; - flist[F_SET_SPEED] = &set_speed; - flist[F_EXECUTE_TRIMMING] = &execute_trimming; - flist[F_EXIT_SERVER] = &exit_server; - flist[F_LOCK_SERVER] = &lock_server; - flist[F_GET_LAST_CLIENT_IP] = &get_last_client_ip; - flist[F_SET_PORT] = &set_port; - flist[F_UPDATE_CLIENT] = &update_client; - flist[F_CONFIGURE_MAC] = &configure_mac; - flist[F_LOAD_IMAGE] = &load_image; - flist[F_SET_MASTER] = &set_master; - flist[F_SET_SYNCHRONIZATION_MODE] = &set_synchronization; - flist[F_READ_COUNTER_BLOCK] = &read_counter_block; - flist[F_RESET_COUNTER_BLOCK] = &reset_counter_block; - flist[F_CALIBRATE_PEDESTAL] = &calibrate_pedestal; - flist[F_ENABLE_TEN_GIGA] = &enable_ten_giga; - flist[F_SET_ALL_TRIMBITS] = &set_all_trimbits; - flist[F_SET_CTB_PATTERN] = &set_ctb_pattern; - flist[F_WRITE_ADC_REG] = &write_adc_register; - flist[F_SET_COUNTER_BIT] = &set_counter_bit; - flist[F_PULSE_PIXEL] = &pulse_pixel; - flist[F_PULSE_PIXEL_AND_MOVE] = &pulse_pixel_and_move; - flist[F_PULSE_CHIP] = &pulse_chip; - flist[F_SET_RATE_CORRECT] = &set_rate_correct; - flist[F_GET_RATE_CORRECT] = &get_rate_correct; - flist[F_SET_NETWORK_PARAMETER] = &set_network_parameter; - flist[F_PROGRAM_FPGA] = &program_fpga; - flist[F_RESET_FPGA] = &reset_fpga; - flist[F_POWER_CHIP] = &power_chip; - flist[F_ACTIVATE] = &set_activate; - flist[F_PREPARE_ACQUISITION] = &prepare_acquisition; - flist[F_CLEANUP_ACQUISITION] = &cleanup_acquisition; - flist[F_THRESHOLD_TEMP] = &threshold_temp; - flist[F_TEMP_CONTROL] = &temp_control; - flist[F_TEMP_EVENT] = &temp_event; - flist[F_AUTO_COMP_DISABLE] = &auto_comp_disable; - flist[F_STORAGE_CELL_START] = &storage_cell_start; - flist[F_CHECK_VERSION] = &check_version; - flist[F_SOFTWARE_TRIGGER] = &software_trigger; - - // check - if (NUM_DET_FUNCTIONS >= TOO_MANY_FUNCTIONS_DEFINED) { - cprintf(BG_RED,"The last detector function enum has reached its limit\nGoodbye!\n"); - exit(EXIT_FAILURE); - } - -#ifdef VERYVERBOSE - { - int i=0; - for (i = 0; i < NUM_DET_FUNCTIONS ; i++) { - printf("function fnum=%d, (%s) located at 0x%x\n", i, getFunctionName((enum detFuncs)i), (unsigned int)flist[i]); - } - } -#endif -} - - -int M_nofunc(int file_des){ - int ret=FAIL,ret1=FAIL; - int n=0; - - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - - sprintf(mess,"Unrecognized Function. Please do not proceed.\n"); - cprintf(BG_RED,"Error: %s",mess); - n = sendData(file_des,&ret1,sizeof(ret1),INT32); - n = sendData(file_des,mess,sizeof(mess),OTHER); - - // return ok / fail - return ret; -} - - - -int M_nofuncMode(int file_des){ - int ret=FAIL,ret1=FAIL; - int n=0; - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - - strcat(mess, "On-board detector server in update mode. Restart detector server in normal mode (without any arguments) to continue.\n"); - cprintf(BG_RED,"Error: %s",mess); - n = sendData(file_des,&ret1,sizeof(ret1),INT32); - n = sendData(file_des,mess,sizeof(mess),OTHER); // mess is defined at function call - - // return ok / fail - return ret; -} - - - -/* functions called by client */ - - - -int exec_command(int file_des) { - int ret=OK,ret1=OK; - int n=0; - char cmd[MAX_STR_LENGTH]=""; - int sysret=0; - - // receive arguments - n = receiveData(file_des,cmd,MAX_STR_LENGTH,OTHER); - if (n < 0) return printSocketReadError(); - - // execute action if the arguments correctly arrived -#ifdef VERBOSE - printf("executing command %s\n", cmd); -#endif - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } else { - sysret=system(cmd); - //should be replaced by popen - if (sysret==0) { - sprintf(mess,"Succeeded\n"); - } else { - ret = FAIL; - sprintf(mess,"Executing Command failed\n"); - cprintf(RED, "Warning: %s", mess); - } - } - - ret1=ret; - n = sendData(file_des,&ret1,sizeof(ret),INT32); - n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); - - // return ok / fail - return ret; -} - - - -int get_error(int file_des) { - int ret=FAIL,ret1=FAIL; - int n=0; - sprintf(mess,"Function (Get Error) is not implemented for this detector\n"); - cprintf(RED, "Error: %s", mess); - - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - - n = sendData(file_des,&ret1,sizeof(ret),INT32); - n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); - - // return ok / fail - return ret; -} - - - -int get_detector_type(int file_des) { - int ret=OK,ret1=OK; - int n=0; - enum detectorType retval=-1; - - // execute action - retval=myDetectorType; -#ifdef VERBOSE - printf("Returning detector type %d\n",retval); -#endif - - if (differentClients) - ret=FORCE_UPDATE; - - // send ok / fail - n += sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; - - -} - - - - -int set_number_of_modules(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=0; - int arg[2]={-1,-1}; - sprintf(mess,"set number of modules failed\n"); - - // receive arguments - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - enum dimension dim=arg[0]; - int nm=arg[1]; - - // execute action -#ifdef VERBOSE - printf("Setting the number of modules in dimension %d to %d\n",dim,nm ); -#endif - if (lockStatus && differentClients && nm!=GET_FLAG) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - retval=setNMod(nm, dim); - dataBytes=calculateDataBytes(); - } -#endif - - if (retval==nm || nm==GET_FLAG) { - ret=OK; - if (differentClients) - ret=FORCE_UPDATE; - } else - ret=FAIL; - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - -int get_max_number_of_modules(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - enum dimension arg=0; - sprintf(mess,"get max number of modules failed\n"); - - // receive arguments - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action -#ifdef VERBOSE - printf("Getting the max number of modules in dimension %d \n",arg); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=getNModBoard(arg); -#endif -#ifdef VERBOSE - printf("Max number of module in dimension %d is %d\n",arg,retval ); -#endif - if (differentClients && ret==OK) { - ret=FORCE_UPDATE; - } - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - -int set_external_signal_flag(int file_des) { - int ret=OK,ret1=OK; - int n=0; - enum externalSignalFlag retval=GET_EXTERNAL_SIGNAL_FLAG; - sprintf(mess,"set external signal flag failed\n"); - -#ifndef MYTHEND - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Set External Signal Flag) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); -#else - - // receive arguments - int arg[2]={-1,-1}; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - int signalindex=arg[0]; - enum externalSignalFlag flag=arg[1]; - - // execute action - if (lockStatus && differentClients && flag!=GET_EXTERNAL_SIGNAL_FLAG) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - -#ifdef SLS_DETECTOR_FUNCTION_LIST - else{ -#ifdef VERBOSE - printf("Setting external signal %d to flag %d\n",signalindex,flag); -#endif - switch (flag) { - case GET_EXTERNAL_SIGNAL_FLAG: - retval=getExtSignal(signalindex); - break; - default: - retval=setExtSignal(signalindex,flag); - if (retval!=flag) { - ret=FAIL; - sprintf(mess,"External signal %d flag should be 0x%04x but is 0x%04x\n", signalindex, flag, retval); - cprintf(RED, "%s", mess); - } - break; - } -#ifdef VERBOSE - printf("Set to flag %d\n",retval); -#endif - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; - -} - - -int set_external_communication_mode(int file_des) { - int ret=OK,ret1=OK; - int n=0; - enum externalCommunicationMode arg=GET_EXTERNAL_COMMUNICATION_MODE; - enum externalCommunicationMode retval=GET_EXTERNAL_COMMUNICATION_MODE; - sprintf(mess,"set external communication mode failed\n"); - - // receive arguments - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action -#ifdef VERBOSE - printf("Setting external communication mode to %d\n", arg); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - switch(arg){ -#ifdef EIGERD - case GET_EXTERNAL_COMMUNICATION_MODE: - case AUTO_TIMING: - case TRIGGER_EXPOSURE: - case GATE_FIX_NUMBER: - case BURST_TRIGGER: -#elif JUNGFRAUD - case GET_EXTERNAL_COMMUNICATION_MODE: - case AUTO_TIMING: - case TRIGGER_EXPOSURE: -#endif - retval=setTiming(arg); - break; - default: - ret = FAIL; - sprintf(mess,"Timing mode (%d) is not implemented for this detector\n",(int)arg); - cprintf(RED, "Warning: %s", mess); - break; - } -#ifdef VERBOSE - if(ret==OK) - printf("retval:%d\n",retval); -#endif - if (ret==OK && differentClients==1) - ret=FORCE_UPDATE; - -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - -int get_id(int file_des) { - int ret=OK,ret1=OK; - int n=0; - enum idMode arg=0; - int imod=-1; - int64_t retval=-1; - sprintf(mess,"get id failed\n"); - - // receive arguments - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - if (arg == MODULE_SERIAL_NUMBER) { - n = receiveData(file_des,&imod,sizeof(imod),INT32); - if (n < 0) return printSocketReadError(); - } - - // execute action -#ifdef VERBOSE - printf("Getting id %d\n", arg); -#endif - -#ifdef SLS_DETECTOR_FUNCTION_LIST - switch (arg) { -#ifdef MYTHEND - case MODULE_SERIAL_NUMBER: - case MODULE_FIRMWARE_VERSION: -#ifdef VERBOSE - printf("of module %d\n", imod); -#endif - - if (imod>=0 && imod 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Digital Test) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); -#else - - enum digitalTestMode arg=0; - int imod=-1; - int ival=-1; - - // receive arguments - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - if (arg == CHIP_TEST) { - n = receiveData(file_des,&imod,sizeof(imod),INT32); - if (n < 0) return printSocketReadError(); - } - - if (arg == DIGITAL_BIT_TEST) { - n = receiveData(file_des,&ival,sizeof(ival),INT32); - if (n < 0) return printSocketReadError(); - } - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } else { -#ifdef VERBOSE - printf("Digital test mode %d\n",arg ); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - switch (arg) { - -#ifdef GOTTHARD - case DIGITAL_BIT_TEST: - retval=0; - break; - -#elif MYTHEND - case CHIP_TEST: -#ifdef VERBOSE - printf("of module %d\n", imod); -#endif - if (imod>=0 && imod 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - - n = sendData(file_des,&ret1,sizeof(ret),INT32); - n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); - - // return ok / fail - return ret; -} - - - -int enable_analog_out(int file_des) { - int ret=FAIL,ret1=FAIL; - int n=0; - sprintf(mess,"Function (Enable Analog Out) is not implemented for this detector\n"); - cprintf(RED, "Error: %s", mess); - - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - - n = sendData(file_des,&ret1,sizeof(ret),INT32); - n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); - - // return ok / fail - return ret; -} - - - -int calibration_pulse(int file_des) { - int ret=FAIL,ret1=FAIL; - int n=0; - sprintf(mess,"Function (Calibration Pulse) is not implemented for this detector\n"); - cprintf(RED, "Error: %s", mess); - - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - - n = sendData(file_des,&ret1,sizeof(ret),INT32); - n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); - - // return ok / fail - return ret; -} - - - - -int set_dac(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int arg[3]={-1,-1,-1}; - int val=-1; - enum dacIndex ind=0; - int imod=-1; - int retval[2]={-1,-1}; - int mV=0; - sprintf(mess,"set DAC failed\n"); - - // receive arguments - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - ind=arg[0]; - imod=arg[1]; - mV=arg[2]; - - n = receiveData(file_des,&val,sizeof(val),INT32); - if (n < 0) return printSocketReadError(); - - // checks -#ifdef MYTHEND -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (imod>=getTotalNumberOfModules()) { - ret = FAIL; - sprintf(mess,"Module number %d out of range\n",imod); - cprintf(RED, "Warning: %s", mess); - } -#endif -#endif - // check if dac exists for this detector - enum DACINDEX idac=0; -#ifdef JUNGFRAUD - if ((ind != HV_NEW) && (ind >= NDAC_OLDBOARD)) { //for compatibility with old board - ret = FAIL; - sprintf(mess,"Dac Index (%d) is not implemented for this detector\n",(int)ind); - cprintf(RED, "Warning: %s", mess); - }else - idac = ind; -#else - switch (ind) { -#ifdef MYTHEND - case TRIMBIT_SIZE: //ind = VTRIM; - case THRESHOLD: - case SHAPER1: - case SHAPER2: - case CALIBRATION_PULSE: - case PREAMP: - break; -#elif GOTTHARDD - case G_VREF_DS : - break; - case G_VCASCN_PB: - break; - case G_VCASCP_PB: - break; - case G_VOUT_CM: - break; - case G_VCASC_OUT: - break; - case G_VIN_CM: - break; - case G_VREF_COMP: - break; - case G_IB_TESTC: - break; - case HV_POT: - break; -#elif EIGERD - case TRIMBIT_SIZE: - idac = VTR; - break; - case THRESHOLD: - idac = VTHRESHOLD; - break; - case E_SvP: - idac = SVP; - break; - case E_SvN: - idac = SVN; - break; - case E_Vtr: - idac = VTR; - break; - case E_Vrf: - idac = VRF; - break; - case E_Vrs: - idac = VRS; - break; - case E_Vtgstv: - idac = VTGSTV; - break; - case E_Vcmp_ll: - idac = VCMP_LL; - break; - case E_Vcmp_lr: - idac = VCMP_LR; - break; - case E_cal: - idac = CAL; - break; - case E_Vcmp_rl: - idac = VCMP_RL; - break; - case E_Vcmp_rr: - idac = VCMP_RR; - break; - case E_rxb_rb: - idac = RXB_RB; - break; - case E_rxb_lb: - idac = RXB_LB; - break; - case E_Vcp: - idac = VCP; - break; - case E_Vcn: - idac = VCN; - break; - case E_Vis: - idac = VIS; - break; - case HV_NEW: - break; - case IO_DELAY: - break; - /* -#elif JUNGFRAUD - case V_DAC0: - idac = VB_COMP; - break; - case V_DAC1: - idac = VDD_PROT; - break; - case V_DAC2: - idac = VIN_COM; - break; - case V_DAC3: - idac = VREF_PRECH; - break; - case V_DAC4: - idac = VB_PIXBUF; - break; - case V_DAC5: - idac = VB_DS; - break; - case V_DAC6: - idac = VREF_DS; - break; - case V_DAC7: - idac = VREF_COMP; - break; - case HV_POT: - break; - */ -#elif MYTHEN3D - case M_vIpre: - idac = vIpre; - break; - case M_vIbias: - idac = vIbias; - break; - case PREAMP: - idac = Vrf; - break; - case SHAPER1: - idac = VrfSh; - break; - case M_vIinSh: - idac = vIinSh; - break; - case M_VdcSh: - idac = VdcSh; - break; - case M_Vth2: - idac = Vth2; - break; - case M_VPL: - idac = VPL; - break; - case THRESHOLD: - idac = Vth1; - break; - case M_Vth3: - idac = Vth3; - break; - case TRIMBIT_SIZE: - idac = Vtrim; - break; - case M_casSh: - idac = casSh; - break; - case M_cas: - idac = cas; - break; - case M_vIbiasSh: - idac = vIbiasSh; - break; - case M_vIcin: - idac = vIcin; - break; - case CALIBRATION_PULSE: // !!! pulse height + 1400 DACu - idac = VPH; - break; - case M_vIpreOut: - idac = vIpreOut; - break; - case V_POWER_A: - idac = V_A; - break; - case V_POWER_B: - ipwr = V_B; - break; - case V_POWER_IO: - idac = V_IO; - break; - case V_POWER_CHIP: - idac = V_CHIP; - break; - case V_LIMIT: - idac = V_LIM; - break; -#endif - default: - ret = FAIL; - sprintf(mess,"Dac Index (%d) is not implemented for this detector\n",(int)ind); - cprintf(RED, "Warning: %s", mess); - break; - } -#endif - - // execute action -#ifdef VERBOSE - printf("Setting DAC %d of module %d to %d \n", idac, imod, val); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - int temp; - if (ret==OK) { - if (differentClients && lockStatus && val!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } else { -#ifdef EIGERD - //iodelay - if(ind == IO_DELAY) - retval[0] = setIODelay(val,imod); - //high voltage - else -#endif - if((ind == HV_POT) || (ind == HV_NEW)) { - retval[0] = setHighVoltage(val); -#ifdef EIGERD - if ((retval[0] != SLAVE_HIGH_VOLTAGE_READ_VAL) && (retval[0] < 0)) { - ret = FAIL; - if(retval[0] == -1) - sprintf(mess, "Setting high voltage failed.Bad value %d. The range is from 0 to 200 V.\n",val); - else if(retval[0] == -2) - strcpy(mess, "Setting high voltage failed. Serial/i2c communication failed.\n"); - else if(retval[0] == -3) - strcpy(mess, "Getting high voltage failed. Serial/i2c communication failed.\n"); - cprintf(RED, "Warning: %s", mess); - } -#endif - } -#ifdef MYTHEN3D - else if ((ind >= V_POWER_A && ind <= V_POWER_CHIP) || ind == V_LIMIT) { - printf("Setting a power %d to %d\n",ind, val); - - if (!mV) { - ret = FAIL; - strcpy(mess, "Power of index %d should be set in mV instead of DACu", idac); - cprintf(RED, "Warning: %s", mess); - val = -1; - } - - int lim = getVLimit(); - if (ind != V_LIMIT && lim != -1 && val > lim) { - ret = FAIL; - strcpy(mess, "Power of index %d is %d, should be less than %dmV\n", idac, val, lim); - cprintf(RED, "Warning: %s", mess); - val = -1; - } - - retval[1] = retval[0] = setPower(idac,val); - if (val >= 0 && retval[1] != val) { - ret = FAIL; - sprintf(mess,"Setting power %d failed: wrote %d but read %d\n", idac, val, retval[1]); - cprintf(RED, "Warning: %s", mess); - } - } -#endif - //dac - else{ -#ifdef MYTHEN3D - if( mV && val > MAX_DACVOLTVAL) { - ret = FAIL; - strcpy(mess, "Dac of index %d should be less than %dmV\n", idac, val, MAX_DACVOLTVAL); - cprintf(RED, "Warning: %s", mess); - val = -1; - } - else if( !mV && val >= MAX_DACVAL) { - ret = FAIL; - strcpy(mess, "Dac of index %d should be less than %d (dac value)\n", idac, val, MAX_DACVAL); - cprintf(RED, "Warning: %s", mess); - val = -1; - } - - if (val >= 0) { - // conver to mV - int v = val; - if (!mV) - v = dacToVoltage(val); - - //checkvlimit compliant - int lim = getVLimit(); - if (lim!= -1 && v > lim) { - ret = FAIL; - strcpy(mess, "Dac of index %d should be less than %dmV (%d dac value)\n", idac, lim, voltageToDac(lim)); - cprintf(RED, "Warning: %s", mess); - val = -1; - } - } -#endif - setDAC(idac,val,imod,mV,retval); -#ifdef EIGERD - if(val != -1) { - //changing dac changes settings to undefined - switch(idac){ - case VCMP_LL: - case VCMP_LR: - case VCMP_RL: - case VCMP_RR: - case VRF: - case VCP: - setSettings(UNDEFINED,-1); - cprintf(RED,"Settings has been changed to undefined (changed specific dacs)\n"); - break; - default: - break; - } - } -#endif - //check - if (ret == OK) { - if(mV) - temp = retval[1]; - else - temp = retval[0]; - if ((abs(temp-val)<=5) || val==-1) { - ret = OK; - } else { - ret = FAIL; - sprintf(mess,"Setting dac %d of module %d: wrote %d but read %d\n", idac, imod, val, temp); - cprintf(RED, "Warning: %s", mess); - } - } - } - } - } -#endif -#ifdef VERBOSE - printf("DAC set to %d in dac units and %d mV\n", retval[0],retval[1]); -#endif - - if(ret == OK && differentClients) - ret=FORCE_UPDATE; - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - - - -int get_adc(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int arg[2]={-1,-1}; - int retval=-1; - enum dacIndex ind=0; - int imod=-1; - sprintf(mess,"get ADC failed\n"); - -#ifdef MYTHEN3D - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Get ADC) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - ind=arg[0]; - imod=arg[1]; - -#ifdef MYTHEND -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (imod>=getTotalNumberOfModules() || imod<0) { - ret = FAIL; - sprintf(mess,"Module number %d out of range\n",imod); - cprintf(RED, "Warning: %s", mess); - } -#endif -#endif - - enum ADCINDEX iadc=0; - switch (ind) { -#ifdef EIGERD - case TEMPERATURE_FPGAEXT: - iadc = TEMP_FPGAEXT; - break; - case TEMPERATURE_10GE: - iadc = TEMP_10GE; - break; - case TEMPERATURE_DCDC: - iadc = TEMP_DCDC; - break; - case TEMPERATURE_SODL: - iadc = TEMP_SODL; - break; - case TEMPERATURE_SODR: - iadc = TEMP_SODR; - break; - case TEMPERATURE_FPGA: - iadc = TEMP_FPGA; - break; - case TEMPERATURE_FPGA2: - iadc = TEMP_FPGAFEBL; - break; - case TEMPERATURE_FPGA3: - iadc = TEMP_FPGAFEBR; - break; -#endif -#if defined(GOTTHARD) || defined(JUNGFRAUD) - case TEMPERATURE_FPGA: - iadc = TEMP_FPGA; - break; - case TEMPERATURE_ADC: - iadc = TEMP_ADC; - break; -#endif - default: - ret = FAIL; - sprintf(mess,"Dac Index (%d) is not implemented for this detector\n",(int)ind); - cprintf(RED, "Warning: %s", mess); - break; - } - -#ifdef VERBOSE - printf("Getting ADC %d of module %d\n", iadc, imod); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) - retval=getADC(iadc,imod); -#endif -#ifdef VERBOSE - printf("ADC is %f\n", retval); -#endif -#endif - - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - - -int write_register(int file_des) { - int ret=OK,ret1=OK; - int n=0; - uint32_t retval=-1; - sprintf(mess,"write to register failed\n"); - - // receive arguments - int arg[2]={-1,-1}; - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - int addr=arg[0]; - uint32_t val=arg[1]; - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { -#ifdef VERBOSE - printf("writing to register 0x%x data 0x%x\n", addr, val); -#endif - retval=writeRegister(addr,val); - if (retval!=val) { - ret = FAIL; - sprintf(mess,"Writing to register 0x%x failed: wrote 0x%x but read 0x%x\n", addr, val, retval); - cprintf(RED, "Warning: %s", mess); - } - } -#endif -#ifdef VERBOSE - printf("Data set to 0x%x\n", retval); -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; - -} - - - - - -int read_register(int file_des) { - int ret=OK,ret1=OK; - int n=0; - uint32_t retval=-1; - sprintf(mess,"read register failed\n"); - - // receive arguments - int arg=0; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - int addr=arg; - - // execute action -#ifdef VERBOSE - printf("reading register 0x%x\n", addr); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=readRegister(addr); -#endif -#ifdef VERBOSE - printf("Returned value 0x%x\n", retval); -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - -int write_memory(int file_des) { - int ret=FAIL,ret1=FAIL; - int n=0; - sprintf(mess,"Function (Write Memory) is not implemented for this detector\n"); - cprintf(RED, "Error: %s", mess); - - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - - n = sendData(file_des,&ret1,sizeof(ret),INT32); - n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); - - // return ok / fail - return ret; -} - - -int read_memory(int file_des) { - int ret=FAIL,ret1=FAIL; - int n=0; - sprintf(mess,"Function (Read Memory) is not implemented for this detector\n"); - cprintf(RED, "Error: %s", mess); - - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - - n = sendData(file_des,&ret1,sizeof(ret),INT32); - n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); - - // return ok / fail - return ret; -} - - - -int set_channel(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"set channel failed\n"); - -#ifndef MYTHEND - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Set Channel) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - sls_detector_channel myChan; - n=receiveChannel(file_des, &myChan); - if (n < 0) return printSocketReadError(); - - // execute action -#ifdef VERBOSE - printf("Setting channel\n"); - printf("channel number is %d, chip number is %d, module number is %d, register is %lld\n", myChan.chan,myChan.chip, myChan.module, myChan.reg); -#endif - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else if (myChan.chan>=getNumberOfChannelsPerChip()) { - ret = FAIL; - sprintf(mess,"channel number %d too large!\n",myChan.chan); - cprintf(RED, "Warning: %s", mess); - } - else if (myChan.chip>=getNumberOfChipsPerModule()) { - ret = FAIL; - sprintf(mess,"chip number %d too large!\n",myChan.chip); - cprintf(RED, "Warning: %s", mess); - } - else if (myChan.module>=getTotalNumberOfModules()) { - ret = FAIL; - sprintf(mess,"module number %d too large!\n",myChan.module); - cprintf(RED, "Warning: %s", mess); - } - else - retval=setChannel(myChan); -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - -int get_channel(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sls_detector_channel retval; - sprintf(mess,"get channel failed\n"); - -#ifndef MYTHEND - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Get Channel) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int arg[3]={-1,-1,-1}; - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - int ichan=arg[0]; - int ichip=arg[1]; - int imod=arg[2]; -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (ichan>=getNumberOfChannelsPerChip()) { - ret=FAIL; - sprintf(mess, "channel number %d too large!\n",myChan.chan); - cprintf(RED, "Warning: %s", mess); - } else - retval.chan=ichan; - if (ichip>=getNumberOfChipsPerModule()) { - ret=FAIL; - sprintf(mess, "chip number %d too large!\n",myChan.chip); - cprintf(RED, "Warning: %s", mess); - } else - retval.chip=ichip; - - if (imod>=getTotalNumberOfModules()) { - ret=FAIL; - sprintf(mess, "module number %d too large!\n",myChan.module); - cprintf(RED, "Warning: %s", mess); - } else { - retval.module=imod; - ret=getChannel(&retval); -#ifdef VERBOSE - printf("Returning channel %d %d %d, 0x%llx\n", retval.chan, retval.chip, retval.mod, (retval.reg)); -#endif - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - ret=sendChannel(file_des, &retval); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - -int set_all_channels(int file_des) { - int ret=FAIL,ret1=FAIL; - int n=0; - sprintf(mess,"Function (Set All Channels) is not implemented for this detector\n"); - cprintf(RED, "Error: %s", mess); - - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - - n = sendData(file_des,&ret1,sizeof(ret),INT32); - n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); - - // return ok / fail - return ret; -} - - - - - -int set_chip(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"set chip failed\n"); - -#ifndef MYTHEND - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Set Chip) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - sls_detector_chip myChip; - -#ifdef SLS_DETECTOR_FUNCTION_LIST - myChip.nchan=getNumberOfChannelsPerChip(); - int *ch(int*)malloc((myChip.nchan)*sizeof(int)); - myChip.chanregs=ch; - - // receive arguments - n=receiveChip(file_des, &myChip); -#ifdef VERBOSE - printf("Chip received\n"); -#endif - if(n < 0) return FAIL; - - // execute action - if (differentClients==1 && lockStatus==1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else{ -#ifdef VERBOSE - printf("Setting chip\n"); - printf("chip number is %d, module number is %d, register is %d, nchan %d\n",myChip.chip, myChip.module, myChip.reg, myChip.nchan); -#endif - if (myChip.chip>=getNumberOfChipsPerModule()) { - ret = FAIL; - sprintf(mess,"chip number %d too large!\n",myChan.chip); - cprintf(RED, "Warning: %s", mess); - } - else if (myChip.module>=getTotalNumberOfModules()) { - ret = FAIL; - sprintf(mess,"module number %d too large!\n",myChan.module); - cprintf(RED, "Warning: %s", mess); - } - else - retval=setChip(myChip); - } - free(ch); -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - -int get_chip(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sls_detector_chip retval; - sprintf(mess,"get chip failed\n"); - -#ifndef MYTHEND - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Get Chip) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int arg[2]={-1,-1}; - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - -#ifdef SLS_DETECTOR_FUNCTION_LIST - int ichip=arg[0]; - int imod=arg[1]; - - // execute action - if (ichip>=getNumberOfChipsPerModule()) { - ret = FAIL; - sprintf(mess,"channel number %d too large!\n",myChan.chan); - cprintf(RED, "Warning: %s", mess); - } else - retval.chip=ichip; - - if (imod>=getTotalNumberOfModules()) { - ret = FAIL; - sprintf(mess,"module number %d too large!\n",imod); - cprintf(RED, "Warning: %s", mess); - } else - retval.module=imod; - - if (ret==OK) - ret=getChip(&retval); -#endif -#ifdef VERBOSE - printf("Returning chip %d %d\n", ichip, imod); -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - ret=sendChip(file_des, &retval); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - -int set_all_chips(int file_des) { - int ret=FAIL,ret1=FAIL; - int n=0; - sprintf(mess,"Function (Set All Chips) is not implemented for this detector\n"); - cprintf(RED, "Error: %s", mess); - - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - - n = sendData(file_des,&ret1,sizeof(ret),INT32); - n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); - - // return ok / fail - return ret; -} - - - - - -int set_module(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sls_detector_module myModule; - int retval=-1; -#ifdef EIGERD - int myIODelay=-1; - int myTau=-1; - int myEV=-1; -#endif - sprintf(mess,"set module failed\n"); - - -#ifdef MYTHEN3D - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Set Module) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - -#ifdef SLS_DETECTOR_FUNCTION_LIST - int *myDac=NULL; - int *myAdc=NULL; - int *myChip = NULL; - int *myChan = NULL; - - myDac=(int*)malloc(getNumberOfDACsPerModule()*sizeof(int)); - if (getNumberOfDACsPerModule() > 0 && myDac == NULL) { - ret = FAIL; - sprintf(mess,"could not allocate dacs\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - myModule.dacs=myDac; - myAdc=(int*)malloc(getNumberOfADCsPerModule()*sizeof(int)); - if (getNumberOfADCsPerModule() > 0 && myAdc == NULL) { - ret = FAIL; - sprintf(mess,"could not allocate adcs\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - myModule.adcs=myAdc; - //no chips and chans allocated for jungfrau, too much memory -#ifdef JUNGFRAUD - myModule.chipregs=NULL; - myModule.chanregs=NULL; -#else - myChip=(int*)malloc(getNumberOfChipsPerModule()*sizeof(int)); - if (getNumberOfChipsPerModule() > 0 && myChip == NULL) { - ret = FAIL; - sprintf(mess,"could not allocate chips\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - myModule.chipregs=myChip; - myChan=(int*)malloc(getNumberOfChannelsPerModule()*sizeof(int)); - if (getNumberOfChannelsPerModule() > 0 && myChan == NULL) { - ret = FAIL; - sprintf(mess,"could not allocate chans\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - myModule.chanregs=myChan; -#endif - myModule.nchip=getNumberOfChipsPerModule(); - myModule.nchan=getNumberOfChannelsPerModule(); - myModule.ndac=getNumberOfDACsPerModule(); - myModule.nadc=getNumberOfADCsPerModule(); - - - // receive arguments -#ifdef VERBOSE - printf("Setting module\n"); -#endif - n=receiveModuleGeneral(file_des, &myModule, -#ifdef JUNGFRAUD - 0 //0 is to receive partially (without trimbits etc.) -#else - 1 -#endif - ); - if (n<0) return FAIL; -#ifdef VERBOSE - printf("module number is %d,register is %d, nchan %d, nchip %d, ndac %d, nadc %d, gain %f, offset %f\n", - myModule.module, myModule.reg, myModule.nchan, myModule.nchip, myModule.ndac, myModule.nadc, myModule.gain,myModule.offset); -#endif -#ifdef EIGERD - n = receiveData(file_des,&myIODelay,sizeof(myIODelay),INT32); - if (n<0) return FAIL; - n = receiveData(file_des,&myTau,sizeof(myTau),INT32); - if (n<0) return FAIL; - n = receiveData(file_des,&myEV,sizeof(myEV),INT32); - if (n<0) return FAIL; -#ifdef VERBOSE - printf("IO Delay:%d\n",myIODelay); - printf("Tau:%d\n",myTau); - printf("eV:%d\n",myEV); -#endif -#endif -#ifndef JUNGFRAUD - } - } -#endif - } - } - - //check settings index - if (ret==OK) { -#ifdef MYTHEND - if (myModule.module>=getNModBoard()) { - ret = FAIL; - sprintf(mess,"Module Number to Set Module (%d) is too large\n", myModule.module); - cprintf(RED, "Warning: %s", mess); - } - if (myModule.module<0) - myModule.module=ALLMOD; -#endif -#if defined(JUNGFRAUD) || defined(EIGERD) - switch(myModule.reg){ - case GET_SETTINGS: - case UNINITIALIZED: -#ifdef EIGERD - case STANDARD: - case HIGHGAIN: - case LOWGAIN: - case VERYHIGHGAIN: - case VERYLOWGAIN: -#elif JUNGFRAUD - case DYNAMICGAIN: - case DYNAMICHG0: - case FIXGAIN1: - case FIXGAIN2: - case FORCESWITCHG1: - case FORCESWITCHG2: -#endif - break; - default: - ret = FAIL; - sprintf(mess,"Setting (%d) is not implemented for this detector\n", myModule.reg); - cprintf(RED, "Warning: %s", mess); - break; - } - } -#endif - - - // execute action - if (ret==OK) { - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef EIGERD - //set dacs, trimbits and iodelay - ret=setModule(myModule, myIODelay); - //set threshhold - if (myEV >= 0) - setThresholdEnergy(myEV,-1); - else { - //changes settings to undefined (loading a random trim file) - setSettings(UNDEFINED,-1); - cprintf(RED,"Settings has been changed to undefined (random trim file)\n"); - } - //rate correction - //switch off rate correction: no value read from load calib/load settings) - if(myTau == -1){ - if(getRateCorrectionEnable()){ - setRateCorrection(0); - ret = FAIL; - strcat(mess,"Cannot set Rate correction. No default tau provided. Deactivating Rate Correction\n"); - cprintf(RED, "Warning: %s", mess); - } - } - //normal tau value (only if enabled) - else{ - setDefaultSettingsTau_in_nsec(myTau); - if (getRateCorrectionEnable()){ - int64_t retvalTau = setRateCorrection(myTau); - if(myTau != retvalTau){ - cprintf(RED,"%s",mess); - ret=FAIL; - } - } - } - retval = getSettings(); -#else - retval=setModule(myModule); - if (retval != myModule.reg) - ret = FAIL; -#endif - if(myChip != NULL) free(myChip); - if(myChan != NULL) free(myChan); - if(myDac != NULL) free(myDac); - if(myAdc != NULL) free(myAdc); - } - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - - - - - -int get_module(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int arg=-1; - int imod=-1; - sls_detector_module myModule; - sprintf(mess,"get module failed\n"); - -#ifdef MYTHEN3D - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Get Module) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - imod=arg; - - // execute action -#ifdef SLS_DETECTOR_FUNCTION_LIST - int *myDac=NULL; - int *myAdc=NULL; - int *myChip = NULL; - int *myChan = NULL; - - if (imod<0 || imod>getTotalNumberOfModules()) { - ret = FAIL; - sprintf(mess,"Module Index (%d) is out of range\n", imod); - cprintf(RED, "Warning: %s", mess); - } - else { - myDac=(int*)malloc(getNumberOfDACsPerModule()*sizeof(int)); - if (getNumberOfDACsPerModule() > 0 && myDac == NULL) { - ret = FAIL; - sprintf(mess,"could not allocate dacs\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - myModule.dacs=myDac; - myAdc=(int*)malloc(getNumberOfADCsPerModule()*sizeof(int)); - if (getNumberOfADCsPerModule() > 0 && myAdc == NULL) { - ret = FAIL; - sprintf(mess,"could not allocate adcs\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - myModule.adcs=myAdc; - //no chips and chans allocated for jungfrau, too much memory -#ifdef JUNGFRAUD - myModule.chipregs=NULL; - myModule.chanregs=NULL; -#else - myChip=(int*)malloc(getNumberOfChipsPerModule()*sizeof(int)); - if (getNumberOfChipsPerModule() > 0 && myChip == NULL) { - ret = FAIL; - sprintf(mess,"could not allocate chips\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - myModule.chipregs=myChip; - myChan=(int*)malloc(getNumberOfChannelsPerModule()*sizeof(int)); - if (getNumberOfChannelsPerModule() > 0 && myChan == NULL) { - ret = FAIL; - sprintf(mess,"could not allocate chans\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - myModule.chanregs=myChan; -#endif - myModule.nchip=getNumberOfChipsPerModule(); - myModule.nchan=getNumberOfChannelsPerModule(); - myModule.ndac=getNumberOfDACsPerModule(); - myModule.nadc=getNumberOfADCsPerModule(); - myModule.module=imod; - getModule(&myModule); -#ifdef VERBOSE - printf("Returning module %d of register %x\n", imod, myModule.reg); -#endif -#ifndef JUNGFRAUD - } - } -#endif - } - } - } -#endif -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - ret=sendModuleGeneral(file_des, &myModule, -#ifdef JUNGFRAUD - 0 //0 is to receive partially (without trimbits etc.) -#else - 1 -#endif - ); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - -#ifdef SLS_DETECTOR_FUNCTION_LIST - if(myChip != NULL) free(myChip); - if(myChan != NULL) free(myChan); - if(myDac != NULL) free(myDac); - if(myAdc != NULL) free(myAdc); -#endif - - // return ok / fail - return ret; - -} - - - -int set_all_modules(int file_des) { - int ret=FAIL,ret1=FAIL; - int n=0; - sprintf(mess,"Function (Set All Modules) is not implemented for this detector\n"); - cprintf(RED, "Error: %s", mess); - - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - - n = sendData(file_des,&ret1,sizeof(ret),INT32); - n = sendData(file_des,mess,MAX_STR_LENGTH,OTHER); - - // return ok / fail - return ret; -} - - - - -int set_settings(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int arg[2]={-1,-1}; - int retval=-1; - int imod=-1; - enum detectorSettings isett=-1; - sprintf(mess,"set settings failed\n"); - -#ifdef MYTHEN3D - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Set Settings) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - isett=arg[0]; - imod=arg[1]; - - // execute action - if (differentClients && lockStatus && isett!=GET_SETTINGS) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - -#ifdef MYTHEND - if ( (ret != FAIL) && (imod>=getTotalNumberOfModules())) { - ret = FAIL; - sprintf(mess,"Module number %d out of range\n",imod); - cprintf(RED, "Warning: %s", mess); - } -#endif - switch(isett) { - case GET_SETTINGS: - case UNINITIALIZED: -#ifdef JUNGFRAUD - case DYNAMICGAIN: - case DYNAMICHG0: - case FIXGAIN1: - case FIXGAIN2: - case FORCESWITCHG1: - case FORCESWITCHG2: - break; - default: - ret = FAIL; - sprintf(mess,"Setting (%d) is not implemented for this detector.\n" - "Options are dynamicgain, dynamichg0, fixgain1, fixgain2, " - "forceswitchg1 and forceswitchg2.\n", isett); - cprintf(RED, "Warning: %s", mess); - break; -// other detectors -// #elif GOTTHARDD, MOENCHD, PROPIXD -#else - break; - default: - ret = FAIL; -#ifdef EIGERD - sprintf(mess,"Cannot set settings via SET_SETTINGS, use SET_MODULE\n"); -#else - sprintf(mess,"Setting (%d) is not implemented for this detector\n", isett); -#endif - cprintf(RED, "Warning: %s", mess); - break; -#endif - } - - if (ret != FAIL) { -#ifdef VERBOSE - printf("Changing settings of module %d to %d\n", imod, isett); -#endif - retval=setSettings(isett, imod); -#ifdef VERBOSE - printf("Settings changed to %d\n", isett); -#endif - if (retval == isett || isett < 0) { - ret=OK; - } else { - ret = FAIL; - sprintf(mess,"Changing settings of module %d: wrote %d but read %d\n", imod, isett, retval); - cprintf(RED, "Warning: %s", mess); - } - } - // set to default dacs, -//# also for #elif GOTTHARDD, MOENCHD, PROPIXD -#ifdef JUNGFRAUD - if (ret == OK && isett >= 0) { - ret = setDefaultDacs(); - if (ret == FAIL) { - strcpy(mess,"Could change settings, but could not set to default dacs\n"); - cprintf(RED, "Warning: %s", mess); - } - } -#endif -#endif -#endif - - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - - -int get_threshold_energy(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"get threshold energy failed\n"); - -#if !defined(MYTHEND) && !defined(EIGERD) - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Get Threshold Energy) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int imod=-1; - n = receiveData(file_des,&imod,sizeof(imod),INT32); - if (n < 0) return printSocketReadError(); - - // execute action -#ifdef VERBOSE - printf("Getting threshold energy of module %d\n", imod); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (imod>=getTotalNumberOfModules()) { - ret=FAIL; - sprintf(mess,"Module number %d out of range\n",imod); - } - else { - retval=getThresholdEnergy(imod); -#ifdef VERBOSE - printf("Threshold is %d eV\n", retval); -#endif - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - -int set_threshold_energy(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"set thhreshold energy failed\n"); - -#ifndef MYTHEND - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; -#ifdef EIGERD - sprintf(mess,"Function (Set Threshold Energy) is only implemented via Set Settings for this detector\n"); -#else - sprintf(mess,"Function (Set Threshold Energy) is not implemented for this detector\n"); -#endif - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int arg[3]={-1,-1,-1}; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - int ethr=arg[0]; - int imod=arg[1]; - enum detectorSettings isett=arg[2]; - if (differentClients && lockStatus) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else if (imod>=getTotalNumberOfModules()) { - ret=FAIL; - sprintf(mess,"Module number %d out of range\n",imod); - } - else { - printf("Setting threshold energy of module %d to %d eV with settings %d\n", imod, ethr, isett); - retval=setThresholdEnergy(ethr, imod); -#ifdef VERBOSE - printf("Threshold set to %d eV\n", retval); -#endif - if (retval!=ethr) { - ret=FAIL; - sprintf(mess,"Setting threshold of module %d: wrote %d but read %d\n", imod, ethr, retval); - cprintf(RED, "Warning: %s", mess); - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - - -int start_acquisition(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"start acquisition failed\n"); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - printf("Starting acquisition\n"); - ret=startStateMachine(); - if (ret==FAIL) - cprintf(RED, "Warning: %s", mess); - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - -int stop_acquisition(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"stop acquisition failed\n"); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - printf("Stopping acquisition\n"); - ret=stopStateMachine(); - if (ret==FAIL) - cprintf(RED, "Warning: %s", mess); - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - - -int start_readout(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"start readout failed\n"); - -#ifdef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Start Readout) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); -#else - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - printf("Starting readout\n"); - ret=startReadOut(); - if (ret==FAIL) - cprintf(RED, "Warning: %s", mess); - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - - - -int get_run_status(int file_des) { - int ret=OK,ret1=OK; - enum runStatus s=ERROR; - - // execute action -#ifdef VERBOSE - printf("Getting status\n"); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - s= getRunStatus(); -#endif - if (differentClients) - ret=FORCE_UPDATE; - - // send ok / fail - sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - sendData(file_des,&s,sizeof(s),INT32); - - // return ok / fail - return ret; -} - - - - - -int start_and_read_all(int file_des) { - int dataret1=FAIL, dataret=FAIL; -#ifdef VERBOSE - printf("Starting and reading all frames\n"); -#endif - - // execute action - if (differentClients && lockStatus) { - dataret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - // ret could be swapped during sendData - dataret1 = dataret; - // send fail - sendData(file_des,&dataret1,sizeof(dataret),INT32); - // send return argument - sendData(file_des,mess,sizeof(mess),OTHER); - // return fail - return dataret; - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - startStateMachine(); - read_all(file_des); -#endif - return OK; -} - - - - -int read_frame(int file_des) { - int dataret1=FAIL, dataret=FAIL; - int n=0; - sprintf(mess, "read frame failed\n"); - - // execute action - if (differentClients && lockStatus) { - dataret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - // ret could be swapped during sendData - dataret1 = dataret; - // send fail - sendData(file_des,&dataret1,sizeof(dataret),INT32); - // send return argument - sendData(file_des,mess,sizeof(mess),OTHER); - // return fail - return dataret; - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - readFrame(&dataret, mess); -#endif - if(dataret == FAIL) - cprintf(RED,"%s\n",mess); - else - cprintf(GREEN,"%s",mess); - - if (differentClients) - dataret=FORCE_UPDATE; - - //dataret could be swapped during sendData - dataret1 = dataret; - // send finished / fail - n=sendData(file_des,&dataret1,sizeof(dataret1),INT32); - if (n<0) return FAIL; // if called from read_all, should fail to stop talking to a closed client socket - // send return argument - n=sendData(file_des,mess,sizeof(mess),OTHER); - if (n<0) return FAIL; // if called from read_all, should fail to stop talking to a closed client socket - // return finished / fail - return dataret; -} - - - - -int read_all(int file_des) { -#ifdef SLS_DETECTOR_FUNCTION_LIST - while(read_frame(file_des)==OK) { -#ifdef VERBOSE - printf("frame read\n"); -#endif - ; - } -#endif -#ifdef VERBOSE - printf("Frames finished or failed\n"); -#endif - return OK; -} - - - - -int set_timer(int file_des) { - int ret=OK,ret1=OK; - int n=0; - enum timerIndex ind=0; - int64_t tns=-1; - int64_t retval=-1; - sprintf(mess,"set timer failed\n"); - - // receive arguments - n = receiveData(file_des,&ind,sizeof(ind),INT32); - if (n < 0) return printSocketReadError(); - - n = receiveData(file_des,&tns,sizeof(tns),INT64); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && tns!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { -#ifdef VERBOSE - printf("setting timer %d to %lld ns\n",ind,tns); -#endif -#ifdef EIGERD - int64_t subexptime = 0; -#endif - switch(ind) { -#ifdef JUNGFRAUD - case STORAGE_CELL_NUMBER: - if (tns > MAX_STORAGE_CELL_VAL) { - ret=FAIL; - strcpy(mess,"Max Storage cell number should not exceed 15\n"); - cprintf(RED, "Warning: %s", mess); - break; - } -#endif -#ifdef EIGERD - case SUBFRAME_ACQUISITION_TIME: - if (tns > ((int64_t)MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS*10) ){ - ret=FAIL; - strcpy(mess,"Sub Frame exposure time should not exceed 5.368 seconds\n"); - cprintf(RED, "Warning: %s", mess); - break; - } - retval = setTimer(ind,tns); - break; - case SUBFRAME_DEADTIME: - subexptime = setTimer(SUBFRAME_ACQUISITION_TIME, -1); - if ((tns + subexptime) > ((int64_t)MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS*10) ){ - ret=FAIL; - sprintf(mess,"Sub Frame Period should not exceed 5.368 seconds. " - "So sub frame dead time should not exceed %lfu seconds (subexptime = %lf seconds)\n", - ((((int64_t)MAX_SUBFRAME_EXPOSURE_VAL_IN_10NS*10) - subexptime)/1E9), (subexptime/1E9)); - cprintf(RED, "Warning: %s", mess); - break; - } - retval = setTimer(ind,tns); - break; -#endif -#ifdef MYTHEN - case PROBES_NUMBER: - case GATES_NUMBER: - case DELAY_AFTER_TRIGGER: -#elif JUNGFRAUD - case DELAY_AFTER_TRIGGER: -#elif MYTHEN3D - case DELAY_AFTER_TRIGGER: - case GATES_NUMBER: - case PROBES_NUMBER: - case SAMPLES_JCTB: -#endif - case FRAME_NUMBER: - case ACQUISITION_TIME: - case FRAME_PERIOD: - case CYCLES_NUMBER: - retval = setTimer(ind,tns); - break; - default: - ret = FAIL; - sprintf(mess,"Timer Index (%d) is not implemented for this detector\n", (int) ind); - cprintf(RED, "%s", mess); - break; - } - - -#if defined(MYTHEND) || defined(GOTTHARD) - if (ret == OK && ind==FRAME_NUMBER) { - ret=allocateRAM(); - if (ret!=OK) { - ret = FAIL; - sprintf(mess,"Could not allocate RAM for %lld frames\n", tns); - cprintf(RED, "%s", mess); - } - } -#endif - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT64); - - // return ok / fail - return ret; -} - - - - - - - - - -int get_time_left(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int64_t retval=-1; - sprintf(mess,"get timer left failed\n"); - - - // receive arguments - enum timerIndex ind=0; - n = receiveData(file_des,&ind,sizeof(ind),INT32); - if (n < 0) return printSocketReadError(); - -#ifdef VERBOSE - printf("getting time left on timer %d \n",ind); -#endif -#ifdef SLS_DETECTOR_FUNCTION_LIST - -#ifdef JUNGFRAUD - if (ind == DELAY_AFTER_TRIGGER) { - ret = FAIL; - sprintf(mess,"Timer Left Index (%d) is not implemented for this release.\n", (int)ind); - cprintf(RED, "%s", mess); - } else { -#endif - - switch(ind) { -#ifdef EIGERD - case MEASURED_PERIOD: - case MEASURED_SUBPERIOD: -#elif MYTHEND - case PROBES_NUMBER: -#elif JUNGFRAUD - case FRAMES_FROM_START: - case FRAMES_FROM_START_PG: -#elif MYTHEN3D - case GATES_NUMBER: - case PROBES_NUMBER: - case SAMPLES_JCTB: -#endif -#ifndef EIGERD -#ifndef JUNGFRAUD - case GATES_NUMBER: -#endif - case FRAME_NUMBER: - case ACQUISITION_TIME: - case FRAME_PERIOD: - case DELAY_AFTER_TRIGGER: - case CYCLES_NUMBER: - case PROGRESS: - case ACTUAL_TIME: - case MEASUREMENT_TIME: -#endif - retval=getTimeLeft(ind); - break; - default: - ret = FAIL; - sprintf(mess,"Timer Left Index (%d) is not implemented for this detector\n", (int)ind); - cprintf(RED, "%s", mess); - break; - } -#ifdef VERBOSE - printf("Time left on timer %d is %lld\n",ind, retval); -#endif - -#ifdef JUNGFRAUD - } // end of if (ind == DELAY_AFTER_TRIGGER) -#endif - -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT64); - - // return ok / fail - return ret; -} - - - - - - -int set_dynamic_range(int file_des) { - int ret=OK,ret1=OK; - int rateret=OK,rateret1=OK; - int n=0; - int dr=-1; - int retval=-1; - sprintf(mess,"set dynamic range failed\n"); - - // receive arguments - n = receiveData(file_des,&dr,sizeof(dr),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && dr>=0) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - switch(dr){ - case -1: - case 16: -#ifdef EIGERD - case 4: case 8: case 32: -#endif - break; - default: - ret = FAIL; - sprintf(mess,"Dynamic Range (%d) is not implemented for this detector\n", dr); - cprintf(RED, "Warning: %s", mess); - } - } - if(ret == OK){ -#ifdef EIGERD - int old_dr = setDynamicRange(-1); - retval=setDynamicRange(dr); - if (dr>=0 && retval!=dr) - ret=FAIL; - //look at rate correction only if dr change worked - if((ret==OK) && (dr!=32) && (dr!=16) && (dr!=-1) && (getRateCorrectionEnable())){ - setRateCorrection(0); - rateret = FAIL; - strcpy(mess,"Switching off Rate Correction. Must be in 32 or 16 bit mode\n"); - cprintf(RED,"%s",mess); - }else{ - //setting it if dr changed from 16 to 32 or vice versa with tau value as in rate table - if((dr!=-1) && (old_dr != dr) && getRateCorrectionEnable() && (dr == 16 || dr == 32)){ - setRateCorrection(-1); //tau_ns will not be -1 here - if(!getRateCorrectionEnable()){ - ret = FAIL; - strcpy(mess,"Deactivating Rate Correction. Could not set it.\n"); - cprintf(RED,"%s",mess); - } - } - } - -#else - retval = setDynamicRange(dr); -#endif - if (dr>=0) dataBytes=calculateDataBytes(); - } -#endif - if ((ret == OK) && dr>=0 && retval!=dr) { - ret = FAIL; - cprintf(RED,"%s",mess); - } - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - - //rate correction ret - // ret could be swapped during sendData - rateret1 = rateret; - // send ok / fail - n = sendData(file_des,&rateret1,sizeof(rateret1),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - - - -int set_readout_flags(int file_des) { - int ret=OK,ret1=OK; - int n=0; - enum readOutFlags retval=-1; - sprintf(mess,"set readout flags failed\n"); - -#if !defined(MYTHEND) && !defined(EIGERD) - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function (Set Read Out Flags) is not implemented for this detector\n"); - cprintf(RED, "%s",mess); -#else - - // receive arguments - enum readOutFlags arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && arg!=GET_READOUT_FLAGS) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { -#ifdef VERBOSE - printf("setting readout flags to %d\n",arg); -#endif - switch(arg) { - case GET_READOUT_FLAGS: -#ifdef MYTHEND - case TOT_MODE: - case NORMAL_READOUT: - case STORE_IN_RAM: - case CONTINOUS_RO: -#elif EIGERD - case STORE_IN_RAM: - case CONTINOUS_RO: - case PARALLEL: - case NONPARALLEL: - case SAFE: - case SHOW_OVERFLOW: - case NOOVERFLOW: -#endif - retval=setReadOutFlags(arg); - break; - default: - ret = FAIL; - sprintf(mess,"Readout Flag Index (%d) is not implemented for this detector\n", (int)arg); - cprintf(RED, "Warning: %s", mess); - break; - } -#endif - if (ret==OK && ((retval == -1) || ((arg!=-1) && ((retval&arg)!=arg)))){ - ret = FAIL; - sprintf(mess,"Could not change readout flag: should be 0x%x but is 0x%x\n", arg, retval); - cprintf(RED, "Warning: %s", mess); - } - - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - } -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - - - -int set_roi(int file_des) { - int ret=OK,ret1=OK; - int n=0; - strcpy(mess,"set nroi failed\n"); - -#ifndef GOTTHARDD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function (Set ROI) is not implemented for this detector\n"); - cprintf(RED, "%s",mess); -#else - - ROI* retval=0; - int retvalsize=0,retvalsize1=0; - - // receive arguments - int nroi=-1; - ROI arg[MAX_ROIS]; - n = receiveData(file_des,&nroi,sizeof(nroi),INT32); - if (n < 0) return printSocketReadError(); - - { - int i; - if(nroi!=-1){ - for(i=0;i=0) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { -#ifdef VERBOSE - printf("setting speed variable %d to %d\n",arg,val); -#endif - switch (arg) { -#ifdef JUNGFRAUD - case ADC_PHASE: - retval = adcPhase(val); - if ((val != 100000) && (retval!=val) && (val>=0)) { - ret=FAIL; - sprintf(mess,"could not change set adc phase: should be %d but is %d \n", val, retval); - cprintf(RED, "Warning: %s", mess); - } - break; -#endif -#ifdef MYTHEND - case CLOCK_DIVIDER: - case WAIT_STATES: - case SET_SIGNAL_LENGTH: - case TOT_CLOCK_DIVIDER: - case TOT_DUTY_CYCLE: -#elif EIGERD - case CLOCK_DIVIDER: -#elif JUNGFRAUD - case CLOCK_DIVIDER: -#elif MYTHEN3D - case DBIT_CLOCK: - case DBIT_PHASE: -#endif - retval=setSpeed(arg, val); - if ((retval!=val) && (val>=0)) { - ret=FAIL; - sprintf(mess,"could not change speed variable %d: should be %d but is %d \n",arg, val, retval); - cprintf(RED, "Warning: %s", mess); - } - break; - default: - ret = FAIL; - sprintf(mess,"Speed Index (%d) is not implemented for this detector\n",(int) arg); - cprintf(RED, "Warning: %s", mess); - break; - } - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - - -int execute_trimming(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"execute trimming failed\n"); - -#ifndef MYTHEND - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Execute Trimming) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - int retval=-1; - - // receive arguments - enum trimMode mode=0; - int arg[3]={-1,-1,-1}; - n = receiveData(file_des,&mode,sizeof(mode),INT32); - if (n < 0) return printSocketReadError(); - - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - int imod, par1,par2; - imod=arg[0]; - par1=arg[1]; - par2=arg[2]; - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else if (imod>=getTotalNumberOfModules()) { - ret = FAIL; - sprintf(mess,"Module Number (%d) is out of range\n"); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef VERBOSE - printf("trimming module %d mode %d, parameters %d %d \n",imod,mode, par1, par2); -#endif - switch(mode) { - case NOISE_TRIMMING: - case BEAM_TRIMMING: - case IMPROVE_TRIMMING: - case FIXEDSETTINGS_TRIMMING: - retval=executeTrimming(mode, par1, par2, imod); - if ((ret!=OK) && (retval>0)) { - ret=FAIL; - sprintf(mess,"Could not trim %d channels\n", retval); - cprintf(RED, "Warning: %s", mess); - } - break; - default: - ret = FAIL; - sprintf(mess,"Trimming Mode (%d) is not implemented for this detector\n", (int) mode); - cprintf(RED, "Warning: %s", mess); - break; - } - - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - - -int exit_server(int file_des) { - int ret=FAIL; - sprintf(mess,"Closing Server\n"); - cprintf(BG_RED,"Error: %s",mess); - // send ok / fail - sendData(file_des,&ret,sizeof(ret),INT32); - // send return argument - sendData(file_des,mess,sizeof(mess),OTHER); - return GOODBYE; -} - - - - -int lock_server(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int lock=0; - sprintf(mess,"lock server failed\n"); - - // receive arguments - n = receiveData(file_des,&lock,sizeof(lock),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (lock>=0) { - if (lockStatus==0 || strcmp(lastClientIP,thisClientIP)==0 || strcmp(lastClientIP,"none")==0) { - lockStatus=lock; - strcpy(lastClientIP,thisClientIP); - } else { - ret = FAIL; - sprintf(mess,"Server already locked by %s\n", lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - } - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&lockStatus,sizeof(lockStatus),INT32); - - // return ok / fail - return ret; -} - - - - - -int get_last_client_ip(int file_des) { - int ret=OK,ret1=OK; - if (differentClients) - ret=FORCE_UPDATE; - // send ok / fail - sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - sendData(file_des,lastClientIP,sizeof(lastClientIP),OTHER); - // return ok / fail - return ret; -} - - - - -int set_port(int file_des) { - int ret=OK,ret1=OK; - int n=0; - enum portType p_type=0; - int p_number=-1; - sprintf(mess,"set port failed\n"); - - // receive arguments - n = receiveData(file_des,&p_type,sizeof(p_type),INT32); - if (n < 0) return printSocketReadError(); - - n = receiveData(file_des,&p_number,sizeof(p_number),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - int sd=-1; - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { - if (p_number<1024) { - ret = FAIL; - sprintf(mess,"Port Number (%d) too low\n", p_number); - cprintf(RED, "Warning: %s", mess); - } - printf("set port %d to %d\n",p_type, p_number); - sd=bindSocket(p_number); - if (sd<0) { - ret = FAIL; - sprintf(mess,"Could not bind port %d\n", p_number); - cprintf(RED, "Warning: %s", mess); - if (sd==-10) { - ret = FAIL; - sprintf(mess,"Port %d already set\n", p_number); - cprintf(RED, "Warning: %s", mess); - } - } - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - } - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n = sendData(file_des,mess,sizeof(mess),OTHER); - } else { - n = sendData(file_des,&p_number,sizeof(p_number),INT32); - closeConnection(file_des); - exitServer(sockfd); - sockfd=sd; - } - - // return ok / fail - return ret; -} - - - - -int update_client(int file_des) { - int ret=OK; - sendData(file_des,&ret,sizeof(ret),INT32); - return send_update(file_des); -} - - - - -int send_update(int file_des) { - int n=0; // if (n<0) should fail to stop talking to a closed client socket - int nm=0; - int64_t retval = 0; - enum detectorSettings t; - - n = sendData(file_des,lastClientIP,sizeof(lastClientIP),OTHER); - if (n < 0) return printSocketReadError(); - - -#ifdef SLS_DETECTOR_FUNCTION_LIST - nm=setNMod(GET_FLAG,X); -#endif - n = sendData(file_des,&nm,sizeof(nm),INT32); - if (n < 0) return printSocketReadError(); - - -#ifdef SLS_DETECTOR_FUNCTION_LIST - nm=setNMod(GET_FLAG,Y); -#endif - n = sendData(file_des,&nm,sizeof(nm),INT32); - if (n < 0) return printSocketReadError(); - - -#ifdef SLS_DETECTOR_FUNCTION_LIST - nm=setDynamicRange(GET_FLAG); -#endif - n = sendData(file_des,&nm,sizeof(nm),INT32); - if (n < 0) return printSocketReadError(); - - -#ifdef SLS_DETECTOR_FUNCTION_LIST - dataBytes=calculateDataBytes(); -#endif - n = sendData(file_des,&dataBytes,sizeof(dataBytes),INT32); - if (n < 0) return printSocketReadError(); - - -#ifdef SLS_DETECTOR_FUNCTION_LIST - t=setSettings(GET_SETTINGS, GET_FLAG); -#endif - n = sendData(file_des,&t,sizeof(t),INT32); - if (n < 0) return printSocketReadError(); - - -#if defined(MYTHEND) || defined(EIGERD) -#ifdef SLS_DETECTOR_FUNCTION_LIST - nm=getThresholdEnergy(GET_FLAG); -#endif - n = sendData(file_des,&nm,sizeof(nm),INT32); - if (n < 0) return printSocketReadError(); -#endif - - -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(FRAME_NUMBER,GET_FLAG); -#endif - n = sendData(file_des,&retval,sizeof(int64_t),INT64); - if (n < 0) return printSocketReadError(); - - -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(ACQUISITION_TIME,GET_FLAG); -#endif - n = sendData(file_des,&retval,sizeof(int64_t),INT64); - if (n < 0) return printSocketReadError(); - - -#ifdef EIGERD -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(SUBFRAME_ACQUISITION_TIME,GET_FLAG); -#endif - n = sendData(file_des,&retval,sizeof(int64_t),INT64); - if (n < 0) return printSocketReadError(); - -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(SUBFRAME_DEADTIME,GET_FLAG); -#endif - n = sendData(file_des,&retval,sizeof(int64_t),INT64); - if (n < 0) return printSocketReadError(); -#endif - - -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(FRAME_PERIOD,GET_FLAG); -#endif - n = sendData(file_des,&retval,sizeof(int64_t),INT64); - if (n < 0) return printSocketReadError(); - - -#ifndef EIGERD -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(DELAY_AFTER_TRIGGER,GET_FLAG); -#endif - n = sendData(file_des,&retval,sizeof(int64_t),INT64); - if (n < 0) return printSocketReadError(); -#endif - - -#if !defined(EIGERD) && !defined(JUNGFRAUD) -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(GATES_NUMBER,GET_FLAG); -#endif - n = sendData(file_des,&retval,sizeof(int64_t),INT64); - if (n < 0) return printSocketReadError(); -#endif - - -#ifdef MYTHEND -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(PROBES_NUMBER,GET_FLAG); -#endif - n = sendData(file_des,&retval,sizeof(int64_t),INT64); - if (n < 0) return printSocketReadError(); -#endif - - -#ifdef SLS_DETECTOR_FUNCTION_LIST - retval=setTimer(CYCLES_NUMBER,GET_FLAG); -#endif - n = sendData(file_des,&retval,sizeof(int64_t),INT64); - if (n < 0) return printSocketReadError(); - - - if (lockStatus==0) { - strcpy(lastClientIP,thisClientIP); - } - - return OK; -} - - - - - - -int configure_mac(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-100; - sprintf(mess,"configure mac failed\n"); - -#ifdef MYTHEND - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - strcpy(mess,"Function (Configure MAC) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - char arg[6][50]; - memset(arg,0,sizeof(arg)); - n = receiveData(file_des,arg,sizeof(arg),OTHER); -#if defined(JUNGFRAUD) || defined(EIGERD) - int pos[3]={0,0,0}; - n = receiveData(file_des,pos,sizeof(pos),INT32); -#endif - if (n < 0) return printSocketReadError(); - - uint32_t ipad; - uint64_t imacadd; - uint64_t idetectormacadd; - uint32_t udpport; - uint32_t udpport2; - uint32_t detipad; - sscanf(arg[0], "%x", &ipad); -#ifdef VIRTUAL - sscanf(arg[1], "%lx", &imacadd); -#else - sscanf(arg[1], "%llx", &imacadd); -#endif - sscanf(arg[2], "%x", &udpport); -#ifdef VIRTUAL - sscanf(arg[3], "%lx", &idetectormacadd); -#else - sscanf(arg[3], "%llx", &idetectormacadd); -#endif - sscanf(arg[4], "%x", &detipad); - sscanf(arg[5], "%x", &udpport2); - - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { -#ifdef VERBOSE - int i; - //#ifdef GOTTHARD - //printf("\ndigital_test_bit in server %d\t",digitalTestBit); - //#endif - printf("\nipadd %x\t",ipad); - printf("destination ip is %d.%d.%d.%d = 0x%x \n",(ipad>>24)&0xff,(ipad>>16)&0xff,(ipad>>8)&0xff,(ipad)&0xff,ipad); - printf("macad:%llx\n",imacadd); - for (i=0;i<6;i++) - printf("mac adress %d is 0x%x \n",6-i,(unsigned int)(((imacadd>>(8*i))&0xFF))); - printf("udp port:0x%x\n",udpport); - printf("detector macad:%llx\n",idetectormacadd); - for (i=0;i<6;i++) - printf("detector mac adress %d is 0x%x \n",6-i,(unsigned int)(((idetectormacadd>>(8*i))&0xFF))); - printf("detipad %x\n",detipad); - printf("udp port2:0x%x\n",udpport2); - printf("\n"); - printf("Configuring MAC of module %d at port %x\n", imod, udpport); - -#if defined(JUNGFRAUD) || defined(EIGERD) - printf("Position: [%d,%d,%d]\n", pos[0],pos[1],pos[2]); -#endif -#endif - if(getRunStatus() == RUNNING){ - ret = stopStateMachine(); - } - if(ret==FAIL) { - sprintf(mess,"Could not stop detector acquisition to configure mac\n"); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef EIGERD - // change mac to hardware mac, (for 1 gbe) change ip to hardware ip - if (idetectormacadd != getDetectorMAC()){ - printf("*************************************************\n"); - printf("WARNING: actual detector mac address %llx does not match " - "the one from client %llx\n", - (long long unsigned int)getDetectorMAC(), - (long long unsigned int)idetectormacadd); - idetectormacadd = getDetectorMAC(); - printf("WARNING: Matched detectormac to the hardware mac now\n"); - printf("*************************************************\n"); - } - - // always remember the ip sent from the client (could be for 10g(if not dhcp)) - if (detipad != getDetectorIP()) - dhcpipad = detipad; - - //only for 1Gbe - if(!enableTenGigabitEthernet(-1)){ - printf("*************************************************\n"); - printf("WARNING: Using DHCP IP for Configuring MAC\n"); - printf("*************************************************\n"); - detipad = getDetectorIP(); - } else - detipad = dhcpipad; -#endif - retval=configureMAC(ipad,imacadd,idetectormacadd,detipad,udpport,udpport2,0); //digitalTestBit); - if(retval==-1) { - ret = FAIL; - sprintf(mess,"Configure Mac failed\n"); - cprintf(RED, "Warning: %s", mess); - } - else { - printf("Configure MAC successful\n"); -#if defined(JUNGFRAUD) || defined(EIGERD) - ret = setDetectorPosition(pos); - if (ret == FAIL) { - sprintf(mess,"could not set detector position\n"); - cprintf(RED, "Warning: %s", mess); - } -#endif - } -#ifdef VERBOSE - printf("Configured MAC with retval %d\n", retval); -#endif - } - - } -#endif - if (differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else { - n += sendData(file_des,&retval,sizeof(retval),INT32); -#ifdef EIGERD - char arg[2][50]; - memset(arg,0,sizeof(arg)); - sprintf(arg[0],"%llx",(long long unsigned int)idetectormacadd); - sprintf(arg[1],"%x",detipad); - n += sendData(file_des,arg,sizeof(arg),OTHER); -#endif - } - // return ok / fail - return ret; -} - - - - - -int load_image(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"Loading image failed\n"); - -#ifndef GOTTHARDD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Load Image) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - enum imageType index=0; - char ImageVals[dataBytes]; - memset(ImageVals,0,dataBytes); - n = receiveData(file_des,&index,sizeof(index),INT32); - if (n < 0) return printSocketReadError(); - - n = receiveData(file_des,ImageVals,dataBytes,OTHER); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - switch (index) { - case DARK_IMAGE : -#ifdef VERBOSE - printf("Loading Dark image\n"); -#endif - case GAIN_IMAGE : -#ifdef VERBOSE - printf("Loading Gain image\n"); -#endif - retval=loadImage(index,ImageVals); - if (retval==-1) { - ret = FAIL; - cprintf(RED, "Warning: %s", mess); - } - break; - default: - ret = FAIL; - sprintf(mess,"Load Image Index (%d) is not implemented for this detector\n", (int)index); - cprintf(RED, "Warning: %s", mess); - break; - } - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - - -int set_master(int file_des) { - int ret=OK,ret1=OK; - int n=0; - enum masterFlags arg=GET_MASTER; - enum masterFlags retval=GET_MASTER; - sprintf(mess,"set master failed\n"); - - // receive arguments - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && ((int)arg!=(int)GET_MASTER)) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { -#ifdef VERBOSE - printf("setting master flags to %d\n",arg); -#endif - retval=setMaster(arg); - if (retval==GET_MASTER) - ret=FAIL; - - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - } -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - - - - -int set_synchronization(int file_des) { - int ret=OK,ret1=OK; - int n=0; - enum synchronizationMode arg=GET_SYNCHRONIZATION_MODE; - enum synchronizationMode retval=GET_SYNCHRONIZATION_MODE; - sprintf(mess,"synchronization mode failed\n"); - - // receive arguments - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && ((int)arg!=(int)GET_SYNCHRONIZATION_MODE)) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { -#ifdef VERBOSE - printf("setting master flags to %d\n",arg); -#endif - retval=setSynchronization(arg); - if (retval==GET_SYNCHRONIZATION_MODE) - ret=FAIL; - - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - } -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - - -int read_counter_block(int file_des) { - int ret=OK,ret1=OK; - int n=0; - char CounterVals[dataBytes]; - memset(CounterVals,0,dataBytes); - sprintf(mess,"Read counter block failed\n"); - -#ifndef GOTTHARDD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Read Counter Block) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int startACQ=-1; - n = receiveData(file_des,&startACQ,sizeof(startACQ),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - ret=readCounterBlock(startACQ,CounterVals); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); -#ifdef VERBOSE - int i; - for(i=0;i<6;i++) - printf("%d:%d\t",i,CounterVals[i]); -#endif - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,CounterVals,dataBytes,OTHER); - - // return ok / fail - return ret; -} - - - - - -int reset_counter_block(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"Reset counter block failed\n"); - -#ifndef GOTTHARDD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Reset Counter Block) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int startACQ=-1; - n = receiveData(file_des,&startACQ,sizeof(startACQ),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - ret=resetCounterBlock(startACQ); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - - -int calibrate_pedestal(int file_des){ - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"calibrate pedestal failed\n"); - - -#ifndef GOTTHARDD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Calibrate Pedestal) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int frames=-1; - n = receiveData(file_des,&frames,sizeof(frames),INT32); - if (n < 0) return printSocketReadError(); - - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - ret=calibratePedestal(frames); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); - } -#endif - if(ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - - - - - -int enable_ten_giga(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"Enabling/disabling 10GbE failed\n"); - - // execute action -#ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Enable 10 GbE) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && arg!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { -#ifdef VERBOSE - printf("Enabling/Disabling 10Gbe :%d \n",arg); -#endif - retval=enableTenGigabitEthernet(arg); - if((arg != -1) && (retval != arg)) { - ret=FAIL; - cprintf(RED, "Warning: %s", mess); - } - else if (differentClients) - ret=FORCE_UPDATE; - } -#endif -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - -int set_all_trimbits(int file_des){ - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"setting all trimbits failed\n"); - -#ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Set All Trimbits) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - - // execute action - if (differentClients && lockStatus && arg!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { -#ifdef VERBOSE - printf("setting all trimbits to %d\n",arg); -#endif - if(arg < -1){ - ret = FAIL; - strcpy(mess,"Cant set trimbits to this value\n"); - cprintf(RED, "Warning: %s", mess); - }else { - if(arg >= 0){ - ret = setAllTrimbits(arg); - //changes settings to undefined - setSettings(UNDEFINED,-1); - cprintf(RED,"Settings has been changed to undefined (change all trimbits)\n"); - } - retval = getAllTrimbits(); - if (arg!=-1 && arg!=retval) { - ret=FAIL; - sprintf(mess,"Could not set all trimbits: should be %d but is %d\n", arg, retval); - cprintf(RED, "Warning: %s", mess); - } - } - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - -int set_ctb_pattern(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"Could not set pattern\n"); - -#ifndef MYTHEN3D - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - - ret = FAIL; - sprintf(mess,"Function (Set CTB Pattern) is not implemented for this detector\n"); - cprintf(RED, "Error: %s", mess); - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - n += sendData(file_des,mess,sizeof(mess),OTHER); - - return ret; - -#else - - int retval=-1; - int mode = -1; - int addr = -1, level = -1, nl = -1, start = -1, stop = -1; - uint64_t word = -1,retval64 = -1, t = -1; - - n = receiveDataOnly(file_des, &mode, sizeof(mode)); - printf("pattern mode is %d\n",mode); - - switch (mode) { - - case 0: //sets word - n = receiveDataOnly(file_des,&addr,sizeof(addr)); - n = receiveDataOnly(file_des,&word,sizeof(word)); - ret=OK; - - printf("pattern addr is %d %llx\n",addr, word); - switch (addr) { - case -1: - retval64=writePatternIOControl(word); - break; - case -2: - retval64=writePatternClkControl(word); - break; - default: - retval64=writePatternWord(addr,word); - }; - - - //write word; - //@param addr address of the word, -1 is I/O control register, -2 is clk control register - //@param word 64bit word to be written, -1 gets - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval64,sizeof(retval64)); - break; - - case 1: //pattern loop - // printf("loop\n"); - n = receiveDataOnly(file_des,&level,sizeof(level)); - n = receiveDataOnly(file_des,&start,sizeof(start)); - n = receiveDataOnly(file_des,&stop,sizeof(stop)); - n = receiveDataOnly(file_des,&nl,sizeof(nl)); - - - - // printf("level %d start %x stop %x nl %d\n",level, start, stop, nl); - /** Sets the pattern or loop limits in the CTB - @param level -1 complete pattern, 0,1,2, loop level - @param start start address if >=0 - @param stop stop address if >=0 - @param n number of loops (if level >=0) - @returns OK/FAIL - */ - ret=setPatternLoop(level, &start, &stop, &nl); - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else { - n += sendDataOnly(file_des,&start,sizeof(start)); - n += sendDataOnly(file_des,&stop,sizeof(stop)); - n += sendDataOnly(file_des,&nl,sizeof(nl)); - } - break; - - - - case 2: //wait address - printf("wait\n"); - n = receiveDataOnly(file_des,&level,sizeof(level)); - n = receiveDataOnly(file_des,&addr,sizeof(addr)); - - - - /** Sets the wait address in the CTB - @param level 0,1,2, wait level - @param addr wait address, -1 gets - @returns actual value - */ - printf("wait addr %d %x\n",level, addr); - retval=setPatternWaitAddress(level,addr); - printf("ret: wait addr %d %x\n",level, retval); - ret=OK; - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else { - n += sendDataOnly(file_des,&retval,sizeof(retval)); - - } - - - break; - - - case 3: //wait time - printf("wait time\n"); - n = receiveDataOnly(file_des,&level,sizeof(level)); - n = receiveDataOnly(file_des,&t,sizeof(t)); - - - /** Sets the wait time in the CTB - @param level 0,1,2, wait level - @param t wait time, -1 gets - @returns actual value - */ - - ret=OK; - - retval64=setPatternWaitTime(level,t); - - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval64,sizeof(retval64)); - - break; - - - - case 4: - n = receiveDataOnly(file_des,pat,sizeof(pat)); - for (addr=0; addr<1024; addr++) - writePatternWord(addr,word); - ret=OK; - retval=0; - n = sendDataOnly(file_des,&ret,sizeof(ret)); - if (ret==FAIL) - n += sendDataOnly(file_des,mess,sizeof(mess)); - else - n += sendDataOnly(file_des,&retval64,sizeof(retval64)); - - break; - - - - default: - ret=FAIL; - printf(mess); - sprintf(mess,"%s - wrong mode %d\n",mess, mode); - n = sendDataOnly(file_des,&ret,sizeof(ret)); - n += sendDataOnly(file_des,mess,sizeof(mess)); - } - - - // return ok / fail - return ret; -#endif -} - - - -int write_adc_register(int file_des) { - int ret=OK, ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"write to adc register failed\n"); - -#ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Write ADC Register) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int arg[2]={-1,-1}; - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - int addr=arg[0]; - int val=arg[1]; - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } - else { -#ifdef VERBOSE - printf("writing to register 0x%x data 0x%x\n", addr, val); -#endif - setAdc(addr,val); -#ifdef VERBOSE - printf("Data set to 0x%x\n", retval); -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - } -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - -int set_counter_bit(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"set counter bit failed \n"); - -#ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - strcpy(mess,"Function (Set Counter Bit) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && arg!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { -#ifdef VERBOSE - printf("Getting/Setting/Resetting counter bit :%d \n",arg); -#endif - retval=setCounterBit(arg); - if((arg != -1) && (retval != arg)) { - ret=FAIL; - cprintf(RED, "Warning: %s", mess); - } - if (ret==OK && differentClients) - ret=FORCE_UPDATE; - } -#endif -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - -int pulse_pixel(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"pulse pixel failed\n"); - -#ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - strcpy(mess,"Function (Pulse Pixel) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int arg[3]={-1,-1,-1}; - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - ret=pulsePixel(arg[0],arg[1],arg[2]); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - -int pulse_pixel_and_move(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"pulse pixel and move failed\n"); - -#ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - strcpy(mess,"Function (Pulse Pixel and Move) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int arg[3]={-1,-1,-1}; - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - ret=pulsePixelNMove(arg[0],arg[1],arg[2]); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); - } -#endif - if(ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - - - -int pulse_chip(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"pulse chip failed\n"); - -#ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - strcpy(mess,"Function (Pulse Chip) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int arg = -1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - ret=pulseChip(arg); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); - } -#endif - if(ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - - -int set_rate_correct(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"Set rate correct failed\n"); - -#ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function (Rate Correction) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int64_t tau_ns=-1; - n = receiveData(file_des,&tau_ns,sizeof(tau_ns),INT64); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - printf("Setting rate correction to %lld ns\n",(long long int)tau_ns); - //set rate - //wrong bit mode - if((setDynamicRange(-1)!=32) && (setDynamicRange(-1)!=16) && (tau_ns!=0)){ - ret=FAIL; - strcpy(mess,"Rate correction Deactivated, must be in 32 or 16 bit mode\n"); - cprintf(RED, "Warning: %s", mess); - } - //16 or 32 bit mode - else{ - if(tau_ns < 0) - tau_ns = getDefaultSettingsTau_in_nsec(); - else if(tau_ns > 0){ - //changing tau to a user defined value changes settings to undefined - setSettings(UNDEFINED,-1); - cprintf(RED,"Settings has been changed to undefined (tau changed)\n"); - } - - int64_t retval = setRateCorrection(tau_ns); - if(tau_ns != retval){ - ret=FAIL; - cprintf(RED, "Warning: %s", mess); - } - } - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n = sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - - -int get_rate_correct(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int64_t retval=-1; - sprintf(mess,"Get Rate correct failed\n"); - -#ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function (Get Rate Correction) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - -#ifdef SLS_DETECTOR_FUNCTION_LIST - - // execute action - retval = getCurrentTau(); - printf("Getting rate correction %lld\n",(long long int)retval); - -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT64); - - // return ok / fail - return ret; -} - - - - - -int set_network_parameter(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"set network parameter failed\n"); - -#if !defined(EIGERD) && !defined(JUNGFRAUD) - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function(Set Network Parmaeter) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - enum NETWORKINDEX index; - - // receive arguments - enum networkParameter mode=0; - int value=-1; - n = receiveData(file_des,&mode,sizeof(mode),INT32); - if (n < 0) return printSocketReadError(); - - n = receiveData(file_des,&value,sizeof(value),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && value >= 0) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { -#ifdef VERBOSE - printf("setting network parameter mode %d to %d\n",(int)mode,value); -#endif - switch (mode) { - -#ifdef EIGERD - case FLOW_CONTROL_10G: - index = FLOWCTRL_10G; - break; - case DETECTOR_TXN_DELAY_LEFT: - index = TXN_LEFT; - break; - case DETECTOR_TXN_DELAY_RIGHT: - index = TXN_RIGHT; - break; -#endif - case DETECTOR_TXN_DELAY_FRAME: - index = TXN_FRAME; -#ifdef JUNGFRAUD - if (value > MAX_TIMESLOT_VAL) { - ret=FAIL; - sprintf(mess,"Transmission delay %d should be in range: 0 - %d\n", value, MAX_TIMESLOT_VAL); - cprintf(RED, "Warning: %s", mess); - } -#endif - break; - default: - ret=FAIL; - sprintf(mess,"Network Parameter Index (%d) is not implemented for this detector\n",(int) mode); - cprintf(RED, "Warning: %s", mess); - break; - } - if (ret==OK) { - retval=setNetworkParameter(index, value); - if ((retval!=value) && (value>=0)) { - ret=FAIL; - sprintf(mess,"could not change network parameter mode %d: should be %d but is %d \n",index, value, retval); - cprintf(RED, "Warning: %s", mess); - } - } - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - - - -int program_fpga(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"program FPGA failed\n"); - -#ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function (Program FPGA) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - if (!debugflag) { - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"FPGA cannot be programmed in this mode. " - "Restart on-board detector server with -update for update mode to continue.\n"); - cprintf(RED, "Warning: %s", mess); - } - - else { - printf("Programming FPGA..."); - size_t filesize = 0; - size_t totalsize = 0; - size_t unitprogramsize = 0; - char* fpgasrc = NULL; - FILE* fp = NULL; - - // receive arguments - filesize - n = receiveData(file_des,&filesize,sizeof(filesize),INT32); - if (n < 0) return printSocketReadError(); - totalsize = filesize; -#ifdef VERY_VERBOSE - printf("\n\n Total size is:%d\n",totalsize); -#endif - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - //opening file pointer to flash and telling FPGA to not touch flash - if(startWritingFPGAprogram(&fp) != OK) { - ret=FAIL; - sprintf(mess,"Could not write to flash. Error at startup.\n"); - cprintf(RED,"%s",mess); - } - - //---------------- first ret ---------------- - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - //---------------- first ret ---------------- - - if(ret!=FAIL) { - //erasing flash - eraseFlash(); - fpgasrc = (char*)malloc(MAX_FPGAPROGRAMSIZE); - } - - //writing to flash part by part - while(ret != FAIL && filesize){ - - unitprogramsize = MAX_FPGAPROGRAMSIZE; //2mb - if(unitprogramsize > filesize) //less than 2mb - unitprogramsize = filesize; -#ifdef VERY_VERBOSE - printf("unit size to receive is:%d\n",unitprogramsize); - printf("filesize:%d currentpointer:%d\n",filesize,currentPointer); -#endif - - //receive - n = receiveData(file_des,fpgasrc,unitprogramsize,OTHER); - if (n < 0) return printSocketReadError(); - - if(!(unitprogramsize - filesize)){ - fpgasrc[unitprogramsize]='\0'; - filesize-=unitprogramsize; - unitprogramsize++; - }else - filesize-=unitprogramsize; - - ret = writeFPGAProgram(fpgasrc,unitprogramsize,fp); - - //---------------- middle rets ---------------- - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - cprintf(RED,"Failure: Breaking out of program receiving\n"); - } - //---------------- middle rets ---------------- - - if(ret != FAIL){ - //print progress - printf("Writing to Flash:%d%%\r",(int) (((double)(totalsize-filesize)/totalsize)*100) ); - fflush(stdout); - } - } - - printf("\n"); - - //closing file pointer to flash and informing FPGA - stopWritingFPGAprogram(fp); - - //free resources - if(fpgasrc != NULL) - free(fpgasrc); - if(fp!=NULL) - fclose(fp); -#ifdef VERY_VERBOSE - printf("Done with program receiving command\n"); -#endif - - if (isControlServer) { - basictests(debugflag); - initControlServer(); - } - } -#endif - if (ret==OK) - ret=FORCE_UPDATE; - } -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - - -int reset_fpga(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"Reset FPGA unsuccessful\n"); - -#ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Reset FPGA) is not implemented for this detector\n"); cprintf(RED, "%s", mess); -#else - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - if (isControlServer) { - basictests(debugflag); // mapping of control server at lease -#ifdef JUNGFRAUD - if (debugflag != PROGRAMMING_MODE) -#endif - initControlServer(); - } - else initStopServer(); //remapping of stop server - ret = FORCE_UPDATE; - } -#endif -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - -int power_chip(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"power chip failed\n"); - -#ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Power Chip) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); -#else - - // receive arguments - int arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && arg!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { -#ifdef VERBOSE - printf("Power chip to %d\n", arg); -#endif - retval=powerChip(arg); - -#ifdef VERBOSE - printf("Chip powered: %d\n",retval); -#endif - if (retval==arg || arg<0) { - ret=OK; - } else { - ret=FAIL; - if(setTemperatureEvent(-1) == 1) - sprintf(mess,"Powering chip failed due to over-temperature event. Clear event & power chip again. Wrote %d, read %d \n", arg, retval); - else - sprintf(mess,"Powering chip failed, wrote %d but read %d\n", arg, retval); - cprintf(RED, "Warning: %s", mess); - } - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - -int set_activate(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"Activate/Deactivate failed\n"); - -#ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function (Set Activate) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && arg!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { -#ifdef VERBOSE - printf("Setting activate mode of detector to %d\n",arg); -#endif - retval=activate(arg); - if ((retval!=arg) && (arg!=-1)) { - ret=FAIL; - sprintf(mess,"Could not set activate mode to %d, is set to %d\n",arg, retval); - cprintf(RED, "Warning: %s", mess); - } - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - -int prepare_acquisition(int file_des) { - int ret=OK,ret1=OK; - int n=0; - strcpy(mess,"prepare acquisition failed\n"); - -#if !defined(GOTTHARDD) && !defined(EIGERD) - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Prepare Acquisition) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - ret = prepareAcquisition(); - if (ret == FAIL) - cprintf(RED, "Warning: %s", mess); - } -#endif - if(ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - -int cleanup_acquisition(int file_des) { - int ret=OK,ret1=OK; - int n=0; - strcpy(mess,"prepare acquisition failed\n"); - -#ifndef GOTTHARDD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Cleanup Acquisition) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else {//to be implemented when used here - ret = FAIL; - sprintf(mess,"Function (Cleanup Acquisition) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); - } -#endif - if(ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - -int threshold_temp(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"could not set/get threshold temperature\n"); - -#ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Threshold Temp) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); -#else - int arg[2]={-1,-1}; - int val=-1; - - // receive arguments - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - val=arg[0]; - //ignoring imod - if (val > MAX_THRESHOLD_TEMP_VAL) { - ret=FAIL; - sprintf(mess,"Threshold Temp %d should be in range: 0 - %d\n", val, MAX_THRESHOLD_TEMP_VAL); - cprintf(RED, "Warning: %s", mess); - } - - -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { -#ifdef VERBOSE - printf("Setting Threshold Temperature to %d\n", val); -#endif - retval=setThresholdTemperature(val); - } -#endif -#ifdef VERBOSE - printf("Threshold temperature is %d\n", retval); -#endif - - if (ret==OK && differentClients && val >= 0) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - -int temp_control(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"could not set/get temperature control\n"); - -#ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Temperature control) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); -#else - int arg[2]={-1,-1}; - int val=-1; - - // receive arguments - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - val=arg[0]; - //ignoring imod - - -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { -#ifdef VERBOSE - printf("Setting Temperature control to %d\n", val); -#endif - retval=setTemperatureControl(val); - } -#endif -#ifdef VERBOSE - printf("Temperature control is %d\n", retval); -#endif - if (ret==OK && differentClients && val >= 0) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - -int temp_event(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"could not set/get temperature event\n"); - -#ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Temperature Event) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); -#else - int arg[2]={-1,-1}; - int val=-1; - - // receive arguments - n = receiveData(file_des,arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - val=arg[0]; - //ignoring imod - -#ifdef SLS_DETECTOR_FUNCTION_LIST - if (ret==OK) { -#ifdef VERBOSE - printf("Setting Temperature Event to %d\n", val); -#endif - retval=setTemperatureEvent(val); - } -#endif -#ifdef VERBOSE - printf("Temperature Event is %d\n", retval); -#endif - - if (ret==OK && differentClients && val >= 0) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret!=FAIL) { - n += sendData(file_des,&retval,sizeof(retval),INT32); - } else { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - - -int auto_comp_disable(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"auto comp disable failed\n"); - -#ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Auto Comp Disable) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); -#else - - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Auto Comp Disable) is not yet implemented for this detector\n"); - cprintf(RED, "%s", mess); - - // receive arguments - int arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && arg!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { -#ifdef VERBOSE - printf("Auto Comp Disable to %d\n", arg); -#endif - retval=autoCompDisable(arg); - -#ifdef VERBOSE - printf("Auto comp disable set to: %d\n",retval); -#endif - if (retval==arg || arg<0) { - ret=OK; - } else { - ret=FAIL; - sprintf(mess,"Atuo Comp Disable failed, wrote %d but read %d\n", arg, retval); - cprintf(RED, "Warning: %s", mess); - } - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - - -int storage_cell_start(int file_des) { - int ret=OK,ret1=OK; - int n=0; - int retval=-1; - sprintf(mess,"storage cell start failed\n"); - -#ifndef JUNGFRAUD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Storage cell start) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); -#else - - // receive arguments - int arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT32); - if (n < 0) return printSocketReadError(); - - // execute action - if (differentClients && lockStatus && arg!=-1) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else if (arg > MAX_STORAGE_CELL_VAL) { - ret=FAIL; - strcpy(mess,"Max Storage cell number should not exceed 15\n"); - cprintf(RED, "Warning: %s", mess); - } else { -#ifdef VERBOSE - printf("Storage cell start to %d\n", arg); -#endif - retval=selectStoragecellStart(arg); - -#ifdef VERBOSE - printf("Storage cell start: %d\n",retval); -#endif - if (retval==arg || arg<0) { - ret=OK; - } else { - sprintf(mess,"Storage cell start select failed, wrote %d but read %d\n", arg, retval); - cprintf(RED, "Warning: %s", mess); - } - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } else - n += sendData(file_des,&retval,sizeof(retval),INT32); - - // return ok / fail - return ret; -} - - - - -int check_version(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"check version failed\n"); - -#if !defined(EIGERD) && !defined(JUNGFRAUD) && !defined(GOTTHARD) - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret=FAIL; - sprintf(mess,"Function (Check Version Compatibility) is not implemented for this detector\n"); - cprintf(RED, "Warning: %s", mess); -#else - - // receive arguments - int64_t arg=-1; - n = receiveData(file_des,&arg,sizeof(arg),INT64); - if (n < 0) return printSocketReadError(); - - // execute action -#ifdef SLS_DETECTOR_FUNCTION_LIST - - // check software- firmware compatibility and basic tests - if (isControlServer) { -#ifdef VERBOSE - printf("Checking software-firmware compatibility and basic test result\n"); -#endif - // check if firmware check is done - if (!isFirmwareCheckDone()) { - usleep(3 * 1000 * 1000); - if (!isFirmwareCheckDone()) { - ret = FAIL; - strcpy(mess,"Firmware Software Compatibility Check (Server Initialization) " - "still not done done in server. Unexpected.\n"); - cprintf(RED, "Warning: %s", mess); - } - } - // check firmware check result - if (ret == OK) { - char* firmware_message = NULL; - if (getFirmwareCheckResult(&firmware_message) == FAIL) { - ret = FAIL; - strcpy(mess, firmware_message); - cprintf(RED, "Warning: %s", mess); - } - } - } - - if (ret == OK) { -#ifdef VERBOSE - printf("Checking versioning compatibility with value %d\n",arg); -#endif - int64_t client_requiredVersion = arg; - int64_t det_apiVersion = getDetectorId(CLIENT_SOFTWARE_API_VERSION); - int64_t det_version = getDetectorId(DETECTOR_SOFTWARE_VERSION); - - // old client - if (det_apiVersion > client_requiredVersion) { - ret = FAIL; - sprintf(mess,"Client's detector SW API version: (0x%llx). " - "Detector's SW API Version: (0x%llx). " - "Incompatible, update client!\n", - (long long int)client_requiredVersion, (long long int)det_apiVersion); - cprintf(RED, "Warning: %s", mess); - } - - // old software - else if (client_requiredVersion > det_version) { - ret = FAIL; - sprintf(mess,"Detector SW Version: (0x%llx). " - "Client's detector SW API Version: (0x%llx). " - "Incompatible, update detector software!\n", - (long long int)det_version, (long long int)client_requiredVersion); - cprintf(RED, "Warning: %s", mess); - } - } -#endif -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - - - - -int software_trigger(int file_des) { - int ret=OK,ret1=OK; - int n=0; - sprintf(mess,"software trigger failed\n"); - -#ifndef EIGERD - //to receive any arguments - while (n > 0) - n = receiveData(file_des,mess,MAX_STR_LENGTH,OTHER); - ret = FAIL; - sprintf(mess,"Function (Software Trigger) is not implemented for this detector\n"); - cprintf(RED, "%s", mess); -#else - - // execute action - if (differentClients && lockStatus) { - ret = FAIL; - sprintf(mess,"Detector locked by %s\n",lastClientIP); - cprintf(RED, "Warning: %s", mess); - } -#ifdef SLS_DETECTOR_FUNCTION_LIST - else { - printf("Software Trigger\n"); - ret=softwareTrigger(); - if (ret==FAIL) - cprintf(RED, "Warning: %s", mess); - } -#endif - if (ret==OK && differentClients) - ret=FORCE_UPDATE; -#endif - - // ret could be swapped during sendData - ret1 = ret; - // send ok / fail - n = sendData(file_des,&ret1,sizeof(ret),INT32); - // send return argument - if (ret==FAIL) { - n += sendData(file_des,mess,sizeof(mess),OTHER); - } - - // return ok / fail - return ret; -} - diff --git a/slsDetectorSoftware/slsDetectorServer/slsDetector_stopServer.c b/slsDetectorSoftware/slsDetectorServer/slsDetector_stopServer.c deleted file mode 100755 index 1772ce2b6..000000000 --- a/slsDetectorSoftware/slsDetectorServer/slsDetector_stopServer.c +++ /dev/null @@ -1,46 +0,0 @@ -/* A simple server in the internet domain using TCP - The port number is passed as an argument */ -#include "communication_funcs.h" - -#include "slsDetectorFunctionList.h"/*#include "slsDetector_firmware.h" for the time being*/ -#include "slsDetectorServer_defs.h" - -#include -#include - -int sockfd; - -int main(int argc, char *argv[]) -{ - int portno; - int retval=0; - int sd,fd; - - portno = DEFAULT_PORTNO; - - - sd=bindSocket(portno); //defined in communication_funcs - if (getServerError(sd)) //defined in communication_funcs - return -1; - - - - /* waits for connection */ - while(retval!=GOODBYE) { -#ifdef VERBOSE - printf("\n"); -#endif -#ifdef VERY_VERBOSE - printf("Stop server: waiting for client call\n"); -#endif - fd=acceptConnection(sd); //defined in communication_funcs - retval=stopStateMachine();//defined in slsDetectorFirmare_funcs - closeConnection(fd); //defined in communication_funcs - } - - exitServer(sd); //defined in communication_funcs - printf("Goodbye!\n"); - - return 0; -} - diff --git a/slsDetectorSoftware/slsDetectorServer/sls_detector_defs.h b/slsDetectorSoftware/slsDetectorServer/sls_detector_defs.h deleted file mode 120000 index c5062e03f..000000000 --- a/slsDetectorSoftware/slsDetectorServer/sls_detector_defs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_defs.h \ No newline at end of file diff --git a/slsDetectorSoftware/slsDetectorServer/sls_detector_funcs.h b/slsDetectorSoftware/slsDetectorServer/sls_detector_funcs.h deleted file mode 120000 index 844b67129..000000000 --- a/slsDetectorSoftware/slsDetectorServer/sls_detector_funcs.h +++ /dev/null @@ -1 +0,0 @@ -../commonFiles/sls_detector_funcs.h \ No newline at end of file diff --git a/slsDetectorSoftware/slsReceiverInterface/receiverInterface.cpp b/slsDetectorSoftware/slsReceiverInterface/receiverInterface.cpp deleted file mode 100644 index 6173d4185..000000000 --- a/slsDetectorSoftware/slsReceiverInterface/receiverInterface.cpp +++ /dev/null @@ -1,217 +0,0 @@ -#include "receiverInterface.h" - - -#include -#include -#include -#include -#include -#include -#include - - - -receiverInterface::receiverInterface(MySocketTCP *socket):dataSocket(socket){} - - - -receiverInterface::~receiverInterface(){} - - - -int receiverInterface::sendString(int fnum, char retval[], char arg[]){ - int ret = slsDetectorDefs::FAIL; - char mess[MAX_STR_LENGTH]; - memset(mess, 0, MAX_STR_LENGTH); - - dataSocket->SendDataOnly(&fnum,sizeof(fnum)); - dataSocket->SendDataOnly(arg,MAX_STR_LENGTH); - dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==slsDetectorDefs::FAIL){ - dataSocket->ReceiveDataOnly(mess,sizeof(mess)); - cprintf(RED, "Receiver returned error: %s", mess); - } - if(strstr(mess,"Unrecognized Function")==NULL) - dataSocket->ReceiveDataOnly(retval,MAX_STR_LENGTH); - - return ret; -} - - - -int receiverInterface::sendUDPDetails(int fnum, char retval[], char arg[3][MAX_STR_LENGTH]){ - char args[3][MAX_STR_LENGTH]; - int ret = slsDetectorDefs::FAIL; - char mess[MAX_STR_LENGTH]; - memset(mess, 0, MAX_STR_LENGTH); - - dataSocket->SendDataOnly(&fnum,sizeof(fnum)); - dataSocket->SendDataOnly(arg,sizeof(args)); - dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==slsDetectorDefs::FAIL){ - dataSocket->ReceiveDataOnly(mess,sizeof(mess)); - cprintf(RED, "Receiver returned error: %s", mess); - } - else - dataSocket->ReceiveDataOnly(retval,MAX_STR_LENGTH); - - return ret; -} - - -int receiverInterface::sendInt(int fnum, int &retval, int arg){ - int ret = slsDetectorDefs::FAIL; - char mess[MAX_STR_LENGTH]; - memset(mess, 0, MAX_STR_LENGTH); - - dataSocket->SendDataOnly(&fnum,sizeof(fnum)); - dataSocket->SendDataOnly(&arg,sizeof(arg)); - dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==slsDetectorDefs::FAIL){ - dataSocket->ReceiveDataOnly(mess,sizeof(mess)); - cprintf(RED, "Receiver returned error: %s", mess); - } - if(strstr(mess,"Unrecognized Function")==NULL) - dataSocket->ReceiveDataOnly(&retval,sizeof(retval)); - - return ret; -} - - - -int receiverInterface::getInt(int fnum, int &retval){ - int ret = slsDetectorDefs::FAIL; - char mess[MAX_STR_LENGTH]; - memset(mess, 0, MAX_STR_LENGTH); - - dataSocket->SendDataOnly(&fnum,sizeof(fnum)); - dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==slsDetectorDefs::FAIL){ - dataSocket->ReceiveDataOnly(mess,sizeof(mess)); - cprintf(RED, "Receiver returned error: %s", mess); - } - if(strstr(mess,"Unrecognized Function")==NULL) - dataSocket->ReceiveDataOnly(&retval,sizeof(retval)); - - return ret; -} - - - -int receiverInterface::sendInt(int fnum, int64_t &retval, int64_t arg){ - int ret = slsDetectorDefs::FAIL; - char mess[MAX_STR_LENGTH]; - memset(mess, 0, MAX_STR_LENGTH); - - dataSocket->SendDataOnly(&fnum,sizeof(fnum)); - dataSocket->SendDataOnly(&arg,sizeof(arg)); - dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==slsDetectorDefs::FAIL){ - dataSocket->ReceiveDataOnly(mess,sizeof(mess)); - cprintf(RED, "Receiver returned error: %s", mess); - } - if(strstr(mess,"Unrecognized Function")==NULL) - dataSocket->ReceiveDataOnly(&retval,sizeof(retval)); - - return ret; -} - - - -int receiverInterface::sendIntArray(int fnum, int64_t &retval, int64_t arg[2], char mess[]){ - int64_t args[2]; - int ret = slsDetectorDefs::FAIL; - memset(mess, 0, MAX_STR_LENGTH); - - dataSocket->SendDataOnly(&fnum,sizeof(fnum)); - dataSocket->SendDataOnly(arg,sizeof(args)); - dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==slsDetectorDefs::FAIL){ - dataSocket->ReceiveDataOnly(mess,MAX_STR_LENGTH); - cprintf(RED, "Receiver returned error: %s", mess); - } - if(strstr(mess,"Unrecognized Function")==NULL) - dataSocket->ReceiveDataOnly(&retval,sizeof(retval)); - - return ret; -} - - - -int receiverInterface::sendIntArray(int fnum, int &retval, int arg[2]){ - int args[2]; - int ret = slsDetectorDefs::FAIL; - char mess[MAX_STR_LENGTH]; - memset(mess, 0, MAX_STR_LENGTH); - - dataSocket->SendDataOnly(&fnum,sizeof(fnum)); - dataSocket->SendDataOnly(arg,sizeof(args)); - dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==slsDetectorDefs::FAIL){ - dataSocket->ReceiveDataOnly(mess,sizeof(mess)); - cprintf(RED, "Receiver returned error: %s", mess); - } - if(strstr(mess,"Unrecognized Function")==NULL) - dataSocket->ReceiveDataOnly(&retval,sizeof(retval)); - - return ret; -} - - - -int receiverInterface::getInt(int fnum, int64_t &retval){ - int ret = slsDetectorDefs::FAIL; - - dataSocket->SendDataOnly(&fnum,sizeof(fnum)); - dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); - dataSocket->ReceiveDataOnly(&retval,sizeof(retval)); - - return ret; -} - - -int receiverInterface::getLastClientIP(int fnum, char retval[]){ - int ret = slsDetectorDefs::FAIL; - - dataSocket->SendDataOnly(&fnum,sizeof(fnum)); - dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); - dataSocket->ReceiveDataOnly(retval,INET_ADDRSTRLEN); - - return ret; -} - - - -int receiverInterface::executeFunction(int fnum,char mess[]){ - int ret = slsDetectorDefs::FAIL; - memset(mess, 0, MAX_STR_LENGTH); - - dataSocket->SendDataOnly(&fnum,sizeof(fnum)); - dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==slsDetectorDefs::FAIL){ - dataSocket->ReceiveDataOnly(mess,MAX_STR_LENGTH); - cprintf(RED, "Receiver returned error: %s", mess); - } - - return ret; -} - - - -int receiverInterface::sendROI(int fnum, int n, slsReceiverDefs::ROI roiLimits[]) { - int ret = slsDetectorDefs::FAIL; - char mess[MAX_STR_LENGTH]; - memset(mess, 0, MAX_STR_LENGTH); - - dataSocket->SendDataOnly(&fnum,sizeof(fnum)); - dataSocket->SendDataOnly(&n,sizeof(n)); - dataSocket->SendDataOnly(roiLimits,n * sizeof(slsReceiverDefs::ROI)); - dataSocket->ReceiveDataOnly(&ret,sizeof(ret)); - if (ret==slsDetectorDefs::FAIL){ - dataSocket->ReceiveDataOnly(mess,sizeof(mess)); - cprintf(RED, "Receiver returned error: %s", mess); - } - return ret; -} - - diff --git a/slsDetectorSoftware/slsReceiverInterface/receiverInterface.h b/slsDetectorSoftware/slsReceiverInterface/receiverInterface.h deleted file mode 100644 index f188c8da8..000000000 --- a/slsDetectorSoftware/slsReceiverInterface/receiverInterface.h +++ /dev/null @@ -1,154 +0,0 @@ - - - -#ifndef SLS_RECEIVER_INTERFACE_H -#define SLS_RECEIVER_INTERFACE_H - -#include "sls_detector_defs.h" -#include "MySocketTCP.h" - - - -/** - * - * @short the slsReceiverInterface class is the interface between the sls detector and the sls receiver - * @author Dhanya Maliakal - * @version 0.1alpha - */ - - -class receiverInterface{ - -public: - - /** - * (default) constructor - * @param socket tcp socket between client and receiver - */ - receiverInterface(MySocketTCP *socket); - - - /** - * destructor - */ - virtual ~receiverInterface(); - - /** - * Set the datasocket - * @param socket the data socket - */ - void setSocket(MySocketTCP *socket){dataSocket=socket;}; - - - /** - * Send a string to receiver - * @param fnum function enum to determine what parameter - * @param retval return value - * @param arg value to send - * \returns success of operation - */ - int sendString(int fnum, char retval[], char arg[]); - - /** - * Send a string to receiver - * @param fnum function enum to send udp ip and udp port - * @param retval return value receiver mac - * @param arg value to send - * \returns success of operation - */ - int sendUDPDetails(int fnum, char retval[], char arg[3][MAX_STR_LENGTH]); - - - /** - * Send an integer to receiver - * @param fnum function enum to determine what parameter - * @param retval return value - * @param arg value to send - * \returns success of operation - */ - int sendInt(int fnum, int &retval, int arg); - - /** - * Get an integer value from receiver - * @param fnum function enum to determine what parameter - * @param retval return value - * \returns success of operation - */ - int getInt(int fnum, int &retval); - - /** - * Send an integer to receiver - * @param fnum function enum to determine what parameter - * @param retval return value - * @param arg value to send - * \returns success of operation - */ - int sendInt(int fnum, int64_t &retval, int64_t arg); - - - /** - * Send an integer to receiver - * @param fnum function enum to determine what parameter - * @param retval return value - * @param arg values to send - * @param mess message returned - * \returns success of operation - */ - int sendIntArray(int fnum, int64_t &retval, int64_t arg[2],char mess[]); - - - /** - * Send an integer to receiver - * @param fnum function enum to determine what parameter - * @param retval return value - * @param arg values to send - * \returns success of operation - */ - int sendIntArray(int fnum, int &retval, int arg[2]); - - /** - * Get an integer value from receiver - * @param fnum function enum to determine what parameter - * @param retval return value - * \returns success of operation - */ - int getInt(int fnum, int64_t &retval); - - /** - * Get last client ip connected to receiver - * @param fnum function enum to get last client up - * @param retval return value - * \returns success of operation - */ - int getLastClientIP(int fnum, char retval[]); - - - /** - * Send a function number to execute function - * @param fnum function enum to determine which function to execute - * @param mess return error message - * \returns success of operation - */ - int executeFunction(int fnum,char mess[]); - - /** - * Send an integer to receiver - * @param fnum function enum to determine what parameter - * @param n number of ROIs to send - * @param roiLimits ROI structure - * \returns success of operation - */ - int sendROI(int fnum, int n, slsReceiverDefs::ROI roiLimits[]); - - //here one should implement the funcs listed in - -private: - - /** - * socket for data acquisition - */ - MySocketTCP *dataSocket; - -}; - -#endif diff --git a/slsDetectorSoftware/src/multiSlsDetector.cpp b/slsDetectorSoftware/src/multiSlsDetector.cpp new file mode 100755 index 000000000..277ab1c0d --- /dev/null +++ b/slsDetectorSoftware/src/multiSlsDetector.cpp @@ -0,0 +1,4255 @@ +#include "multiSlsDetector.h" +#include "SharedMemory.h" +#include "ZmqSocket.h" +#include "detectorData.h" +#include "file_utils.h" +#include "logger.h" +#include "multiSlsDetectorClient.h" +#include "slsDetector.h" +#include "slsDetectorCommand.h" +#include "sls_detector_exceptions.h" +#include "versionAPI.h" + + +#include "container_utils.h" +#include "string_utils.h" +#include "network_utils.h" + +#include +#include +#include +#include //json header in zmq stream +#include +#include +#include +#include + + + +#include +#include +#include + +using namespace sls; + +multiSlsDetector::multiSlsDetector(int multi_id, bool verify, bool update) + : multiId(multi_id), multi_shm(multi_id, -1) { + setupMultiDetector(verify, update); +} + +multiSlsDetector::~multiSlsDetector() = default; + +void multiSlsDetector::setupMultiDetector(bool verify, bool update) { + initSharedMemory(verify); + initializeMembers(verify); + if (update) { + updateUserdetails(); + } +} + +template +std::vector multiSlsDetector::serialCall(RT (slsDetector::*somefunc)(CT...), + typename NonDeduced::type... Args) { + std::vector result; + result.reserve(detectors.size()); + for (auto &d : detectors) { + result.push_back((d.get()->*somefunc)(Args...)); + } + return result; +} + +template +std::vector multiSlsDetector::serialCall(RT (slsDetector::*somefunc)(CT...) const, + typename NonDeduced::type... Args) const { + std::vector result; + result.reserve(detectors.size()); + for (auto &d : detectors) { + result.push_back((d.get()->*somefunc)(Args...)); + } + return result; +} + +template +std::vector multiSlsDetector::parallelCall(RT (slsDetector::*somefunc)(CT...), + typename NonDeduced::type... Args) { + std::vector> futures; + for (auto &d : detectors) { + futures.push_back(std::async(std::launch::async, somefunc, d.get(), Args...)); + } + std::vector result; + result.reserve(detectors.size()); + for (auto &i : futures) { + result.push_back(i.get()); + } + return result; +} + +template +std::vector multiSlsDetector::parallelCall(RT (slsDetector::*somefunc)(CT...) const, + typename NonDeduced::type... Args) const { + std::vector> futures; + for (auto &d : detectors) { + futures.push_back(std::async(std::launch::async, somefunc, d.get(), Args...)); + } + std::vector result; + result.reserve(detectors.size()); + for (auto &i : futures) { + result.push_back(i.get()); + } + return result; +} + +template +void multiSlsDetector::parallelCall(void (slsDetector::*somefunc)(CT...), + typename NonDeduced::type... Args) { + std::vector> futures; + for (auto &d : detectors) { + futures.push_back(std::async(std::launch::async, somefunc, d.get(), Args...)); + } + for (auto &i : futures) { + i.get(); + } + return; +} + +template +void multiSlsDetector::parallelCall(void (slsDetector::*somefunc)(CT...) const, + typename NonDeduced::type... Args) const{ + std::vector> futures; + for (auto &d : detectors) { + futures.push_back(std::async(std::launch::async, somefunc, d.get(), Args...)); + } + for (auto &i : futures) { + i.get(); + } + return; +} + + +int multiSlsDetector::decodeNChannel(int offsetX, int offsetY, int &channelX, int &channelY) { + channelX = -1; + channelY = -1; + // loop over + for (size_t i = 0; i < detectors.size(); ++i) { + int x = detectors[i]->getDetectorOffset(X); + int y = detectors[i]->getDetectorOffset(Y); + // check x offset range + if ((offsetX >= x) && + (offsetX < (x + detectors[i]->getTotalNumberOfChannelsInclGapPixels(X)))) { + if (offsetY == -1) { + channelX = offsetX - x; + return i; + } else { + // check y offset range + if ((offsetY >= y) && + (offsetY < (y + detectors[i]->getTotalNumberOfChannelsInclGapPixels(Y)))) { + channelX = offsetX - x; + channelY = offsetY - y; + return i; + } + } + } + } + return -1; +} + + +void multiSlsDetector::setAcquiringFlag(bool flag) { multi_shm()->acquiringFlag = flag; } + +bool multiSlsDetector::getAcquiringFlag() const { return multi_shm()->acquiringFlag; } + +bool multiSlsDetector::isAcquireReady() { + if (multi_shm()->acquiringFlag) { + FILE_LOG(logWARNING) << "Acquire has already started. " + "If previous acquisition terminated unexpectedly, " + "reset busy flag to restart.(sls_detector_put busy 0)"; + return FAIL; + } + multi_shm()->acquiringFlag = true; + return OK; +} + +int multiSlsDetector::checkDetectorVersionCompatibility(int detPos) { + if (detPos >= 0) { + return detectors[detPos]->checkDetectorVersionCompatibility(); + } + + auto r = parallelCall(&slsDetector::checkDetectorVersionCompatibility); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::checkReceiverVersionCompatibility(int detPos) { + if (detPos >= 0) { + return detectors[detPos]->checkReceiverVersionCompatibility(); + } + + auto r = parallelCall(&slsDetector::checkReceiverVersionCompatibility); + return sls::minusOneIfDifferent(r); +} + +int64_t multiSlsDetector::getId(idMode mode, int detPos) { + if (detPos >= 0) { + return detectors[detPos]->getId(mode); + } + + auto r = parallelCall(&slsDetector::getId, mode); + return sls::minusOneIfDifferent(r); +} + +int64_t multiSlsDetector::getClientSoftwareVersion() const { + return APILIB; +} + +int64_t multiSlsDetector::getReceiverSoftwareVersion(int detPos) const { + if (detPos >= 0) { + return detectors[detPos]->getReceiverSoftwareVersion(); + } + + auto r = parallelCall(&slsDetector::getReceiverSoftwareVersion); + return sls::minusOneIfDifferent(r); +} + +std::vector multiSlsDetector::getDetectorNumber() { + return parallelCall(&slsDetector::getId, slsDetectorDefs::DETECTOR_SERIAL_NUMBER); +} + +void multiSlsDetector::freeSharedMemory(int multiId, int detPos) { + // single + if (detPos >= 0) { + slsDetector::freeSharedMemory(multiId, detPos); + return; + } + + // multi - get number of detectors from shm + SharedMemory multiShm(multiId, -1); + int numDetectors = 0; + + if (multiShm.IsExisting()) { + multiShm.OpenSharedMemory(); + numDetectors = multiShm()->numberOfDetectors; + multiShm.RemoveSharedMemory(); + } + + for (int i = 0; i < numDetectors; ++i) { + SharedMemory shm(multiId, i); + shm.RemoveSharedMemory(); + } +} + +void multiSlsDetector::freeSharedMemory(int detPos) { + // single + if (detPos >= 0) { + detectors[detPos]->freeSharedMemory(); + return; + } + + // multi + zmqSocket.clear(); + for (auto &d : detectors) { + d->freeSharedMemory(); + } + detectors.clear(); + + // clear multi detector shm + multi_shm.RemoveSharedMemory(); + client_downstream = false; +} + +std::string multiSlsDetector::getUserDetails() { + if (detectors.empty()) { + return std::string("none"); + } + + std::ostringstream sstream; + sstream << "\nHostname: " << getHostname(); + sstream << "\nType: "; + for (auto &d : detectors) { + sstream << d->getDetectorTypeAsString() << "+"; + } + + sstream << "\nPID: " << multi_shm()->lastPID << "\nUser: " << multi_shm()->lastUser + << "\nDate: " << multi_shm()->lastDate << std::endl; + + return sstream.str(); +} + +void multiSlsDetector::initSharedMemory(bool verify) { + if (!multi_shm.IsExisting()) { + multi_shm.CreateSharedMemory(); + initializeDetectorStructure(); + } else { + multi_shm.OpenSharedMemory(); + if (verify && multi_shm()->shmversion != MULTI_SHMVERSION) { + FILE_LOG(logERROR) << "Multi shared memory (" << multiId + << ") version mismatch " + "(expected 0x" + << std::hex << MULTI_SHMVERSION << " but got 0x" + << multi_shm()->shmversion << std::dec; + throw SharedMemoryError("Shared memory version mismatch!"); + } + } +} + +void multiSlsDetector::initializeDetectorStructure() { + multi_shm()->shmversion = MULTI_SHMVERSION; + multi_shm()->numberOfDetectors = 0; + multi_shm()->numberOfDetector[X] = 0; + multi_shm()->numberOfDetector[Y] = 0; + multi_shm()->onlineFlag = 1; + multi_shm()->stoppedFlag = 0; + multi_shm()->dataBytes = 0; + multi_shm()->dataBytesInclGapPixels = 0; + multi_shm()->numberOfChannels = 0; + multi_shm()->numberOfChannel[X] = 0; + multi_shm()->numberOfChannel[Y] = 0; + multi_shm()->numberOfChannelInclGapPixels[X] = 0; + multi_shm()->numberOfChannelInclGapPixels[Y] = 0; + multi_shm()->maxNumberOfChannelsPerDetector[X] = 0; + multi_shm()->maxNumberOfChannelsPerDetector[Y] = 0; + for (int64_t &i : multi_shm()->timerValue) { + i = 0; + } + + multi_shm()->acquiringFlag = false; + multi_shm()->receiverOnlineFlag = OFFLINE_FLAG; + multi_shm()->receiver_upstream = false; +} + +void multiSlsDetector::initializeMembers(bool verify) { + // multiSlsDetector + zmqSocket.clear(); + + // get objects from single det shared memory (open) + for (int i = 0; i < multi_shm()->numberOfDetectors; i++) { + try { + detectors.push_back(sls::make_unique(multiId, i, verify)); + } catch (...) { + detectors.clear(); + throw; + } + } + + // depend on number of detectors + updateOffsets(); +} + +void multiSlsDetector::updateUserdetails() { + multi_shm()->lastPID = getpid(); + memset(multi_shm()->lastUser, 0, SHORT_STRING_LENGTH); + memset(multi_shm()->lastDate, 0, SHORT_STRING_LENGTH); + try { + sls::strcpy_safe(multi_shm()->lastUser, exec("whoami").c_str()); + sls::strcpy_safe(multi_shm()->lastDate, exec("date").c_str()); + } catch (...) { + sls::strcpy_safe(multi_shm()->lastUser, "errorreading"); + sls::strcpy_safe(multi_shm()->lastDate, "errorreading"); + } +} + +std::string multiSlsDetector::exec(const char *cmd) { + int bufsize = 128; + char buffer[bufsize]; + std::string result = ""; + FILE *pipe = popen(cmd, "r"); + if (!pipe) { + throw RuntimeError("Could not open pipe"); + } + try { + while (!feof(pipe)) { + if (fgets(buffer, bufsize, pipe) != nullptr) { + result += buffer; + } + } + } catch (...) { + pclose(pipe); + throw; + } + pclose(pipe); + result.erase(result.find_last_not_of(" \t\n\r") + 1); + return result; +} + +void multiSlsDetector::setHostname(const char *name, int detPos) { + // single + if (detPos >= 0) { + detectors[detPos]->setHostname(name); + return; + } + + // multi + // this check is there only to allow the previous detsizechan command + if (multi_shm()->numberOfDetectors) { + FILE_LOG(logWARNING) << "There are already detector(s) in shared memory." + "Freeing Shared memory now."; + freeSharedMemory(); + setupMultiDetector(); + } + addMultipleDetectors(name); +} + +std::string multiSlsDetector::getHostname(int detPos) const { + // single + if (detPos >= 0) { + return detectors[detPos]->getHostname(); + } + + // multi + auto r = serialCall(&slsDetector::getHostname); + return sls::concatenateIfDifferent(r); +} + +void multiSlsDetector::addMultipleDetectors(const char *name) { + for (const auto &hostname : sls::split(name, '+')) { + addSlsDetector(hostname); + } + + setOnline(); + updateOffsets(); +} + +void multiSlsDetector::addSlsDetector(const std::string &hostname) { + FILE_LOG(logDEBUG1) << "Adding detector " << hostname; + + for (auto &d : detectors) { + if (d->getHostname() == hostname) { + FILE_LOG(logWARNING) << "Detector " << hostname << "already part of the multiDetector!" + << std::endl + << "Remove it before adding it back in a new position!"; + return; + } + } + + // get type by connecting + detectorType type = slsDetector::getTypeFromDetector(hostname.c_str(), DEFAULT_PORTNO); + int pos = (int)detectors.size(); + detectors.push_back(sls::make_unique(type, multiId, pos, false)); + multi_shm()->numberOfDetectors = detectors.size(); + multi_shm()->dataBytes += detectors[pos]->getDataBytes(); + multi_shm()->dataBytesInclGapPixels += detectors[pos]->getDataBytesInclGapPixels(); + multi_shm()->numberOfChannels += detectors[pos]->getTotalNumberOfChannels(); + + detectors[pos]->setHostname(hostname); + detectors[pos]->setOnline(true); +} + +void multiSlsDetector::addSlsDetector(std::unique_ptr det){ + detectors.push_back(std::move(det)); + multi_shm()->numberOfDetectors = detectors.size(); + multi_shm()->dataBytes += detectors.back()->getDataBytes(); + multi_shm()->dataBytesInclGapPixels += + detectors.back()->getDataBytesInclGapPixels(); + multi_shm()->numberOfChannels += detectors.back()->getTotalNumberOfChannels(); +} + +slsDetectorDefs::detectorType multiSlsDetector::getDetectorTypeAsEnum(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getDetectorTypeAsEnum(); + } + + // multi + auto r = serialCall(&slsDetector::getDetectorTypeAsEnum); + return (detectorType)sls::minusOneIfDifferent(r); +} + +std::string multiSlsDetector::getDetectorTypeAsString(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getDetectorTypeAsString(); + } + + // multi + auto r = serialCall(&slsDetector::getDetectorTypeAsString); + return sls::concatenateIfDifferent(r); +} + +int multiSlsDetector::getNumberOfDetectors() const { return detectors.size(); } + +int multiSlsDetector::getNumberOfDetectors(dimension d) const { + return multi_shm()->numberOfDetector[d]; +} + +void multiSlsDetector::getNumberOfDetectors(int &nx, int &ny) const { + nx = multi_shm()->numberOfDetector[X]; + ny = multi_shm()->numberOfDetector[Y]; +} + +int multiSlsDetector::getTotalNumberOfChannels(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getTotalNumberOfChannels(); + } + + // multi + return multi_shm()->numberOfChannels; +} + +int multiSlsDetector::getTotalNumberOfChannels(dimension d, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getTotalNumberOfChannels(d); + } + + // multi + return multi_shm()->numberOfChannel[d]; +} + +int multiSlsDetector::getTotalNumberOfChannelsInclGapPixels(dimension d, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getTotalNumberOfChannelsInclGapPixels(d); + } + + // multi + return multi_shm()->numberOfChannelInclGapPixels[d]; +} + +int multiSlsDetector::getMaxNumberOfChannelsPerDetector(dimension d) { + return multi_shm()->maxNumberOfChannelsPerDetector[d]; +} + +int multiSlsDetector::setMaxNumberOfChannelsPerDetector(dimension d, int i) { + multi_shm()->maxNumberOfChannelsPerDetector[d] = i; + return multi_shm()->maxNumberOfChannelsPerDetector[d]; +} + +int multiSlsDetector::getDetectorOffset(dimension d, int detPos) { + return detectors[detPos]->getDetectorOffset(d); +} + +void multiSlsDetector::setDetectorOffset(dimension d, int off, int detPos) { + detectors[detPos]->setDetectorOffset(d, off); +} + +void multiSlsDetector::updateOffsets() { + FILE_LOG(logDEBUG1) << "Updating Multi-Detector Offsets"; + + int offsetX = 0, offsetY = 0, numX = 0, numY = 0; + int maxChanX = multi_shm()->maxNumberOfChannelsPerDetector[X]; + int maxChanY = multi_shm()->maxNumberOfChannelsPerDetector[Y]; + int prevChanX = 0; + int prevChanY = 0; + bool firstTime = true; + + multi_shm()->numberOfChannel[X] = 0; + multi_shm()->numberOfChannel[Y] = 0; + multi_shm()->numberOfDetector[X] = 0; + multi_shm()->numberOfDetector[Y] = 0; + + // gap pixels + int offsetX_gp = 0, offsetY_gp = 0, numX_gp = 0, numY_gp = 0; + int prevChanX_gp = 0, prevChanY_gp = 0; + multi_shm()->numberOfChannelInclGapPixels[X] = 0; + multi_shm()->numberOfChannelInclGapPixels[Y] = 0; + + for (size_t idet = 0; idet < detectors.size(); ++idet) { + FILE_LOG(logDEBUG1) << "offsetX:" << offsetX << " prevChanX:" << prevChanX + << " offsetY:" << offsetY << " prevChanY:" << prevChanY + << " offsetX_gp:" << offsetX_gp << " prevChanX_gp:" << prevChanX_gp + << " offsetY_gp:" << offsetY_gp << " prevChanY_gp:" << prevChanY_gp; + + // incrementing in both direction + if (firstTime) { + // incrementing in both directions + firstTime = false; + if ((maxChanX > 0) && + ((offsetX + detectors[idet]->getTotalNumberOfChannels(X)) > maxChanX)) { + FILE_LOG(logWARNING) << "\nDetector[" << idet + << "] exceeds maximum channels " + "allowed for complete detector set in X dimension!"; + } + if ((maxChanY > 0) && + ((offsetY + detectors[idet]->getTotalNumberOfChannels(Y)) > maxChanY)) { + FILE_LOG(logERROR) << "\nDetector[" << idet + << "] exceeds maximum channels " + "allowed for complete detector set in Y dimension!"; + } + prevChanX = detectors[idet]->getTotalNumberOfChannels(X); + prevChanY = detectors[idet]->getTotalNumberOfChannels(Y); + prevChanX_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); + prevChanY_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); + numX += detectors[idet]->getTotalNumberOfChannels(X); + numY += detectors[idet]->getTotalNumberOfChannels(Y); + numX_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); + numY_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); + ++multi_shm()->numberOfDetector[X]; + ++multi_shm()->numberOfDetector[Y]; + FILE_LOG(logDEBUG1) << "incrementing in both direction"; + } + + // incrementing in y direction + else if ((maxChanY == -1) || + ((maxChanY > 0) && ((offsetY + prevChanY + + detectors[idet]->getTotalNumberOfChannels(Y)) <= maxChanY))) { + offsetY += prevChanY; + offsetY_gp += prevChanY_gp; + prevChanY = detectors[idet]->getTotalNumberOfChannels(Y); + prevChanY_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); + numY += detectors[idet]->getTotalNumberOfChannels(Y); + numY_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); + // increment in y again only in the first column (else you double increment) + if (multi_shm()->numberOfDetector[X] == 1) + ++multi_shm()->numberOfDetector[Y]; + FILE_LOG(logDEBUG1) << "incrementing in y direction"; + } + + // incrementing in x direction + else { + if ((maxChanX > 0) && + ((offsetX + prevChanX + detectors[idet]->getTotalNumberOfChannels(X)) > maxChanX)) { + FILE_LOG(logDEBUG1) << "\nDetector[" << idet + << "] exceeds maximum channels " + "allowed for complete detector set in X dimension!"; + } + offsetY = 0; + offsetY_gp = 0; + prevChanY = detectors[idet]->getTotalNumberOfChannels(Y); + prevChanY_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y); + numY = 0; // assuming symmetry with this statement. + // whats on 1st column should be on 2nd column + numY_gp = 0; + offsetX += prevChanX; + offsetX_gp += prevChanX_gp; + prevChanX = detectors[idet]->getTotalNumberOfChannels(X); + prevChanX_gp = detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); + numX += detectors[idet]->getTotalNumberOfChannels(X); + numX_gp += detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X); + ++multi_shm()->numberOfDetector[X]; + FILE_LOG(logDEBUG1) << "incrementing in x direction"; + } + + double bytesperchannel = (double)detectors[idet]->getDataBytes() / + (double)(detectors[idet]->getTotalNumberOfChannels(X) * + detectors[idet]->getTotalNumberOfChannels(Y)); + detectors[idet]->setDetectorOffset(X, (bytesperchannel >= 1.0) ? offsetX_gp : offsetX); + detectors[idet]->setDetectorOffset(Y, (bytesperchannel >= 1.0) ? offsetY_gp : offsetY); + + FILE_LOG(logDEBUG1) << "Detector[" << idet << "] has offsets (" + << detectors[idet]->getDetectorOffset(X) << ", " + << detectors[idet]->getDetectorOffset(Y) << ")"; + // offsetY has been reset sometimes and offsetX the first time, + // but remember the highest values + if (numX > multi_shm()->numberOfChannel[X]) { + multi_shm()->numberOfChannel[X] = numX; + } + if (numY > multi_shm()->numberOfChannel[Y]) { + multi_shm()->numberOfChannel[Y] = numY; + } + if (numX_gp > multi_shm()->numberOfChannelInclGapPixels[X]) { + multi_shm()->numberOfChannelInclGapPixels[X] = numX_gp; + } + if (numY_gp > multi_shm()->numberOfChannelInclGapPixels[Y]) { + multi_shm()->numberOfChannelInclGapPixels[Y] = numY_gp; + } + } + FILE_LOG(logDEBUG1) << "\n\tNumber of Channels in X direction:" + << multi_shm()->numberOfChannel[X] + << "\n\tNumber of Channels in Y direction:" + << multi_shm()->numberOfChannel[Y] + << "\n\tNumber of Channels in X direction with Gap Pixels:" + << multi_shm()->numberOfChannelInclGapPixels[X] + << "\n\tNumber of Channels in Y direction with Gap Pixels:" + << multi_shm()->numberOfChannelInclGapPixels[Y]; + + multi_shm()->numberOfChannels = + multi_shm()->numberOfChannel[0] * multi_shm()->numberOfChannel[1]; + + for (auto &d : detectors) { + d->updateMultiSize(multi_shm()->numberOfDetector[0], multi_shm()->numberOfDetector[1]); + } +} + +int multiSlsDetector::setOnline(int value, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setOnline(value); + } + + // multi + if (value != GET_ONLINE_FLAG) { + auto r = parallelCall(&slsDetector::setOnline, value); + multi_shm()->onlineFlag = sls::minusOneIfDifferent(r); + } + return multi_shm()->onlineFlag; +} + +std::string multiSlsDetector::checkOnline(int detPos) { + if (detPos >= 0) { + return detectors[detPos]->checkOnline(); + } + + auto r = parallelCall(&slsDetector::checkOnline); + return sls::concatenateNonEmptyStrings(r); +} + +int multiSlsDetector::setControlPort(int port_number, int detPos) { + if (detPos >= 0) { + return detectors[detPos]->setControlPort(port_number); + } + + auto r = serialCall(&slsDetector::setControlPort, port_number); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setStopPort(int port_number, int detPos) { + if (detPos >= 0) { + return detectors[detPos]->setStopPort(port_number); + } + + auto r = serialCall(&slsDetector::setStopPort, port_number); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setReceiverPort(int port_number, int detPos) { + if (detPos >= 0) { + return detectors[detPos]->setReceiverPort(port_number); + } + + auto r = serialCall(&slsDetector::setReceiverPort, port_number); + return sls::minusOneIfDifferent(r); +} + +std::vector multiSlsDetector::getReceiverPort() const { + return parallelCall(&slsDetector::getReceiverPort); +} + +int multiSlsDetector::lockServer(int p, int detPos) { + if (detPos >= 0) { + return detectors[detPos]->lockServer(p); + } + auto r = parallelCall(&slsDetector::lockServer, p); + return sls::minusOneIfDifferent(r); +} + +std::string multiSlsDetector::getLastClientIP(int detPos) { + if (detPos >= 0) { + return detectors[detPos]->getLastClientIP(); + } + auto r = parallelCall(&slsDetector::getLastClientIP); + return sls::concatenateIfDifferent(r); +} + +int multiSlsDetector::exitServer(int detPos) { + if (detPos >= 0) { + return detectors[detPos]->exitServer(); + } + auto r = parallelCall(&slsDetector::exitServer); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::execCommand(const std::string &cmd, int detPos) { + if (detPos >= 0) { + return detectors[detPos]->execCommand(cmd); + } + auto r = parallelCall(&slsDetector::execCommand, cmd); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +void multiSlsDetector::readConfigurationFile(const std::string &fname) { + freeSharedMemory(); + setupMultiDetector(); + FILE_LOG(logINFO) << "Loading configuration file: " << fname; + + std::ifstream input_file; + input_file.open(fname, std::ios_base::in); + if (!input_file.is_open()) { + throw RuntimeError("Could not open configuration file " + fname + " for reading"); + } + std::string current_line; + while (input_file.good()) { + getline(input_file, current_line); + if (current_line.find('#') != std::string::npos) { + current_line.erase(current_line.find('#')); + } + FILE_LOG(logDEBUG1) << "current_line after removing comments:\n\t" << current_line; + if (current_line.length() > 1) { + multiSlsDetectorClient(current_line, PUT_ACTION, this); + } + } + input_file.close(); +} + +int multiSlsDetector::writeConfigurationFile(const std::string &fname) { + // TODO! make exception safe! + const std::vector names = {"detsizechan", "hostname", "outdir", "threaded"}; + + int ret = OK, ret1 = OK; + std::ofstream outfile; + size_t iline = 0; + + outfile.open(fname.c_str(), std::ios_base::out); + if (outfile.is_open()) { + char *args[100]; + for (auto &arg : args) { + arg = new char[1000]; + } + + auto cmd = slsDetectorCommand(this); + + // complete size of detector + FILE_LOG(logINFO) << "Command to write: " << iline << " " << names[iline]; + strcpy(args[0], names[iline].c_str()); + outfile << names[iline] << " " << cmd.executeLine(1, args, GET_ACTION) << std::endl; + ++iline; + + // hostname of the detectors + FILE_LOG(logINFO) << "Command to write: " << iline << " " << names[iline]; + strcpy(args[0], names[iline].c_str()); + outfile << names[iline] << " " << cmd.executeLine(1, args, GET_ACTION) << std::endl; + ++iline; + + // single detector configuration + for (size_t idet = 0; idet < detectors.size(); ++idet) { + outfile << std::endl; + ret1 = detectors[idet]->writeConfigurationFile(outfile, this); + if (ret1 == FAIL) { + ret = FAIL; + } + } + + outfile << std::endl; + // other configurations + while (iline < names.size()) { + FILE_LOG(logINFO) << "Command to write:" << iline << " " << names[iline]; + strcpy(args[0], names[iline].c_str()); + outfile << names[iline] << " " << cmd.executeLine(1, args, GET_ACTION) << std::endl; + ++iline; + } + outfile.close(); + FILE_LOG(logDEBUG1) << "wrote " << iline << " lines to configuration file "; + for (auto &arg : args) { + delete[] arg; + } + } else { + throw RuntimeError("Could not open configuration file " + fname + " for writing"); + } + return ret; +} + +slsDetectorDefs::detectorSettings multiSlsDetector::getSettings(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getSettings(); + } + + // multi + auto r = parallelCall(&slsDetector::getSettings); + return (detectorSettings)sls::minusOneIfDifferent(r); +} + +slsDetectorDefs::detectorSettings multiSlsDetector::setSettings(detectorSettings isettings, + int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setSettings(isettings); + } + + // multi + auto r = parallelCall(&slsDetector::setSettings, isettings); + return (detectorSettings)sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::getThresholdEnergy(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getThresholdEnergy(); + } + + // multi + auto r = parallelCall(&slsDetector::getThresholdEnergy); + if (sls::allEqualWithTol(r, 200)) { + return r.front(); + } + return -1; +} + +int multiSlsDetector::setThresholdEnergy(int e_eV, detectorSettings isettings, int tb, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setThresholdEnergy(e_eV, isettings, tb); + } + + // multi + auto r = parallelCall(&slsDetector::setThresholdEnergy, e_eV, isettings, tb); + if (sls::allEqualWithTol(r, 200)) { + return r.front(); + } + return -1; +} + +std::string multiSlsDetector::getSettingsDir(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getSettingsDir(); + } + + // multi + auto r = serialCall(&slsDetector::getSettingsDir); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::setSettingsDir(const std::string &directory, int detPos) { + if (detPos >= 0) { + return detectors[detPos]->setSettingsDir(directory); + } + + auto r = parallelCall(&slsDetector::setSettingsDir, directory); + return sls::concatenateIfDifferent(r); +} + +int multiSlsDetector::loadSettingsFile(const std::string &fname, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->loadSettingsFile(fname); + } + + // multi + auto r = parallelCall(&slsDetector::loadSettingsFile, fname); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::saveSettingsFile(const std::string &fname, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->saveSettingsFile(fname); + } + + // multi + auto r = parallelCall(&slsDetector::saveSettingsFile, fname); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +slsDetectorDefs::runStatus multiSlsDetector::getRunStatus(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getRunStatus(); + } + + // multi + auto r = parallelCall(&slsDetector::getRunStatus); + if (sls::allEqual(r)) { + return r.front(); + } + if (sls::anyEqualTo(r, ERROR)) { + return ERROR; + } + for (const auto &value : r) { + if (value != IDLE) { + return value; + } + } + return IDLE; +} + +int multiSlsDetector::prepareAcquisition(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->prepareAcquisition(); + } + + // multi + auto r = parallelCall(&slsDetector::prepareAcquisition); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::startAcquisition(int detPos) { + // single + if (detPos >= 0) { + if (detectors[detPos]->getDetectorTypeAsEnum() == EIGER) { + if (detectors[detPos]->prepareAcquisition() == FAIL) { + return FAIL; + } + } + return detectors[detPos]->startAcquisition(); + } + + // multi + if (getDetectorTypeAsEnum() == EIGER) { + if (prepareAcquisition() == FAIL) { + return FAIL; + } + } + auto r = parallelCall(&slsDetector::startAcquisition); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::stopAcquisition(int detPos) { + // locks to synchronize using client->receiver simultaneously (processing + // thread) + std::lock_guard lock(mg); + if (detPos >= 0) { + // if only 1 detector, set flag to stop current acquisition + if (detectors.size() == 1) { + multi_shm()->stoppedFlag = 1; + } + + return detectors[detPos]->stopAcquisition(); + } else { + multi_shm()->stoppedFlag = 1; + auto r = parallelCall(&slsDetector::stopAcquisition); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; + } +} + +int multiSlsDetector::sendSoftwareTrigger(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->sendSoftwareTrigger(); + } + + // multi + auto r = parallelCall(&slsDetector::sendSoftwareTrigger); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::startAndReadAll(int detPos) { + // single + if (detPos >= 0) { + if (detectors[detPos]->getDetectorTypeAsEnum() == EIGER) { + if (detectors[detPos]->prepareAcquisition() == FAIL) { + return FAIL; + } + } + return detectors[detPos]->startAndReadAll(); + } + + // multi + if (getDetectorTypeAsEnum() == EIGER) { + if (prepareAcquisition() == FAIL) { + return FAIL; + } + } + auto r = parallelCall(&slsDetector::startAndReadAll); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::startReadOut(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->startReadOut(); + } + + // multi + auto r = parallelCall(&slsDetector::startReadOut); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::readAll(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->readAll(); + } + + // multi + auto r = parallelCall(&slsDetector::readAll); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::configureMAC(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->configureMAC(); + } + + // multi + auto r = parallelCall(&slsDetector::configureMAC); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int64_t multiSlsDetector::setTimer(timerIndex index, int64_t t, int detPos) { + // single + if (detPos >= 0) { + // error for setting values individually + // FIXME: what else? and error code + if (t != -1) { + switch (index) { + case FRAME_NUMBER: + case CYCLES_NUMBER: + case STORAGE_CELL_NUMBER: + case MEASUREMENTS_NUMBER: + throw RuntimeError("Cannot set number of frames, cycles,storage cells or " + "measurements individually."); + default: + break; + } + } + return detectors[detPos]->setTimer(index, t); + } + + // multi + auto r = parallelCall(&slsDetector::setTimer, index, t); + int64_t ret = sls::minusOneIfDifferent(r); + + if (index == SAMPLES) { + setDynamicRange(); + } + + // set progress + if (t != -1) { + switch (index) { + case FRAME_NUMBER: + case CYCLES_NUMBER: + case STORAGE_CELL_NUMBER: + case MEASUREMENTS_NUMBER: + setTotalProgress(); + break; + default: + break; + } + } + + multi_shm()->timerValue[index] = ret; + return ret; +} + +double multiSlsDetector::setExposureTime(double t, bool inseconds, int detPos) { + if (!inseconds) { + return setTimer(ACQUISITION_TIME, (int64_t)t, detPos); + } + + // + 0.5 to round for precision lost from converting double to int64_t + int64_t tms = (int64_t)(t * (1E+9) + 0.5); + if (t < 0) { + tms = -1; + } + tms = setTimer(ACQUISITION_TIME, tms, detPos); + if (tms < 0) { + return -1; + } + return ((1E-9) * (double)tms); +} + +double multiSlsDetector::setExposurePeriod(double t, bool inseconds, int detPos) { + if (!inseconds) { + return setTimer(FRAME_PERIOD, (int64_t)t, detPos); + } + + // + 0.5 to round for precision lost from converting double to int64_t + int64_t tms = (int64_t)(t * (1E+9) + 0.5); + if (t < 0) { + tms = -1; + } + tms = setTimer(FRAME_PERIOD, tms, detPos); + if (tms < 0) { + return -1; + } + return ((1E-9) * (double)tms); +} + +double multiSlsDetector::setDelayAfterTrigger(double t, bool inseconds, int detPos) { + if (!inseconds) { + return setTimer(DELAY_AFTER_TRIGGER, (int64_t)t, detPos); + } + + // + 0.5 to round for precision lost from converting double to int64_t + int64_t tms = (int64_t)(t * (1E+9) + 0.5); + if (t < 0) { + tms = -1; + } + tms = setTimer(DELAY_AFTER_TRIGGER, tms, detPos); + if (tms < 0) { + return -1; + } + return ((1E-9) * (double)tms); +} + +double multiSlsDetector::setSubFrameExposureTime(double t, bool inseconds, int detPos) { + if (!inseconds) { + return setTimer(SUBFRAME_ACQUISITION_TIME, (int64_t)t, detPos); + } else { + // + 0.5 to round for precision lost from converting double to int64_t + int64_t tms = (int64_t)(t * (1E+9) + 0.5); + if (t < 0) { + tms = -1; + } + tms = setTimer(SUBFRAME_ACQUISITION_TIME, tms, detPos); + if (tms < 0) { + return -1; + } + return ((1E-9) * (double)tms); + } +} + +double multiSlsDetector::setSubFrameExposureDeadTime(double t, bool inseconds, int detPos) { + if (!inseconds) { + return setTimer(SUBFRAME_DEADTIME, (int64_t)t, detPos); + } else { + // + 0.5 to round for precision lost from converting double to int64_t + int64_t tms = (int64_t)(t * (1E+9) + 0.5); + if (t < 0) { + tms = -1; + } + tms = setTimer(SUBFRAME_DEADTIME, tms, detPos); + if (tms < 0) { + return -1; + } + return ((1E-9) * (double)tms); + } +} + +int64_t multiSlsDetector::setNumberOfFrames(int64_t t, int detPos) { + return setTimer(FRAME_NUMBER, t, detPos); +} + +int64_t multiSlsDetector::setNumberOfCycles(int64_t t, int detPos) { + return setTimer(CYCLES_NUMBER, t, detPos); +} + +int64_t multiSlsDetector::setNumberOfGates(int64_t t, int detPos) { + return setTimer(GATES_NUMBER, t, detPos); +} + +int64_t multiSlsDetector::setNumberOfStorageCells(int64_t t, int detPos) { + return setTimer(STORAGE_CELL_NUMBER, t, detPos); +} + +double multiSlsDetector::getMeasuredPeriod(bool inseconds, int detPos) { + if (!inseconds) { + return getTimeLeft(MEASURED_PERIOD, detPos); + } else { + int64_t tms = getTimeLeft(MEASURED_PERIOD, detPos); + if (tms < 0) { + return -1; + } + return ((1E-9) * (double)tms); + } +} + +double multiSlsDetector::getMeasuredSubFramePeriod(bool inseconds, int detPos) { + if (!inseconds) { + return getTimeLeft(MEASURED_SUBPERIOD, detPos); + } else { + int64_t tms = getTimeLeft(MEASURED_SUBPERIOD, detPos); + if (tms < 0) { + return -1; + } + return ((1E-9) * (double)tms); + } +} + +int64_t multiSlsDetector::getTimeLeft(timerIndex index, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getTimeLeft(index); + } + + // multi + auto r = parallelCall(&slsDetector::getTimeLeft, index); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setSpeed(speedVariable index, int value, int mode, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setSpeed(index, value, mode); + } + + // multi + auto r = parallelCall(&slsDetector::setSpeed, index, value, mode); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setDynamicRange(int dr, int detPos) { + // single + if (detPos >= 0) { + throw RuntimeError("Dynamic Range cannot be set individually"); + } + + // multi + auto r = parallelCall(&slsDetector::setDynamicRange, dr); + int ret = sls::minusOneIfDifferent(r); + + // update shm + int prevValue = multi_shm()->dataBytes; + int prevGValue = multi_shm()->dataBytesInclGapPixels; + multi_shm()->dataBytes = 0; + multi_shm()->dataBytesInclGapPixels = 0; + multi_shm()->numberOfChannels = 0; + for (auto &d : detectors) { + multi_shm()->dataBytes += d->getDataBytes(); + multi_shm()->dataBytesInclGapPixels += d->getDataBytesInclGapPixels(); + multi_shm()->numberOfChannels += d->getTotalNumberOfChannels(); + } + + // for usability + if (getDetectorTypeAsEnum() == EIGER) { + switch (dr) { + case 32: + FILE_LOG(logINFO) << "Setting Clock to Quarter Speed to cope with " + "Dynamic Range of 32"; + setSpeed(CLOCK_DIVIDER, 2); + break; + case 16: + FILE_LOG(logINFO) << "Setting Clock to Half Speed for Dynamic Range of 16"; + setSpeed(CLOCK_DIVIDER, 1); + break; + default: + break; + } + } + + // update offsets if there was a change FIXME:add dr to sls shm and check + // that instead + if ((prevValue != multi_shm()->dataBytes) || + (prevGValue != multi_shm()->dataBytesInclGapPixels)) { + updateOffsets(); + } + + return ret; +} + +int multiSlsDetector::getDataBytes(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getDataBytes(); + } + + // multi + auto r = parallelCall(&slsDetector::getDataBytes); + return sls::sum(r); +} + +int multiSlsDetector::setDAC(int val, dacIndex index, int mV, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setDAC(val, index, mV); + } + + // multi + auto r = parallelCall(&slsDetector::setDAC, val, index, mV); + if (getDetectorTypeAsEnum() != EIGER && index != HIGH_VOLTAGE) { + return sls::minusOneIfDifferent(r); + } + + // ignore slave values for hv (-999) + int firstValue = r.front(); + for (const auto &value : r) { + if ((value != -999) && (value != firstValue)) { + return -1; + } + } + + return firstValue; +} + +int multiSlsDetector::getADC(dacIndex index, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getADC(index); + } + + // multi + auto r = parallelCall(&slsDetector::getADC, index); + return sls::minusOneIfDifferent(r); +} + +slsDetectorDefs::externalCommunicationMode +multiSlsDetector::setExternalCommunicationMode(externalCommunicationMode pol, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setExternalCommunicationMode(pol); + } + + // multi + auto r = parallelCall(&slsDetector::setExternalCommunicationMode, pol); + return sls::minusOneIfDifferent(r); +} + +slsDetectorDefs::externalSignalFlag +multiSlsDetector::setExternalSignalFlags(externalSignalFlag pol, int signalindex, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setExternalSignalFlags(pol, signalindex); + } + + // multi + auto r = parallelCall(&slsDetector::setExternalSignalFlags, pol, signalindex); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setReadOutFlags(readOutFlags flag, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReadOutFlags(flag); + } + + // multi + auto r = parallelCall(&slsDetector::setReadOutFlags, flag); + return sls::minusOneIfDifferent(r); +} + +uint32_t multiSlsDetector::writeRegister(uint32_t addr, uint32_t val, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->writeRegister(addr, val); + } + + // multi + auto r = parallelCall(&slsDetector::writeRegister, addr, val); + if (sls::allEqual(r)) { + return r.front(); + } + + // can't have different values + std::ostringstream ss; + ss << "Error: Different Values for function writeRegister (write 0x" << std::hex << val + << " to addr 0x" << std::hex << addr << std::dec << ")"; + throw RuntimeError(ss.str()); +} + +uint32_t multiSlsDetector::readRegister(uint32_t addr, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->readRegister(addr); + } + + // multi + auto r = parallelCall(&slsDetector::readRegister, addr); + if (sls::allEqual(r)) { + return r.front(); + } + + // can't have different values + std::ostringstream ss; + ss << "Error: Different Values for function readRegister (read from 0x" << std::hex << addr + << std::dec << ")"; + throw RuntimeError(ss.str()); +} + +uint32_t multiSlsDetector::setBit(uint32_t addr, int n, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setBit(addr, n); + } + + // multi + auto r = parallelCall(&slsDetector::setBit, addr, n); + if (sls::allEqual(r)) { + return r.front(); + } + + // can't have different values + std::ostringstream ss; + ss << "Error: Different Values for function setBit " + "(set bit " + << n << " to addr 0x" << std::hex << addr << std::dec << ")"; + throw RuntimeError(ss.str()); +} + +uint32_t multiSlsDetector::clearBit(uint32_t addr, int n, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->clearBit(addr, n); + } + + // multi + auto r = parallelCall(&slsDetector::clearBit, addr, n); + if (sls::allEqual(r)) { + return r.front(); + } + + // can't have different values + std::ostringstream ss; + ss << "Error: Different Values for function clearBit (clear bit " << n << " to addr 0x" + << std::hex << addr << std::dec << ")"; + throw RuntimeError(ss.str()); +} + +std::string multiSlsDetector::setDetectorMAC(const std::string &detectorMAC, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setDetectorMAC(detectorMAC); + } + + // multi + auto r = parallelCall(&slsDetector::setDetectorMAC, detectorMAC); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::getDetectorMAC(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getDetectorMAC().str(); + } + + // multi + auto r = serialCall(&slsDetector::getDetectorMAC); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::setDetectorMAC2(const std::string &detectorMAC, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setDetectorMAC2(detectorMAC); + } + + // multi + auto r = parallelCall(&slsDetector::setDetectorMAC2, detectorMAC); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::getDetectorMAC2(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getDetectorMAC2().str(); + } + + // multi + auto r = serialCall(&slsDetector::getDetectorMAC2); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::setDetectorIP(const std::string &detectorIP, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setDetectorIP(detectorIP); + } + + // multi + auto r = parallelCall(&slsDetector::setDetectorIP, detectorIP); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::getDetectorIP(int detPos) const { + // single + if (detPos >= 0) { + return detectors[detPos]->getDetectorIP().str(); + } + + // multi + auto r = serialCall(&slsDetector::getDetectorIP); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::setDetectorIP2(const std::string &detectorIP, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setDetectorIP2(detectorIP); + } + + // multi + auto r = parallelCall(&slsDetector::setDetectorIP2, detectorIP); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::getDetectorIP2(int detPos) const { + // single + if (detPos >= 0) { + return detectors[detPos]->getDetectorIP2().str(); + } + + // multi + auto r = serialCall(&slsDetector::getDetectorIP2); + return sls::concatenateIfDifferent(r); +} + + +std::string multiSlsDetector::setReceiverHostname(const std::string &receiver, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverHostname(receiver); + } + + // multi + auto r = parallelCall(&slsDetector::setReceiverHostname, receiver); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::getReceiverHostname(int detPos) const { + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverHostname(); + } + + // multi + auto r = parallelCall(&slsDetector::getReceiverHostname); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::setReceiverUDPIP(const std::string &udpip, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverUDPIP(udpip); + } + + // multi + auto r = parallelCall(&slsDetector::setReceiverUDPIP, udpip); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::getReceiverUDPIP(int detPos) const { + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverUDPIP().str(); + } + + // multi + auto r = serialCall(&slsDetector::getReceiverUDPIP); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::setReceiverUDPIP2(const std::string &udpip, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverUDPIP2(udpip); + } + + // multi + auto r = parallelCall(&slsDetector::setReceiverUDPIP2, udpip); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::getReceiverUDPIP2(int detPos) const { + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverUDPIP2().str(); + } + + // multi + auto r = serialCall(&slsDetector::getReceiverUDPIP2); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::setReceiverUDPMAC(const std::string &udpmac, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverUDPMAC(udpmac); + } + + // multi + auto r = parallelCall(&slsDetector::setReceiverUDPMAC, udpmac); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::getReceiverUDPMAC(int detPos) const { + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverUDPMAC().str(); + } + + // multi + auto r = serialCall(&slsDetector::getReceiverUDPMAC); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::setReceiverUDPMAC2(const std::string &udpmac, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverUDPMAC2(udpmac); + } + + // multi + auto r = parallelCall(&slsDetector::setReceiverUDPMAC2, udpmac); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::getReceiverUDPMAC2(int detPos) const { + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverUDPMAC2().str(); + } + + // multi + auto r = serialCall(&slsDetector::getReceiverUDPMAC2); + return sls::concatenateIfDifferent(r); +} + +int multiSlsDetector::setReceiverUDPPort(int udpport, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverUDPPort(udpport); + } + + // multi + auto r = parallelCall(&slsDetector::setReceiverUDPPort, udpport); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::getReceiverUDPPort(int detPos) const { + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverUDPPort(); + } + + // multi + auto r = serialCall(&slsDetector::getReceiverUDPPort); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setReceiverUDPPort2(int udpport, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverUDPPort2(udpport); + } + + // multi + auto r = parallelCall(&slsDetector::setReceiverUDPPort2, udpport); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::getReceiverUDPPort2(int detPos) const { + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverUDPPort2(); + } + + // multi + auto r = serialCall(&slsDetector::getReceiverUDPPort2); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setNumberofUDPInterfaces(int n, int detPos) { + + int previouslyClientStreaming = enableDataStreamingToClient(); + int previouslyReceiverStreaming = enableDataStreamingFromReceiver(); + + // single + int ret = OK; + if (detPos >= 0) { + ret = detectors[detPos]->setNumberofUDPInterfaces(n); + } + + // multi + auto r = parallelCall(&slsDetector::setNumberofUDPInterfaces,n); + + // redo the zmq sockets + if (previouslyClientStreaming) { + enableDataStreamingToClient(0); + enableDataStreamingToClient(1); + } + if (previouslyReceiverStreaming) { + enableDataStreamingFromReceiver(0); + enableDataStreamingFromReceiver(1); + } + + // return single + if (detPos >= 0) + return ret; + + // return multi + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::getNumberofUDPInterfaces(int detPos) const { + // single + if (detPos >= 0) { + return detectors[detPos]->getNumberofUDPInterfaces(); + } + + // multi + auto r = serialCall(&slsDetector::getNumberofUDPInterfaces); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::selectUDPInterface(int n, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->selectUDPInterface(n); + } + + // multi + auto r = parallelCall(&slsDetector::selectUDPInterface,n); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::getSelectedUDPInterface(int detPos) const { + // single + if (detPos >= 0) { + return detectors[detPos]->getSelectedUDPInterface(); + } + + // multi + auto r = serialCall(&slsDetector::getSelectedUDPInterface); + return sls::minusOneIfDifferent(r); +} + +void multiSlsDetector::setClientDataStreamingInPort(int i, int detPos) { + if (i >= 0) { + int prev_streaming = enableDataStreamingToClient(); + + // single + if (detPos >= 0) { + detectors[detPos]->setClientStreamingPort(i); + } + // multi + else { + // calculate ports individually + int firstPort = i; + int numSockets = (getDetectorTypeAsEnum() == EIGER) ? 2 : 1; + if (getNumberofUDPInterfaces() == 2) + numSockets *= 2; + + for (size_t idet = 0; idet < detectors.size(); ++idet) { + auto port = firstPort + (idet * numSockets); + detectors[idet]->setClientStreamingPort(port); + } + } + + if (prev_streaming) { + enableDataStreamingToClient(0); + enableDataStreamingToClient(1); + } + } +} + +int multiSlsDetector::getClientStreamingPort(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getClientStreamingPort(); + } + + // multi + auto r = serialCall(&slsDetector::getClientStreamingPort); + return sls::minusOneIfDifferent(r); +} + +void multiSlsDetector::setReceiverDataStreamingOutPort(int i, int detPos) { + if (i >= 0) { + int prev_streaming = enableDataStreamingFromReceiver(-1, detPos); + + // single + if (detPos >= 0) { + detectors[detPos]->setReceiverStreamingPort(i); + } + // multi + else { + // calculate ports individually + int firstPort = i; + int numSockets = (getDetectorTypeAsEnum() == EIGER) ? 2 : 1; + if (getNumberofUDPInterfaces() == 2) + numSockets *= 2; + + for (size_t idet = 0; idet < detectors.size(); ++idet) { + auto port = firstPort + (idet * numSockets); + detectors[idet]->setReceiverStreamingPort(port); + } + } + + if (prev_streaming) { + enableDataStreamingFromReceiver(0, detPos); + enableDataStreamingFromReceiver(1, detPos); + } + } +} + +int multiSlsDetector::getReceiverStreamingPort(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverStreamingPort(); + } + + // multi + auto r = serialCall(&slsDetector::getReceiverStreamingPort); + return sls::minusOneIfDifferent(r); +} + +void multiSlsDetector::setClientDataStreamingInIP(const std::string &ip, int detPos) { + if (ip.length()) { + int prev_streaming = enableDataStreamingToClient(-1); + + // single + if (detPos >= 0) { + detectors[detPos]->setClientStreamingIP(ip); + } + // multi + else { + for (auto &d : detectors) { + d->setClientStreamingIP(ip); + } + } + + if (prev_streaming) { + enableDataStreamingToClient(0); + enableDataStreamingToClient(1); + } + } +} + +std::string multiSlsDetector::getClientStreamingIP(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getClientStreamingIP(); + } + + // multi + auto r = serialCall(&slsDetector::getClientStreamingIP); + return sls::concatenateIfDifferent(r); +} + +void multiSlsDetector::setReceiverDataStreamingOutIP(const std::string &ip, int detPos) { + if (ip.length()) { + int prev_streaming = enableDataStreamingFromReceiver(-1, detPos); + + // single + if (detPos >= 0) { + detectors[detPos]->setReceiverStreamingIP(ip); + } + // multi + else { + for (auto &d : detectors) { + d->setReceiverStreamingIP(ip); + } + } + + if (prev_streaming) { + enableDataStreamingFromReceiver(0, detPos); + enableDataStreamingFromReceiver(1, detPos); + } + } +} + +std::string multiSlsDetector::getReceiverStreamingIP(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverStreamingIP(); + } + + // multi + auto r = serialCall(&slsDetector::getReceiverStreamingIP); + return sls::concatenateIfDifferent(r); +} + +int multiSlsDetector::setDetectorNetworkParameter(networkParameter index, int value, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setDetectorNetworkParameter(index, value); + } + + // multi + auto r = parallelCall(&slsDetector::setDetectorNetworkParameter, index, value); + return sls::minusOneIfDifferent(r); +} + +std::string multiSlsDetector::setAdditionalJsonHeader(const std::string &jsonheader, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setAdditionalJsonHeader(jsonheader); + } + + // multi + auto r = parallelCall(&slsDetector::setAdditionalJsonHeader, jsonheader); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::getAdditionalJsonHeader(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getAdditionalJsonHeader(); + } + + // multi + auto r = serialCall(&slsDetector::getAdditionalJsonHeader); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::setAdditionalJsonParameter(const std::string &key, + const std::string &value, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setAdditionalJsonParameter(key, value); + } + + // multi + auto r = parallelCall(&slsDetector::setAdditionalJsonParameter, key, value); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::getAdditionalJsonParameter(const std::string &key, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getAdditionalJsonParameter(key); + } + + // multi + auto r = serialCall(&slsDetector::getAdditionalJsonParameter, key); + return sls::concatenateIfDifferent(r); +} + +int multiSlsDetector::setDetectorMinMaxEnergyThreshold(const int index, int value, int detPos) { + std::string parameter = (index ? "emax" : "emin"); + + std::string result; + if (value < 0) { + result = getAdditionalJsonParameter(parameter, detPos); + } else { + result = setAdditionalJsonParameter(parameter, std::to_string(value), detPos); + } + + // convert to integer + try { + return stoi(result); + } + // not found or cannot scan integer + catch (...) { + return -1; + } +} + +int multiSlsDetector::setFrameMode(frameModeType value, int detPos) { + std::string parameter = "frameMode"; + std::string result; + + if (value == GET_FRAME_MODE) { + result = getAdditionalJsonParameter(parameter, detPos); + } else { + result = setAdditionalJsonParameter(parameter, getFrameModeType(value), detPos); + } + + return getFrameModeType(result); +} + +int multiSlsDetector::setDetectorMode(detectorModeType value, int detPos) { + std::string parameter = "detectorMode"; + std::string result; + + if (value == GET_DETECTOR_MODE) { + result = getAdditionalJsonParameter(parameter, detPos); + } else { + result = setAdditionalJsonParameter(parameter, getDetectorModeType(value), detPos); + } + + return getDetectorModeType(result); +} + +int64_t multiSlsDetector::setReceiverUDPSocketBufferSize(int64_t udpsockbufsize, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverUDPSocketBufferSize(udpsockbufsize); + } + + // multi + auto r = parallelCall(&slsDetector::setReceiverUDPSocketBufferSize, udpsockbufsize); + return sls::minusOneIfDifferent(r); +} + +int64_t multiSlsDetector::getReceiverUDPSocketBufferSize(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverUDPSocketBufferSize(); + } + + // multi + auto r = serialCall(&slsDetector::getReceiverUDPSocketBufferSize); + return sls::minusOneIfDifferent(r); +} + +int64_t multiSlsDetector::getReceiverRealUDPSocketBufferSize(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverRealUDPSocketBufferSize(); + } + + // multi + auto r = serialCall(&slsDetector::getReceiverRealUDPSocketBufferSize); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setFlowControl10G(int enable, int detPos) { + if (enable != -1) { + enable = ((enable >= 1) ? 1 : 0); + } + return setDetectorNetworkParameter(FLOW_CONTROL_10G, enable, detPos); +} + +int multiSlsDetector::digitalTest(digitalTestMode mode, int ival, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->digitalTest(mode, ival); + } + + // multi + auto r = parallelCall(&slsDetector::digitalTest, mode, ival); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::loadImageToDetector(imageType index, const std::string &fname, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->loadImageToDetector(index, fname); + } + + // multi + + // read image for all + int nch = multi_shm()->numberOfChannels; + short int imageVals[nch]; + if (readDataFile(fname, imageVals, nch) < nch * (int)sizeof(short int)) { + throw RuntimeError( + "Could not open file or not enough data in file to load image to detector."); + } + + // send image to all + std::vector r; + for (size_t idet = 0; idet < detectors.size(); ++idet) { + r.push_back(detectors[idet]->sendImageToDetector( + index, imageVals + idet * detectors[idet]->getTotalNumberOfChannels())); + } + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::writeCounterBlockFile(const std::string &fname, int startACQ, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->writeCounterBlockFile(fname, startACQ); + } + + // multi + + // get image from all + int nch = multi_shm()->numberOfChannels; + short int imageVals[nch]; + std::vector r; + for (size_t idet = 0; idet < detectors.size(); ++idet) { + r.push_back(detectors[idet]->getCounterBlock( + imageVals + idet * detectors[idet]->getTotalNumberOfChannels(), startACQ)); + } + + // write image if all ok + if (sls::allEqualTo(r, static_cast(OK))) { + if (writeDataFile(fname, nch, imageVals) < nch * (int)sizeof(short int)) { + throw RuntimeError("Could not open file to write or did not write enough data" + " in file to write counter block file from detector."); + } + return OK; + } + return FAIL; +} + +int multiSlsDetector::resetCounterBlock(int startACQ, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->resetCounterBlock(startACQ); + } + + // multi + auto r = parallelCall(&slsDetector::resetCounterBlock, startACQ); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::setCounterBit(int i, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setCounterBit(i); + } + + // multi + auto r = parallelCall(&slsDetector::setCounterBit, i); + return sls::minusOneIfDifferent(r); +} + +void multiSlsDetector::verifyMinMaxROI(int n, ROI r[]) { + int temp; + for (int i = 0; i < n; ++i) { + if ((r[i].xmax) < (r[i].xmin)) { + temp = r[i].xmax; + r[i].xmax = r[i].xmin; + r[i].xmin = temp; + } + if ((r[i].ymax) < (r[i].ymin)) { + temp = r[i].ymax; + r[i].ymax = r[i].ymin; + r[i].ymin = temp; + } + } +} + +int multiSlsDetector::setROI(int n, ROI roiLimits[], int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setROI(n, roiLimits); + } + + // multi + int xmin = 0, xmax = 0, ymin = 0, ymax = 0, channelX = 0, channelY = 0, idet = 0, + lastChannelX = 0, lastChannelY = 0, index = 0, offsetX = 0, offsetY = 0; + + bool invalidroi = false; + int ndet = detectors.size(); + ROI allroi[ndet][n]; + int nroi[ndet]; + for (int i = 0; i < ndet; ++i) { + nroi[i] = 0; + } + + if ((n < 0) || (roiLimits == nullptr)) { + return FAIL; + } + + // ensures min < max + verifyMinMaxROI(n, roiLimits); + FILE_LOG(logDEBUG1) << "Setting ROI for " << n << "rois:"; + for (int i = 0; i < n; ++i) { + FILE_LOG(logDEBUG1) << i << ":" << roiLimits[i].xmin << "\t" << roiLimits[i].xmax << "\t" + << roiLimits[i].ymin << "\t" << roiLimits[i].ymax; + } + // for each roi + for (int i = 0; i < n; ++i) { + xmin = roiLimits[i].xmin; + xmax = roiLimits[i].xmax; + ymin = roiLimits[i].ymin; + ymax = roiLimits[i].ymax; + + if (getNumberOfDetectors() > 1) { + // check roi max values + idet = decodeNChannel(xmax, ymax, channelX, channelY); + FILE_LOG(logDEBUG1) << "Decoded Channel max vals: " << std::endl + << "det:" << idet << "\t" << xmax << "\t" << ymax << "\t" + << channelX << "\t" << channelY; + if (idet == -1) { + FILE_LOG(logERROR) << "invalid roi"; + continue; + } + + // split in x dir + while (xmin <= xmax) { + invalidroi = false; + ymin = roiLimits[i].ymin; + // split in y dir + while (ymin <= ymax) { + // get offset for each detector + idet = decodeNChannel(xmin, ymin, channelX, channelY); + FILE_LOG(logDEBUG1) << "Decoded Channel min vals: " << std::endl + << "det:" << idet << "\t" << xmin << "\t" << ymin << "\t" + << channelX << "\t" << channelY; + if (idet < 0 || idet >= (int)detectors.size()) { + FILE_LOG(logDEBUG1) << "invalid roi"; + invalidroi = true; + break; + } + // get last channel for each det in x and y dir + lastChannelX = (detectors[idet]->getTotalNumberOfChannelsInclGapPixels(X)) - 1; + lastChannelY = (detectors[idet]->getTotalNumberOfChannelsInclGapPixels(Y)) - 1; + + offsetX = detectors[idet]->getDetectorOffset(X); + offsetY = detectors[idet]->getDetectorOffset(Y); + // at the end in x dir + if ((offsetX + lastChannelX) >= xmax) { + lastChannelX = xmax - offsetX; + } + // at the end in y dir + if ((offsetY + lastChannelY) >= ymax) { + lastChannelY = ymax - offsetY; + } + + FILE_LOG(logDEBUG1) << "lastChannelX:" << lastChannelX << "\t" + << "lastChannelY:" << lastChannelY; + + // creating the list of roi for corresponding detector + index = nroi[idet]; + allroi[idet][index].xmin = channelX; + allroi[idet][index].xmax = lastChannelX; + allroi[idet][index].ymin = channelY; + allroi[idet][index].ymax = lastChannelY; + nroi[idet] = nroi[idet] + 1; + + ymin = lastChannelY + offsetY + 1; + if ((lastChannelY + offsetY) == ymax) { + ymin = ymax + 1; + } + + FILE_LOG(logDEBUG1) << "nroi[idet]:" << nroi[idet] << "\tymin:" << ymin; + } + if (invalidroi) { + break; + } + + xmin = lastChannelX + offsetX + 1; + if ((lastChannelX + offsetX) == xmax) { + xmin = xmax + 1; + } + } + } else { // FIXME: check if xmax is greater? or reduce logic above? + idet = 0; + nroi[idet] = n; + index = 0; + allroi[idet][index].xmin = xmin; + allroi[idet][index].xmax = xmax; + allroi[idet][index].ymin = ymin; + allroi[idet][index].ymax = ymax; + // nroi[idet] = nroi[idet] + 1; + } + } + + FILE_LOG(logDEBUG1) << "Setting ROI :"; + for (size_t i = 0; i < detectors.size(); ++i) { + FILE_LOG(logDEBUG1) << "detector " << i; + for (int j = 0; j < nroi[i]; ++j) { + FILE_LOG(logDEBUG1) << allroi[i][j].xmin << "\t" << allroi[i][j].xmax << "\t" + << allroi[i][j].ymin << "\t" << allroi[i][j].ymax; + } + } + + // settings the rois for each detector + std::vector r; + r.reserve(detectors.size()); + for (size_t i = 0; i != detectors.size(); ++i) { + r.push_back(detectors[i]->setROI(nroi[i], allroi[i])); + } + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +const slsDetectorDefs::ROI *multiSlsDetector::getROI(int &n, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getROI(n); + } + + // multi + n = 0; + int num = 0; + int ndet = detectors.size(); + int maxroi = ndet * MAX_ROIS; + ROI temproi; + ROI roiLimits[maxroi]; + ROI *retval = new ROI[maxroi]; + const ROI *temp = nullptr; + int index = 0; + + // get each detector's roi array + for (size_t idet = 0; idet < detectors.size(); ++idet) { + temp = detectors[idet]->getROI(index); + if (temp) { + if (index) { + FILE_LOG(logINFO) << "detector " << idet << ":"; + } + for (int j = 0; j < index; ++j) { + FILE_LOG(logINFO) << temp[j].xmin << "\t" << temp[j].xmax << "\t" << temp[j].ymin + << "\t" << temp[j].ymax; + int x = detectors[idet]->getDetectorOffset(X); + int y = detectors[idet]->getDetectorOffset(Y); + roiLimits[n].xmin = temp[j].xmin + x; + roiLimits[n].xmax = temp[j].xmax + x; + roiLimits[n].ymin = temp[j].ymin + y; + roiLimits[n].ymax = temp[j].ymin + y; + ++n; + } + } + } + + // empty roi + if (!n) { + return nullptr; + } + + FILE_LOG(logDEBUG1) << "ROI :" << std::endl; + for (int j = 0; j < n; ++j) { + FILE_LOG(logDEBUG1) << roiLimits[j].xmin << "\t" << roiLimits[j].xmax << "\t" + << roiLimits[j].ymin << "\t" << roiLimits[j].ymax; + } + + // combine all the adjacent rois in x direction + for (int i = 0; i < n; ++i) { + // since the ones combined are replaced by -1 + if ((roiLimits[i].xmin) == -1) { + continue; + } + for (int j = i + 1; j < n; ++j) { + // since the ones combined are replaced by -1 + if ((roiLimits[j].xmin) == -1) { + continue; + } + // if y values are same + if (((roiLimits[i].ymin) == (roiLimits[j].ymin)) && + ((roiLimits[i].ymax) == (roiLimits[j].ymax))) { + // if adjacent, increase [i] range and replace all [j] with -1 + if ((roiLimits[i].xmax) + 1 == roiLimits[j].xmin) { + roiLimits[i].xmax = roiLimits[j].xmax; + roiLimits[j].xmin = -1; + roiLimits[j].xmax = -1; + roiLimits[j].ymin = -1; + roiLimits[j].ymax = -1; + } + // if adjacent, increase [i] range and replace all [j] with -1 + else if ((roiLimits[i].xmin) - 1 == roiLimits[j].xmax) { + roiLimits[i].xmin = roiLimits[j].xmin; + roiLimits[j].xmin = -1; + roiLimits[j].xmax = -1; + roiLimits[j].ymin = -1; + roiLimits[j].ymax = -1; + } + } + } + } + + FILE_LOG(logDEBUG1) << "Combined along x axis Getting ROI :\ndetector " << n; + for (int j = 0; j < n; ++j) { + FILE_LOG(logDEBUG1) << roiLimits[j].xmin << "\t" << roiLimits[j].xmax << "\t" + << roiLimits[j].ymin << "\t" << roiLimits[j].ymax; + } + + // combine all the adjacent rois in y direction + for (int i = 0; i < n; ++i) { + // since the ones combined are replaced by -1 + if ((roiLimits[i].ymin) == -1) { + continue; + } + for (int j = i + 1; j < n; ++j) { + // since the ones combined are replaced by -1 + if ((roiLimits[j].ymin) == -1) { + continue; + } + // if x values are same + if (((roiLimits[i].xmin) == (roiLimits[j].xmin)) && + ((roiLimits[i].xmax) == (roiLimits[j].xmax))) { + // if adjacent, increase [i] range and replace all [j] with -1 + if ((roiLimits[i].ymax) + 1 == roiLimits[j].ymin) { + roiLimits[i].ymax = roiLimits[j].ymax; + roiLimits[j].xmin = -1; + roiLimits[j].xmax = -1; + roiLimits[j].ymin = -1; + roiLimits[j].ymax = -1; + } + // if adjacent, increase [i] range and replace all [j] with -1 + else if ((roiLimits[i].ymin) - 1 == roiLimits[j].ymax) { + roiLimits[i].ymin = roiLimits[j].ymin; + roiLimits[j].xmin = -1; + roiLimits[j].xmax = -1; + roiLimits[j].ymin = -1; + roiLimits[j].ymax = -1; + } + } + } + } + + // get rid of -1s + for (int i = 0; i < n; ++i) { + if ((roiLimits[i].xmin) != -1) { + retval[num] = roiLimits[i]; + ++num; + } + } + // sort final roi + for (int i = 0; i < num; ++i) { + for (int j = i + 1; j < num; ++j) { + if (retval[j].xmin < retval[i].xmin) { + temproi = retval[i]; + retval[i] = retval[j]; + retval[j] = temproi; + } + } + } + n = num; + + FILE_LOG(logDEBUG1) << "\nxmin\txmax\tymin\tymax"; + for (int i = 0; i < n; ++i) { + FILE_LOG(logDEBUG1) << retval[i].xmin << "\t" << retval[i].xmax << "\t" << retval[i].ymin + << "\t" << retval[i].ymax; + } + return retval; +} + +int multiSlsDetector::writeAdcRegister(int addr, int val, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->writeAdcRegister(addr, val); + } + + // multi + auto r = parallelCall(&slsDetector::writeAdcRegister, addr, val); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::activate(int const enable, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->activate(enable); + } + + // multi + auto r = parallelCall(&slsDetector::activate, enable); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setDeactivatedRxrPaddingMode(int padding, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setDeactivatedRxrPaddingMode(padding); + } + + // multi + auto r = parallelCall(&slsDetector::setDeactivatedRxrPaddingMode, padding); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::getFlippedData(dimension d, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getFlippedData(d); + } + + // multi + auto r = serialCall(&slsDetector::getFlippedData, d); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setFlippedData(dimension d, int value, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setFlippedData(d, value); + } + + // multi + auto r = parallelCall(&slsDetector::setFlippedData, d, value); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setAllTrimbits(int val, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setAllTrimbits(val); + } + + // multi + auto r = parallelCall(&slsDetector::setAllTrimbits, val); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::enableGapPixels(int val, int detPos) { + if (getDetectorTypeAsEnum() != EIGER) { + if (val >= 0) { + throw NotImplementedError( + "Function (enableGapPixels) not implemented for this detector"); + } + return 0; + } + + // single + if (detPos >= 0) { + if (val >= 0) { + throw RuntimeError( + "Function (enableGapPixels) must be called from a multi detector level."); + } + return detectors[detPos]->enableGapPixels(val); + } + + // multi + auto r = parallelCall(&slsDetector::enableGapPixels, val); + int ret = sls::minusOneIfDifferent(r); + + // update data bytes incl gap pixels + if (val != -1) { + auto r2 = serialCall(&slsDetector::getDataBytesInclGapPixels); + multi_shm()->dataBytesInclGapPixels = sls::sum(r2); + + // update + updateOffsets(); + } + return ret; +} + +int multiSlsDetector::setTrimEn(std::vector energies, int detPos) { + if (detPos >= 0) { + return detectors[detPos]->setTrimEn(energies); + } + auto r = parallelCall(&slsDetector::setTrimEn, energies); + return sls::minusOneIfDifferent(r); +} + +std::vector multiSlsDetector::getTrimEn(int detPos) { + if (detPos >= 0) { + return detectors[detPos]->getTrimEn(); + } + auto r = parallelCall(&slsDetector::getTrimEn); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::pulsePixel(int n, int x, int y, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->pulsePixel(n, x, y); + } + + // multi + auto r = parallelCall(&slsDetector::pulsePixel, n, x, y); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::pulsePixelNMove(int n, int x, int y, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->pulsePixelNMove(n, x, y); + } + + // multi + auto r = parallelCall(&slsDetector::pulsePixelNMove, n, x, y); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::pulseChip(int n, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->pulseChip(n); + } + + // multi + auto r = parallelCall(&slsDetector::pulseChip, n); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::setThresholdTemperature(int val, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setThresholdTemperature(val); + } + + // multi + auto r = parallelCall(&slsDetector::setThresholdTemperature, val); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setTemperatureControl(int val, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setTemperatureControl(val); + } + + // multi + auto r = parallelCall(&slsDetector::setTemperatureControl, val); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setTemperatureEvent(int val, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setTemperatureEvent(val); + } + + // multi + auto r = parallelCall(&slsDetector::setTemperatureEvent, val); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setStoragecellStart(int pos, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setStoragecellStart(pos); + } + + // multi + auto r = parallelCall(&slsDetector::setStoragecellStart, pos); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::programFPGA(const std::string &fname, int detPos) { + FILE_LOG(logINFO) << "This can take awhile. Please be patient..."; + // read pof file + std::vector buffer = readPofFile(fname); + + // single + if (detPos >= 0) { + return detectors[detPos]->programFPGA(buffer); + } + + // multi + auto r = parallelCall(&slsDetector::programFPGA, buffer); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::resetFPGA(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->resetFPGA(); + } + + // multi + auto r = parallelCall(&slsDetector::resetFPGA); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::copyDetectorServer(const std::string &fname, const std::string &hostname, int detPos) { + // single + if (detPos >= 0) { + detectors[detPos]->copyDetectorServer(fname, hostname); + return detectors[detPos]->rebootController(); // reboot and copy should be independant for update command + } + + // multi + parallelCall(&slsDetector::copyDetectorServer,fname, hostname); + auto r = parallelCall(&slsDetector::rebootController); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::rebootController(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->rebootController(); + } + + // multi + auto r = parallelCall(&slsDetector::rebootController); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::update(const std::string &sname, const std::string &hostname, const std::string &fname, int detPos) { + FILE_LOG(logINFO) << "This can take awhile. Please be patient..."; + // read pof file + std::vector buffer = readPofFile(fname); + + // single + if (detPos >= 0) { + detectors[detPos]->copyDetectorServer(sname, hostname); + return detectors[detPos]->programFPGA(buffer); + } + + // multi + parallelCall(&slsDetector::copyDetectorServer,sname, hostname); + auto r = parallelCall(&slsDetector::programFPGA, buffer); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::powerChip(int ival, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->powerChip(ival); + } + + // multi + auto r = parallelCall(&slsDetector::powerChip, ival); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setAutoComparatorDisableMode(int ival, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setAutoComparatorDisableMode(ival); + } + + // multi + auto r = parallelCall(&slsDetector::setAutoComparatorDisableMode, ival); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::getChanRegs(double *retval, int detPos) { + + int offset = 0; + std::vector r; + for (auto &d : detectors) { + int nch = d->getTotalNumberOfChannels(); + double result[nch]; + r.push_back(d->getChanRegs(result)); + memcpy(retval + offset, result, nch * sizeof(double)); + } + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setRateCorrection(int64_t t, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setRateCorrection(t); + } + + // multi + auto r = parallelCall(&slsDetector::setRateCorrection, t); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int64_t multiSlsDetector::getRateCorrection(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getRateCorrection(); + } + + // multi + auto r = parallelCall(&slsDetector::getRateCorrection); + return sls::minusOneIfDifferent(r); +} + +void multiSlsDetector::printReceiverConfiguration(TLogLevel level, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->printReceiverConfiguration(level); + } + + // multi + for (auto &d : detectors) { + d->printReceiverConfiguration(level); + } +} + +int multiSlsDetector::setReceiverOnline(int value, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverOnline(value); + } + + // multi + if (value != GET_ONLINE_FLAG) { + auto r = parallelCall(&slsDetector::setReceiverOnline, value); + multi_shm()->receiverOnlineFlag = sls::minusOneIfDifferent(r); + } + return multi_shm()->receiverOnlineFlag; +} + +std::string multiSlsDetector::checkReceiverOnline(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->checkReceiverOnline(); + } + + // multi + auto r = parallelCall(&slsDetector::checkReceiverOnline); + return sls::concatenateNonEmptyStrings(r); +} + +int multiSlsDetector::lockReceiver(int lock, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->lockReceiver(lock); + } + + // multi + auto r = parallelCall(&slsDetector::lockReceiver, lock); + return sls::minusOneIfDifferent(r); +} + +std::string multiSlsDetector::getReceiverLastClientIP(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverLastClientIP(); + } + + // multi + auto r = parallelCall(&slsDetector::getReceiverLastClientIP); + return sls::concatenateIfDifferent(r); +} + +int multiSlsDetector::exitReceiver(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->exitReceiver(); + } + + // multi + auto r = parallelCall(&slsDetector::exitReceiver); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::execReceiverCommand(const std::string &cmd, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->execReceiverCommand(cmd); + } + + // multi + auto r = parallelCall(&slsDetector::execReceiverCommand, cmd); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +std::string multiSlsDetector::getFilePath(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getFilePath(); + } + + // multi + auto r = serialCall(&slsDetector::getFilePath); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::setFilePath(const std::string &path, int detPos) { + if (path.empty()) { + return getFilePath(detPos); + } + + // single + if (detPos >= 0) { + return detectors[detPos]->setFilePath(path); + } + + // multi + auto r = parallelCall(&slsDetector::setFilePath, path); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::getFileName(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getFileName(); + } + + // multi + auto r = serialCall(&slsDetector::getFileName); + return sls::concatenateIfDifferent(r); +} + +std::string multiSlsDetector::setFileName(const std::string &fname, int detPos) { + if (fname.empty()) { + return getFileName(detPos); + } + + // single + if (detPos >= 0) { + return detectors[detPos]->setFileName(fname); + } + + // multi + auto r = parallelCall(&slsDetector::setFileName, fname); + return sls::concatenateIfDifferent(r); +} + +int multiSlsDetector::setFramesPerFile(int f, int detPos) { + if (detPos >= 0) { + return detectors[detPos]->setFramesPerFile(f); + } + auto r = parallelCall(&slsDetector::setFramesPerFile, f); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::getFramesPerFile(int detPos) const { + if (detPos >= 0) { + return detectors[detPos]->getFramesPerFile(); + } + auto r = parallelCall(&slsDetector::getFramesPerFile); + return sls::minusOneIfDifferent(r); +} + +slsDetectorDefs::frameDiscardPolicy +multiSlsDetector::setReceiverFramesDiscardPolicy(frameDiscardPolicy f, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverFramesDiscardPolicy(f); + } + + // multi + auto r = parallelCall(&slsDetector::setReceiverFramesDiscardPolicy, f); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setPartialFramesPadding(bool padding, int detPos) { + if (detPos >= 0) + return detectors[detPos]->setPartialFramesPadding(padding); + auto r = parallelCall(&slsDetector::setPartialFramesPadding, padding); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::getPartialFramesPadding(int detPos) const { + if (detPos >= 0) + return detectors[detPos]->getPartialFramesPadding(); + auto r = parallelCall(&slsDetector::getPartialFramesPadding); + return sls::minusOneIfDifferent(r); +} + +slsDetectorDefs::fileFormat multiSlsDetector::getFileFormat(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getFileFormat(); + } + + // multi + auto r = serialCall(&slsDetector::getFileFormat); + return sls::minusOneIfDifferent(r); +} + +slsDetectorDefs::fileFormat multiSlsDetector::setFileFormat(fileFormat f, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setFileFormat(f); + } + + // multi + auto r = parallelCall(&slsDetector::setFileFormat, f); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::getFileIndex(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getFileIndex(); + } + + // multi + auto r = serialCall(&slsDetector::getFileIndex); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::incrementFileIndex(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->incrementFileIndex(); + } + + // multi + auto r = parallelCall(&slsDetector::incrementFileIndex); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setFileIndex(int i, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setFileIndex(i); + } + + // multi + auto r = parallelCall(&slsDetector::setFileIndex, i); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::getFileIndex(int detPos) const { + if (detPos >= 0) + return detectors[detPos]->getFileIndex(); + auto r = parallelCall(&slsDetector::getFileIndex); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::startReceiver(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->startReceiver(); + } + + // multi + auto r = parallelCall(&slsDetector::startReceiver); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::stopReceiver(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->stopReceiver(); + } + + // multi + auto r = parallelCall(&slsDetector::stopReceiver); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +slsDetectorDefs::runStatus multiSlsDetector::getReceiverStatus(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverStatus(); + } + + // multi + auto r = parallelCall(&slsDetector::getReceiverStatus); + if (sls::allEqual(r)) { + return r.front(); + } + if (sls::anyEqualTo(r, ERROR)) { + return ERROR; + } + for (const auto &value : r) { + if (value != IDLE) { + return value; + } + } + return IDLE; +} + +int multiSlsDetector::getFramesCaughtByReceiver(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getFramesCaughtByReceiver(); + } + + // multi + auto r = parallelCall(&slsDetector::getFramesCaughtByReceiver); + + // prevent divide by all or do not take avg when -1 for "did not connect" + if ((!detectors.size()) || (sls::anyEqualTo(r, -1))) { + return -1; + } + + // return average + return ((sls::sum(r)) / (int)detectors.size()); +} + +int multiSlsDetector::getReceiverCurrentFrameIndex(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getReceiverCurrentFrameIndex(); + } + + // multi + auto r = parallelCall(&slsDetector::getReceiverCurrentFrameIndex); + + // prevent divide by all or do not take avg when -1 for "did not connect" + if ((!detectors.size()) || (sls::anyEqualTo(r, -1))) { + return -1; + } + + // return average + return ((sls::sum(r)) / (int)detectors.size()); +} + +int multiSlsDetector::resetFramesCaught(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->resetFramesCaught(); + } + + // multi + auto r = parallelCall(&slsDetector::resetFramesCaught); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::createReceivingDataSockets(const bool destroy) { + if (destroy) { + FILE_LOG(logINFO) << "Going to destroy data sockets"; + // close socket + zmqSocket.clear(); + + client_downstream = false; + FILE_LOG(logINFO) << "Destroyed Receiving Data Socket(s)"; + return OK; + } + + FILE_LOG(logINFO) << "Going to create data sockets"; + + size_t numSockets = detectors.size(); + size_t numSocketsPerDetector = 1; + if (getDetectorTypeAsEnum() == EIGER) { + numSocketsPerDetector = 2; + } + if (getNumberofUDPInterfaces() == 2) { + numSocketsPerDetector = 2; + } + numSockets *= numSocketsPerDetector; + + for (size_t iSocket = 0; iSocket < numSockets; ++iSocket) { + uint32_t portnum = (detectors[iSocket / numSocketsPerDetector]->getClientStreamingPort()); + portnum += (iSocket % numSocketsPerDetector); + try { + zmqSocket.push_back(sls::make_unique( + detectors[iSocket / numSocketsPerDetector]->getClientStreamingIP().c_str(), + portnum)); + FILE_LOG(logINFO) << "Zmq Client[" << iSocket << "] at " + << zmqSocket.back()->GetZmqServerAddress(); + } catch (...) { + FILE_LOG(logERROR) << "Could not create Zmq socket on port " << portnum; + createReceivingDataSockets(true); + return FAIL; + } + } + + client_downstream = true; + FILE_LOG(logINFO) << "Receiving Data Socket(s) created"; + return OK; +} + +void multiSlsDetector::readFrameFromReceiver() { + + int nX = multi_shm()->numberOfDetector[X]; // to copy data in multi module + int nY = multi_shm()->numberOfDetector[Y]; // for eiger, to reverse the data + bool gappixelsenable = false; + bool eiger = false; + if (getDetectorTypeAsEnum() == EIGER) { + eiger = true; + nX *= 2; + gappixelsenable = detectors[0]->enableGapPixels(-1) >= 1 ? true : false; + } + if (getNumberofUDPInterfaces() == 2) { + nY *= 2; + } + + bool runningList[zmqSocket.size()], connectList[zmqSocket.size()]; + int numRunning = 0; + for (size_t i = 0; i < zmqSocket.size(); ++i) { + if (!zmqSocket[i]->Connect()) { + connectList[i] = true; + runningList[i] = true; + ++numRunning; + } else { + // to remember the list it connected to, to disconnect later + connectList[i] = false; + FILE_LOG(logERROR) << "Could not connect to socket " + << zmqSocket[i]->GetZmqServerAddress(); + runningList[i] = false; + } + } + int numConnected = numRunning; + bool data = false; + char *image = nullptr; + char *multiframe = nullptr; + char *multigappixels = nullptr; + int multisize = 0; + // only first message header + uint32_t size = 0, nPixelsX = 0, nPixelsY = 0, dynamicRange = 0; + float bytesPerPixel = 0; + // header info every header + std::string currentFileName = ""; + uint64_t currentAcquisitionIndex = -1, currentFrameIndex = -1, currentFileIndex = -1; + uint32_t currentSubFrameIndex = -1, coordX = -1, coordY = -1, flippedDataX = -1; + + // wait for real time acquisition to start + bool running = true; + sem_wait(&sem_newRTAcquisition); + if (getJoinThreadFlag()) { + running = false; + } + + while (running) { + // reset data + data = false; + if (multiframe != nullptr) { + memset(multiframe, 0xFF, multisize); + } + + // get each frame + for (unsigned int isocket = 0; isocket < zmqSocket.size(); ++isocket) { + + // if running + if (runningList[isocket]) { + + // HEADER + { + rapidjson::Document doc; + if (!zmqSocket[isocket]->ReceiveHeader(isocket, doc, + SLS_DETECTOR_JSON_HEADER_VERSION)) { + // parse error, version error or end of acquisition for + // socket + runningList[isocket] = false; + --numRunning; + continue; + } + + // if first message, allocate (all one time stuff) + if (image == nullptr) { + // allocate + size = doc["size"].GetUint(); + multisize = size * zmqSocket.size(); + image = new char[size]; + multiframe = new char[multisize]; + memset(multiframe, 0xFF, multisize); + // dynamic range + dynamicRange = doc["bitmode"].GetUint(); + bytesPerPixel = (float)dynamicRange / 8; + // shape + nPixelsX = doc["shape"][0].GetUint(); + nPixelsY = doc["shape"][1].GetUint(); + + FILE_LOG(logDEBUG1) + << "One Time Header Info:" + "\n\tsize: " + << size << "\n\tmultisize: " << multisize + << "\n\tdynamicRange: " << dynamicRange + << "\n\tbytesPerPixel: " << bytesPerPixel + << "\n\tnPixelsX: " << nPixelsX << "\n\tnPixelsY: " << nPixelsY; + } + // each time, parse rest of header + currentFileName = doc["fname"].GetString(); + currentAcquisitionIndex = doc["acqIndex"].GetUint64(); + currentFrameIndex = doc["fIndex"].GetUint64(); + currentFileIndex = doc["fileIndex"].GetUint64(); + currentSubFrameIndex = doc["expLength"].GetUint(); + coordY = doc["row"].GetUint(); + coordX = doc["column"].GetUint(); + if (eiger) { + coordY = (nY - 1) - coordY; + } + flippedDataX = doc["flippedDataX"].GetUint(); + FILE_LOG(logDEBUG1) + << "Header Info:" + "\n\tcurrentFileName: " + << currentFileName + << "\n\tcurrentAcquisitionIndex: " << currentAcquisitionIndex + << "\n\tcurrentFrameIndex: " << currentFrameIndex + << "\n\tcurrentFileIndex: " << currentFileIndex + << "\n\tcurrentSubFrameIndex: " << currentSubFrameIndex + << "\n\tcoordX: " << coordX << "\n\tcoordY: " << coordY + << "\n\tflippedDataX: " << flippedDataX; + } + + // DATA + data = true; + zmqSocket[isocket]->ReceiveData(isocket, image, size); + + // creating multi image + { + uint32_t xoffset = coordX * nPixelsX * bytesPerPixel; + uint32_t yoffset = coordY * nPixelsY; + uint32_t singledetrowoffset = nPixelsX * bytesPerPixel; + uint32_t rowoffset = nX * singledetrowoffset; + FILE_LOG(logDEBUG1) << "Multi Image Info:" + "\n\txoffset: " + << xoffset << "\n\tyoffset: " << yoffset + << "\n\tsingledetrowoffset: " << singledetrowoffset + << "\n\trowoffset: " << rowoffset; + + if (eiger && flippedDataX) { + for (uint32_t i = 0; i < nPixelsY; ++i) { + memcpy(((char *)multiframe) + + ((yoffset + (nPixelsY - 1 - i)) * rowoffset) + xoffset, + (char *)image + (i * singledetrowoffset), singledetrowoffset); + } + } else { + for (uint32_t i = 0; i < nPixelsY; ++i) { + memcpy(((char *)multiframe) + ((yoffset + i) * rowoffset) + xoffset, + (char *)image + (i * singledetrowoffset), singledetrowoffset); + } + } + } + } + } + + // send data to callback + if (data) { + int nCompletePixelsX = multi_shm()->numberOfChannelInclGapPixels[X]; + int nCompletePixelsY = multi_shm()->numberOfChannelInclGapPixels[Y]; + // 4bit gap pixels + if (dynamicRange == 4 && gappixelsenable) { + int n = processImageWithGapPixels(multiframe, multigappixels); + thisData = + new detectorData(getCurrentProgress(), currentFileName.c_str(), nCompletePixelsX, + nCompletePixelsY, multigappixels, n, dynamicRange, currentFileIndex); + } + // normal pixels + else { + thisData = new detectorData(getCurrentProgress(), currentFileName.c_str(), nCompletePixelsX, + nCompletePixelsY, multiframe, multisize, dynamicRange, + currentFileIndex); + } + dataReady(thisData, currentFrameIndex, + ((dynamicRange == 32) ? currentSubFrameIndex : -1), pCallbackArg); + delete thisData; + setCurrentProgress(currentAcquisitionIndex + 1); + } + + // all done + if (!numRunning) { + // let main thread know that all dummy packets have been received + //(also from external process), + // main thread can now proceed to measurement finished call back + sem_post(&sem_endRTAcquisition); + // wait for next scan/measurement, else join thread + sem_wait(&sem_newRTAcquisition); + // done with complete acquisition + if (getJoinThreadFlag()) { + running = false; + } else { + // starting a new scan/measurement (got dummy data) + for (size_t i = 0; i < zmqSocket.size(); ++i) { + runningList[i] = connectList[i]; + } + numRunning = numConnected; + } + } + } + + // Disconnect resources + for (size_t i = 0; i < zmqSocket.size(); ++i) { + if (connectList[i]) { + zmqSocket[i]->Disconnect(); + } + } + + // free resources + delete[] image; + delete[] multiframe; + delete[] multigappixels; +} + +int multiSlsDetector::processImageWithGapPixels(char *image, char *&gpImage) { + // eiger 4 bit mode + int nxb = multi_shm()->numberOfDetector[X] * (512 + 3); + int nyb = multi_shm()->numberOfDetector[Y] * (256 + 1); + int gapdatabytes = nxb * nyb; + + int nxchip = multi_shm()->numberOfDetector[X] * 4; + int nychip = multi_shm()->numberOfDetector[Y] * 1; + + // allocate + if (gpImage == nullptr) { + gpImage = new char[gapdatabytes]; + } + // fill value + memset(gpImage, 0xFF, gapdatabytes); + + const int b1chipx = 128; + const int b1chipy = 256; + char *src = nullptr; + char *dst = nullptr; + + // copying line by line + src = image; + dst = gpImage; + for (int row = 0; row < nychip; ++row) { // for each chip in a row + for (int ichipy = 0; ichipy < b1chipy; ++ichipy) { // for each row in a chip + for (int col = 0; col < nxchip; ++col) { + memcpy(dst, src, b1chipx); + src += b1chipx; + dst += b1chipx; + if ((col + 1) % 4) { + ++dst; + } + } + } + + dst += (2 * nxb); + } + + // vertical filling of values + { + uint8_t temp, g1, g2; + int mod; + dst = gpImage; + for (int row = 0; row < nychip; ++row) { // for each chip in a row + for (int ichipy = 0; ichipy < b1chipy; ++ichipy) { // for each row in a chip + for (int col = 0; col < nxchip; ++col) { + dst += b1chipx; + mod = (col + 1) % 4; + // copy gap pixel(chip 0, 1, 2) + if (mod) { + // neighbouring gap pixels to left + temp = (*((uint8_t *)(dst - 1))); + g1 = ((temp & 0xF) / 2); + (*((uint8_t *)(dst - 1))) = (temp & 0xF0) + g1; + + // neighbouring gap pixels to right + temp = (*((uint8_t *)(dst + 1))); + g2 = ((temp >> 4) / 2); + (*((uint8_t *)(dst + 1))) = (g2 << 4) + (temp & 0x0F); + + // gap pixels + (*((uint8_t *)dst)) = (g1 << 4) + g2; + + // increment to point to proper chip destination + ++dst; + } + } + } + + dst += (2 * nxb); + } + } + + // return gapdatabytes; + // horizontal filling + { + uint8_t temp, g1, g2; + char *dst_prevline = nullptr; + dst = gpImage; + for (int row = 0; row < nychip; ++row) { // for each chip in a row + dst += (b1chipy * nxb); + // horizontal copying of gap pixels from neighboring past line + // (bottom parts) + if (row < nychip - 1) { + dst_prevline = dst - nxb; + for (int gapline = 0; gapline < nxb; ++gapline) { + temp = (*((uint8_t *)dst_prevline)); + g1 = ((temp >> 4) / 2); + g2 = ((temp & 0xF) / 2); + (*((uint8_t *)dst_prevline)) = (g1 << 4) + g2; + (*((uint8_t *)dst)) = (*((uint8_t *)dst_prevline)); + ++dst; + ++dst_prevline; + } + } + + // horizontal copying of gap pixels from neihboring future line (top + // part) + if (row > 0) { + dst -= ((b1chipy + 1) * nxb); + dst_prevline = dst + nxb; + for (int gapline = 0; gapline < nxb; ++gapline) { + temp = (*((uint8_t *)dst_prevline)); + g1 = ((temp >> 4) / 2); + g2 = ((temp & 0xF) / 2); + temp = (g1 << 4) + g2; + (*((uint8_t *)dst_prevline)) = temp; + (*((uint8_t *)dst)) = temp; + ++dst; + ++dst_prevline; + } + dst += ((b1chipy + 1) * nxb); + } + + dst += nxb; + } + } + + return gapdatabytes; +} + +int multiSlsDetector::setFileWrite(bool value, int detPos) { + if (detPos >= 0) { + return detectors[detPos]->setFileWrite(value); + } + auto r = parallelCall(&slsDetector::setFileWrite, value); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::getFileWrite(int detPos) const{ + if (detPos >= 0) { + return detectors[detPos]->getFileWrite(); + } + auto r = parallelCall(&slsDetector::getFileWrite); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setFileOverWrite(bool enable, int detPos) { + if (detPos >= 0) { + return detectors[detPos]->setFileOverWrite(enable); + } + auto r = parallelCall(&slsDetector::setFileOverWrite, enable); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::getFileOverWrite(int detPos) const { + if (detPos >= 0) { + return detectors[detPos]->getFileOverWrite(); + } + auto r = parallelCall(&slsDetector::getFileOverWrite); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setReceiverStreamingFrequency(int freq, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverStreamingFrequency(freq); + } + + // multi + auto r = parallelCall(&slsDetector::setReceiverStreamingFrequency, freq); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setReceiverStreamingTimer(int time_in_ms, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverStreamingTimer(time_in_ms); + } + + // multi + auto r = parallelCall(&slsDetector::setReceiverStreamingTimer, time_in_ms); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::enableDataStreamingToClient(int enable) { + if (enable >= 0) { + // destroy data threads + if (!enable) { + createReceivingDataSockets(true); + // create data threads + } else { + if (createReceivingDataSockets() == FAIL) { + throw RuntimeError("Could not create data threads in client."); + } + } + } + return client_downstream; +} + +int multiSlsDetector::enableDataStreamingFromReceiver(int enable, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->enableDataStreamingFromReceiver(enable); + } + + // multi + auto r = parallelCall(&slsDetector::enableDataStreamingFromReceiver, enable); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::enableTenGigabitEthernet(int i, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->enableTenGigabitEthernet(i); + } + + // multi + auto r = parallelCall(&slsDetector::enableTenGigabitEthernet, i); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setReceiverFifoDepth(int i, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverFifoDepth(i); + } + + // multi + auto r = parallelCall(&slsDetector::setReceiverFifoDepth, i); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setReceiverSilentMode(int i, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setReceiverSilentMode(i); + } + + // multi + auto r = parallelCall(&slsDetector::setReceiverSilentMode, i); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setPattern(const std::string &fname, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setPattern(fname); + } + FILE *fd = fopen(fname.c_str(), "r"); + if (fd == nullptr) { + throw RuntimeError("multiSlsDetector::setPattern: Could not open file"); + } else { + int addr{0}; + uint64_t word{0}; + while (fread(&word, sizeof(word), 1, fd)) { + serialCall(&slsDetector::setPatternWord, addr, word); + ++addr; + } + fclose(fd); + return addr; + } +} + +uint64_t multiSlsDetector::setPatternWord(int addr, uint64_t word, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setPatternWord(addr, word); + } + + // multi + auto r = parallelCall(&slsDetector::setPatternWord, addr, word); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setPatternLoops(int level, int &start, int &stop, int &n, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setPatternLoops(level, start, stop, n); + } + + // multi + std::vector r; + for (auto &d : detectors) { + r.push_back(d->setPatternLoops(level, start, stop, n)); + } + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::setPatternWaitAddr(int level, int addr, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setPatternWaitAddr(level, addr); + } + + // multi + auto r = parallelCall(&slsDetector::setPatternWaitAddr, level, addr); + return sls::minusOneIfDifferent(r); +} + +uint64_t multiSlsDetector::setPatternWaitTime(int level, uint64_t t, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setPatternWaitTime(level, t); + } + + // multi + auto r = parallelCall(&slsDetector::setPatternWaitTime, level, t); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setPatternMask(uint64_t mask, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setPatternMask(mask); + } + + // multi + auto r = parallelCall(&slsDetector::setPatternMask, mask); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +uint64_t multiSlsDetector::getPatternMask(int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->getPatternMask(); + } + + // multi + auto r = parallelCall(&slsDetector::getPatternMask); + if (sls::allEqual(r)) { + return r.front(); + } + // should not have different values + throw RuntimeError("multiSlsDetector::getPatternMask: Error: Different Values returned)"); +} + +int multiSlsDetector::setPatternBitMask(uint64_t mask, int detPos) { + if (detPos >= 0) { + return detectors[detPos]->setPatternBitMask(mask); + } + auto r = parallelCall(&slsDetector::setPatternBitMask, mask); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +uint64_t multiSlsDetector::getPatternBitMask(int detPos) { + if (detPos >= 0) { + return detectors[detPos]->getPatternBitMask(); + } + auto r = parallelCall(&slsDetector::getPatternBitMask); + if (sls::allEqual(r)) { + return r.front(); + } + + // should not have different values + throw RuntimeError("multiSlsDetector::getPatternBitMask Different Values returned)"); +} + +int multiSlsDetector::setLEDEnable(int enable, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setLEDEnable(enable); + } + + // multi + auto r = parallelCall(&slsDetector::setLEDEnable, enable); + return sls::minusOneIfDifferent(r); +} + +int multiSlsDetector::setDigitalIODelay(uint64_t pinMask, int delay, int detPos) { + // single + if (detPos >= 0) { + return detectors[detPos]->setDigitalIODelay(pinMask, delay); + } + + // multi + auto r = parallelCall(&slsDetector::setDigitalIODelay, pinMask, delay); + return sls::allEqualTo(r, static_cast(OK)) ? OK : FAIL; +} + +int multiSlsDetector::retrieveDetectorSetup(const std::string &fname1, int level) { + + int skip = 0; + std::string fname; + std::string str; + std::ifstream infile; + int iargval; + int interrupt = 0; + char *args[10]; + + char myargs[10][1000]; + + std::string sargname, sargval; + int iline = 0; + + if (level == 2) { + FILE_LOG(logDEBUG1) << "config file read"; + fname = fname1 + std::string(".det"); + } else { + fname = fname1; + } + + infile.open(fname.c_str(), std::ios_base::in); + if (infile.is_open()) { + auto cmd = slsDetectorCommand(this); + while (infile.good() and interrupt == 0) { + sargname = "none"; + sargval = "0"; + getline(infile, str); + iline++; + FILE_LOG(logDEBUG1) << str; + if (str.find('#') != std::string::npos) { + FILE_LOG(logDEBUG1) << "Line is a comment \n" << str; + continue; + } else { + std::istringstream ssstr(str); + iargval = 0; + while (ssstr.good()) { + ssstr >> sargname; + // if (ssstr.good()) { + sls::strcpy_safe(myargs[iargval], sargname.c_str()); + args[iargval] = myargs[iargval]; + FILE_LOG(logDEBUG1) << args[iargval]; + iargval++; + // } + skip = 0; + } + if (level != 2) { + if (std::string(args[0]) == std::string("trimbits")) { + skip = 1; + } + } + if (skip == 0) { + cmd.executeLine(iargval, args, PUT_ACTION); + } + } + iline++; + } + infile.close(); + + } else { + throw RuntimeError("Error opening " + fname + " for reading"); + } + FILE_LOG(logDEBUG1) << "Read " << iline << " lines"; + return OK; +} + +int multiSlsDetector::dumpDetectorSetup(const std::string &fname, int level) { + detectorType type = getDetectorTypeAsEnum(); + std::vector names; + // common config + names.emplace_back("fname"); + names.emplace_back("index"); + names.emplace_back("enablefwrite"); + names.emplace_back("overwrite"); + names.emplace_back("dr"); + names.emplace_back("settings"); + names.emplace_back("exptime"); + names.emplace_back("period"); + names.emplace_back("frames"); + names.emplace_back("cycles"); + names.emplace_back("measurements"); + names.emplace_back("timing"); + + switch (type) { + case EIGER: + names.emplace_back("flags"); + names.emplace_back("clkdivider"); + names.emplace_back("threshold"); + names.emplace_back("ratecorr"); + names.emplace_back("trimbits"); + break; + case GOTTHARD: + names.emplace_back("delay"); + break; + case JUNGFRAU: + names.emplace_back("delay"); + names.emplace_back("clkdivider"); + break; + case CHIPTESTBOARD: + names.emplace_back("dac:0"); + names.emplace_back("dac:1"); + names.emplace_back("dac:2"); + names.emplace_back("dac:3"); + names.emplace_back("dac:4"); + names.emplace_back("dac:5"); + names.emplace_back("dac:6"); + names.emplace_back("dac:7"); + names.emplace_back("dac:8"); + names.emplace_back("dac:9"); + names.emplace_back("dac:10"); + names.emplace_back("dac:11"); + names.emplace_back("dac:12"); + names.emplace_back("dac:13"); + names.emplace_back("dac:14"); + names.emplace_back("dac:15"); + names.emplace_back("dac:16"); + names.emplace_back("dac:17"); + names.emplace_back("dac:18"); + names.emplace_back("dac:19"); + names.emplace_back("dac:20"); + names.emplace_back("dac:21"); + names.emplace_back("dac:22"); + names.emplace_back("dac:23"); + names.emplace_back("adcvpp"); + names.emplace_back("adcclk"); + names.emplace_back("clkdivider"); + names.emplace_back("adcphase"); + names.emplace_back("adcpipeline"); + names.emplace_back("adcinvert"); // + names.emplace_back("adcdisable"); + names.emplace_back("patioctrl"); + names.emplace_back("patclkctrl"); + names.emplace_back("patlimits"); + names.emplace_back("patloop0"); + names.emplace_back("patnloop0"); + names.emplace_back("patwait0"); + names.emplace_back("patwaittime0"); + names.emplace_back("patloop1"); + names.emplace_back("patnloop1"); + names.emplace_back("patwait1"); + names.emplace_back("patwaittime1"); + names.emplace_back("patloop2"); + names.emplace_back("patnloop2"); + names.emplace_back("patwait2"); + names.emplace_back("patwaittime2"); + break; + default: + break; + } + + // Workaround to bo able to suplly ecexuteLine with char** + const int n_arguments = 1; + char buffer[1000]; // TODO! this should not be hardcoded! + char *args[n_arguments] = {buffer}; + + std::string outfname; + if (level == 2) { + writeConfigurationFile(fname + ".config"); + outfname = fname + ".det"; + } else { + outfname = fname; + } + + std::ofstream outfile; + outfile.open(outfname.c_str(), std::ios_base::out); + if (outfile.is_open()) { + auto cmd = slsDetectorCommand(this); + for (auto &name : names) { + sls::strcpy_safe(buffer, name.c_str()); // this is... + outfile << name << " " << cmd.executeLine(n_arguments, args, GET_ACTION) << std::endl; + } + outfile.close(); + } else { + throw RuntimeError("Error opening parameters file " + fname + " for writing"); + } + + FILE_LOG(logDEBUG1) << "wrote " << names.size() << " lines to " << outfname; + return OK; +} + +void multiSlsDetector::registerAcquisitionFinishedCallback(int (*func)(double, int, void *), + void *pArg) { + acquisition_finished = func; + acqFinished_p = pArg; +} + +void multiSlsDetector::registerMeasurementFinishedCallback(int (*func)(int, int, void *), + void *pArg) { + measurement_finished = func; + measFinished_p = pArg; +} + +void multiSlsDetector::registerProgressCallback(int (*func)(double, void *), void *pArg) { + progress_call = func; + pProgressCallArg = pArg; +} + +void multiSlsDetector::registerDataCallback(int (*userCallback)(detectorData *, int, int, void *), + void *pArg) { + dataReady = userCallback; + pCallbackArg = pArg; + if (setReceiverOnline() == slsDetectorDefs::ONLINE_FLAG) { + enableDataStreamingToClient(1); + enableDataStreamingFromReceiver(1); + } +} + +int multiSlsDetector::setTotalProgress() { + int nf = 1, nc = 1, ns = 1, nm = 1; + + if (multi_shm()->timerValue[FRAME_NUMBER]) { + nf = multi_shm()->timerValue[FRAME_NUMBER]; + } + + if (multi_shm()->timerValue[CYCLES_NUMBER] > 0) { + nc = multi_shm()->timerValue[CYCLES_NUMBER]; + } + + if (multi_shm()->timerValue[STORAGE_CELL_NUMBER] > 0) { + ns = multi_shm()->timerValue[STORAGE_CELL_NUMBER] + 1; + } + + if (multi_shm()->timerValue[MEASUREMENTS_NUMBER] > 0) { + nm = multi_shm()->timerValue[MEASUREMENTS_NUMBER]; + } + + totalProgress = nm * nf * nc * ns; + + FILE_LOG(logDEBUG1) << "nm " << nm << " nf " << nf << " nc " << nc << " ns " << ns; + FILE_LOG(logDEBUG1) << "Set total progress " << totalProgress << std::endl; + return totalProgress; +} + +double multiSlsDetector::getCurrentProgress() { + std::lock_guard lock(mp); + return 100. * ((double)progressIndex) / ((double)totalProgress); +} + +void multiSlsDetector::incrementProgress() { + std::lock_guard lock(mp); + progressIndex++; + std::cout << std::fixed << std::setprecision(2) << std::setw(6) + << 100. * ((double)progressIndex) / ((double)totalProgress) << " \%"; + std::cout << '\r' << std::flush; +} + +void multiSlsDetector::setCurrentProgress(int i) { + std::lock_guard lock(mp); + progressIndex = i; + std::cout << std::fixed << std::setprecision(2) << std::setw(6) + << 100. * ((double)progressIndex) / ((double)totalProgress) << " \%"; + std::cout << '\r' << std::flush; +} + +int multiSlsDetector::acquire() { + // ensure acquire isnt started multiple times by same client + if (isAcquireReady() == FAIL) { + return FAIL; + } + + struct timespec begin, end; + clock_gettime(CLOCK_REALTIME, &begin); + + // in the real time acquisition loop, processing thread will wait for a post + // each time + sem_init(&sem_newRTAcquisition, 1, 0); + // in the real time acquistion loop, main thread will wait for processing + // thread to be done each time (which in turn waits for receiver/ext + // process) + sem_init(&sem_endRTAcquisition, 1, 0); + + bool receiver = (setReceiverOnline() == ONLINE_FLAG); + progressIndex = 0; + multi_shm()->stoppedFlag = 0; + setJoinThreadFlag(false); + + int nm = multi_shm()->timerValue[MEASUREMENTS_NUMBER]; + if (nm < 1) { + nm = 1; + } + + // verify receiver is idle + if (receiver) { + std::lock_guard lock(mg); + if (getReceiverStatus() != IDLE) { + if (stopReceiver() == FAIL) { + multi_shm()->stoppedFlag = 1; + } + } + } + + startProcessingThread(); + + // resets frames caught in receiver + if (receiver) { + std::lock_guard lock(mg); + if (resetFramesCaught() == FAIL) { + multi_shm()->stoppedFlag = 1; + } + } + + // loop through measurements + for (int im = 0; im < nm; ++im) { + if (multi_shm()->stoppedFlag) { + break; + } + + // start receiver + if (receiver) { + std::lock_guard lock(mg); + if (startReceiver() == FAIL) { + FILE_LOG(logERROR) << "Start receiver failed "; + stopReceiver(); + multi_shm()->stoppedFlag = 1; + break; + } + // let processing thread listen to these packets + sem_post(&sem_newRTAcquisition); + } + + startAndReadAll(); + + // stop receiver + std::lock_guard lock(mg); + if (receiver) { + if (stopReceiver() == FAIL) { + multi_shm()->stoppedFlag = 1; + } else { + if (dataReady) { + sem_wait(&sem_endRTAcquisition); // waits for receiver's + } + // external process to be + // done sending data to gui + } + } + int findex = 0; + findex = incrementFileIndex(); + + if (measurement_finished) { + measurement_finished(im, findex, measFinished_p); + } + if (multi_shm()->stoppedFlag) { + break; + } + + } // end measurements loop im + + // waiting for the data processing thread to finish! + setJoinThreadFlag(true); + sem_post(&sem_newRTAcquisition); + dataProcessingThread.join(); + + if (progress_call) { + progress_call(getCurrentProgress(), pProgressCallArg); + } + + if (acquisition_finished) { + acquisition_finished(getCurrentProgress(), getRunStatus(), acqFinished_p); + } + + sem_destroy(&sem_newRTAcquisition); + sem_destroy(&sem_endRTAcquisition); + + clock_gettime(CLOCK_REALTIME, &end); + FILE_LOG(logDEBUG1) << "Elapsed time for acquisition:" + << ((end.tv_sec - begin.tv_sec) + + (end.tv_nsec - begin.tv_nsec) / 1000000000.0) + << " seconds"; + + setAcquiringFlag(false); + + return OK; +} + +void multiSlsDetector::startProcessingThread() { + setTotalProgress(); + dataProcessingThread = std::thread(&multiSlsDetector::processData, this); +} + + +void multiSlsDetector::processData() { + if (setReceiverOnline() == OFFLINE_FLAG) { + return; + } else { + if (dataReady) { + readFrameFromReceiver(); + } + // only update progress + else { + int caught = -1; + while (true) { + // to exit acquire by typing q + if (kbhit() != 0) { + if (fgetc(stdin) == 'q') { + FILE_LOG(logINFO) << "Caught the command to stop acquisition"; + stopAcquisition(); + } + } + // get progress + if (setReceiverOnline() == ONLINE_FLAG) { + std::lock_guard lock(mg); + caught = getFramesCaughtByReceiver(0); + } + // updating progress + if (caught != -1) { + setCurrentProgress(caught); + } + // exiting loop + if (getJoinThreadFlag()) { + break; + } + // otherwise error when connecting to the receiver too fast + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + } + } + return; +} + +bool multiSlsDetector::getJoinThreadFlag() const { + std::lock_guard lock(mp); + return jointhread; +} + +void multiSlsDetector::setJoinThreadFlag(bool value) { + std::lock_guard lock(mp); + jointhread = value; +} + +int multiSlsDetector::kbhit() { + struct timeval tv; + fd_set fds; + tv.tv_sec = 0; + tv.tv_usec = 0; + FD_ZERO(&fds); + FD_SET(STDIN_FILENO, &fds); // STDIN_FILENO is 0 + select(STDIN_FILENO + 1, &fds, nullptr, nullptr, &tv); + return FD_ISSET(STDIN_FILENO, &fds); +} + + + +std::vector multiSlsDetector::readPofFile(const std::string &fname) { + FILE_LOG(logDEBUG1) << "Programming FPGA with file name:" << fname; + size_t filesize = 0; + // check if it exists + + struct stat st; + if (stat(fname.c_str(), &st)) { + throw RuntimeError("Program FPGA: Programming file does not exist"); + } + + + + // open src + FILE *src = fopen(fname.c_str(), "rb"); + if (src == nullptr) { + throw RuntimeError("Program FPGA: Could not open source file for programming: " + + fname); + } + + // create temp destination file + char destfname[] = "/tmp/SLS_DET_MCB.XXXXXX"; + int dst = mkstemp(destfname); // create temporary file and open it in r/w + if (dst == -1) { + fclose(src); + throw RuntimeError( + std::string("Could not create destination file in /tmp for programming: ") + + destfname); + } + + // convert src to dst rawbin + FILE_LOG(logDEBUG1) << "Converting " << fname << " to " << destfname; + { + int filepos, x, y, i; + // Remove header (0...11C) + for (filepos = 0; filepos < 0x11C; ++filepos) { + fgetc(src); + } + // Write 0x80 times 0xFF (0...7F) + { + char c = 0xFF; + for (filepos = 0; filepos < 0x80; ++filepos) { + write(dst, &c, 1); + } + } + // Swap bits and write to file + for (filepos = 0x80; filepos < 0x1000000; ++filepos) { + x = fgetc(src); + if (x < 0) { + break; + } + y = 0; + for (i = 0; i < 8; ++i) { + y = y | (((x & (1 << i)) >> i) << (7 - i)); // This swaps the bits + } + write(dst, &y, 1); + } + if (filepos < 0x1000000) { + throw RuntimeError("Could not convert programming file. EOF before end of flash"); + } + } + if (fclose(src)) { + throw RuntimeError("Program FPGA: Could not close source file"); + } + if (close(dst)) { + throw RuntimeError("Program FPGA: Could not close destination file"); + } + FILE_LOG(logDEBUG1) << "File has been converted to " << destfname; + + // loading dst file to memory + FILE *fp = fopen(destfname, "r"); + if (fp == nullptr) { + throw RuntimeError("Program FPGA: Could not open rawbin file"); + } + if (fseek(fp, 0, SEEK_END)) { + throw RuntimeError("Program FPGA: Seek error in rawbin file"); + } + filesize = ftell(fp); + if (filesize <= 0) { + throw RuntimeError("Program FPGA: Could not get length of rawbin file"); + } + rewind(fp); + + std::vector buffer(filesize, 0); + if (fread(buffer.data(), sizeof(char), filesize, fp) != filesize) { + throw RuntimeError("Program FPGA: Could not read rawbin file"); + } + + if (fclose(fp)) { + throw RuntimeError("Program FPGA: Could not close destination file after converting"); + } + unlink(destfname); // delete temporary file + FILE_LOG(logDEBUG1) << "Successfully loaded the rawbin file to program memory"; + FILE_LOG(logINFO) << "Read file into memory"; + return buffer; +} + + + + + + diff --git a/slsDetectorSoftware/src/slsDetector.cpp b/slsDetectorSoftware/src/slsDetector.cpp new file mode 100755 index 000000000..76ac1d4f2 --- /dev/null +++ b/slsDetectorSoftware/src/slsDetector.cpp @@ -0,0 +1,5172 @@ +#include "slsDetector.h" +#include "ClientInterface.h" +#include "ClientSocket.h" +#include "MySocketTCP.h" +#include "ServerInterface.h" +#include "SharedMemory.h" +#include "file_utils.h" +#include "multiSlsDetector.h" +#include "network_utils.h" +#include "slsDetectorCommand.h" +#include "sls_detector_exceptions.h" +#include "string_utils.h" +#include "versionAPI.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +using namespace sls; + +#define DEFAULT_HOSTNAME "localhost" + +slsDetector::slsDetector(detectorType type, int multi_id, int det_id, + bool verify) + : detId(det_id), detector_shm(multi_id, det_id) { + /* called from put hostname command, + * so sls shared memory will be created */ + + // ensure shared memory was not created before + if (detector_shm.IsExisting()) { + FILE_LOG(logWARNING) << "This shared memory should have been " + "deleted before! " + << detector_shm.GetName() << ". Freeing it again"; + freeSharedMemory(multi_id, det_id); + } + + initSharedMemory(type, multi_id, verify); +} + +slsDetector::slsDetector(int multi_id, int det_id, bool verify) + : detId(det_id), detector_shm(multi_id, det_id) { + /* called from multi constructor to populate structure, + * so sls shared memory will be opened, not created */ + + // getDetectorType From shm will check if it was already existing + detectorType type = getDetectorTypeFromShm(multi_id, verify); + initSharedMemory(type, multi_id, verify); +} + +slsDetector::~slsDetector() = default; + +int slsDetector::checkDetectorVersionCompatibility() { + // TODO! Verify that this works as intended when version don't match + int fnum = F_CHECK_VERSION; + int ret = FAIL; + int64_t arg = 0; + + // get api version number for detector server + switch (detector_shm()->myDetectorType) { + case EIGER: + arg = APIEIGER; + break; + case JUNGFRAU: + arg = APIJUNGFRAU; + break; + case GOTTHARD: + arg = APIGOTTHARD; + break; + case CHIPTESTBOARD: + arg = APICTB; + break; + case MOENCH: + arg = APIMOENCH; + break; + default: + throw NotImplementedError( + "Check version compatibility is not implemented for this detector"); + } + FILE_LOG(logDEBUG1) + << "Checking version compatibility with detector with value " + << std::hex << arg << std::dec; + + // control server + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + // in case it throws + detector_shm()->detectorControlAPIVersion = 0; + detector_shm()->detectorStopAPIVersion = 0; + detector_shm()->onlineFlag = OFFLINE_FLAG; + + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), nullptr, 0); + + auto stop = + DetectorSocket(detector_shm()->hostname, detector_shm()->stopPort); + ret = stop.sendCommandThenRead(fnum, &arg, sizeof(arg), nullptr, 0); + + // success + detector_shm()->detectorControlAPIVersion = arg; + detector_shm()->detectorStopAPIVersion = arg; + detector_shm()->onlineFlag = ONLINE_FLAG; + } + return ret; +} + +int slsDetector::checkReceiverVersionCompatibility() { + // TODO! Verify that this works as intended when version don't match + int fnum = F_RECEIVER_CHECK_VERSION; + int ret = FAIL; + int64_t arg = APIRECEIVER; + + FILE_LOG(logDEBUG1) + << "Checking version compatibility with receiver with value " + << std::hex << arg << std::dec; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + // in case it throws + detector_shm()->receiverAPIVersion = 0; + detector_shm()->receiverOnlineFlag = OFFLINE_FLAG; + + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), nullptr, 0); + + // success + detector_shm()->receiverAPIVersion = arg; + detector_shm()->receiverOnlineFlag = ONLINE_FLAG; + } + return ret; +} + +int64_t slsDetector::getId(idMode mode) { + int arg = static_cast(mode); + int64_t retval = -1; + FILE_LOG(logDEBUG1) << "Getting id type " << mode; + + // These should not go to detector... + assert(mode != THIS_SOFTWARE_VERSION); + assert(mode != RECEIVER_VERSION); + assert(mode != CLIENT_SOFTWARE_API_VERSION); + assert(mode != CLIENT_RECEIVER_API_VERSION); + + int fnum = F_GET_ID; + int ret = FAIL; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + } + FILE_LOG(logDEBUG1) << "Id (" << mode << "): 0x" << std::hex << retval + << std::dec; + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +int64_t slsDetector::getReceiverSoftwareVersion() const { + int ret = FAIL; + int arg = RECEIVER_VERSION; + int64_t retval = -1; + FILE_LOG(logDEBUG1) << "Getting id type " << arg; + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + int fnum = F_GET_RECEIVER_ID; + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, nullptr, 0, &retval, + sizeof(retval)); + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return retval; +} + +void slsDetector::freeSharedMemory(int multi_id, int slsId) { + SharedMemory shm(multi_id, slsId); + if (shm.IsExisting()) { + shm.RemoveSharedMemory(); + } +} + +void slsDetector::freeSharedMemory() { + if (detector_shm.IsExisting()) { + detector_shm.RemoveSharedMemory(); + } +} + +void slsDetector::setHostname(const std::string &hostname) { + sls::strcpy_safe(detector_shm()->hostname, hostname.c_str()); + updateDetector(); +} + +std::string slsDetector::getHostname() const { + return detector_shm()->hostname; +} + +void slsDetector::initSharedMemory(detectorType type, int multi_id, + bool verify) { + + detector_shm = SharedMemory(multi_id, detId); + if (!detector_shm.IsExisting()) { + detector_shm.CreateSharedMemory(); + initializeDetectorStructure(type); + } else { + detector_shm.OpenSharedMemory(); + if (verify && detector_shm()->shmversion != SLS_SHMVERSION) { + std::ostringstream ss; + ss << "Single shared memory (" << multi_id << "-" << detId + << ":) version mismatch (expected 0x" << std::hex + << SLS_SHMVERSION << " but got 0x" << detector_shm()->shmversion + << ")" << std::dec; + throw SharedMemoryError(ss.str()); + } + } +} + +void slsDetector::setDetectorSpecificParameters(detectorType type, + detParameters &list) { + switch (type) { + case GOTTHARD: + list.nChanX = 128; + list.nChanY = 1; + list.nChipX = 10; + list.nChipY = 1; + list.nDacs = 8; + list.dynamicRange = 16; + list.nGappixelsX = 0; + list.nGappixelsY = 0; + break; + case JUNGFRAU: + list.nChanX = 256; + list.nChanY = 256; + list.nChipX = 4; + list.nChipY = 2; + list.nDacs = 8; + list.dynamicRange = 16; + list.nGappixelsX = 0; + list.nGappixelsY = 0; + break; + case CHIPTESTBOARD: + list.nChanX = 36; + list.nChanY = 1; + list.nChipX = 1; + list.nChipY = 1; + list.nDacs = 24; + list.dynamicRange = 16; + list.nGappixelsX = 0; + list.nGappixelsY = 0; + break; + case MOENCH: + list.nChanX = 32; + list.nChanY = 1; + list.nChipX = 1; + list.nChipY = 1; + list.nDacs = 8; + list.dynamicRange = 16; + list.nGappixelsX = 0; + list.nGappixelsY = 0; + break; + case EIGER: + list.nChanX = 256; + list.nChanY = 256; + list.nChipX = 4; + list.nChipY = 1; + list.nDacs = 16; + list.dynamicRange = 16; + list.nGappixelsX = 6; + list.nGappixelsY = 1; + break; + default: + throw RuntimeError("Unknown detector type! " + + slsDetectorDefs::detectorTypeToString(type)); + } +} + +void slsDetector::initializeDetectorStructure(detectorType type) { + detector_shm()->shmversion = SLS_SHMVERSION; + detector_shm()->onlineFlag = OFFLINE_FLAG; + detector_shm()->stoppedFlag = 0; + sls::strcpy_safe(detector_shm()->hostname, DEFAULT_HOSTNAME); + detector_shm()->myDetectorType = type; + detector_shm()->offset[X] = 0; + detector_shm()->offset[Y] = 0; + detector_shm()->multiSize[X] = 0; + detector_shm()->multiSize[Y] = 0; + detector_shm()->controlPort = DEFAULT_PORTNO; + detector_shm()->stopPort = DEFAULT_PORTNO + 1; + sls::strcpy_safe(detector_shm()->settingsDir, getenv("HOME")); + detector_shm()->nTrimEn = 0; + for (int &trimEnergie : detector_shm()->trimEnergies) { + trimEnergie = 0; + } + detector_shm()->nROI = 0; + memset(detector_shm()->roiLimits, 0, MAX_ROIS * sizeof(ROI)); + detector_shm()->roFlags = NORMAL_READOUT; + detector_shm()->currentSettings = UNINITIALIZED; + detector_shm()->currentThresholdEV = -1; + detector_shm()->timerValue[FRAME_NUMBER] = 1; + detector_shm()->timerValue[ACQUISITION_TIME] = 0; + detector_shm()->timerValue[FRAME_PERIOD] = 0; + detector_shm()->timerValue[DELAY_AFTER_TRIGGER] = 0; + detector_shm()->timerValue[GATES_NUMBER] = 0; + detector_shm()->timerValue[CYCLES_NUMBER] = 1; + detector_shm()->timerValue[ACTUAL_TIME] = 0; + detector_shm()->timerValue[MEASUREMENT_TIME] = 0; + detector_shm()->timerValue[PROGRESS] = 0; + detector_shm()->timerValue[MEASUREMENTS_NUMBER] = 1; + detector_shm()->timerValue[FRAMES_FROM_START] = 0; + detector_shm()->timerValue[FRAMES_FROM_START_PG] = 0; + detector_shm()->timerValue[SAMPLES] = 1; + detector_shm()->timerValue[SUBFRAME_ACQUISITION_TIME] = 0; + detector_shm()->timerValue[STORAGE_CELL_NUMBER] = 0; + detector_shm()->timerValue[SUBFRAME_DEADTIME] = 0; + sls::strcpy_safe(detector_shm()->receiver_hostname, "none"); + detector_shm()->receiverTCPPort = DEFAULT_PORTNO + 2; + detector_shm()->receiverUDPPort = DEFAULT_UDP_PORTNO; + detector_shm()->receiverUDPPort2 = DEFAULT_UDP_PORTNO + 1; + + detector_shm()->receiverUDPIP = 0u; + detector_shm()->receiverUDPIP2 = 0u; + detector_shm()->receiverUDPMAC = 0ul; + detector_shm()->receiverUDPMAC2 = 0ul; + + detector_shm()->detectorMAC = DEFAULT_DET_MAC; + detector_shm()->detectorMAC2 = DEFAULT_DET_MAC2; + detector_shm()->detectorIP = DEFAULT_DET_MAC; + detector_shm()->detectorIP2 = DEFAULT_DET_MAC2; + + detector_shm()->numUDPInterfaces = 1; + detector_shm()->selectedUDPInterface = 1; + detector_shm()->receiverOnlineFlag = OFFLINE_FLAG; + detector_shm()->tenGigaEnable = 0; + detector_shm()->flippedData[X] = 0; + detector_shm()->flippedData[Y] = 0; + detector_shm()->zmqport = + DEFAULT_ZMQ_CL_PORTNO + + (detId * ((detector_shm()->myDetectorType == EIGER) ? 2 : 1)); + detector_shm()->receiver_zmqport = + DEFAULT_ZMQ_RX_PORTNO + + (detId * ((detector_shm()->myDetectorType == EIGER) ? 2 : 1)); + detector_shm()->receiver_upstream = false; + detector_shm()->receiver_read_freq = 0; + memset(detector_shm()->zmqip, 0, MAX_STR_LENGTH); + memset(detector_shm()->receiver_zmqip, 0, MAX_STR_LENGTH); + detector_shm()->gappixels = 0; + memset(detector_shm()->receiver_additionalJsonHeader, 0, MAX_STR_LENGTH); + detector_shm()->detectorControlAPIVersion = 0; + detector_shm()->detectorStopAPIVersion = 0; + detector_shm()->receiverAPIVersion = 0; + detector_shm()->receiver_frameDiscardMode = NO_DISCARD; + detector_shm()->rxFramePadding = true; + detector_shm()->activated = true; + detector_shm()->receiver_deactivatedPaddingEnable = true; + detector_shm()->receiver_silentMode = false; + sls::strcpy_safe(detector_shm()->receiver_filePath, "/"); + sls::strcpy_safe(detector_shm()->receiver_fileName, "run"); + detector_shm()->rxFileIndex = 0; + detector_shm()->rxFileFormat = BINARY; + switch (detector_shm()->myDetectorType) { + case GOTTHARD: + detector_shm()->rxFramesPerFile = MAX_FRAMES_PER_FILE; + break; + case EIGER: + detector_shm()->rxFramesPerFile = EIGER_MAX_FRAMES_PER_FILE; + break; + case JUNGFRAU: + detector_shm()->rxFramesPerFile = JFRAU_MAX_FRAMES_PER_FILE; + break; + case CHIPTESTBOARD: + detector_shm()->rxFramesPerFile = CTB_MAX_FRAMES_PER_FILE; + break; + case MOENCH: + detector_shm()->rxFramesPerFile = MOENCH_MAX_FRAMES_PER_FILE; + break; + default: + break; + } + detector_shm()->rxFileWrite = true; + detector_shm()->rxFileOverWrite = true; + + // get the detector parameters based on type + detParameters parameters{}; + setDetectorSpecificParameters(type, parameters); + detector_shm()->nChan[X] = parameters.nChanX; + detector_shm()->nChan[Y] = parameters.nChanY; + detector_shm()->nChip[X] = parameters.nChipX; + detector_shm()->nChip[Y] = parameters.nChipY; + detector_shm()->nDacs = parameters.nDacs; + detector_shm()->dynamicRange = parameters.dynamicRange; + detector_shm()->nGappixels[X] = parameters.nGappixelsX; + detector_shm()->nGappixels[Y] = parameters.nGappixelsY; + + // derived parameters + detector_shm()->nChans = + detector_shm()->nChan[X] * detector_shm()->nChan[Y]; + detector_shm()->nChips = + detector_shm()->nChip[X] * detector_shm()->nChip[Y]; + + // calculating databytes + detector_shm()->dataBytes = detector_shm()->nChips * + detector_shm()->nChans * + detector_shm()->dynamicRange / 8; + detector_shm()->dataBytesInclGapPixels = + (detector_shm()->nChip[X] * detector_shm()->nChan[X] + + detector_shm()->gappixels * detector_shm()->nGappixels[X]) * + (detector_shm()->nChip[Y] * detector_shm()->nChan[Y] + + detector_shm()->gappixels * detector_shm()->nGappixels[Y]) * + detector_shm()->dynamicRange / 8; + + // update #nchans and databytes, as it depends on #samples, roi, + // readoutflags (ctb only) + if (detector_shm()->myDetectorType == CHIPTESTBOARD || + detector_shm()->myDetectorType == MOENCH) { + updateTotalNumberOfChannels(); + } +} + +slsDetectorDefs::sls_detector_module *slsDetector::createModule() { + return createModule(detector_shm()->myDetectorType); +} + +slsDetectorDefs::sls_detector_module * +slsDetector::createModule(detectorType type) { + // get the detector parameters based on type + detParameters parameters{}; + int nch = 0, nc = 0, nd = 0; + try { + setDetectorSpecificParameters(type, parameters); + nch = parameters.nChanX * parameters.nChanY; + nc = parameters.nChipX * parameters.nChipY; + nd = parameters.nDacs; + } catch (...) { + return nullptr; + } + int *dacs = new int[nd]; + int *chanregs = new int[nch * nc]; + + auto *myMod = new sls_detector_module; + myMod->ndac = nd; + myMod->nchip = nc; + myMod->nchan = nch * nc; + myMod->dacs = dacs; + myMod->chanregs = chanregs; + return myMod; +} + +void slsDetector::deleteModule(sls_detector_module *myMod) { + if (myMod != nullptr) { + delete[] myMod->dacs; + delete[] myMod->chanregs; + delete myMod; + } +} + +int slsDetector::sendModule(sls_detector_module *myMod, + sls::ClientSocket &client) { + TLogLevel level = logDEBUG1; + FILE_LOG(level) << "Sending Module"; + int ts = 0; + int n = 0; + n = client.sendData(&(myMod->serialnumber), sizeof(myMod->serialnumber)); + ts += n; + FILE_LOG(level) << "Serial number sent. " << n + << " bytes. serialno: " << myMod->serialnumber; + + n = client.sendData(&(myMod->nchan), sizeof(myMod->nchan)); + ts += n; + FILE_LOG(level) << "nchan sent. " << n + << " bytes. serialno: " << myMod->nchan; + + n = client.sendData(&(myMod->nchip), sizeof(myMod->nchip)); + ts += n; + FILE_LOG(level) << "nchip sent. " << n + << " bytes. serialno: " << myMod->nchip; + + n = client.sendData(&(myMod->ndac), sizeof(myMod->ndac)); + ts += n; + FILE_LOG(level) << "ndac sent. " << n + << " bytes. serialno: " << myMod->ndac; + + n = client.sendData(&(myMod->reg), sizeof(myMod->reg)); + ts += n; + FILE_LOG(level) << "reg sent. " << n << " bytes. serialno: " << myMod->reg; + + n = client.sendData(&(myMod->iodelay), sizeof(myMod->iodelay)); + ts += n; + FILE_LOG(level) << "iodelay sent. " << n + << " bytes. serialno: " << myMod->iodelay; + + n = client.sendData(&(myMod->tau), sizeof(myMod->tau)); + ts += n; + FILE_LOG(level) << "tau sent. " << n << " bytes. serialno: " << myMod->tau; + + n = client.sendData(&(myMod->eV), sizeof(myMod->eV)); + ts += n; + FILE_LOG(level) << "ev sent. " << n << " bytes. serialno: " << myMod->eV; + + n = client.sendData(myMod->dacs, sizeof(int) * (myMod->ndac)); + ts += n; + FILE_LOG(level) << "dacs sent. " << n << " bytes"; + + if (detector_shm()->myDetectorType == EIGER) { + n = client.sendData(myMod->chanregs, sizeof(int) * (myMod->nchan)); + ts += n; + FILE_LOG(level) << "channels sent. " << n << " bytes"; + } + return ts; +} + +int slsDetector::receiveModule(sls_detector_module *myMod, + sls::ClientSocket &client) { + int ts = 0; + ts += + client.receiveData(&(myMod->serialnumber), sizeof(myMod->serialnumber)); + ts += client.receiveData(&(myMod->nchan), sizeof(myMod->nchan)); + ts += client.receiveData(&(myMod->nchip), sizeof(myMod->nchip)); + ts += client.receiveData(&(myMod->ndac), sizeof(myMod->ndac)); + ts += client.receiveData(&(myMod->reg), sizeof(myMod->reg)); + ts += client.receiveData(&(myMod->iodelay), sizeof(myMod->iodelay)); + ts += client.receiveData(&(myMod->tau), sizeof(myMod->tau)); + ts += client.receiveData(&(myMod->eV), sizeof(myMod->eV)); + + ts += client.receiveData(myMod->dacs, sizeof(int) * (myMod->ndac)); + FILE_LOG(logDEBUG1) << "received dacs of size " << ts; + if (detector_shm()->myDetectorType == EIGER) { + ts += client.receiveData(myMod->chanregs, sizeof(int) * (myMod->nchan)); + FILE_LOG(logDEBUG1) + << "nchans= " << detector_shm()->nChans + << " nchips= " << detector_shm()->nChips + << "mod - nchans= " << myMod->nchan << " nchips= " << myMod->nchip + << "received chans of size " << ts; + } + FILE_LOG(logDEBUG1) << "received module of size " << ts << " register " + << myMod->reg; + return ts; +} + +slsDetectorDefs::detectorType slsDetector::getDetectorTypeFromShm(int multi_id, + bool verify) { + if (!detector_shm.IsExisting()) { + throw SharedMemoryError("Shared memory " + detector_shm.GetName() + + "does not exist.\n Corrupted Multi Shared " + "memory. Please free shared memory."); + } + + detector_shm.OpenSharedMemory(); + if (verify && detector_shm()->shmversion != SLS_SHMVERSION) { + std::ostringstream ss; + ss << "Single shared memory (" << multi_id << "-" << detId + << ":)version mismatch (expected 0x" << std::hex << SLS_SHMVERSION + << " but got 0x" << detector_shm()->shmversion << ")" << std::dec; + detector_shm.UnmapSharedMemory(); + throw SharedMemoryError(ss.str()); + } + auto type = detector_shm()->myDetectorType; + return type; +} + +// static function +slsDetectorDefs::detectorType +slsDetector::getTypeFromDetector(const std::string &hostname, int cport) { + int fnum = F_GET_DETECTOR_TYPE; + int ret = FAIL; + detectorType retval = GENERIC; + FILE_LOG(logDEBUG1) << "Getting detector type "; + sls::ClientSocket cs("Detector", hostname, cport); + cs.sendData(reinterpret_cast(&fnum), sizeof(fnum)); + cs.receiveData(reinterpret_cast(&ret), sizeof(ret)); + cs.receiveData(reinterpret_cast(&retval), sizeof(retval)); + FILE_LOG(logDEBUG1) << "Detector type is " << retval; + return retval; +} + +int slsDetector::setDetectorType(detectorType const type) { + int fnum = F_GET_DETECTOR_TYPE; + int ret = FAIL; + detectorType retval = GENERIC; + FILE_LOG(logDEBUG1) << "Setting detector type to " << type; + + // if unspecified, then get from detector + if (type == GET_DETECTOR_TYPE) { + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, &retval, + sizeof(retval)); + detector_shm()->myDetectorType = static_cast(retval); + FILE_LOG(logDEBUG1) << "Detector Type: " << retval; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + } else { + ret = OK; + } + + // receiver + if ((detector_shm()->receiverOnlineFlag == ONLINE_FLAG) && ret == OK) { + fnum = F_GET_RECEIVER_TYPE; + auto arg = static_cast(detector_shm()->myDetectorType); + retval = GENERIC; + FILE_LOG(logDEBUG1) << "Sending detector type to Receiver: " << arg; + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver Type: " << retval; + if (ret == FORCE_UPDATE) { + receiver.close(); // TODO! Should find a better solution + updateCachedReceiverVariables(); + } + } + return retval; +} + +slsDetectorDefs::detectorType slsDetector::getDetectorTypeAsEnum() const { + return detector_shm()->myDetectorType; +} + +std::string slsDetector::getDetectorTypeAsString() const { + return slsDetectorDefs::detectorTypeToString(getDetectorTypeAsEnum()); +} + +int slsDetector::getTotalNumberOfChannels() const { + return detector_shm()->nChans * detector_shm()->nChips; +} + +void slsDetector::updateTotalNumberOfChannels() { + if (detector_shm()->myDetectorType == CHIPTESTBOARD || + detector_shm()->myDetectorType == MOENCH) { + + // default number of channels + detector_shm()->nChan[X] = 32; + + // if roi, recalculate #nchanX + if (detector_shm()->nROI > 0) { + detector_shm()->nChan[X] = 0; + for (int iroi = 0; iroi < detector_shm()->nROI; ++iroi) { + detector_shm()->nChan[X] += + (detector_shm()->roiLimits[iroi].xmax - + detector_shm()->roiLimits[iroi].xmin + 1); + } + } + + // add digital signals depending on readout flags + if (detector_shm()->myDetectorType == CHIPTESTBOARD && + (detector_shm()->roFlags & DIGITAL_ONLY || + detector_shm()->roFlags & ANALOG_AND_DIGITAL)) { + detector_shm()->nChan[X] += 4; + } + + // recalculate derived parameters chans and databytes + detector_shm()->nChans = detector_shm()->nChan[X]; + detector_shm()->dataBytes = detector_shm()->nChans * + detector_shm()->nChips * + (detector_shm()->dynamicRange / 8) * + detector_shm()->timerValue[SAMPLES]; + FILE_LOG(logDEBUG1) << "Number of Channels:" << detector_shm()->nChans + << " Databytes: " << detector_shm()->dataBytes; + } +} + +int slsDetector::getTotalNumberOfChannels(dimension d) const { + return detector_shm()->nChan[d] * detector_shm()->nChip[d]; +} + +int slsDetector::getTotalNumberOfChannelsInclGapPixels(dimension d) const { + return (detector_shm()->nChan[d] * detector_shm()->nChip[d] + + detector_shm()->gappixels * detector_shm()->nGappixels[d]); +} + +int slsDetector::getNChans() const { return detector_shm()->nChans; } + +int slsDetector::getNChans(dimension d) const { + return detector_shm()->nChan[d]; +} + +int slsDetector::getNChips() const { return detector_shm()->nChips; } + +int slsDetector::getNChips(dimension d) const { + return detector_shm()->nChip[d]; +} + +int slsDetector::getDetectorOffset(dimension d) const { + return detector_shm()->offset[d]; +} + +void slsDetector::setDetectorOffset(dimension d, int off) { + if (off >= 0) { + detector_shm()->offset[d] = off; + } +} + +void slsDetector::updateMultiSize(int detx, int dety) { + detector_shm()->multiSize[0] = detx; + detector_shm()->multiSize[1] = dety; +} + +int slsDetector::setOnline(int value) { + if (value != GET_ONLINE_FLAG) { + int old_flag = detector_shm()->onlineFlag; + detector_shm()->onlineFlag = OFFLINE_FLAG; + + if (value == ONLINE_FLAG) { + + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + client.close(); + detector_shm()->onlineFlag = ONLINE_FLAG; + + if (old_flag == OFFLINE_FLAG) { + + // check version compatibility (first time) + if ((detector_shm()->detectorControlAPIVersion == 0) || + (detector_shm()->detectorStopAPIVersion == 0)) { + checkDetectorVersionCompatibility(); + } + + FILE_LOG(logINFO) << "Detector connecting - updating!"; + updateDetector(); + } + } + } + return detector_shm()->onlineFlag; +} + +int slsDetector::getOnlineFlag() const { return detector_shm()->onlineFlag; } + +std::string slsDetector::checkOnline() { + std::string retval; + try { + // Need both control and stop socket to work! + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + auto stop = + DetectorSocket(detector_shm()->hostname, detector_shm()->stopPort); + detector_shm()->onlineFlag = ONLINE_FLAG; + } catch (...) { + detector_shm()->onlineFlag = OFFLINE_FLAG; + retval = detector_shm()->hostname; + } + return retval; +} + +int slsDetector::setControlPort(int port_number) { + int fnum = F_SET_PORT; + int ret = FAIL; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting control port to " << port_number; + + if (port_number >= 0 && port_number != detector_shm()->controlPort) { + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &port_number, + sizeof(port_number), &retval, + sizeof(retval)); + detector_shm()->controlPort = retval; + FILE_LOG(logDEBUG1) << "Control port: " << retval; + } else { + detector_shm()->controlPort = port_number; + } + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return detector_shm()->controlPort; +} + +int slsDetector::setStopPort(int port_number) { + int fnum = F_SET_PORT; + int ret = FAIL; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting stop port " + << " to " << port_number; + + if (port_number >= 0 && port_number != detector_shm()->stopPort) { + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto stop = DetectorSocket(detector_shm()->hostname, + detector_shm()->stopPort); + ret = stop.sendCommandThenRead(fnum, &port_number, + sizeof(port_number), &retval, + sizeof(retval)); + detector_shm()->stopPort = retval; + FILE_LOG(logDEBUG1) << "Stop port: " << retval; + } else { + detector_shm()->stopPort = port_number; + } + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return detector_shm()->stopPort; +} + +int slsDetector::setReceiverPort(int port_number) { + int fnum = F_SET_RECEIVER_PORT; + int ret = FAIL; + int retval = -1; + + FILE_LOG(logDEBUG1) << "Setting reciever port to " << port_number; + + if (port_number >= 0 && port_number != detector_shm()->receiverTCPPort) { + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto stop = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = stop.sendCommandThenRead(fnum, &port_number, + sizeof(port_number), &retval, + sizeof(retval)); + detector_shm()->receiverTCPPort = retval; + FILE_LOG(logDEBUG1) << "Receiver port: " << retval; + + } else { + detector_shm()->receiverTCPPort = port_number; + } + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return detector_shm()->receiverTCPPort; +} + +int slsDetector::getReceiverPort() const { + return detector_shm()->receiverTCPPort; +} + +int slsDetector::getControlPort() const { return detector_shm()->controlPort; } + +int slsDetector::getStopPort() const { return detector_shm()->stopPort; } + +int slsDetector::lockServer(int lock) { + int fnum = F_LOCK_SERVER; + int ret = FAIL; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting detector server lock to " << lock; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &lock, sizeof(lock), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Lock: " << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +std::string slsDetector::getLastClientIP() { + int fnum = F_GET_LAST_CLIENT_IP; + int ret = FAIL; + char retval[INET_ADDRSTRLEN]{}; + FILE_LOG(logDEBUG1) << "Getting last client ip to detector server"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Last client IP to detector: " << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +int slsDetector::exitServer() { + int fnum = F_EXIT_SERVER; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Sending exit command to detector server"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + FILE_LOG(logINFO) << "Shutting down the Detector server"; + } + return ret; +} + +int slsDetector::execCommand(const std::string &cmd) { + int fnum = F_EXEC_COMMAND; + int ret = FAIL; + char arg[MAX_STR_LENGTH] = {}; + char retval[MAX_STR_LENGTH] = {}; + sls::strcpy_safe(arg, cmd.c_str()); + FILE_LOG(logDEBUG1) << "Sending command to detector " << arg; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, arg, sizeof(arg), retval, + sizeof(retval)); + if (strlen(retval) != 0u) { + FILE_LOG(logINFO) << "Detector " << detId << " returned:\n" + << retval; + } + } + return ret; +} + +int slsDetector::updateDetectorNoWait(sls::ClientSocket &client) { + int n = 0, i32 = 0; + int64_t i64 = 0; + char lastClientIP[INET_ADDRSTRLEN] = {0}; + n += client.receiveData(lastClientIP, sizeof(lastClientIP)); + FILE_LOG(logDEBUG1) << "Updating detector last modified by " + << lastClientIP; + + // dr + n += client.receiveData(&i32, sizeof(i32)); + detector_shm()->dynamicRange = i32; + + // databytes + n += client.receiveData(&i32, sizeof(i32)); + detector_shm()->dataBytes = i32; + + // settings + if ((detector_shm()->myDetectorType != CHIPTESTBOARD) && + (detector_shm()->myDetectorType != MOENCH)) { + n += client.receiveData(&i32, sizeof(i32)); + detector_shm()->currentSettings = static_cast(i32); + } + + // threshold + if (detector_shm()->myDetectorType == EIGER) { + n += client.receiveData(&i32, sizeof(i32)); + detector_shm()->currentThresholdEV = i32; + } + + // frame number + n += client.receiveData(&i64, sizeof(i64)); + detector_shm()->timerValue[FRAME_NUMBER] = i64; + + // exptime + n += client.receiveData(&i64, sizeof(i64)); + detector_shm()->timerValue[ACQUISITION_TIME] = i64; + + // subexptime, subdeadtime + if (detector_shm()->myDetectorType == EIGER) { + n += client.receiveData(&i64, sizeof(i64)); + detector_shm()->timerValue[SUBFRAME_ACQUISITION_TIME] = i64; + + n += client.receiveData(&i64, sizeof(i64)); + detector_shm()->timerValue[SUBFRAME_DEADTIME] = i64; + } + + // period + n += client.receiveData(&i64, sizeof(i64)); + detector_shm()->timerValue[FRAME_PERIOD] = i64; + + // delay + if (detector_shm()->myDetectorType != EIGER) { + n += client.receiveData(&i64, sizeof(i64)); + detector_shm()->timerValue[DELAY_AFTER_TRIGGER] = i64; + } + + if (detector_shm()->myDetectorType == JUNGFRAU) { + // storage cell + n += client.receiveData(&i64, sizeof(i64)); + detector_shm()->timerValue[STORAGE_CELL_NUMBER] = i64; + + // storage cell delay + n += client.receiveData(&i64, sizeof(i64)); + detector_shm()->timerValue[STORAGE_CELL_DELAY] = i64; + } + + // cycles + n += client.receiveData(&i64, sizeof(i64)); + detector_shm()->timerValue[CYCLES_NUMBER] = i64; + + // readout flags + if (detector_shm()->myDetectorType == EIGER || + detector_shm()->myDetectorType == CHIPTESTBOARD) { + n += client.receiveData(&i32, sizeof(i32)); + detector_shm()->roFlags = static_cast(i32); + } + + // samples + if (detector_shm()->myDetectorType == CHIPTESTBOARD || + detector_shm()->myDetectorType == MOENCH) { + n += client.receiveData(&i64, sizeof(i64)); + if (i64 >= 0) { + detector_shm()->timerValue[SAMPLES] = i64; + } + } + + // roi + if (detector_shm()->myDetectorType == CHIPTESTBOARD || + detector_shm()->myDetectorType == MOENCH || + detector_shm()->myDetectorType == GOTTHARD) { + n += client.receiveData(&i32, sizeof(i32)); + detector_shm()->nROI = i32; + for (int i = 0; i < detector_shm()->nROI; ++i) { + n += client.receiveData(&i32, sizeof(i32)); + detector_shm()->roiLimits[i].xmin = i32; + n += client.receiveData(&i32, sizeof(i32)); + detector_shm()->roiLimits[i].xmax = i32; + n += client.receiveData(&i32, sizeof(i32)); + detector_shm()->roiLimits[i].ymin = i32; + n += client.receiveData(&i32, sizeof(i32)); + detector_shm()->roiLimits[i].xmax = i32; + } + // moench (send to processor) + if (detector_shm()->myDetectorType == MOENCH) { + sendROIToProcessor(); + } + } + + // update #nchans and databytes, as it depends on #samples, roi, + // readoutflags (ctb only) + if (detector_shm()->myDetectorType == CHIPTESTBOARD || + detector_shm()->myDetectorType == MOENCH) { + updateTotalNumberOfChannels(); + } + + if (n == 0) { + FILE_LOG(logERROR) << "Could not update detector, received 0 bytes"; + } + + return OK; +} + +int slsDetector::updateDetector() { + int fnum = F_UPDATE_CLIENT; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Sending update client to detector server"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + // if it returns ok (jungfrau in programming mode), dont update + if (ret == FORCE_UPDATE) { + ret = updateDetectorNoWait(client); + } + } + return ret; +} + +int slsDetector::writeConfigurationFile(const std::string &fname, + multiSlsDetector *m) { + int iline = 0; + std::ofstream outfile; + outfile.open(fname.c_str(), std::ios_base::out); + if (outfile.is_open()) { + iline = writeConfigurationFile(outfile, m); + outfile.close(); + } else { + throw RuntimeError("Could not open configuration file for writing"); + } + FILE_LOG(logINFO) << iline << " lines written to configuration file"; + return OK; +} + +int slsDetector::writeConfigurationFile(std::ofstream &outfile, + multiSlsDetector *m) { + + FILE_LOG(logDEBUG1) << "Write configuration file"; + + std::vector names; + // common config + names.emplace_back("hostname"); + names.emplace_back("port"); + names.emplace_back("stopport"); + names.emplace_back("settingsdir"); + names.emplace_back("ffdir"); + names.emplace_back("outdir"); + names.emplace_back("lock"); + // receiver config + names.emplace_back("zmqport"); + names.emplace_back("rx_zmqport"); + names.emplace_back("zmqip"); + names.emplace_back("rx_zmqip"); + names.emplace_back("rx_tcpport"); + + // detector specific config + switch (detector_shm()->myDetectorType) { + case GOTTHARD: + names.emplace_back("detectormac"); + names.emplace_back("detectorip"); + names.emplace_back("rx_udpport"); + names.emplace_back("rx_udpip"); + names.emplace_back("rx_udpmac"); + names.emplace_back("rx_hostname"); + + names.emplace_back("extsig:0"); + names.emplace_back("vhighvoltage"); + break; + case EIGER: + names.emplace_back("detectormac"); + names.emplace_back("detectorip"); + names.emplace_back("rx_udpport"); + names.emplace_back("rx_udpport2"); + names.emplace_back("rx_udpip"); + names.emplace_back("rx_udpmac"); + names.emplace_back("rx_hostname"); + + names.emplace_back("vhighvoltage"); + names.emplace_back("trimen"); + names.emplace_back("iodelay"); + names.emplace_back("tengiga"); + break; + case JUNGFRAU: + names.emplace_back("detectormac"); + names.emplace_back("detectormac2"); + names.emplace_back("detectorip"); + names.emplace_back("detectorip2"); + names.emplace_back("rx_udpport"); + names.emplace_back("rx_udpport2"); + names.emplace_back("rx_udpip"); + names.emplace_back("rx_udpip2"); + names.emplace_back("rx_udpmac"); + names.emplace_back("rx_udpmac2"); + names.emplace_back("rx_hostname"); + + names.emplace_back("powerchip"); + names.emplace_back("vhighvoltage"); + break; + case CHIPTESTBOARD: + names.emplace_back("detectormac"); + names.emplace_back("detectorip"); + names.emplace_back("rx_udpport"); + names.emplace_back("rx_udpip"); + names.emplace_back("rx_udpmac"); + names.emplace_back("rx_hostname"); + + names.emplace_back("vhighvoltage"); + break; + case MOENCH: + names.emplace_back("detectormac"); + names.emplace_back("detectorip"); + names.emplace_back("rx_udpport"); + names.emplace_back("rx_udpip"); + names.emplace_back("rx_udpmac"); + names.emplace_back("rx_hostname"); + + names.emplace_back("powerchip"); + names.emplace_back("vhighvoltage"); + break; + default: + throw RuntimeError( + "Write configuration file called with unknown detector: " + + std::to_string(detector_shm()->myDetectorType)); + } + + names.emplace_back("r_readfreq"); + names.emplace_back("rx_udpsocksize"); + names.emplace_back("rx_realudpsocksize"); + + auto cmd = slsDetectorCommand(m); + for (auto &name : names) { + char *args[] = {(char *)name.c_str()}; + outfile << detId << ":"; + outfile << name << " " << cmd.executeLine(1, args, GET_ACTION) + << std::endl; + } + return OK; +} + +slsDetectorDefs::detectorSettings slsDetector::getSettings() { + return sendSettingsOnly(GET_SETTINGS); +} + +slsDetectorDefs::detectorSettings +slsDetector::setSettings(detectorSettings isettings) { + FILE_LOG(logDEBUG1) << "slsDetector setSettings " << isettings; + + if (isettings == -1) { + return getSettings(); + } + + // eiger: only set shm, setting threshold loads the module data + if (detector_shm()->myDetectorType == EIGER) { + switch (isettings) { + case STANDARD: + case HIGHGAIN: + case LOWGAIN: + case VERYHIGHGAIN: + case VERYLOWGAIN: + detector_shm()->currentSettings = isettings; + return detector_shm()->currentSettings; + default: + std::ostringstream ss; + ss << "Unknown settings " << getDetectorSettings(isettings) + << " for this detector!"; + throw RuntimeError(ss.str()); + } + } + + // others: send only the settings, detector server will update dac values + // already in server + return sendSettingsOnly(isettings); +} + +slsDetectorDefs::detectorSettings +slsDetector::sendSettingsOnly(detectorSettings isettings) { + int fnum = F_SET_SETTINGS; + int ret = FAIL; + int arg = (int)isettings; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting settings to " << arg; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + client.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Settings: " << retval; + detector_shm()->currentSettings = (detectorSettings)retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return detector_shm()->currentSettings; +} + +int slsDetector::getThresholdEnergy() { + // moench - get threshold energy from processor (due to different clients, + // diff shm) + if (detector_shm()->myDetectorType == MOENCH) { + // get json from rxr, parse for threshold and update shm + getAdditionalJsonHeader(); + std::string result = getAdditionalJsonParameter("threshold"); + // convert to integer + try { + // udpate shm + detector_shm()->currentThresholdEV = stoi(result); + return detector_shm()->currentThresholdEV; + } + // not found or cannot scan integer + catch (...) { + return -1; + } + } + + int fnum = F_GET_THRESHOLD_ENERGY; + int ret = FAIL; + int retval = -1; + FILE_LOG(logDEBUG1) << "Getting threshold energy"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Threshold: " << retval; + detector_shm()->currentThresholdEV = retval; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return detector_shm()->currentThresholdEV; +} + +int slsDetector::setThresholdEnergy(int e_eV, detectorSettings isettings, + int tb) { + + // check as there is client processing + if (detector_shm()->myDetectorType == EIGER) { + setThresholdEnergyAndSettings(e_eV, isettings, tb); + return detector_shm()->currentThresholdEV; + } + + // moench - send threshold energy to processor + else if (detector_shm()->myDetectorType == MOENCH) { + std::string result = + setAdditionalJsonParameter("threshold", std::to_string(e_eV)); + if (result == std::to_string(e_eV)) { + // update shm + detector_shm()->currentThresholdEV = e_eV; + return detector_shm()->currentThresholdEV; + } + return -1; + } + throw RuntimeError( + "Set threshold energy not implemented for this detector"); +} + +int slsDetector::setThresholdEnergyAndSettings(int e_eV, + detectorSettings isettings, + int tb) { + + // if settings provided, use that, else use the shared memory variable + detectorSettings is = + ((isettings != GET_SETTINGS) ? isettings + : detector_shm()->currentSettings); + std::string ssettings; + switch (is) { + case STANDARD: + ssettings = "/standard"; + detector_shm()->currentSettings = STANDARD; + break; + case HIGHGAIN: + ssettings = "/highgain"; + detector_shm()->currentSettings = HIGHGAIN; + break; + case LOWGAIN: + ssettings = "/lowgain"; + detector_shm()->currentSettings = LOWGAIN; + break; + case VERYHIGHGAIN: + ssettings = "/veryhighgain"; + detector_shm()->currentSettings = VERYHIGHGAIN; + break; + case VERYLOWGAIN: + ssettings = "/verylowgain"; + detector_shm()->currentSettings = VERYLOWGAIN; + break; + default: + std::ostringstream ss; + ss << "Unknown settings " << getDetectorSettings(is) + << " for this detector!"; + throw RuntimeError(ss.str()); + } + + // verify e_eV exists in trimEneregies[] + if (!detector_shm()->nTrimEn || (e_eV < detector_shm()->trimEnergies[0]) || + (e_eV > detector_shm()->trimEnergies[detector_shm()->nTrimEn - 1])) { + throw RuntimeError("This energy " + std::to_string(e_eV) + + " not defined for this module!"); + } + + // find if interpolation required + bool interpolate = true; + for (int i = 0; i < detector_shm()->nTrimEn; ++i) { + if (detector_shm()->trimEnergies[i] == e_eV) { + interpolate = false; + break; + } + } + + // fill detector module structure + sls_detector_module *myMod = nullptr; + + // normal + if (!interpolate) { + // find their directory names + std::ostringstream ostfn; + ostfn << detector_shm()->settingsDir << ssettings << "/" << e_eV << "eV" + << "/noise.sn" << std::setfill('0') << std::setw(3) << std::dec + << getId(DETECTOR_SERIAL_NUMBER) << std::setbase(10); + std::string settingsfname = ostfn.str(); + FILE_LOG(logDEBUG1) << "Settings File is " << settingsfname; + + // read the files + // myMod = createModule(); // readSettings also checks if create module + // is null + if (nullptr == readSettingsFile(settingsfname, myMod, tb)) { + if (myMod) { + deleteModule(myMod); + } + return FAIL; + } + } + + // interpolate + else { + // find the trim values + int trim1 = -1, trim2 = -1; + for (int i = 0; i < detector_shm()->nTrimEn; ++i) { + if (e_eV < detector_shm()->trimEnergies[i]) { + trim2 = detector_shm()->trimEnergies[i]; + trim1 = detector_shm()->trimEnergies[i - 1]; + break; + } + } + // find their directory names + std::ostringstream ostfn; + ostfn << detector_shm()->settingsDir << ssettings << "/" << trim1 + << "eV" + << "/noise.sn" << std::setfill('0') << std::setw(3) << std::dec + << getId(DETECTOR_SERIAL_NUMBER) << std::setbase(10); + std::string settingsfname1 = ostfn.str(); + ostfn.str(""); + ostfn.clear(); + ostfn << detector_shm()->settingsDir << ssettings << "/" << trim2 + << "eV" + << "/noise.sn" << std::setfill('0') << std::setw(3) << std::dec + << getId(DETECTOR_SERIAL_NUMBER) << std::setbase(10); + std::string settingsfname2 = ostfn.str(); + // read the files + FILE_LOG(logDEBUG1) << "Settings Files are " << settingsfname1 + << " and " << settingsfname2; + sls_detector_module *myMod1 = createModule(); + sls_detector_module *myMod2 = createModule(); + if (nullptr == readSettingsFile(settingsfname1, myMod1, tb)) { + + deleteModule(myMod1); + deleteModule(myMod2); + throw RuntimeError( + "setThresholdEnergyAndSettings: Could not open settings file"); + } + if (nullptr == readSettingsFile(settingsfname2, myMod2, tb)) { + deleteModule(myMod1); + deleteModule(myMod2); + throw RuntimeError( + "setThresholdEnergyAndSettings: Could not open settings file"); + } + if (myMod1->iodelay != myMod2->iodelay) { + deleteModule(myMod1); + deleteModule(myMod2); + throw RuntimeError("setThresholdEnergyAndSettings: Iodelays do not " + "match between files"); + } + + // interpolate module + myMod = interpolateTrim(myMod1, myMod2, e_eV, trim1, trim2, tb); + if (myMod == nullptr) { + deleteModule(myMod1); + deleteModule(myMod2); + throw RuntimeError("setThresholdEnergyAndSettings: Could not " + "interpolate, different " + "dac values in files"); + } + // interpolate tau + myMod->iodelay = myMod1->iodelay; + myMod->tau = + linearInterpolation(e_eV, trim1, trim2, myMod1->tau, myMod2->tau); + // printf("new tau:%d\n",tau); + + deleteModule(myMod1); + deleteModule(myMod2); + } + + myMod->reg = detector_shm()->currentSettings; + myMod->eV = e_eV; + setModule(*myMod, tb); + deleteModule(myMod); + if (getSettings() != is) { + throw RuntimeError("setThresholdEnergyAndSettings: Could not set " + "settings in detector"); + } + return OK; +} + +std::string slsDetector::getSettingsDir() { + return std::string(detector_shm()->settingsDir); +} + +std::string slsDetector::setSettingsDir(const std::string &dir) { + sls::strcpy_safe(detector_shm()->settingsDir, dir.c_str()); + return detector_shm()->settingsDir; +} + +int slsDetector::loadSettingsFile(const std::string &fname) { + std::string fn = fname; + std::ostringstream ostfn; + ostfn << fname; + + // find specific file if it has detid in file name (.snxxx) + if (detector_shm()->myDetectorType == EIGER) { + if (fname.find(".sn") == std::string::npos && + fname.find(".trim") == std::string::npos && + fname.find(".settings") == std::string::npos) { + ostfn << ".sn" << std::setfill('0') << std::setw(3) << std::dec + << getId(DETECTOR_SERIAL_NUMBER); + } + } + fn = ostfn.str(); + + // read settings file + sls_detector_module *myMod = nullptr; + myMod = readSettingsFile(fn, myMod); + + // set module + int ret = FAIL; + if (myMod != nullptr) { + myMod->reg = -1; + myMod->eV = -1; + ret = setModule(*myMod); + deleteModule(myMod); + } + return ret; +} + +int slsDetector::saveSettingsFile(const std::string &fname) { + std::string fn = fname; + std::ostringstream ostfn; + ostfn << fname; + + // find specific file if it has detid in file name (.snxxx) + if (detector_shm()->myDetectorType == EIGER) { + ostfn << ".sn" << std::setfill('0') << std::setw(3) << std::dec + << getId(DETECTOR_SERIAL_NUMBER); + } + fn = ostfn.str(); + + // get module + int ret = FAIL; + sls_detector_module *myMod = getModule(); + if (myMod != nullptr) { + ret = writeSettingsFile(fn, *myMod); + deleteModule(myMod); + } + return ret; +} + +slsDetectorDefs::runStatus slsDetector::getRunStatus() { + int fnum = F_GET_RUN_STATUS; + int ret = FAIL; + runStatus retval = ERROR; + FILE_LOG(logDEBUG1) << "Getting status"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto stop = + DetectorSocket(detector_shm()->hostname, detector_shm()->stopPort); + ret = + stop.sendCommandThenRead(fnum, nullptr, 0, &retval, sizeof(retval)); + FILE_LOG(logDEBUG1) << "Detector status: " << runStatusType(retval); + if (ret == FORCE_UPDATE) { + updateDetector(); + } + } + return retval; +} + +int slsDetector::prepareAcquisition() { + int fnum = F_PREPARE_ACQUISITION; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Preparing Detector for Acquisition"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + FILE_LOG(logDEBUG1) << "Prepare Acquisition successful"; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int slsDetector::startAcquisition() { + int fnum = F_START_ACQUISITION; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Starting Acquisition"; + + detector_shm()->stoppedFlag = 0; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + FILE_LOG(logDEBUG1) << "Starting Acquisition successful"; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int slsDetector::stopAcquisition() { + // get status before stopping acquisition + runStatus s = ERROR, r = ERROR; + if (detector_shm()->receiver_upstream) { + s = getRunStatus(); + r = getReceiverStatus(); + } + int fnum = F_STOP_ACQUISITION; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Stopping Acquisition"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto stop = + DetectorSocket(detector_shm()->hostname, detector_shm()->stopPort); + ret = stop.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + FILE_LOG(logDEBUG1) << "Stopping Acquisition successful"; + if (ret == FORCE_UPDATE) { + updateDetector(); + } + } + detector_shm()->stoppedFlag = 1; + // if rxr streaming and acquisition finished, restream dummy stop packet + if ((detector_shm()->receiver_upstream) && (s == IDLE) && (r == IDLE)) { + restreamStopFromReceiver(); + } + return ret; +} + +int slsDetector::sendSoftwareTrigger() { + int fnum = F_SOFTWARE_TRIGGER; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Sending software trigger"; + + detector_shm()->stoppedFlag = 0; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + FILE_LOG(logDEBUG1) << "Sending software trigger successful"; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int slsDetector::startAndReadAll() { + int fnum = F_START_AND_READ_ALL; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Starting and reading all frames"; + + detector_shm()->stoppedFlag = 0; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + // TODO! how to we hande this? ret == FAIL --> + // detector_shm()->stoppedFlag = 1; + FILE_LOG(logDEBUG1) << "Detector successfully finished acquisition"; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int slsDetector::startReadOut() { + int fnum = F_START_READOUT; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Starting readout"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + FILE_LOG(logDEBUG1) << "Starting detector readout successful"; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int slsDetector::readAll() { + int fnum = F_READ_ALL; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Reading all frames"; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + // TODO! how to we hande this? ret == FAIL --> + // detector_shm()->stoppedFlag = 1; + FILE_LOG(logDEBUG1) + << "Detector successfully finished reading all frames"; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int slsDetector::configureMAC() { + int fnum = F_CONFIGURE_MAC; + int ret = FAIL; + const size_t array_size = 50; + const size_t n_args = 14; + const size_t n_retvals = 2; + char args[n_args][array_size]{}; + char retvals[n_retvals][array_size]{}; + FILE_LOG(logDEBUG1) << "Configuring MAC"; + if (detector_shm()->receiverUDPIP == 0) { + // If hostname is valid ip use that, oterwise lookup hostname + detector_shm()->receiverUDPIP = detector_shm()->receiver_hostname; + if (detector_shm()->receiverUDPIP == 0) { + detector_shm()->receiverUDPIP = + HostnameToIp(detector_shm()->receiver_hostname); + } + } + + if (detector_shm()->receiverUDPMAC == 0) { + throw RuntimeError( + "configureMAC: Error. Receiver UDP MAC Addresses not set"); + } + FILE_LOG(logDEBUG1) << "rx_hostname and rx_udpmac are valid "; + + // Jungfrau second interface + if (detector_shm()->numUDPInterfaces == 2) { + if (detector_shm()->receiverUDPIP2 == 0) { + detector_shm()->receiverUDPIP2 = detector_shm()->receiverUDPIP; + } + if (detector_shm()->receiverUDPMAC2 == 0) { + throw RuntimeError( + "configureMAC: Error. Receiver UDP MAC Addresses 2 not set"); + } + FILE_LOG(logDEBUG1) << "rx_udpmac2 is valid "; + } + + // copy to args and convert to hex + snprintf(args[0], array_size, "%x", detector_shm()->receiverUDPPort); + sls::strcpy_safe(args[1], getReceiverUDPIP().hex()); + sls::strcpy_safe(args[2], getReceiverUDPMAC().hex()); + sls::strcpy_safe(args[3], getDetectorIP().hex()); + sls::strcpy_safe(args[4], getDetectorMAC().hex()); + snprintf(args[5], array_size, "%x", detector_shm()->receiverUDPPort2); + sls::strcpy_safe(args[6], getReceiverUDPIP2().hex()); + sls::strcpy_safe(args[7], getReceiverUDPMAC2().hex()); + sls::strcpy_safe(args[8], getDetectorIP2().hex()); + sls::strcpy_safe(args[9], getDetectorMAC2().hex()); + snprintf(args[10], array_size, "%x", detector_shm()->numUDPInterfaces); + snprintf(args[11], array_size, "%x", detector_shm()->selectedUDPInterface); + + // 2d positions to detector to put into udp header + { + int pos[2] = {0, 0}; + int max = + detector_shm()->multiSize[1] * (detector_shm()->numUDPInterfaces); + // row + pos[0] = (detId % max); + // col for horiz. udp ports + pos[1] = + (detId / max) * ((detector_shm()->myDetectorType == EIGER) ? 2 : 1); + // pos[2] (z is reserved) + FILE_LOG(logDEBUG1) << "Detector [" << detId << "] - (" << pos[0] << "," + << pos[1] << ")"; + snprintf(args[12], array_size, "%x", pos[0]); + snprintf(args[13], array_size, "%x", pos[1]); + } + + FILE_LOG(logDEBUG1) << "receiver udp port:" << std::dec << args[0] << "-"; + FILE_LOG(logDEBUG1) << "receiver udp ip:" << args[1] << "-"; + FILE_LOG(logDEBUG1) << "receiver udp mac:" << args[2] << "-"; + FILE_LOG(logDEBUG1) << "detecotor udp ip:" << args[3] << "-"; + FILE_LOG(logDEBUG1) << "detector udp mac:" << args[4] << "-"; + FILE_LOG(logDEBUG1) << "receiver udp port2:" << std::dec << args[5] << "-"; + FILE_LOG(logDEBUG1) << "receiver udp ip2:" << args[6] << "-"; + FILE_LOG(logDEBUG1) << "receiver udp mac2:" << args[7] << "-"; + FILE_LOG(logDEBUG1) << "detecotor udp ip2:" << args[8] << "-"; + FILE_LOG(logDEBUG1) << "detector udp mac2:" << args[9] << "-"; + FILE_LOG(logDEBUG1) << "number of udp interfaces:" << std::dec << args[10] + << "-"; + FILE_LOG(logDEBUG1) << "selected udp interface:" << std::dec << args[11] + << "-"; + FILE_LOG(logDEBUG1) << "row:" << args[12] << "-"; + FILE_LOG(logDEBUG1) << "col:" << args[13] << "-"; + + // send to server + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), retvals, + sizeof(retvals)); + + uint64_t detector_mac = 0; + uint32_t detector_ip = 0; + sscanf(retvals[0], "%lx", + &detector_mac); // TODO! (Erik) send mac and ip as int + sscanf(retvals[1], "%x", &detector_ip); + detector_ip = __builtin_bswap32(detector_ip); + + if (detector_shm()->detectorMAC != detector_mac) { + detector_shm()->detectorMAC = detector_mac; + FILE_LOG(logINFO) + << detId << ": Detector MAC updated to " << getDetectorMAC(); + } + + if (detector_shm()->detectorIP != detector_ip) { + detector_shm()->detectorIP = detector_ip; + FILE_LOG(logINFO) + << detId << ": Detector IP updated to " << getDetectorIP(); + } + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int64_t slsDetector::setTimer(timerIndex index, int64_t t) { + int fnum = F_SET_TIMER; + int ret = FAIL; + int64_t args[2] = {(int64_t)index, t}; + int64_t retval = -1; + FILE_LOG(logDEBUG1) << "Setting " << getTimerType(index) << " to " << t + << " ns/value"; + + // meausurement is only shm level + if (index == MEASUREMENTS_NUMBER) { + if (t >= 0) { + detector_shm()->timerValue[index] = t; + FILE_LOG(logDEBUG1) << getTimerType(index) << ": " << t; + } + return detector_shm()->timerValue[index]; + } + + // send to detector + int64_t oldtimer = detector_shm()->timerValue[index]; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << getTimerType(index) << ": " << retval; + detector_shm()->timerValue[index] = retval; + // update #nchans and databytes, as it depends on #samples, roi, + // readoutflags (ctb only) + if (index == SAMPLES && + (detector_shm()->myDetectorType == CHIPTESTBOARD || + detector_shm()->myDetectorType == MOENCH)) { + updateTotalNumberOfChannels(); + } + if (ret == FORCE_UPDATE) { + client.close(); + ret = updateDetector(); + } + } + + // setting timers consequences (eiger (ratecorr) ) + // (a get can also change timer value, hence check difference) + if (oldtimer != detector_shm()->timerValue[index]) { + // eiger: change exptime/subexptime, set rate correction to update table + if (detector_shm()->myDetectorType == EIGER) { + int dr = detector_shm()->dynamicRange; + if ((dr == 32 && index == SUBFRAME_ACQUISITION_TIME) || + (dr == 16 && index == ACQUISITION_TIME)) { + int r = getRateCorrection(); + if (r) { + setRateCorrection(r); + } + } + } + } + + // send to reciever + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG && ret == OK) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + // char mess[MAX_STR_LENGTH]{}; + switch (index) { + case FRAME_NUMBER: + case FRAME_PERIOD: + case CYCLES_NUMBER: + case ACQUISITION_TIME: + case SUBFRAME_ACQUISITION_TIME: + case SUBFRAME_DEADTIME: + case SAMPLES: + case STORAGE_CELL_NUMBER: + // send + fnum = F_SET_RECEIVER_TIMER; + ret = FAIL; + args[1] = detector_shm() + ->timerValue[index]; // to the value given by detector + retval = -1; + + // rewrite args + if ((index == FRAME_NUMBER) || (index == CYCLES_NUMBER) || + (index == STORAGE_CELL_NUMBER)) { + args[1] = + detector_shm()->timerValue[FRAME_NUMBER] * + ((detector_shm()->timerValue[CYCLES_NUMBER] > 0) + ? (detector_shm()->timerValue[CYCLES_NUMBER]) + : 1) * + ((detector_shm()->timerValue[STORAGE_CELL_NUMBER] > 0) + ? (detector_shm()->timerValue[STORAGE_CELL_NUMBER]) + 1 + : 1); + } + FILE_LOG(logDEBUG1) + << "Sending " + << (((index == FRAME_NUMBER) || (index == CYCLES_NUMBER) || + (index == STORAGE_CELL_NUMBER)) + ? "(#Frames) * (#cycles) * (#storage cells)" + : getTimerType(index)) + << " to receiver: " << args[1]; + ret = receiver.sendCommandThenRead(fnum, args, sizeof(args), + &retval, sizeof(retval)); + if (ret == FORCE_UPDATE) { + receiver.close(); + ret = updateCachedReceiverVariables(); + } + break; + default: + break; + } + } + return detector_shm()->timerValue[index]; +} + +int64_t slsDetector::getTimeLeft(timerIndex index) { + int fnum = F_GET_TIME_LEFT; + int ret = FAIL; + int64_t retval = -1; + FILE_LOG(logDEBUG1) << "Getting " << getTimerType(index) << " left"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto stop = + DetectorSocket(detector_shm()->hostname, detector_shm()->stopPort); + ret = stop.sendCommandThenRead(fnum, &index, sizeof(index), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << getTimerType(index) << " left: " << retval; + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + } + return retval; +} + +int slsDetector::setSpeed(speedVariable sp, int value, int mode) { + int fnum = F_SET_SPEED; + int ret = FAIL; + int args[3] = {(int)sp, value, mode}; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting speed index " << sp << " to " << value + << " mode: " << mode; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Speed index " << sp << ": " << retval; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return retval; +} + +int slsDetector::setDynamicRange(int n) { + // TODO! Properly handle fail + int fnum = F_SET_DYNAMIC_RANGE; + int ret = FAIL; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting dynamic range to " << n; + + // send to detector + int olddr = detector_shm()->dynamicRange; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + // char mess[MAX_STR_LENGTH] = {}; + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &n, sizeof(n), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Dynamic Range: " << retval; + detector_shm()->dynamicRange = retval; + if (ret == FORCE_UPDATE) { + client.close(); + ret = updateDetector(); + } + } + + // only for eiger + // setting dr consequences on databytes shm + // (a get can also change timer value, hence check difference) + if (olddr != detector_shm()->dynamicRange) { + detector_shm()->dataBytes = + detector_shm()->nChips * detector_shm()->nChans * retval / 8; + detector_shm()->dataBytesInclGapPixels = + (detector_shm()->nChip[X] * detector_shm()->nChan[X] + + detector_shm()->gappixels * detector_shm()->nGappixels[X]) * + (detector_shm()->nChip[Y] * detector_shm()->nChan[Y] + + detector_shm()->gappixels * detector_shm()->nGappixels[Y]) * + retval / 8; + FILE_LOG(logDEBUG1) << "Data bytes " << detector_shm()->dataBytes; + FILE_LOG(logDEBUG1) << "Data bytes including gap pixels" + << detector_shm()->dataBytesInclGapPixels; + } + + // send to receiver + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG && ret == OK) { + fnum = F_SET_RECEIVER_DYNAMIC_RANGE; + ret = FAIL; + n = detector_shm()->dynamicRange; + retval = -1; + FILE_LOG(logDEBUG1) << "Sending dynamic range to receiver: " << n; + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &n, sizeof(n), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver Dynamic range: " << retval; + if (ret == FORCE_UPDATE) { + receiver.close(); + ret = updateCachedReceiverVariables(); + } + } + return detector_shm()->dynamicRange; +} + +int slsDetector::getDataBytes() { return detector_shm()->dataBytes; } + +int slsDetector::getDataBytesInclGapPixels() { + return detector_shm()->dataBytesInclGapPixels; +} + +int slsDetector::setDAC(int val, dacIndex index, int mV) { + int fnum = F_SET_DAC; + int ret = FAIL; + int args[3]{static_cast(index), mV, val}; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting DAC " << index << " to " << val + << (mV ? "mV" : "dac units"); + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Dac index " << index << ": " << retval + << (mV ? "mV" : "dac units"); + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +int slsDetector::getADC(dacIndex index) { + int fnum = F_GET_ADC; + int arg = static_cast(index); + int retval = -1; + FILE_LOG(logDEBUG1) << "Getting ADC " << index; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + client.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "ADC (" << index << "): " << retval; + } + return retval; +} + +slsDetectorDefs::externalCommunicationMode +slsDetector::setExternalCommunicationMode(externalCommunicationMode pol) { + int fnum = F_SET_EXTERNAL_COMMUNICATION_MODE; + int ret = FAIL; + auto arg = static_cast(pol); + externalCommunicationMode retval = GET_EXTERNAL_COMMUNICATION_MODE; + FILE_LOG(logDEBUG1) << "Setting communication to mode " << pol; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Timing Mode: " << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +slsDetectorDefs::externalSignalFlag +slsDetector::setExternalSignalFlags(externalSignalFlag pol, int signalindex) { + int fnum = F_SET_EXTERNAL_SIGNAL_FLAG; + int ret = FAIL; + int args[2]{signalindex, pol}; + externalSignalFlag retval = GET_EXTERNAL_SIGNAL_FLAG; + FILE_LOG(logDEBUG1) << "Setting signal " << signalindex << " to flag " + << pol; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Ext Signal (" << signalindex << "): " << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +int slsDetector::setReadOutFlags(readOutFlags flag) { + int fnum = F_SET_READOUT_FLAGS; + int ret = FAIL; + auto arg = static_cast(flag); + readOutFlags retval = GET_READOUT_FLAGS; + FILE_LOG(logDEBUG1) << "Setting readout flags to " << flag; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Readout flag: " << retval; + detector_shm()->roFlags = (readOutFlags)retval; + // update #nchans and databytes, as it depends on #samples, roi, + // readoutflags (ctb only) + if (detector_shm()->myDetectorType == CHIPTESTBOARD) { + updateTotalNumberOfChannels(); + } + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + + // sending to receiver + if (ret != FAIL) { + fnum = F_RECEIVER_SET_READOUT_FLAGS; + ret = FAIL; + arg = detector_shm()->roFlags; + retval = static_cast(-1); + FILE_LOG(logDEBUG1) << "Setting receiver readout flags to " << arg; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver readout flag: " << retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + } + return detector_shm()->roFlags; +} + +uint32_t slsDetector::writeRegister(uint32_t addr, uint32_t val) { + int fnum = F_WRITE_REGISTER; + int ret = FAIL; + uint32_t args[]{addr, val}; + uint32_t retval = -1; + FILE_LOG(logDEBUG1) << "Writing to register 0x" << std::hex << addr + << "data: 0x" << std::hex << val << std::dec; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Register 0x" << std::hex << addr << ": 0x" + << std::hex << retval << std::dec; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return retval; +} + +uint32_t slsDetector::readRegister(uint32_t addr) { + int fnum = F_READ_REGISTER; + int ret = FAIL; + uint32_t arg = addr; + uint32_t retval = -1; + FILE_LOG(logDEBUG1) << "Reading register 0x" << std::hex << addr + << std::dec; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Register 0x" << std::hex << addr << ": 0x" + << std::hex << retval << std::dec; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +uint32_t slsDetector::setBit(uint32_t addr, int n) { + if (n < 0 || n > 31) { + throw RuntimeError("Bit number " + std::to_string(n) + " out of Range"); + } else { + uint32_t val = readRegister(addr); + return writeRegister(addr, val | 1 << n); + } +} + +uint32_t slsDetector::clearBit(uint32_t addr, int n) { + if (n < 0 || n > 31) { + throw RuntimeError("Bit number " + std::to_string(n) + " out of Range"); + } else { + uint32_t val = readRegister(addr); + return writeRegister(addr, val & ~(1 << n)); + } +} + +std::string slsDetector::setDetectorMAC(const std::string &detectorMAC) { + auto addr = MacAddr(detectorMAC); + if (addr == 0) { + throw RuntimeError( + "server MAC Address should be in xx:xx:xx:xx:xx:xx format"); + } + detector_shm()->detectorMAC = addr; + if (strcmp(detector_shm()->receiver_hostname, "none") == 0) { + FILE_LOG(logDEBUG1) << "Receiver hostname not set yet"; + } else if (setUDPConnection() == FAIL) { + FILE_LOG(logWARNING) << "UDP connection set up failed"; + } + + return getDetectorMAC().str(); +} + +MacAddr slsDetector::getDetectorMAC() { return detector_shm()->detectorMAC; } + +std::string slsDetector::setDetectorMAC2(const std::string &detectorMAC) { + auto addr = MacAddr(detectorMAC); + if (addr == 0) { + throw RuntimeError( + "server MAC Address 2 should be in xx:xx:xx:xx:xx:xx format"); + } + detector_shm()->detectorMAC2 = addr; + if (strcmp(detector_shm()->receiver_hostname, "none") == 0) { + FILE_LOG(logDEBUG1) << "Receiver hostname not set yet"; + } else if (setUDPConnection() == FAIL) { + FILE_LOG(logWARNING) << "UDP connection set up failed"; + } + return getDetectorMAC2().str(); +} + +MacAddr slsDetector::getDetectorMAC2() { return detector_shm()->detectorMAC2; } + +std::string slsDetector::setDetectorIP(const std::string &ip) { + auto addr = IpAddr(ip); + if (addr == 0) { + throw RuntimeError("setDetectorIP: IP Address should be VALID and " + "in xxx.xxx.xxx.xxx format"); + } + detector_shm()->detectorIP = ip; + if (strcmp(detector_shm()->receiver_hostname, "none") == 0) { + FILE_LOG(logDEBUG1) << "Receiver hostname not set yet"; + } else if (setUDPConnection() == FAIL) { + FILE_LOG(logWARNING) << "UDP connection set up failed"; + } + return getDetectorIP().str(); +} + +IpAddr slsDetector::getDetectorIP() const { return detector_shm()->detectorIP; } + +std::string slsDetector::setDetectorIP2(const std::string &ip) { + auto addr = IpAddr(ip); + if (addr == 0) { + throw RuntimeError("setDetectorIP: IP2 Address should be VALID and " + "in xxx.xxx.xxx.xxx format"); + } + detector_shm()->detectorIP2 = ip; + if (strcmp(detector_shm()->receiver_hostname, "none") == 0) { + FILE_LOG(logDEBUG1) << "Receiver hostname not set yet"; + } else if (setUDPConnection() == FAIL) { + FILE_LOG(logWARNING) << "UDP connection set up failed"; + } + return getDetectorIP().str(); +} + +IpAddr slsDetector::getDetectorIP2() const { + return detector_shm()->detectorIP2; +} + +std::string slsDetector::setReceiverHostname(const std::string &receiverIP) { + FILE_LOG(logDEBUG1) << "Setting up Receiver with " << receiverIP; + // recieverIP is none + if (receiverIP == "none") { + memset(detector_shm()->receiver_hostname, 0, MAX_STR_LENGTH); + sls::strcpy_safe(detector_shm()->receiver_hostname, "none"); + detector_shm()->receiverOnlineFlag = OFFLINE_FLAG; + return std::string(detector_shm()->receiver_hostname); + } + // stop acquisition if running + if (getRunStatus() == RUNNING) { + FILE_LOG(logWARNING) << "Acquisition already running, Stopping it."; + stopAcquisition(); + } + // update detector before receiver + updateDetector(); + + // start updating + sls::strcpy_safe(detector_shm()->receiver_hostname, receiverIP.c_str()); + + if (setReceiverOnline(ONLINE_FLAG) == ONLINE_FLAG) { + FILE_LOG(logDEBUG1) + << "detector type:" + << (slsDetectorDefs::detectorTypeToString( + detector_shm()->myDetectorType)) + << "\ndetector id:" << detId + << "\ndetector hostname:" << detector_shm()->hostname + << "\nfile path:" << detector_shm()->receiver_filePath + << "\nfile name:" << detector_shm()->receiver_fileName + << "\nfile index:" << detector_shm()->rxFileIndex + << "\nfile format:" << detector_shm()->rxFileFormat + << "\nr_framesperfile:" << detector_shm()->rxFramesPerFile + << "\nr_discardpolicy:" << detector_shm()->receiver_frameDiscardMode + << "\nr_padding:" << detector_shm()->rxFramePadding + << "\nwrite enable:" << detector_shm()->rxFileWrite + << "\noverwrite enable:" << detector_shm()->rxFileOverWrite + << "\nframe index needed:" + << ((detector_shm()->timerValue[FRAME_NUMBER] * + detector_shm()->timerValue[CYCLES_NUMBER]) > 1) + << "\nframe period:" << (detector_shm()->timerValue[FRAME_PERIOD]) + << "\nframe number:" << (detector_shm()->timerValue[FRAME_NUMBER]) + << "\nsub exp time:" + << (detector_shm()->timerValue[SUBFRAME_ACQUISITION_TIME]) + << "\nsub dead time:" + << (detector_shm()->timerValue[SUBFRAME_DEADTIME]) + << "\nsamples:" << (detector_shm()->timerValue[SAMPLES]) + << "\ndynamic range:" << detector_shm()->dynamicRange + << "\nflippeddatax:" << (detector_shm()->flippedData[X]) + << "\nactivated: " << detector_shm()->activated + << "\nreceiver deactivated padding: " + << detector_shm()->receiver_deactivatedPaddingEnable + << "\nsilent Mode:" << detector_shm()->receiver_silentMode + << "\n10GbE:" << detector_shm()->tenGigaEnable + << "\nGap pixels: " << detector_shm()->gappixels + << "\nr_readfreq:" << detector_shm()->receiver_read_freq + << "\nrx streaming port:" << detector_shm()->receiver_zmqport + << "\nrx streaming source ip:" << detector_shm()->receiver_zmqip + << "\nrx additional json header:" + << detector_shm()->receiver_additionalJsonHeader + << "\nrx_datastream:" << enableDataStreamingFromReceiver(-1) + << std::endl; + + if (setDetectorType(detector_shm()->myDetectorType) != GENERIC) { + sendMultiDetectorSize(); + setDetectorId(); + setDetectorHostname(); + setUDPConnection(); + setReceiverUDPSocketBufferSize(0); + setFilePath(detector_shm()->receiver_filePath); + setFileName(detector_shm()->receiver_fileName); + setFileIndex(detector_shm()->rxFileIndex); + setFileFormat(detector_shm()->rxFileFormat); + setFramesPerFile(detector_shm()->rxFramesPerFile); + setReceiverFramesDiscardPolicy( + detector_shm()->receiver_frameDiscardMode); + setPartialFramesPadding(detector_shm()->rxFramePadding); + setFileWrite(detector_shm()->rxFileWrite); + setFileOverWrite(detector_shm()->rxFileOverWrite); + setTimer(FRAME_PERIOD, detector_shm()->timerValue[FRAME_PERIOD]); + setTimer(FRAME_NUMBER, detector_shm()->timerValue[FRAME_NUMBER]); + setTimer(ACQUISITION_TIME, + detector_shm()->timerValue[ACQUISITION_TIME]); + + // detector specific + switch (detector_shm()->myDetectorType) { + + case EIGER: + setTimer(SUBFRAME_ACQUISITION_TIME, + detector_shm()->timerValue[SUBFRAME_ACQUISITION_TIME]); + setTimer(SUBFRAME_DEADTIME, + detector_shm()->timerValue[SUBFRAME_DEADTIME]); + setDynamicRange(detector_shm()->dynamicRange); + setFlippedData(X, -1); + activate(-1); + setDeactivatedRxrPaddingMode( + detector_shm()->receiver_deactivatedPaddingEnable); + enableGapPixels(detector_shm()->gappixels); + enableTenGigabitEthernet(detector_shm()->tenGigaEnable); + setReadOutFlags(GET_READOUT_FLAGS); + break; + + case CHIPTESTBOARD: + setTimer(SAMPLES, detector_shm()->timerValue[SAMPLES]); + enableTenGigabitEthernet(detector_shm()->tenGigaEnable); + setReadOutFlags(GET_READOUT_FLAGS); + break; + + case MOENCH: + setTimer(SAMPLES, detector_shm()->timerValue[SAMPLES]); + enableTenGigabitEthernet(detector_shm()->tenGigaEnable); + break; + + default: + break; + } + + setReceiverSilentMode(detector_shm()->receiver_silentMode); + // data streaming + setReceiverStreamingFrequency(detector_shm()->receiver_read_freq); + setReceiverStreamingPort(getReceiverStreamingPort()); + setReceiverStreamingIP(getReceiverStreamingIP()); + setAdditionalJsonHeader( + detector_shm()->receiver_additionalJsonHeader); + enableDataStreamingFromReceiver( + enableDataStreamingFromReceiver(-1)); + if (detector_shm()->myDetectorType == GOTTHARD || + detector_shm()->myDetectorType == CHIPTESTBOARD || + detector_shm()->myDetectorType == MOENCH) { + sendROI(-1, nullptr); + } + } + } + return std::string(detector_shm()->receiver_hostname); +} + +std::string slsDetector::getReceiverHostname() const { + return std::string(detector_shm()->receiver_hostname); +} + +std::string slsDetector::setReceiverUDPIP(const std::string &udpip) { + auto ip = IpAddr(udpip); + if (ip == 0) { + throw ReceiverError("setReceiverUDPIP: UDP IP Address should be " + "VALID and in xxx.xxx.xxx.xxx format"); + } + detector_shm()->receiverUDPIP = ip; + if (!strcmp(detector_shm()->receiver_hostname, "none")) { + FILE_LOG(logDEBUG1) << "Receiver hostname not set yet"; + } else if (setUDPConnection() == FAIL) { + FILE_LOG(logWARNING) << "UDP connection set up failed"; + } + return getReceiverUDPIP().str(); +} + +sls::IpAddr slsDetector::getReceiverUDPIP() const { + return detector_shm()->receiverUDPIP; +} + +std::string slsDetector::setReceiverUDPIP2(const std::string &udpip) { + auto ip = IpAddr(udpip); + if (ip == 0) { + throw ReceiverError("setReceiverUDPIP: UDP IP Address 2 should be " + "VALID and in xxx.xxx.xxx.xxx format"); + } + detector_shm()->receiverUDPIP2 = ip; + if (!strcmp(detector_shm()->receiver_hostname, "none")) { + FILE_LOG(logDEBUG1) << "Receiver hostname not set yet"; + } else if (setUDPConnection() == FAIL) { + FILE_LOG(logWARNING) << "UDP connection set up failed"; + } + return getReceiverUDPIP2().str(); +} + +sls::IpAddr slsDetector::getReceiverUDPIP2() const { + return detector_shm()->receiverUDPIP2; +} + +std::string slsDetector::setReceiverUDPMAC(const std::string &udpmac) { + auto mac = MacAddr(udpmac); + if (mac == 0) { + throw ReceiverError("Could not decode UDPMAC from: " + udpmac); + } + detector_shm()->receiverUDPMAC = mac; + return getReceiverUDPMAC().str(); +} + +MacAddr slsDetector::getReceiverUDPMAC() const { + return detector_shm()->receiverUDPMAC; +} + +std::string slsDetector::setReceiverUDPMAC2(const std::string &udpmac) { + auto mac = MacAddr(udpmac); + if (mac == 0) { + throw ReceiverError("Could not decode UDPMA2C from: " + udpmac); + } + detector_shm()->receiverUDPMAC2 = mac; + return getReceiverUDPMAC2().str(); +} + +MacAddr slsDetector::getReceiverUDPMAC2() const { + return detector_shm()->receiverUDPMAC2; +} + +int slsDetector::setReceiverUDPPort(int udpport) { + detector_shm()->receiverUDPPort = udpport; + if (!strcmp(detector_shm()->receiver_hostname, "none")) { + FILE_LOG(logDEBUG1) << "Receiver hostname not set yet"; + } else if (setUDPConnection() == FAIL) { + FILE_LOG(logWARNING) << "UDP connection set up failed"; + } + return detector_shm()->receiverUDPPort; +} + +int slsDetector::getReceiverUDPPort() const { + return detector_shm()->receiverUDPPort; +} + +int slsDetector::setReceiverUDPPort2(int udpport) { + detector_shm()->receiverUDPPort2 = udpport; + if (!strcmp(detector_shm()->receiver_hostname, "none")) { + FILE_LOG(logDEBUG1) << "Receiver hostname not set yet"; + } else if (setUDPConnection() == FAIL) { + FILE_LOG(logWARNING) << "UDP connection set up failed"; + } + return detector_shm()->receiverUDPPort2; +} + +int slsDetector::getReceiverUDPPort2() const { + return detector_shm()->receiverUDPPort2; +} + +int slsDetector::setNumberofUDPInterfaces(int n) { + if (detector_shm()->myDetectorType != JUNGFRAU) { + throw RuntimeError( + "Cannot choose number of interfaces for this detector"); + } + detector_shm()->numUDPInterfaces = (n > 1 ? 2 : 1); + if (!strcmp(detector_shm()->receiver_hostname, "none")) { + FILE_LOG(logDEBUG1) << "Receiver hostname not set yet"; + } else if (setUDPConnection() == FAIL) { + FILE_LOG(logWARNING) << "UDP connection set up failed"; + } + return detector_shm()->numUDPInterfaces; +} + +int slsDetector::getNumberofUDPInterfaces() const { + return detector_shm()->numUDPInterfaces; +} + +int slsDetector::selectUDPInterface(int n) { + if (detector_shm()->myDetectorType != JUNGFRAU) { + throw RuntimeError("Cannot select an interface for this detector"); + } + detector_shm()->selectedUDPInterface = (n > 1 ? 2 : 1); + if (!strcmp(detector_shm()->receiver_hostname, "none")) { + FILE_LOG(logDEBUG1) << "Receiver hostname not set yet"; + } else if (setUDPConnection() == FAIL) { + FILE_LOG(logWARNING) << "UDP connection set up failed"; + } + return detector_shm()->selectedUDPInterface; +} + +int slsDetector::getSelectedUDPInterface() const { + return detector_shm()->selectedUDPInterface; +} + +void slsDetector::setClientStreamingPort(int port) { + detector_shm()->zmqport = port; +} + +int slsDetector::getClientStreamingPort() { return detector_shm()->zmqport; } + +void slsDetector::setReceiverStreamingPort(int port) { + // copy now else it is lost if rx_hostname not set yet + detector_shm()->receiver_zmqport = port; + + int fnum = F_SET_RECEIVER_STREAMING_PORT; + int ret = FAIL; + int arg = detector_shm()->receiver_zmqport; + int retval = -1; + FILE_LOG(logDEBUG1) << "Sending receiver streaming port to receiver: " + << arg; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver streaming port: " << retval; + detector_shm()->receiver_zmqport = retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } +} + +int slsDetector::getReceiverStreamingPort() { + return detector_shm()->receiver_zmqport; +} + +void slsDetector::setClientStreamingIP(const std::string &sourceIP) { + struct addrinfo *result; + // on failure to convert to a valid ip + if (sls::ConvertHostnameToInternetAddress(sourceIP.c_str(), &result)) { + throw RuntimeError("Could not convert zmqip into a valid IP" + + sourceIP); + } + // on success put IP as std::string into arg + memset(detector_shm()->zmqip, 0, MAX_STR_LENGTH); + sls::ConvertInternetAddresstoIpString(result, detector_shm()->zmqip, + MAX_STR_LENGTH); +} + +std::string slsDetector::getClientStreamingIP() { + return std::string(detector_shm()->zmqip); +} + +void slsDetector::setReceiverStreamingIP(std::string sourceIP) { + int fnum = F_RECEIVER_STREAMING_SRC_IP; + int ret = FAIL; + char args[MAX_STR_LENGTH] = {0}; + char retvals[MAX_STR_LENGTH] = {0}; + FILE_LOG(logDEBUG1) << "Sending receiver streaming IP to receiver: " + << sourceIP; + + // if empty, give rx_hostname + if (sourceIP.empty()) { + if (!strcmp(detector_shm()->receiver_hostname, "none")) { + throw RuntimeError("Receiver hostname not set yet. Cannot create " + "rx_zmqip from none"); + } + sourceIP.assign(detector_shm()->receiver_hostname); + } + + // verify the ip + { + struct addrinfo *result; + // on failure to convert to a valid ip + if (sls::ConvertHostnameToInternetAddress(sourceIP.c_str(), &result)) { + throw RuntimeError("Could not convert rx_zmqip into a valid IP" + + sourceIP); + } + // on success put IP as std::string into arg + sls::ConvertInternetAddresstoIpString(result, args, sizeof(args)); + } + + // set it anyway, else it is lost if rx_hostname is not set yet + memset(detector_shm()->receiver_zmqip, 0, MAX_STR_LENGTH); + sls::strcpy_safe(detector_shm()->receiver_zmqip, args); + // if zmqip is empty, update it + if (!strlen(detector_shm()->zmqip)) { + sls::strcpy_safe(detector_shm()->zmqip, args); + } + FILE_LOG(logDEBUG1) << "Sending receiver streaming IP to receiver: " + << args; + + // send to receiver + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, args, sizeof(args), retvals, + sizeof(retvals)); + FILE_LOG(logDEBUG1) << "Receiver streaming port: " << retvals; + memset(detector_shm()->receiver_zmqip, 0, MAX_STR_LENGTH); + sls::strcpy_safe(detector_shm()->receiver_zmqip, retvals); + if (ret == FORCE_UPDATE) { + receiver.close(); + ret = updateCachedReceiverVariables(); + } + } +} + +std::string slsDetector::getReceiverStreamingIP() { + return std::string(detector_shm()->receiver_zmqip); +} + +int slsDetector::setDetectorNetworkParameter(networkParameter index, + int delay) { + int fnum = F_SET_NETWORK_PARAMETER; + int ret = FAIL; + int args[2]{static_cast(index), delay}; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting network parameter index " << index << " to " + << delay; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) + << "Network Parameter (" << index << "): " << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +std::string +slsDetector::setAdditionalJsonHeader(const std::string &jsonheader) { + int fnum = F_ADDITIONAL_JSON_HEADER; + int ret = FAIL; + char args[MAX_STR_LENGTH] = {0}; + char retvals[MAX_STR_LENGTH] = {0}; + sls::strcpy_safe(args, jsonheader.c_str()); + FILE_LOG(logDEBUG1) << "Sending additional json header " << args; + + if (detector_shm()->receiverOnlineFlag != ONLINE_FLAG) { + sls::strcpy_safe(detector_shm()->receiver_additionalJsonHeader, + jsonheader.c_str()); + } else { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, args, sizeof(args), retvals, + sizeof(retvals)); + FILE_LOG(logDEBUG1) << "Additional json header: " << retvals; + memset(detector_shm()->receiver_additionalJsonHeader, 0, + MAX_STR_LENGTH); + sls::strcpy_safe(detector_shm()->receiver_additionalJsonHeader, + retvals); + } + if (ret == FORCE_UPDATE) { + ret = updateCachedReceiverVariables(); + } + return std::string(detector_shm()->receiver_additionalJsonHeader); +} + +std::string slsDetector::getAdditionalJsonHeader() { + int fnum = F_GET_ADDITIONAL_JSON_HEADER; + int ret = FAIL; + char retvals[MAX_STR_LENGTH] = {0}; + FILE_LOG(logDEBUG1) << "Getting additional json header "; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, nullptr, 0, retvals, + sizeof(retvals)); + FILE_LOG(logDEBUG1) << "Additional json header: " << retvals; + memset(detector_shm()->receiver_additionalJsonHeader, 0, + MAX_STR_LENGTH); + sls::strcpy_safe(detector_shm()->receiver_additionalJsonHeader, + retvals); + } + if (ret == FORCE_UPDATE) { + ret = updateCachedReceiverVariables(); + } + return std::string(detector_shm()->receiver_additionalJsonHeader); +} + +std::string slsDetector::setAdditionalJsonParameter(const std::string &key, + const std::string &value) { + if (key.empty() || value.empty()) { + throw("Could not set additional json header parameter as the key or " + "value is empty"); + } + + // validation (ignore if key or value has , : ") + if (key.find_first_of(",\":") != std::string::npos || + value.find_first_of(",\":") != std::string::npos) { + throw RuntimeError("Could not set additional json header parameter as " + "the key or value has " + "illegal characters (,\":)"); + } + + // create actual key to search for and actual value to put, (key has + // additional ':' as value could exist the same way) + std::string keyLiteral(std::string("\"") + key + std::string("\":")); + std::string valueLiteral(value); + // add quotations to value only if it is a string + try { + stoi(valueLiteral); + } catch (...) { + // add quotations if it failed to convert to integer, otherwise nothing + valueLiteral.insert(0, "\""); + valueLiteral.append("\""); + } + + std::string header(detector_shm()->receiver_additionalJsonHeader); + size_t keyPos = header.find(keyLiteral); + + // if key found, replace value + if (keyPos != std::string::npos) { + size_t valueStartPos = header.find(std::string(":"), keyPos) + 1; + size_t valueEndPos = header.find(std::string(","), valueStartPos) - 1; + // if valueEndPos doesnt find comma (end of string), it goes anyway to + // end of line + header.replace(valueStartPos, valueEndPos - valueStartPos + 1, + valueLiteral); + } + + // key not found, append key value pair + else { + if (header.length()) { + header.append(","); + } + header.append(keyLiteral + valueLiteral); + } + + // update additional json header + setAdditionalJsonHeader(header); + return getAdditionalJsonParameter(key); +} + +std::string slsDetector::getAdditionalJsonParameter(const std::string &key) { + // additional json header is empty + if (!strlen(detector_shm()->receiver_additionalJsonHeader)) + return std::string(); + + // add quotations before and after the key value + std::string keyLiteral = key; + keyLiteral.insert(0, "\""); + keyLiteral.append("\""); + + // loop through the parameters + for (const auto ¶meter : + sls::split(detector_shm()->receiver_additionalJsonHeader, ',')) { + // get a vector of key value pair for each parameter + const auto &pairs = sls::split(parameter, ':'); + // match for key + if (pairs[0] == keyLiteral) { + // return value without quotations (if it has any) + if (pairs[1][0] == '\"') + return pairs[1].substr(1, pairs[1].length() - 2); + else + return pairs[1]; + } + } + + // return empty string as no match found with key + return std::string(); +} + +int64_t slsDetector::setReceiverUDPSocketBufferSize(int64_t udpsockbufsize) { + int fnum = F_RECEIVER_UDP_SOCK_BUF_SIZE; + int ret = FAIL; + int64_t arg = udpsockbufsize; + int64_t retval = -1; + FILE_LOG(logDEBUG1) << "Sending UDP Socket Buffer size to receiver: " + << arg; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver UDP Socket Buffer size: " << retval; + } + if (ret == FORCE_UPDATE) { + ret = updateCachedReceiverVariables(); + } + return retval; +} + +int64_t slsDetector::getReceiverUDPSocketBufferSize() { + return setReceiverUDPSocketBufferSize(); +} + +int64_t slsDetector::getReceiverRealUDPSocketBufferSize() { + int fnum = F_RECEIVER_REAL_UDP_SOCK_BUF_SIZE; + int ret = FAIL; + int64_t retval = -1; + FILE_LOG(logDEBUG1) << "Getting real UDP Socket Buffer size to receiver"; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, nullptr, 0, &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) + << "Real Receiver UDP Socket Buffer size: " << retval; + } + if (ret == FORCE_UPDATE) { + ret = updateCachedReceiverVariables(); + } + return retval; +} + +int slsDetector::setUDPConnection() { + int fnum = F_SETUP_RECEIVER_UDP; + int ret = FAIL; + char args[6][MAX_STR_LENGTH] = {{}, {}, {}, {}, {}, {}}; + char retvals[2][MAX_STR_LENGTH] = {{}, {}}; + FILE_LOG(logDEBUG1) << "Setting UDP Connection"; + + // called before set up + if (!strcmp(detector_shm()->receiver_hostname, "none")) { + FILE_LOG(logDEBUG1) << "Receiver hostname not set yet."; + return FAIL; + } + + if (detector_shm()->receiverUDPIP == 0) { + // Hostname could be ip try to decode otherwise look up the hostname + detector_shm()->receiverUDPIP = detector_shm()->receiver_hostname; + if (detector_shm()->receiverUDPIP == 0) { + detector_shm()->receiverUDPIP = + HostnameToIp(detector_shm()->receiver_hostname); + } + } + // jungfrau 2 interfaces or (1 interface and 2nd interface), copy udpip if + // udpip2 empty + if (detector_shm()->numUDPInterfaces == 2 || + detector_shm()->selectedUDPInterface == 2) { + if (detector_shm()->receiverUDPIP2 == 0) { + detector_shm()->receiverUDPIP2 = detector_shm()->receiverUDPIP; + } + } + + // copy arguments to args[][] + snprintf(args[0], sizeof(args[0]), "%d", detector_shm()->numUDPInterfaces); + snprintf(args[1], sizeof(args[1]), "%d", + detector_shm()->selectedUDPInterface); + sls::strcpy_safe(args[2], getReceiverUDPIP().str()); + sls::strcpy_safe(args[3], getReceiverUDPIP2().str()); + snprintf(args[4], sizeof(args[4]), "%d", detector_shm()->receiverUDPPort); + snprintf(args[5], sizeof(args[5]), "%d", detector_shm()->receiverUDPPort2); + FILE_LOG(logDEBUG1) << "Receiver Number of UDP Interfaces: " + << detector_shm()->numUDPInterfaces; + FILE_LOG(logDEBUG1) << "Receiver Selected Interface: " + << detector_shm()->selectedUDPInterface; + FILE_LOG(logDEBUG1) << "Receiver udp ip address: " + << detector_shm()->receiverUDPIP; + FILE_LOG(logDEBUG1) << "Receiver udp ip address2: " + << detector_shm()->receiverUDPIP2; + FILE_LOG(logDEBUG1) << "Receiver udp port: " + << detector_shm()->receiverUDPPort; + FILE_LOG(logDEBUG1) << "Receiver udp port2: " + << detector_shm()->receiverUDPPort2; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, args, sizeof(args), retvals, + sizeof(retvals)); + if (strlen(retvals[0])) { + FILE_LOG(logDEBUG1) << "Receiver UDP MAC returned : " << retvals[0]; + detector_shm()->receiverUDPMAC = retvals[0]; + } + if (strlen(retvals[1])) { + FILE_LOG(logDEBUG1) + << "Receiver UDP MAC2 returned : " << retvals[1]; + detector_shm()->receiverUDPMAC2 = retvals[1]; + } + if (ret == FORCE_UPDATE) { + receiver.close(); + ret = updateCachedReceiverVariables(); + } + // configure detector with udp details + if (configureMAC() == FAIL) { + setReceiverOnline(OFFLINE_FLAG); + } + } else { + throw ReceiverError("setUDPConnection: Receiver is OFFLINE"); + } + + printReceiverConfiguration(logDEBUG1); + return ret; +} + +int slsDetector::digitalTest(digitalTestMode mode, int ival) { + int fnum = F_DIGITAL_TEST; + int ret = FAIL; + int args[2]{static_cast(mode), ival}; + int retval = -1; + FILE_LOG(logDEBUG1) << "Sending digital test of mode " << mode << ", ival " + << ival; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Digital Test returned: " << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +int slsDetector::loadImageToDetector(imageType index, + const std::string &fname) { + int nChan = getTotalNumberOfChannels(); + int16_t args[nChan]; + FILE_LOG(logDEBUG1) << "Loading " << (!index ? "Dark" : "Gain") + << "image from file " << fname; + + if (readDataFile(fname, args, nChan)) { + return sendImageToDetector(index, args); + } else { + throw RuntimeError( + "slsDetector::loadImageToDetector: Could not open file: " + fname); + } +} + +int slsDetector::sendImageToDetector(imageType index, int16_t imageVals[]) { + int fnum = F_LOAD_IMAGE; + int ret = FAIL; + int nChan = getTotalNumberOfChannels(); + int args[2] = {(int)index, nChan}; + FILE_LOG(logDEBUG1) << "Sending image to detector"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + client.sendData(&fnum, sizeof(fnum)); + client.sendData(args, sizeof(args)); + client.sendData(imageVals, nChan * sizeof(int16_t)); + client.receiveData(&ret, sizeof(ret)); + if (ret == FAIL) { + char mess[MAX_STR_LENGTH]{}; + client.receiveData(mess, MAX_STR_LENGTH); + throw DetectorError("Detector " + std::to_string(detId) + + " returned error: " + std::string(mess)); + } + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int slsDetector::writeCounterBlockFile(const std::string &fname, int startACQ) { + int ret = FAIL; + int nChan = getTotalNumberOfChannels(); + short int retvals[nChan]; + FILE_LOG(logDEBUG1) << "Reading Counter to " << fname + << (startACQ ? " and Restarting Acquisition" : "\n"); + + ret = getCounterBlock(retvals, startACQ); + if (ret != FAIL) { + return writeDataFile(fname, nChan, retvals); + } else { + throw RuntimeError( + "slsDetector::writeCounterBlockFile: getCounterBlock failed"); + } +} + +int slsDetector::getCounterBlock(int16_t image[], int startACQ) { + int fnum = F_READ_COUNTER_BLOCK; + int ret = FAIL; + int nChan = getTotalNumberOfChannels(); + int args[2] = {startACQ, nChan}; + FILE_LOG(logDEBUG1) << "Reading Counter block with startacq: " << startACQ; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), image, + nChan * sizeof(int16_t)); + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int slsDetector::resetCounterBlock(int startACQ) { + int fnum = F_RESET_COUNTER_BLOCK; + int ret = FAIL; + int arg = startACQ; + FILE_LOG(logDEBUG1) << "Resetting Counter with startacq: " << startACQ; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), nullptr, 0); + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int slsDetector::setCounterBit(int i) { + int fnum = F_SET_COUNTER_BIT; + int ret = FAIL; + int arg = i; + int retval = -1; + FILE_LOG(logDEBUG1) << "Sending counter bit " << arg; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Counter bit: " << retval; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return retval; +} + +int slsDetector::sendROIToProcessor() { + std::ostringstream os; + os << "[" << detector_shm()->roiLimits[0].xmin << ", " + << detector_shm()->roiLimits[0].xmax << ", " + << detector_shm()->roiLimits[0].ymin << ", " + << detector_shm()->roiLimits[0].ymax << "]"; + std::string sroi = os.str(); + std::string result = setAdditionalJsonParameter("roi", sroi); + if (result == sroi) + return OK; + return FAIL; +} + +int slsDetector::setROI(int n, ROI roiLimits[]) { + std::sort(roiLimits, roiLimits + n, + [](ROI a, ROI b) { return a.xmin < b.xmin; }); + + int ret = sendROI(n, roiLimits); + if (detector_shm()->myDetectorType == MOENCH) { + sendROIToProcessor(); + } + // update #nchans and databytes, as it depends on #samples, roi, + if (detector_shm()->myDetectorType == CHIPTESTBOARD || + detector_shm()->myDetectorType == MOENCH) { + updateTotalNumberOfChannels(); + } + return ret; +} + +const slsDetectorDefs::ROI *slsDetector::getROI(int &n) { + sendROI(-1, nullptr); + n = detector_shm()->nROI; + // moench - get json header(due to different clients, diff shm) (get roi is + // from detector: updated anyway) + if (detector_shm()->myDetectorType == MOENCH) { + getAdditionalJsonHeader(); + } + // update #nchans and databytes, as it depends on #samples, roi, + // readoutflags (ctb only) + if (detector_shm()->myDetectorType == CHIPTESTBOARD || + detector_shm()->myDetectorType == MOENCH) { + updateTotalNumberOfChannels(); + } + return detector_shm()->roiLimits; +} + +int slsDetector::getNRoi() { return detector_shm()->nROI; } + +int slsDetector::sendROI(int n, ROI roiLimits[]) { + int fnum = F_SET_ROI; + int ret = FAIL; + int narg = n; + // send roiLimits if given, else from shm + ROI *arg = (roiLimits != nullptr) ? roiLimits : detector_shm()->roiLimits; + int nretval = 0; + ROI retval[MAX_ROIS]; + FILE_LOG(logDEBUG1) << "Sending ROI to detector" << narg; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + client.sendData(&fnum, sizeof(fnum)); + client.sendData(&narg, sizeof(narg)); + if (narg != -1) { + for (int i = 0; i < narg; ++i) { + client.sendData(&arg[i].xmin, sizeof(int)); + client.sendData(&arg[i].xmax, sizeof(int)); + client.sendData(&arg[i].ymin, sizeof(int)); + client.sendData(&arg[i].ymax, sizeof(int)); + } + } + client.receiveData(&ret, sizeof(ret)); + + // handle ret + if (ret == FAIL) { + char mess[MAX_STR_LENGTH]{}; + client.receiveData(mess, MAX_STR_LENGTH); + throw RuntimeError("Detector " + std::to_string(detId) + + " returned error: " + std::string(mess)); + } else { + client.receiveData(&nretval, sizeof(nretval)); + int nrec = 0; + for (int i = 0; i < nretval; ++i) { + nrec += client.receiveData(&retval[i].xmin, sizeof(int)); + nrec += client.receiveData(&retval[i].xmax, sizeof(int)); + nrec += client.receiveData(&retval[i].ymin, sizeof(int)); + nrec += client.receiveData(&retval[i].ymax, sizeof(int)); + } + detector_shm()->nROI = nretval; + FILE_LOG(logDEBUG1) << "nRoi: " << nretval; + for (int i = 0; i < nretval; ++i) { + detector_shm()->roiLimits[i] = retval[i]; + FILE_LOG(logDEBUG1) << "ROI [" << i << "] (" + << detector_shm()->roiLimits[i].xmin << "," + << detector_shm()->roiLimits[i].xmax << "," + << detector_shm()->roiLimits[i].ymin << "," + << detector_shm()->roiLimits[i].ymax << ")"; + } + } + } else { + // detector is offline lets just update SHM + if (n != -1) { + detector_shm()->nROI = n; + for (int i = 0; i != n; ++i) { + detector_shm()->roiLimits[i] = roiLimits[i]; + } + } + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + // old firmware requires configuremac after setting roi + if (detector_shm()->myDetectorType == GOTTHARD && n != -1) { + ret = configureMAC(); + } + + // update roi in receiver + if (ret == OK && detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + fnum = F_RECEIVER_SET_ROI; + ret = FAIL; + narg = detector_shm()->nROI; + arg = detector_shm()->roiLimits; + FILE_LOG(logDEBUG1) + << "Sending ROI to receiver: " << detector_shm()->nROI; + + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + receiver.sendData(&fnum, sizeof(fnum)); + receiver.sendData(&narg, sizeof(narg)); + if (narg != -1) { + for (int i = 0; i < narg; ++i) { + receiver.sendData(&arg[i].xmin, sizeof(int)); + receiver.sendData(&arg[i].xmax, sizeof(int)); + receiver.sendData(&arg[i].ymin, sizeof(int)); + receiver.sendData(&arg[i].ymax, sizeof(int)); + } + } + receiver.receiveData(&ret, sizeof(ret)); + + if (ret == FAIL) { + char mess[MAX_STR_LENGTH]{}; + receiver.receiveData(mess, MAX_STR_LENGTH); + throw ReceiverError("Receiver " + std::to_string(detId) + + " returned error: " + std::string(mess)); + } + if (ret == FORCE_UPDATE) { + ret = updateCachedReceiverVariables(); + } + } + return ret; +} + +int slsDetector::writeAdcRegister(int addr, int val) { + int fnum = F_WRITE_ADC_REG; + int ret = FAIL; + uint32_t args[2] = {(uint32_t)addr, (uint32_t)val}; + FILE_LOG(logDEBUG1) << "Writing to ADC register 0x" << std::hex << addr + << "data: 0x" << std::hex << val << std::dec; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), nullptr, 0); + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int slsDetector::activate(int enable) { + int fnum = F_ACTIVATE; + int ret = FAIL; + int arg = enable; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting activate flag to " << arg; + + // detector + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Activate: " << retval; + detector_shm()->activated = retval; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + + // receiver + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG && ret == OK) { + fnum = F_RECEIVER_ACTIVATE; + ret = FAIL; + arg = detector_shm()->activated; + retval = -1; + FILE_LOG(logDEBUG1) + << "Setting activate flag " << arg << " to receiver"; + + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + if (ret == FORCE_UPDATE) { + receiver.close(); + updateCachedReceiverVariables(); + } + } + return detector_shm()->activated; +} + +int slsDetector::setDeactivatedRxrPaddingMode(int padding) { + int fnum = F_RECEIVER_DEACTIVATED_PADDING_ENABLE; + int ret = OK; + int arg = padding; + int retval = -1; + FILE_LOG(logDEBUG1) << "Deactivated Receiver Padding Enable: " << arg; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Deactivated Receiver Padding Enable:" << retval; + detector_shm()->receiver_deactivatedPaddingEnable = retval; + } + if (ret == FORCE_UPDATE) { + ret = updateCachedReceiverVariables(); + } + return detector_shm()->receiver_deactivatedPaddingEnable; +} + +int slsDetector::getFlippedData(dimension d) const { + return detector_shm()->flippedData[d]; +} + +int slsDetector::setFlippedData(dimension d, int value) { + int fnum = F_SET_FLIPPED_DATA_RECEIVER; + int ret = OK; + int args[2] = {(int)d, value}; + int retval = -1; + + // flipped across y + if (d == Y) { + throw RuntimeError("Flipped across Y axis is not implemented"); + } + + // replace get with shm value (write to shm right away as it is a det value, + // not rx value) + if (value > -1) { + detector_shm()->flippedData[d] = (value > 0) ? 1 : 0; + } + args[1] = detector_shm()->flippedData[d]; + FILE_LOG(logDEBUG1) << "Setting flipped data across axis " << d + << " with value: " << value; + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, args, sizeof(args), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Flipped data:" << retval << " ret: " << ret; + } + if (ret == FORCE_UPDATE) { + ret = updateCachedReceiverVariables(); + } + return detector_shm()->flippedData[d]; +} + +int slsDetector::setAllTrimbits(int val) { + int fnum = F_SET_ALL_TRIMBITS; + int ret = FAIL; + int arg = val; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting all trimbits to " << val; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "All trimbit value: " << retval; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return retval; +} + +int slsDetector::enableGapPixels(int val) { + if (val >= 0) { + int fnum = F_ENABLE_GAPPIXELS_IN_RECEIVER; + int ret = OK; + int arg = val; + int retval = -1; + FILE_LOG(logDEBUG1) << "Sending gap pixels enable to receiver: " << arg; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Gap pixels enable to receiver:" << retval; + detector_shm()->gappixels = retval; + + // update databytes + detector_shm()->dataBytesInclGapPixels = 0; + if (detector_shm()->dynamicRange != 4) { + detector_shm()->dataBytesInclGapPixels = + (detector_shm()->nChip[X] * detector_shm()->nChan[X] + + detector_shm()->gappixels * + detector_shm()->nGappixels[X]) * + (detector_shm()->nChip[Y] * detector_shm()->nChan[Y] + + detector_shm()->gappixels * + detector_shm()->nGappixels[Y]) * + detector_shm()->dynamicRange / 8; + } + } + if (ret == FORCE_UPDATE) { + ret = updateCachedReceiverVariables(); + } + } + return detector_shm()->gappixels; +} + +int slsDetector::setTrimEn(std::vector energies) { + if (energies.size() > MAX_TRIMEN) { + std::ostringstream os; + os << "Size of trim energies: " << energies.size() + << " exceeds what can " + << "be stored in shared memory: " << MAX_TRIMEN << "\n"; + throw RuntimeError(os.str()); + } + + for (size_t i = 0; i != energies.size(); ++i) { + detector_shm()->trimEnergies[i] = energies[i]; + } + detector_shm()->nTrimEn = energies.size(); + return (detector_shm()->nTrimEn); +} + +std::vector slsDetector::getTrimEn() { + std::vector energies; + energies.reserve(detector_shm()->nTrimEn); + for (int i = 0; i != detector_shm()->nTrimEn; ++i) { + energies.push_back(detector_shm()->trimEnergies[i]); + } + return energies; +} + +int slsDetector::pulsePixel(int n, int x, int y) { + int fnum = F_PULSE_PIXEL; + int ret = FAIL; + int args[3] = {n, x, y}; + FILE_LOG(logDEBUG1) << "Pulsing pixel " << n << " number of times at (" << x + << "," << y << ")"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), nullptr, 0); + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int slsDetector::pulsePixelNMove(int n, int x, int y) { + int fnum = F_PULSE_PIXEL_AND_MOVE; + int ret = FAIL; + int args[3] = {n, x, y}; + FILE_LOG(logDEBUG1) << "Pulsing pixel " << n + << " number of times and move by delta (" << x << "," + << y << ")"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), nullptr, 0); + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int slsDetector::pulseChip(int n) { + int fnum = F_PULSE_CHIP; + int ret = FAIL; + int arg = n; + FILE_LOG(logDEBUG1) << "Pulsing chip " << n << " number of times"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), nullptr, 0); + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int slsDetector::setThresholdTemperature(int val) { + int fnum = F_THRESHOLD_TEMP; + int arg = val; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting threshold temperature to " << val; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto stop = + DetectorSocket(detector_shm()->hostname, detector_shm()->stopPort); + stop.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Threshold temperature: " << retval; + // no updateDetector as it is stop server + } + return retval; +} + +int slsDetector::setTemperatureControl(int val) { + int fnum = F_TEMP_CONTROL; + int arg = val; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting temperature control to " << val; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto stop = + DetectorSocket(detector_shm()->hostname, detector_shm()->stopPort); + stop.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Temperature control: " << retval; + // no updateDetector as it is stop server + } + return retval; +} + +int slsDetector::setTemperatureEvent(int val) { + int fnum = F_TEMP_EVENT; + int arg = val; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting temperature event to " << val; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto stop = + DetectorSocket(detector_shm()->hostname, detector_shm()->stopPort); + stop.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Temperature event: " << retval; + // no updateDetector as it is stop server + } + return retval; +} + +int slsDetector::setStoragecellStart(int pos) { + int fnum = F_STORAGE_CELL_START; + int ret = FAIL; + int arg = pos; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting storage cell start to " << pos; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Storage cell start: " << retval; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return retval; +} + +int slsDetector::programFPGA(std::vector buffer) { + // validate type + switch (detector_shm()->myDetectorType) { + case JUNGFRAU: + case CHIPTESTBOARD: + case MOENCH: + break; + default: + throw RuntimeError("Program FPGA is not implemented for this detector"); + } + + size_t filesize = buffer.size(); + + // send program from memory to detector + int fnum = F_PROGRAM_FPGA; + int ret = FAIL; + char mess[MAX_STR_LENGTH] = {0}; + FILE_LOG(logINFO) << "Sending programming binary to detector " << detId + << " (" << detector_shm()->hostname << ")"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + client.sendData(&fnum, sizeof(fnum)); + client.sendData(&filesize, sizeof(filesize)); + client.receiveData(&ret, sizeof(ret)); + // error in detector at opening file pointer to flash + if (ret == FAIL) { + client.receiveData(mess, sizeof(mess)); + std::ostringstream os; + os << "Detector " << detId << " (" << detector_shm()->hostname + << ")" + << " returned error: " << mess; + throw RuntimeError(os.str()); + } + + // erasing flash + if (ret != FAIL) { + FILE_LOG(logINFO) << "Erasing Flash for detector " << detId << " (" + << detector_shm()->hostname << ")"; + printf("%d%%\r", 0); + std::cout << std::flush; + // erasing takes 65 seconds, printing here (otherwise need threads + // in server-unnecessary) + const int ERASE_TIME = 65; + int count = ERASE_TIME + 1; + while (count > 0) { + usleep(1 * 1000 * 1000); + --count; + printf( + "%d%%\r", + (int)(((double)(ERASE_TIME - count) / ERASE_TIME) * 100)); + std::cout << std::flush; + } + printf("\n"); + FILE_LOG(logINFO) << "Writing to Flash to detector " << detId + << " (" << detector_shm()->hostname << ")"; + printf("%d%%\r", 0); + std::cout << std::flush; + } + + // sending program in parts of 2mb each + size_t unitprogramsize = 0; + int currentPointer = 0; + size_t totalsize = filesize; + while (ret != FAIL && (filesize > 0)) { + + unitprogramsize = MAX_FPGAPROGRAMSIZE; // 2mb + if (unitprogramsize > filesize) { // less than 2mb + unitprogramsize = filesize; + } + FILE_LOG(logDEBUG1) << "unitprogramsize:" << unitprogramsize + << "\t filesize:" << filesize; + + client.sendData(&buffer[currentPointer], unitprogramsize); + client.receiveData(&ret, sizeof(ret)); + if (ret != FAIL) { + filesize -= unitprogramsize; + currentPointer += unitprogramsize; + + // print progress + printf( + "%d%%\r", + (int)(((double)(totalsize - filesize) / totalsize) * 100)); + std::cout << std::flush; + } else { + printf("\n"); + client.receiveData(mess, sizeof(mess)); + std::ostringstream os; + os << "Detector " << detId << " (" << detector_shm()->hostname + << ")" + << " returned error: " << mess; + throw RuntimeError(os.str()); + } + } + printf("\n"); + } + if (ret != FAIL) { + ret = rebootController(); + } + return ret; +} + +int slsDetector::resetFPGA() { + int fnum = F_RESET_FPGA; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Sending reset FPGA"; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int slsDetector::copyDetectorServer(const std::string &fname, + const std::string &hostname) { + int fnum = F_COPY_DET_SERVER; + int ret = FAIL; + char args[2][MAX_STR_LENGTH] = {}; + sls::strcpy_safe(args[0], fname.c_str()); + sls::strcpy_safe(args[1], hostname.c_str()); + FILE_LOG(logINFO) << "Sending detector server " << args[0] << " from host " + << args[1]; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), nullptr, 0); + } + return ret; +} + +int slsDetector::rebootController() { + if (detector_shm()->myDetectorType == EIGER) { + throw RuntimeError( + "Reboot controller not implemented for this detector"); + } + + int fnum = F_REBOOT_CONTROLLER; + int ret = FAIL; + FILE_LOG(logINFO) << "Sending reboot controller to detector " << detId + << " (" << detector_shm()->hostname << ")"; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + client.sendData(&fnum, sizeof(fnum)); + ret = OK; + } + return ret; +} + +int slsDetector::powerChip(int ival) { + int fnum = F_POWER_CHIP; + int ret = FAIL; + int arg = ival; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting power chip to " << ival; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Power chip: " << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +int slsDetector::setAutoComparatorDisableMode(int ival) { + int fnum = F_AUTO_COMP_DISABLE; + int ret = FAIL; + int arg = ival; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting auto comp disable mode to " << ival; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Auto comp disable: " << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +int slsDetector::getChanRegs(double *retval) { + int n = getTotalNumberOfChannels(); + // update chanregs + sls_detector_module *myMod = getModule(); + + if (myMod != nullptr) { + // the original array has 0 initialized + if (myMod->chanregs != nullptr) { + for (int i = 0; i < n; ++i) { + retval[i] = (double)(myMod->chanregs[i] & TRIMBITMASK); + } + } + deleteModule(myMod); + } + return n; +} + +int slsDetector::setModule(sls_detector_module module, int tb) { + int fnum = F_SET_MODULE; + int ret = FAIL; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting module with tb:" << tb; + // to exclude trimbits + if (tb == 0) { + module.nchan = 0; + module.nchip = 0; + } + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + client.sendData(&fnum, sizeof(fnum)); + sendModule(&module, client); + client.receiveData(&ret, sizeof(ret)); + if (ret == FAIL) { + char mess[MAX_STR_LENGTH] = {0}; + client.receiveData(mess, sizeof(mess)); + throw RuntimeError("Detector " + std::to_string(detId) + + " returned error: " + mess); + } + client.receiveData(&retval, sizeof(retval)); + FILE_LOG(logDEBUG1) << "Set Module returned: " << retval; + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + + // update client structure + if (ret == OK) { + if (module.eV != -1) { + detector_shm()->currentThresholdEV = module.eV; + } + } + return ret; +} + +slsDetectorDefs::sls_detector_module *slsDetector::getModule() { + int fnum = F_GET_MODULE; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Getting module"; + + sls_detector_module *myMod = createModule(); + if (myMod == nullptr) { + throw RuntimeError("Could not create module"); + } + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + receiveModule(myMod, client); + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + if (ret == OK) { + if (myMod->eV != -1) { + detector_shm()->currentThresholdEV = myMod->eV; + } + } + return myMod; +} + +int slsDetector::setRateCorrection(int64_t t) { + int fnum = F_SET_RATE_CORRECT; + int ret = FAIL; + int64_t arg = t; + FILE_LOG(logDEBUG1) << "Setting Rate Correction to " << arg; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), nullptr, 0); + } + if (ret == FORCE_UPDATE) { + ret = updateDetector(); + } + return ret; +} + +int64_t slsDetector::getRateCorrection() { + int fnum = F_GET_RATE_CORRECT; + int ret = FAIL; + int64_t retval = -1; + FILE_LOG(logDEBUG1) << "Getting rate correction"; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Rate correction: " << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +void slsDetector::printReceiverConfiguration(TLogLevel level) { + FILE_LOG(level) << "#Detector " << detId << ":\n Receiver Hostname:\t" + << getReceiverHostname() + << "\nDetector UDP IP (Source):\t\t" << getDetectorIP() + << "\nDetector UDP IP2 (Source):\t\t" << getDetectorIP2() + << "\nDetector UDP MAC:\t\t" << getDetectorMAC() + << "\nDetector UDP MAC2:\t\t" << getDetectorMAC2() + << "\nReceiver UDP IP:\t" << getReceiverUDPIP() + << "\nReceiver UDP IP2:\t" << getReceiverUDPIP2() + << "\nReceiver UDP MAC:\t" << getReceiverUDPMAC() + << "\nReceiver UDP MAC2:\t" << getReceiverUDPMAC2() + << "\nReceiver UDP Port:\t" << getReceiverUDPPort() + << "\nReceiver UDP Port2:\t" << getReceiverUDPPort2(); +} + +int slsDetector::setReceiverOnline(int value) { + if (value != GET_ONLINE_FLAG) { + // no receiver + if (strcmp(detector_shm()->receiver_hostname, "none") == 0) { + detector_shm()->receiverOnlineFlag = OFFLINE_FLAG; + } else { + detector_shm()->receiverOnlineFlag = OFFLINE_FLAG; + + // set online + if (value == ONLINE_FLAG) { + // connect and set offline flag + auto receiver = + ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + receiver.close(); + detector_shm()->receiverOnlineFlag = ONLINE_FLAG; + if (detector_shm()->receiverAPIVersion == 0) { + checkReceiverVersionCompatibility(); + } + } + } + } + return detector_shm()->receiverOnlineFlag; +} + +int slsDetector::getReceiverOnline() const { + return detector_shm()->receiverOnlineFlag; +} + +std::string slsDetector::checkReceiverOnline() { + std::string retval; + try { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + detector_shm()->receiverOnlineFlag = ONLINE_FLAG; + } catch (...) { + detector_shm()->receiverOnlineFlag = OFFLINE_FLAG; + retval = detector_shm()->receiver_hostname; + } + return retval; +} + +int slsDetector::lockReceiver(int lock) { + int fnum = F_LOCK_RECEIVER; + int ret = FAIL; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting receiver server lock to " << lock; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &lock, sizeof(lock), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver Lock: " << retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return retval; +} + +std::string slsDetector::getReceiverLastClientIP() { + int fnum = F_GET_LAST_RECEIVER_CLIENT_IP; + int ret = FAIL; + char retval[INET_ADDRSTRLEN] = {}; + FILE_LOG(logDEBUG1) << "Getting last client ip to receiver server"; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, nullptr, 0, &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Last client IP to receiver: " << retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return retval; +} + +int slsDetector::exitReceiver() { + int fnum = F_EXIT_RECEIVER; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Sending exit command to receiver server"; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + // no ret handling as ret never fail + FILE_LOG(logINFO) << "Shutting down the receiver server"; + } + return ret; +} + +int slsDetector::execReceiverCommand(const std::string &cmd) { + int fnum = F_EXEC_RECEIVER_COMMAND; + int ret = FAIL; + char arg[MAX_STR_LENGTH] = {0}; + char retval[MAX_STR_LENGTH] = {0}; + sls::strcpy_safe(arg, cmd.c_str()); + FILE_LOG(logDEBUG1) << "Sending command to receiver: " << arg; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, arg, sizeof(arg), retval, + sizeof(retval)); + FILE_LOG(logINFO) << "Receiver " << detId << " returned:\n" << retval; + } + return ret; +} + +int slsDetector::updateCachedReceiverVariables() const { + int fnum = F_UPDATE_RECEIVER_CLIENT; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Sending update client to receiver server"; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = sls::ClientSocket("Receiver", detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + if (ret == FAIL) { + std::string msg = "Could not update receiver: " + + std::string(detector_shm()->receiver_hostname); + throw RuntimeError(msg); + } else { + int n = 0, i32 = 0; + char cstring[MAX_STR_LENGTH] = {}; + char lastClientIP[INET_ADDRSTRLEN] = {}; + + n += receiver.receiveData(lastClientIP, sizeof(lastClientIP)); + FILE_LOG(logDEBUG1) + << "Updating receiver last modified by " << lastClientIP; + + // filepath + n += receiver.receiveData(cstring, sizeof(cstring)); + sls::strcpy_safe(detector_shm()->receiver_filePath, cstring); + + // filename + n += receiver.receiveData(cstring, sizeof(cstring)); + sls::strcpy_safe(detector_shm()->receiver_fileName, cstring); + + // index + n += receiver.receiveData(&i32, sizeof(i32)); + detector_shm()->rxFileIndex = i32; + + // file format + n += receiver.receiveData(&i32, sizeof(i32)); + detector_shm()->rxFileFormat = static_cast(i32); + + // frames per file + n += receiver.receiveData(&i32, sizeof(i32)); + detector_shm()->rxFramesPerFile = i32; + + // frame discard policy + n += receiver.receiveData(&i32, sizeof(i32)); + detector_shm()->receiver_frameDiscardMode = + static_cast(i32); + + // frame padding + n += receiver.receiveData(&i32, sizeof(i32)); + detector_shm()->rxFramePadding = static_cast(i32); + + // file write enable + n += receiver.receiveData(&i32, sizeof(i32)); + detector_shm()->rxFileWrite = static_cast(i32); + + // file overwrite enable + n += receiver.receiveData(&i32, sizeof(i32)); + detector_shm()->rxFileOverWrite = static_cast(i32); + + // gap pixels + n += receiver.receiveData(&i32, sizeof(i32)); + detector_shm()->gappixels = i32; + + // receiver read frequency + n += receiver.receiveData(&i32, sizeof(i32)); + detector_shm()->receiver_read_freq = i32; + + // receiver streaming port + n += receiver.receiveData(&i32, sizeof(i32)); + detector_shm()->receiver_zmqport = i32; + + // streaming source ip + n += receiver.receiveData(cstring, sizeof(cstring)); + sls::strcpy_safe(detector_shm()->receiver_zmqip, cstring); + + // additional json header + n += receiver.receiveData(cstring, sizeof(cstring)); + sls::strcpy_safe(detector_shm()->receiver_additionalJsonHeader, + cstring); + + // receiver streaming enable + n += receiver.receiveData(&i32, sizeof(i32)); + detector_shm()->receiver_upstream = static_cast(i32); + + // activate + n += receiver.receiveData(&i32, sizeof(i32)); + detector_shm()->activated = static_cast(i32); + + // deactivated padding enable + n += receiver.receiveData(&i32, sizeof(i32)); + detector_shm()->receiver_deactivatedPaddingEnable = + static_cast(i32); + + // silent mode + n += receiver.receiveData(&i32, sizeof(i32)); + detector_shm()->receiver_silentMode = static_cast(i32); + + if (n == 0) { + throw RuntimeError( + "Could not update receiver: " + + std::string(detector_shm()->receiver_hostname) + + ", received 0 bytes\n"); + } + return OK; + } + } + return ret; +} + +void slsDetector::sendMultiDetectorSize() { + int fnum = F_SEND_RECEIVER_MULTIDETSIZE; + int ret = FAIL; + int args[2] = {detector_shm()->multiSize[0], detector_shm()->multiSize[1]}; + int retval = -1; + FILE_LOG(logDEBUG1) << "Sending multi detector size to receiver: (" + << detector_shm()->multiSize[0] << "," + << detector_shm()->multiSize[1] << ")"; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, args, sizeof(args), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver multi size returned: " << retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } +} + +void slsDetector::setDetectorId() { + int fnum = F_SEND_RECEIVER_DETPOSID; + int ret = FAIL; + int arg = detId; + int retval = -1; + FILE_LOG(logDEBUG1) << "Sending detector pos id to receiver: " << detId; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver Position Id returned: " << retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } +} + +void slsDetector::setDetectorHostname() { + int fnum = F_SEND_RECEIVER_DETHOSTNAME; + int ret = FAIL; + char args[MAX_STR_LENGTH] = {}; + char retvals[MAX_STR_LENGTH] = {}; + sls::strcpy_safe(args, detector_shm()->hostname); + FILE_LOG(logDEBUG1) << "Sending detector hostname to receiver: " << args; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, args, sizeof(args), retvals, + sizeof(retvals)); + FILE_LOG(logDEBUG1) << "Receiver set detector hostname: " << retvals; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } +} + +std::string slsDetector::getFilePath() { + return detector_shm()->receiver_filePath; +} + +std::string slsDetector::setFilePath(const std::string &path) { + if (!path.empty()) { + int fnum = F_SET_RECEIVER_FILE_PATH; + int ret = FAIL; + char args[MAX_STR_LENGTH] = {}; + char retvals[MAX_STR_LENGTH] = {}; + sls::strcpy_safe(args, path.c_str()); + FILE_LOG(logDEBUG1) << "Sending file path to receiver: " << args; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, args, sizeof(args), + retvals, sizeof(retvals)); + FILE_LOG(logDEBUG1) << "Receiver file path: " << retvals; + sls::strcpy_safe(detector_shm()->receiver_filePath, retvals); + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + } + return detector_shm()->receiver_filePath; +} + +std::string slsDetector::getFileName() { + return detector_shm()->receiver_fileName; +} + +std::string slsDetector::setFileName(const std::string &fname) { + if (!fname.empty()) { + int fnum = F_SET_RECEIVER_FILE_NAME; + int ret = FAIL; + char args[MAX_STR_LENGTH]{}; + char retvals[MAX_STR_LENGTH]{}; + sls::strcpy_safe(args, fname.c_str()); + FILE_LOG(logDEBUG1) << "Sending file name to receiver: " << args; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, args, sizeof(args), + retvals, sizeof(retvals)); + FILE_LOG(logDEBUG1) << "Receiver file name: " << retvals; + sls::strcpy_safe(detector_shm()->receiver_fileName, retvals); + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + } + return detector_shm()->receiver_fileName; +} + +int slsDetector::setFramesPerFile(int f) { + if (f >= 0) { + int fnum = F_SET_RECEIVER_FRAMES_PER_FILE; + int ret = FAIL; + int arg = f; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting receiver frames per file to " << arg; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver frames per file: " << retval; + detector_shm()->rxFramesPerFile = retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + } + return getFramesPerFile(); +} + +int slsDetector::getFramesPerFile() const { + return detector_shm()->rxFramesPerFile; +} + +slsDetectorDefs::frameDiscardPolicy +slsDetector::setReceiverFramesDiscardPolicy(frameDiscardPolicy f) { + int fnum = F_RECEIVER_DISCARD_POLICY; + int ret = FAIL; + int arg = static_cast(f); + auto retval = static_cast(-1); + FILE_LOG(logDEBUG1) << "Setting receiver frames discard policy to " << arg; + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver frames discard policy: " << retval; + detector_shm()->receiver_frameDiscardMode = retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return detector_shm()->receiver_frameDiscardMode; +} + +bool slsDetector::setPartialFramesPadding(bool padding) { + int fnum = F_RECEIVER_PADDING_ENABLE; + int ret = FAIL; + int arg = static_cast(padding); + int retval = static_cast(padding); + FILE_LOG(logDEBUG1) << "Setting receiver partial frames enable to " << arg; + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver partial frames enable: " << retval; + } + detector_shm()->rxFramePadding = static_cast(retval); + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return getPartialFramesPadding(); +} + +bool slsDetector::getPartialFramesPadding() const { + return detector_shm()->rxFramePadding; +} + +slsDetectorDefs::fileFormat slsDetector::setFileFormat(fileFormat f) { + if (f != GET_FILE_FORMAT) { + int fnum = F_SET_RECEIVER_FILE_FORMAT; + int ret = FAIL; + auto arg = static_cast(f); + auto retval = static_cast(-1); + FILE_LOG(logDEBUG1) << "Setting receiver file format to " << arg; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver file format: " << retval; + detector_shm()->rxFileFormat = retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + } + return getFileFormat(); +} + +slsDetectorDefs::fileFormat slsDetector::getFileFormat() const { + return detector_shm()->rxFileFormat; +} + +int slsDetector::getFileIndex() { return detector_shm()->rxFileIndex; } + +int slsDetector::setFileIndex(int i) { + if (i >= 0) { + int fnum = F_SET_RECEIVER_FILE_INDEX; + int ret = FAIL; + int arg = i; + int retval = -1; + FILE_LOG(logDEBUG1) << "Setting file index to " << arg; + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver file index: " << retval; + detector_shm()->rxFileIndex = retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + } + return getFileIndex(); +} + +int slsDetector::getFileIndex() const { return detector_shm()->rxFileIndex; } + +int slsDetector::incrementFileIndex() { + if (detector_shm()->rxFileWrite) { + return setFileIndex(detector_shm()->rxFileIndex + 1); + } + return detector_shm()->rxFileIndex; +} + +int slsDetector::startReceiver() { + int fnum = F_START_RECEIVER; + int ret = FAIL; + // char mess[MAX_STR_LENGTH]{}; + FILE_LOG(logDEBUG1) << "Starting Receiver"; + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return ret; +} + +int slsDetector::stopReceiver() { + int fnum = F_STOP_RECEIVER; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Stopping Receiver"; + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + } + if (ret == FORCE_UPDATE) { + ret = updateCachedReceiverVariables(); + } + return ret; +} + +slsDetectorDefs::runStatus slsDetector::getReceiverStatus() { + int fnum = F_GET_RECEIVER_STATUS; + int ret = FAIL; + runStatus retval = ERROR; + FILE_LOG(logDEBUG1) << "Getting Receiver Status"; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, nullptr, 0, &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver Status: " << runStatusType(retval); + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); // Do we need to handle this ret? + } + return retval; +} + +int slsDetector::getFramesCaughtByReceiver() { + int fnum = F_GET_RECEIVER_FRAMES_CAUGHT; + int ret = FAIL; + int retval = -1; + FILE_LOG(logDEBUG1) << "Getting Frames Caught by Receiver"; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, nullptr, 0, &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Frames Caught by Receiver: " << retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return retval; +} + +int slsDetector::getReceiverCurrentFrameIndex() { + int fnum = F_GET_RECEIVER_FRAME_INDEX; + int ret = FAIL; + int retval = -1; + FILE_LOG(logDEBUG1) << "Getting Current Frame Index of Receiver"; + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, nullptr, 0, &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Current Frame Index of Receiver: " << retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return retval; +} + +int slsDetector::resetFramesCaught() { + int fnum = F_RESET_RECEIVER_FRAMES_CAUGHT; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Reset Frames Caught by Receiver"; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return ret; +} + +bool slsDetector::setFileWrite(bool value) { + int fnum = F_ENABLE_RECEIVER_FILE_WRITE; + int ret = FAIL; + int arg = static_cast(value); + int retval = -1; + FILE_LOG(logDEBUG1) << "Sending enable file write to receiver: " << arg; + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver file write enable: " << retval; + detector_shm()->rxFileWrite = static_cast(retval); + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return getFileWrite(); +} + +bool slsDetector::getFileWrite() const { return detector_shm()->rxFileWrite; } + +bool slsDetector::setFileOverWrite(bool value) { + int fnum = F_ENABLE_RECEIVER_OVERWRITE; + int ret = FAIL; + int arg = static_cast(value); + int retval = -1; + FILE_LOG(logDEBUG1) << "Sending enable file overwrite to receiver: " << arg; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver file overwrite enable: " << retval; + detector_shm()->rxFileOverWrite = static_cast(retval); + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return getFileOverWrite(); +} + +bool slsDetector::getFileOverWrite() const { + return detector_shm()->rxFileOverWrite; +} + +int slsDetector::setReceiverStreamingFrequency(int freq) { + if (freq >= 0) { + int fnum = F_RECEIVER_STREAMING_FREQUENCY; + int ret = FAIL; + int arg = freq; + int retval = -1; + FILE_LOG(logDEBUG1) << "Sending read frequency to receiver: " << arg; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver read frequency: " << retval; + detector_shm()->receiver_read_freq = retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + } + return detector_shm()->receiver_read_freq; +} + +int slsDetector::setReceiverStreamingTimer(int time_in_ms) { + int fnum = F_RECEIVER_STREAMING_TIMER; + int ret = FAIL; + int arg = time_in_ms; + int retval = -1; + FILE_LOG(logDEBUG1) << "Sending read timer to receiver: " << arg; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver read timer: " << retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return retval; +} + +bool slsDetector::enableDataStreamingFromReceiver(int enable) { + if (enable >= 0) { + int fnum = F_STREAM_DATA_FROM_RECEIVER; + int ret = FAIL; + int arg = enable; + int retval = -1; + FILE_LOG(logDEBUG1) << "Sending Data Streaming to receiver: " << arg; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver Data Streaming: " << retval; + detector_shm()->receiver_upstream = static_cast(retval); + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + } + return detector_shm()->receiver_upstream; +} + +int slsDetector::enableTenGigabitEthernet(int i) { + int fnum = F_ENABLE_TEN_GIGA; + int ret = FAIL; + int arg = i; + int retval = -1; + FILE_LOG(logDEBUG1) << "Enabling / Disabling 10Gbe: " << arg; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "10Gbe: " << retval; + detector_shm()->tenGigaEnable = retval; + client.close(); + if (ret == FORCE_UPDATE) { + updateDetector(); + } + ret = configureMAC(); + } + + // receiver + if ((detector_shm()->receiverOnlineFlag == ONLINE_FLAG) && ret == OK) { + fnum = F_ENABLE_RECEIVER_TEN_GIGA; + arg = detector_shm()->tenGigaEnable; + retval = -1; + FILE_LOG(logDEBUG1) << "Sending 10Gbe enable to receiver: " << arg; + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver 10Gbe enable: " << retval; + if (ret == FORCE_UPDATE) { + receiver.close(); + updateCachedReceiverVariables(); + } + } + return detector_shm()->tenGigaEnable; +} + +int slsDetector::setReceiverFifoDepth(int i) { + int fnum = F_SET_RECEIVER_FIFO_DEPTH; + int ret = FAIL; + int arg = i; + int retval = -1; + FILE_LOG(logDEBUG1) << "Sending Receiver Fifo Depth: " << arg; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver Fifo Depth: " << retval; + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return retval; +} + +bool slsDetector::setReceiverSilentMode(int i) { + int fnum = F_SET_RECEIVER_SILENT_MODE; + int ret = FAIL; + int arg = i; + int retval = -1; + FILE_LOG(logDEBUG1) << "Sending Receiver Silent Mode: " << arg; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Receiver Data Streaming: " << retval; + detector_shm()->receiver_silentMode = static_cast(retval); + } + if (ret == FORCE_UPDATE) { + updateCachedReceiverVariables(); + } + return detector_shm()->receiver_silentMode; +} + +int slsDetector::restreamStopFromReceiver() { + int fnum = F_RESTREAM_STOP_FROM_RECEIVER; + int ret = FAIL; + FILE_LOG(logDEBUG1) << "Restream stop dummy from Receiver via zmq"; + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto receiver = ReceiverSocket(detector_shm()->receiver_hostname, + detector_shm()->receiverTCPPort); + ret = receiver.sendCommandThenRead(fnum, nullptr, 0, nullptr, 0); + } + if (ret == FORCE_UPDATE) { + ret = updateCachedReceiverVariables(); + } + return ret; +} + +int slsDetector::setPattern(const std::string &fname) { + uint64_t word; + uint64_t addr = 0; + FILE *fd = fopen(fname.c_str(), "r"); + if (fd != nullptr) { + while (fread(&word, sizeof(word), 1, fd) != 0u) { + setPatternWord(addr, word); // TODO! (Erik) do we need to send + // pattern in 64bit chunks? + ++addr; + } + fclose(fd); + } else { + return -1; + } + return addr; +} + +uint64_t slsDetector::setPatternWord(uint64_t addr, uint64_t word) { + int fnum = F_SET_PATTERN; + int ret = FAIL; + uint64_t mode = 0; // sets word + uint64_t args[]{mode, addr, word}; + uint64_t retval = -1; + FILE_LOG(logDEBUG1) << "Setting Pattern word, addr: 0x" << std::hex << addr + << ", word: 0x" << word << std::dec; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Set Pattern word: " << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +int slsDetector::setPatternLoops(int level, int &start, int &stop, int &n) { + // TODO!(Erik) Should we change function signature to accept uint64_t? + int fnum = F_SET_PATTERN; + int ret = FAIL; + uint64_t mode = 1; // sets loop + uint64_t args[5]{mode, static_cast(level), + static_cast(start), static_cast(stop), + static_cast(n)}; + int retvals[3]{}; + FILE_LOG(logDEBUG1) << "Setting Pat Loops, level: " << level + << ", start: " << start << ", stop: " << stop + << ", n: " << n; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), retvals, + sizeof(retvals)); + FILE_LOG(logDEBUG1) << "Set Pat Loops: " << retvals[0] << ", " + << retvals[1] << ", " << retvals[2]; + start = retvals[0]; + stop = retvals[1]; + n = retvals[2]; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return ret; +} + +int slsDetector::setPatternWaitAddr(uint64_t level, uint64_t addr) { + int fnum = F_SET_PATTERN; + int ret = FAIL; + uint64_t mode = 2; // sets loop + int retval = -1; + std::array args{mode, level, addr}; + FILE_LOG(logDEBUG1) << "Setting Pat Wait Addr, " + "level: " + << level << ", addr: 0x" << std::hex << addr + << std::dec; + + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args.data(), sizeof(args), + &retval, sizeof(retval)); + FILE_LOG(logDEBUG1) << "Set Pat Wait Addr: " << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +uint64_t slsDetector::setPatternWaitTime(uint64_t level, uint64_t t) { + int fnum = F_SET_PATTERN; + int ret = FAIL; + uint64_t mode = 3; // sets loop + uint64_t retval = -1; // TODO! is this what we want? + std::array args{mode, level, t}; + FILE_LOG(logDEBUG1) << "Setting Pat Wait Time, level: " << level + << ", t: " << t; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args.data(), sizeof(args), + &retval, sizeof(retval)); + FILE_LOG(logDEBUG1) << "Set Pat Wait Time: " << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +int slsDetector::setPatternMask(uint64_t mask) { + int fnum = F_SET_PATTERN_MASK; + int ret = FAIL; + uint64_t arg = mask; + FILE_LOG(logDEBUG1) << "Setting Pattern Mask " << std::hex << mask + << std::dec; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), nullptr, 0); + FILE_LOG(logDEBUG1) << "Pattern Mask successful"; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return ret; +} + +uint64_t slsDetector::getPatternMask() { + int fnum = F_GET_PATTERN_MASK; + int ret = FAIL; + uint64_t retval = -1; + FILE_LOG(logDEBUG1) << "Getting Pattern Mask "; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Pattern Mask:" << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +int slsDetector::setPatternBitMask(uint64_t mask) { + int fnum = F_SET_PATTERN_BIT_MASK; + int ret = FAIL; + uint64_t arg = mask; + FILE_LOG(logDEBUG1) << "Setting Pattern Bit Mask " << std::hex << mask + << std::dec; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), nullptr, 0); + FILE_LOG(logDEBUG1) << "Pattern Bit Mask successful"; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return ret; +} + +uint64_t slsDetector::getPatternBitMask() { + int fnum = F_GET_PATTERN_BIT_MASK; + int ret = FAIL; + uint64_t retval = -1; + FILE_LOG(logDEBUG1) << "Getting Pattern Bit Mask "; + if (detector_shm()->onlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, nullptr, 0, &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "Pattern Bit Mask:" << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +int slsDetector::setLEDEnable(int enable) { + int fnum = F_LED; + int ret = FAIL; + int arg = enable; + int retval = -1; + FILE_LOG(logDEBUG1) << "Sending LED Enable: " << arg; + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, &arg, sizeof(arg), &retval, + sizeof(retval)); + FILE_LOG(logDEBUG1) << "LED Enable: " << retval; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return retval; +} + +int slsDetector::setDigitalIODelay(uint64_t pinMask, int delay) { + int fnum = F_DIGITAL_IO_DELAY; + int ret = FAIL; + uint64_t args[2] = {pinMask, static_cast(delay)}; + FILE_LOG(logDEBUG1) << "Sending Digital IO Delay, pin mask: " << std::hex + << args[0] << ", delay: " << std::dec << args[1] + << " ps"; + + if (detector_shm()->receiverOnlineFlag == ONLINE_FLAG) { + auto client = DetectorSocket(detector_shm()->hostname, + detector_shm()->controlPort); + ret = client.sendCommandThenRead(fnum, args, sizeof(args), nullptr, 0); + FILE_LOG(logDEBUG1) << "Digital IO Delay successful"; + } + if (ret == FORCE_UPDATE) { + updateDetector(); + } + return ret; +} + +slsDetectorDefs::sls_detector_module * +slsDetector::interpolateTrim(sls_detector_module *a, sls_detector_module *b, + const int energy, const int e1, const int e2, + int tb) { + + // only implemented for eiger currently (in terms of which dacs) + if (detector_shm()->myDetectorType != EIGER) { + throw NotImplementedError( + "Interpolation of Trim values not implemented for this detector!"); + } + + sls_detector_module *myMod = createModule(detector_shm()->myDetectorType); + if (myMod == nullptr) { + throw RuntimeError("Could not create module"); + } + enum eiger_DacIndex { + SVP, + VTR, + VRF, + VRS, + SVN, + VTGSTV, + VCMP_LL, + VCMP_LR, + CAL, + VCMP_RL, + RXB_RB, + RXB_LB, + VCMP_RR, + VCP, + VCN, + VIS + }; + + // Copy other dacs + int dacs_to_copy[] = {SVP, VTR, SVN, VTGSTV, RXB_RB, RXB_LB, VCN, VIS}; + int num_dacs_to_copy = sizeof(dacs_to_copy) / sizeof(dacs_to_copy[0]); + for (int i = 0; i < num_dacs_to_copy; ++i) { + if (a->dacs[dacs_to_copy[i]] != b->dacs[dacs_to_copy[i]]) { + deleteModule(myMod); + return nullptr; + } + myMod->dacs[dacs_to_copy[i]] = a->dacs[dacs_to_copy[i]]; + } + + // Copy irrelevant dacs (without failing): CAL + if (a->dacs[CAL] != b->dacs[CAL]) { + FILE_LOG(logWARNING) << "DAC CAL differs in both energies " + "(" + << a->dacs[CAL] << "," << b->dacs[CAL] + << ")!\n" + "Taking first: " + << a->dacs[CAL]; + } + myMod->dacs[CAL] = a->dacs[CAL]; + + // Interpolate vrf, vcmp, vcp + int dacs_to_interpolate[] = {VRF, VCMP_LL, VCMP_LR, VCMP_RL, + VCMP_RR, VCP, VRS}; + int num_dacs_to_interpolate = + sizeof(dacs_to_interpolate) / sizeof(dacs_to_interpolate[0]); + for (int i = 0; i < num_dacs_to_interpolate; ++i) { + myMod->dacs[dacs_to_interpolate[i]] = + linearInterpolation(energy, e1, e2, a->dacs[dacs_to_interpolate[i]], + b->dacs[dacs_to_interpolate[i]]); + } + + // Interpolate all trimbits + if (tb != 0) { + for (int i = 0; i < myMod->nchan; ++i) { + myMod->chanregs[i] = linearInterpolation( + energy, e1, e2, a->chanregs[i], b->chanregs[i]); + } + } + return myMod; +} + +slsDetectorDefs::sls_detector_module * +slsDetector::readSettingsFile(const std::string &fname, + sls_detector_module *myMod, int tb) { + + FILE_LOG(logDEBUG1) << "Read settings file " << fname; + bool modCreated = + false; // If we create a module it must be deleted, TODO! usre RAII + if (myMod == nullptr) { + myMod = createModule(detector_shm()->myDetectorType); + if (myMod == nullptr) { + throw RuntimeError("Could not create module"); + } + modCreated = true; + } + + std::vector names; + switch (detector_shm()->myDetectorType) { + case GOTTHARD: + names.emplace_back("Vref"); + names.emplace_back("VcascN"); + names.emplace_back("VcascP"); + names.emplace_back("Vout"); + names.emplace_back("Vcasc"); + names.emplace_back("Vin"); + names.emplace_back("Vref_comp"); + names.emplace_back("Vib_test"); + break; + case EIGER: + break; + case JUNGFRAU: + names.emplace_back("VDAC0"); + names.emplace_back("VDAC1"); + names.emplace_back("VDAC2"); + names.emplace_back("VDAC3"); + names.emplace_back("VDAC4"); + names.emplace_back("VDAC5"); + names.emplace_back("VDAC6"); + names.emplace_back("VDAC7"); + break; + default: + if (modCreated) { + if (myMod != nullptr) { + deleteModule(myMod); + } + } + throw RuntimeError( + "Unknown detector type - unknown format for settings file"); + } + + // open file + std::ifstream infile; + if (detector_shm()->myDetectorType == EIGER) { + infile.open(fname.c_str(), std::ifstream::binary); + } else { + infile.open(fname.c_str(), std::ios_base::in); + } + if (!infile.is_open()) { + if (modCreated) { + deleteModule(myMod); + } + throw RuntimeError("Could not open settings file for reading: " + + fname); + } + + // eiger + if (detector_shm()->myDetectorType == EIGER) { + bool allread = false; + infile.read(reinterpret_cast(myMod->dacs), + sizeof(int) * (myMod->ndac)); + if (infile.good()) { + infile.read(reinterpret_cast(&myMod->iodelay), + sizeof(myMod->iodelay)); + if (infile.good()) { + infile.read(reinterpret_cast(&myMod->tau), + sizeof(myMod->tau)); + if (tb != 0) { + if (infile.good()) { + infile.read(reinterpret_cast(myMod->chanregs), + sizeof(int) * (myMod->nchan)); + if (infile) { + allread = true; + } + } + } else if (infile) { + allread = true; + } + } + } + if (!allread) { + if (modCreated) { + deleteModule(myMod); + } + infile.close(); + throw RuntimeError("readSettingsFile: Could not load all values " + "for settings for " + + fname); + } + for (int i = 0; i < myMod->ndac; ++i) { + FILE_LOG(logDEBUG1) << "dac " << i << ":" << myMod->dacs[i]; + } + FILE_LOG(logDEBUG1) << "iodelay:" << myMod->iodelay; + FILE_LOG(logDEBUG1) << "tau:" << myMod->tau; + } + + // gotthard, jungfrau + else { + size_t idac = 0; + std::string str; + while (infile.good()) { + getline(infile, str); + if (str.empty()) { + break; + } + FILE_LOG(logDEBUG1) << str; + std::string sargname; + int ival = 0; + std::istringstream ssstr(str); + ssstr >> sargname >> ival; + bool found = false; + for (size_t i = 0; i < names.size(); ++i) { + if (sargname == names[i]) { + myMod->dacs[i] = ival; + found = true; + FILE_LOG(logDEBUG1) + << names[i] << "(" << i << "): " << ival; + ++idac; + } + } + if (!found) { + throw RuntimeError("readSettingsFile: Unknown dac: " + + sargname); + if (modCreated) { + deleteModule(myMod); + } + infile.close(); + } + } + // not all read + if (idac != names.size()) { + if (modCreated) { + deleteModule(myMod); + } + infile.close(); + throw RuntimeError("Could read only " + std::to_string(idac) + + " dacs. Expected " + + std::to_string(names.size()) + " dacs"); + } + } + + infile.close(); + FILE_LOG(logINFO) << "Settings file loaded: " << fname.c_str(); + return myMod; +} + +int slsDetector::writeSettingsFile(const std::string &fname, + sls_detector_module &mod) { + + FILE_LOG(logDEBUG1) << "Write settings file " << fname; + + std::vector names; + switch (detector_shm()->myDetectorType) { + case GOTTHARD: + names.emplace_back("Vref"); + names.emplace_back("VcascN"); + names.emplace_back("VcascP"); + names.emplace_back("Vout"); + names.emplace_back("Vcasc"); + names.emplace_back("Vin"); + names.emplace_back("Vref_comp"); + names.emplace_back("Vib_test"); + break; + case EIGER: + break; + case JUNGFRAU: + names.emplace_back("VDAC0"); + names.emplace_back("VDAC1"); + names.emplace_back("VDAC2"); + names.emplace_back("VDAC3"); + names.emplace_back("VDAC4"); + names.emplace_back("VDAC5"); + names.emplace_back("VDAC6"); + names.emplace_back("VDAC7"); + names.emplace_back("VDAC8"); + names.emplace_back("VDAC9"); + names.emplace_back("VDAC10"); + names.emplace_back("VDAC11"); + names.emplace_back("VDAC12"); + names.emplace_back("VDAC13"); + names.emplace_back("VDAC14"); + names.emplace_back("VDAC15"); + break; + default: + throw RuntimeError( + "Unknown detector type - unknown format for settings file"); + } + + // open file + std::ofstream outfile; + if (detector_shm()->myDetectorType == EIGER) { + outfile.open(fname.c_str(), std::ofstream::binary); + } else { + outfile.open(fname.c_str(), std::ios_base::out); + } + if (!outfile.is_open()) { + throw RuntimeError("Could not open settings file for writing: " + + fname); + } + + // eiger + if (detector_shm()->myDetectorType == EIGER) { + for (int i = 0; i < mod.ndac; ++i) { + FILE_LOG(logINFO) << "dac " << i << ":" << mod.dacs[i]; + } + FILE_LOG(logINFO) << "iodelay: " << mod.iodelay; + FILE_LOG(logINFO) << "tau: " << mod.tau; + + outfile.write(reinterpret_cast(mod.dacs), + sizeof(int) * (mod.ndac)); + outfile.write(reinterpret_cast(&mod.iodelay), + sizeof(mod.iodelay)); + outfile.write(reinterpret_cast(&mod.tau), sizeof(mod.tau)); + outfile.write(reinterpret_cast(mod.chanregs), + sizeof(int) * (mod.nchan)); + } + + // gotthard, jungfrau + else { + for (int i = 0; i < mod.ndac; ++i) { + FILE_LOG(logDEBUG1) << "dac " << i << ": " << mod.dacs[i]; + outfile << names[i] << " " << mod.dacs[i] << std::endl; + } + } + + outfile.close(); + return OK; +} diff --git a/slsDetectorSoftware/src/slsDetectorCommand.cpp b/slsDetectorSoftware/src/slsDetectorCommand.cpp new file mode 100755 index 000000000..21fd974fa --- /dev/null +++ b/slsDetectorSoftware/src/slsDetectorCommand.cpp @@ -0,0 +1,5773 @@ +#include "slsDetectorCommand.h" +#include "multiSlsDetector.h" +#include "string_utils.h" + +#include +#include +#include +#include + +#include + + +/*! \mainpage Introduction + +This program is intended to control the SLS detectors via command line interface. +This is the only way to access all possible functionality of the detectors, however it is often recommendable to avoid changing the most advanced settings, rather leaving the task to configuration files, as when using the GUI or the API provided. + +The command line interface consists in four main functions: + +- \b sls_detector_acquire to acquire data from the detector +- \b sls_detector_put to set detector parameters +- \b sls_detector_get to retrieve detector parameters +- \b sls_detector_help to get help concerning the text commands +Additionally the program slsReceiver should be started on the machine expected to receive the data from the detector. + + +If you need control a single detector, the use of the command line interface does not need any additional arguments. + +For commands addressing a single controller of your detector, the command cmd should be called with the index i of the controller: + + +sls_detector_clnt i:cmd + + +where \b sls_detector_clnt is the text client (put, get, acquire, help). + +In case more than one detector is configured on the control PC, the command cmd should be called with their respective index j: + + +sls_detector_clnt j-cmd + + +where \b sls_detector_clnt is the text client (put, get, acquire, help). + +To address a specific controller i of detector j use: + +sls_detector_clnt j-i:cmd + + +To use different shared memory segements for different detectors on the same +client pc, one can use environment variable SLSDETNAME set to any string to +different strings to make the shared memory segments unique. One can then use +the same multi detector id for both detectors as they have a different shared memory names. + +For additional questions concerning the indexing of the detector, please refer to the SLS Detectors FAQ documentation. + +The commands are sudivided into different pages depending on their functionalities: + - \ref acquisition "Acquisition": commands to start/stop the acquisition and retrieve data + - \ref config "Configuration": commands to configure the detector + - \ref timing "Timing": commands to configure the detector timing + - \ref data "Data postprocessing": commands to process the data + - \ref settings "Settings": commands to define detector settings/threshold. + - \ref output "Output": commands to define output file destination and format + - \ref network "Network": commands to setup the network between client, detector and receiver + - \ref receiver "Receiver": commands to configure the receiver + - \ref prototype "Chip Test Board / Moench": commands specific for the chiptest board or moench + - \ref test "Developer": commands to be used only for software debugging. Avoid using them! + + */ + +slsDetectorCommand::slsDetectorCommand(multiSlsDetector *det) { + + myDet = det; + + int i = 0; + + cmd = std::string("none"); + + /*! \page test Developer + Commands to be used only for software debugging. Avoid using them! + - \b test returns an error + */ + + descrToFuncMap[i].m_pFuncName = "test"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdUnderDevelopment; + ++i; + + /*! \page test + - help Returns a list of possible commands. + */ + descrToFuncMap[i].m_pFuncName = "help"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdHelp; + ++i; + + /*! \page test + - exitserver Shuts down all the detector servers. Don't use it!!!! + */ + descrToFuncMap[i].m_pFuncName = "exitserver"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdExitServer; + ++i; + + /*! \page test + - exitreceiver Shuts down all the receivers. Don't use it!!!! + */ + descrToFuncMap[i].m_pFuncName = "exitreceiver"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdExitServer; + ++i; + + /*! \page test + - execcommand Executes a command on the detector server. Don't use it!!!! + */ + descrToFuncMap[i].m_pFuncName = "execcommand"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdExitServer; + ++i; + + /*! \page test + - rx_execcommand Executes a command on the receiver server. Don't use it!!!! + */ + descrToFuncMap[i].m_pFuncName = "rx_execcommand"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdExitServer; + ++i; + + /*! \page test + - flippeddatay [i] enables/disables data being flipped across y axis. 1 enables, 0 disables. Not implemented. + */ + descrToFuncMap[i].m_pFuncName = "flippeddatay"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDetectorSize; + ++i; + + /* digital test and debugging */ + + /*! \page test + - digibittest:[i] performs digital test of the module i. Returns 0 if succeeded, otherwise error mask. Gotthard only. Only put! + */ + descrToFuncMap[i].m_pFuncName = "digibittest"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDigiTest; + ++i; + + /*! \page test + - bustest performs test of the bus interface between FPGA and embedded Linux system. Can last up to a few minutes. Cannot set! Jungfrau only. Only get! + */ + descrToFuncMap[i].m_pFuncName = "bustest"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDigiTest; + ++i; + + /*! \page test + - firmwaretest performs the firmware test. Cannot set! Jungfrau only. Only get! + */ + descrToFuncMap[i].m_pFuncName = "firmwaretest"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDigiTest; + ++i; + + /*! \page test + - reg [addr] [val] ??? writes to an register \c addr with \c value in hexadecimal format. + */ + descrToFuncMap[i].m_pFuncName = "reg"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdRegister; + ++i; + + /*! \page test + - adcreg [addr] [val] ??? writes to an adc register \c addr with \c value in hexadecimal format. Only put! + */ + descrToFuncMap[i].m_pFuncName = "adcreg"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdRegister; + ++i; + + /*! \page test + - setbit ??? Only put! + */ + descrToFuncMap[i].m_pFuncName = "setbit"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdRegister; + ++i; + + /*! \page test + - clearbit ??? Only put! + */ + descrToFuncMap[i].m_pFuncName = "clearbit"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdRegister; + ++i; + + /*! \page test + - getbit ??? Only get! + */ + descrToFuncMap[i].m_pFuncName = "getbit"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdRegister; + ++i; + + /* Acquisition and status commands */ + /*! \page acquisition Acquition commands + Commands to control the acquisition + */ + /*! \page acquisition + - \b acquire blocking acquisition (like calling sls_detector_acquire). Starts receiver and detector, writes and processes the data, stops detector. Only get! + \c Returns (string)\c "acquire failed" if fails, else \c "Acquired (int)", where int is number of frames caught. + */ + descrToFuncMap[i].m_pFuncName = "acquire"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdAcquire; + ++i; + + /*! \page acquisition + - busy i sets/gets acquiring flag. \c 1 the acquisition is active, \c 0 otherwise. Acquire command will set this flag to 1 at the beginning and to 0 at the end. Use this to clear flag if acquisition terminated unexpectedly. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "busy"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdStatus; + ++i; + + /*! \page acquisition + - status [s] starts or stops acquisition in detector in non blocking mode. When using stop acquisition and if acquisition is done, it will restream the stop packet from receiver (if data streaming in receiver is on). Eiger can also provide an internal software trigger. \c s: [\c start, \c stop, \c trigger(EIGER only)]. \c Returns the detector status: [\c running, \c error, \c transmitting, \c finished, \c waiting, \c idle]. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "status"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdStatus; + ++i; + + /*! \page acquisition + - \b data gets all data from the detector (if any) processes them and writes them to file according to the preferences already setup (Eigerr store in ram only). Only get! + */ + descrToFuncMap[i].m_pFuncName = "data"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdData; + ++i; + + /*! \page acquisition + - readctr Reads the counters from the detector memory (analog detector returning values translated into number of photons - only GOTTHARD). Cannot put. + */ + descrToFuncMap[i].m_pFuncName = "readctr"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdCounter; + ++i; + + /*! \page acquisition + - resetctr i Resets counter in detector, restarts acquisition if i=1(analog detector returning values translated into number of photons - only GOTTHARD). Cannot put. + */ + descrToFuncMap[i].m_pFuncName = "resetctr"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdCounter; + ++i; + + /*! \page acquisition + - resmat i sets/resets counter bit in detector.gets the counter bit in detector ???? + */ + descrToFuncMap[i].m_pFuncName = "resmat"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdCounter; + ++i; + + /*! \page config Configuration commands + Commands to configure the detector. these commands are often left to the configuration file. + - \ref configstructure "Data Structure": commands to configure detector data structure + - \ref configstatus "Status": commands to configure detector status + - \ref configsize "Data Size": commands to configure detector data size + - \ref configflags "Flags": commands to configure detector flags + - \ref configchip "Chip": commands to configure chip of the detector + - \ref configversions "Versions": commands to check version of each subsytem + - \ref configspeed "Speed": commands to configure speed of detector + - \ref configsettings "Detector Parameters": commands to configure/retrieve configuration of detector + */ + /*! \page timing Timing commands + Commands to setup the timing + */ + /* Detector structure configuration and debugging commands */ + /*! \page config + \section configstructure Data Structure + commands to configure detector data structure + */ + + /*! \page config + - \b free Free shared memory on the control PC + */ + descrToFuncMap[i].m_pFuncName = "free"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdFree; + ++i; + + /*! \page config + - hostname \c put frees shared memory and sets the hostname (or IP adress). Only allowed at multi detector level. \c Returns the list of the hostnames of the multi-detector structure. \c (string) + */ + descrToFuncMap[i].m_pFuncName = "hostname"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdHostname; + ++i; + + /*! \page config + - \b add appends a hostname (or IP address) at the end of the multi-detector structure. Only allowed at multi detector level. Cannot get. \c Returns the current list of detector hostnames. \c (string) + */ + descrToFuncMap[i].m_pFuncName = "add"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdHostname; + ++i; + + /*! \page config + - replace \c Sets the hostname (or IP adress) for a single detector. Only allowed at single detector level. Cannot get. \c Returns the hostnames for that detector \c (string) + */ + descrToFuncMap[i].m_pFuncName = "replace"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdHostname; + ++i; + + /*! \page config + - user \c Returns user details from shared memory. Only allowed at multi detector level. Cannot put. \c (string) + */ + descrToFuncMap[i].m_pFuncName = "user"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdUser; + ++i; + + /*! \page config + \section configstatus Status + commands to configure detector status + */ + + /*! \page config + - online [i] sets the detector in online (1) or offline (0) mode. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "online"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdOnline; + ++i; + + /*! \page config + - checkonline returns the hostnames of all detectors without connecting to them. \c Returns (string) "All online" or "[list of offline hostnames] : Not online". + */ + descrToFuncMap[i].m_pFuncName = "checkonline"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdOnline; + ++i; + /*! \page config + - activate [b] [p] Activates/Deactivates the detector. \c b is 1 for activate, 0 for deactivate. Deactivated detector does not send data. \c p is optional and can be padding (default) or nonpadding for receivers for deactivated detectors. Used for EIGER only. \c Returns \c (int) (string) + */ + descrToFuncMap[i].m_pFuncName = "activate"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdOnline; + ++i; + + /* detector and data size */ + /*! \page config + \section configsize Data Size + commands to configure detector data size + */ + + /*! \page config + - dr [i] sets/gets the dynamic range of detector. Eiger [4,8,16,32]. Others cannot put! \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "dr"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDetectorSize; + ++i; + + /*! \page config + - roi [i] [xmin] [xmax] [ymin] [ymax] sets region of interest of the detector, where i is number of rois;i=0 to clear rois. Used for GOTTHARD only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "roi"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDetectorSize; + ++i; + + /*! \page config + - detsizechan [xmax] [ymax] sets the maximum number of channels in each dimension for complete detector set; -1 is no limit. Use for multi-detector system as first command in config file. \c Returns \c ("int int") + */ + descrToFuncMap[i].m_pFuncName = "detsizechan"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDetectorSize; + ++i; + + /*! \page config + - flippeddatax [i] enables/disables data being flipped across x axis. 1 enables, 0 disables. Used for EIGER only. 1 for bottom half-module, 0 for top-half module. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "flippeddatax"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDetectorSize; + ++i; + + /*! \page config + - tengiga [i] enables/disables 10GbE in system (detector & receiver). 1 enabled 10GbE, 0 enables 1GbE. Used in EIGER, Moench and ChipTestBoard only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "tengiga"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdReceiver; + ++i; + + /*! \page config + - gappixels [i] enables/disables gap pixels in system (detector & receiver). 1 sets, 0 unsets. Used in EIGER only and only in multi detector level command. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "gappixels"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDetectorSize; + ++i; + + /* flags */ + /*! \page config + \section configflags Flags + commands to configure detector flags + */ + + /*! \page config + - flags [flag] sets/gets the readout flags to mode. Options: none, storeinram, tot, continous, parallel, nonparallel, safe, digital, analog_digital, overflow, nooverflow, unknown. Used for EIGER only. \c Returns \c (string). put takes one string and \c returns concatenation of all active flags separated by spaces. + */ + descrToFuncMap[i].m_pFuncName = "flags"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdAdvanced; + ++i; + + /*! \page config + - extsig:[i] [flag] sets/gets the mode of the external signal i. Options: \c off, \c gate_in_active_high, \c gate_in_active_low, \c trigger_in_rising_edge, \c trigger_in_falling_edge, + \c ro_trigger_in_rising_edge, \c ro_trigger_in_falling_edge, \c gate_out_active_high, \c gate_out_active_low, \c trigger_out_rising_edge, \c trigger_out_falling_edge, \c ro_trigger_out_rising_edge, + \c ro_trigger_out_falling_edge. \n Used in GOTTHARDonly. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "extsig"; /* find command! */ + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdAdvanced; + ++i; + + /* fpga */ + + /*! \page config + - programfpga [file] programs the FPGA with file f (with .pof extension). Used for JUNGFRAU only. Only put! \c Returns \c ("successful", "failed") + */ + descrToFuncMap[i].m_pFuncName = "programfpga"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdAdvanced; + ++i; + + /*! \page config + - resetfpga [f] resets FPGA, where f can be any value. Used for JUNGFRAU only. Only put! \c Returns \c ("successful", "failed") + */ + descrToFuncMap[i].m_pFuncName = "resetfpga"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdAdvanced; + ++i; + + /*! \page config + - copydetectorserver [sname] [phost] copies the detector server sname via tftp from pc with hostname phost and changes respawn server for all detector. Not for Eiger. Only put! \c Returns \c ("successful", "failed") + */ + descrToFuncMap[i].m_pFuncName = "copydetectorserver"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdAdvanced; + ++i; + + /*! \page config + - rebootdetpc reboot detector controller blackfin. Only put! Not for Eiger. \c Returns \c ("successful", "failed") + */ + descrToFuncMap[i].m_pFuncName = "rebootcontroller"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdAdvanced; + ++i; + + /*! \page config + - update [sname] [phost] [file] updates the firmware to file and detector server to sname from phost via tftp and then reboots controller (blackfin). Only put! Not for Eiger. \c Returns \c ("successful", "failed") + */ + descrToFuncMap[i].m_pFuncName = "update"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdAdvanced; + ++i; + + /* chip */ + /*! \page config + \section configchip Chip + commands to configure chip of the detector + */ + + /*! \page config + - powerchip [i] Powers on/off the chip. 1 powers on, 0 powers off. Can also get the power status. Used for JUNGFRAU only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "powerchip"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdAdvanced; + ++i; + + /*! \page config + - led [i] sets/gets the led status. 1 on, 0 off. Used for MOENCH only ?? \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "led"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdAdvanced; + ++i; + + /*! \page config + - diodelay [i] [v] sets the delay for the digital IO pins selected by mask i and delay set by v. mask is upto 64 bits in hex, delay is a max is 775ps, and set in steps of 25 ps. Used for MOENCH/CTB only. Cannot get. \c Returns \c ("successful", failed") + */ + descrToFuncMap[i].m_pFuncName = "diodelay"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdAdvanced; + ++i; + + /*! \page config + - auto_comp_disable i Currently not implemented. this mode disables the on-chip gain switching comparator automatically after 93.75% of exposure time (only for longer than 100us). 1 enables mode, 0 disables mode. By default, mode is disabled (comparator is enabled throughout). (JUNGFRAU only). \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "auto_comp_disable"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdAdvanced; + ++i; + + /*! \page config + - pulse [n] [x] [y] pulses pixel at coordinates (x,y) n number of times. Used in EIGER only. Only put! \c Returns \c ("successful", "failed") + */ + descrToFuncMap[i].m_pFuncName = "pulse"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPulse; + ++i; + + /*! \page config + - pulsenmove [n] [x] [y] pulses pixel n number of times and moves relatively by x value (x axis) and y value(y axis). Used in EIGER only. Only put! \c Returns \c ("successful", "failed") + */ + descrToFuncMap[i].m_pFuncName = "pulsenmove"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPulse; + ++i; + + /*! \page config + - pulsechip [n]pulses chip n number of times, while n=-1 will reset it to normal mode. Used in EIGER only. Only put! \c Returns \c ("successful", "failed") + */ + descrToFuncMap[i].m_pFuncName = "pulsechip"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPulse; + ++i; + + /* versions/ serial numbers getId */ + /*! \page config + \section configversions Versions + Commands to check versions of each subsystem + */ + + /*! \page config + - checkdetversion Checks the version compatibility with detector server (if hostname is in shared memory). Only get! Only for Eiger, Jungfrau & Gotthard. \c Returns \c ("compatible", "incompatible") + */ + descrToFuncMap[i].m_pFuncName = "checkdetversion"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSN; + ++i; + + /*! \page config + - checkrecversion Checks the version compatibility with receiver server (if rx_hostname is in shared memory). Only get! Only for Eiger, Jungfrau & Gotthard. \c Returns \c ("compatible", "incompatible") + */ + descrToFuncMap[i].m_pFuncName = "checkrecversion"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSN; + ++i; + + /*! \page config + - detectornumber Gets the serial number or MAC of detector. Only get! \c Returns \c (long int) in hexadecimal + */ + descrToFuncMap[i].m_pFuncName = "detectornumber"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSN; + ++i; + + /*! \page config + - detectorversion Gets the firmware version of detector. Only get! \c Returns \c (long int) in hexadecimal + */ + descrToFuncMap[i].m_pFuncName = "detectorversion"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSN; + ++i; + + /*! \page config + - softwareversion Gets the software version of detector server. Only get! \c Returns \c (long int) in hexadecimal + */ + descrToFuncMap[i].m_pFuncName = "softwareversion"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSN; + ++i; + + /*! \page config + - thisversion Gets the software version of this client software. Only get! \c Returns \c (long int) in hexadecimal + */ + descrToFuncMap[i].m_pFuncName = "thisversion"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSN; + ++i; + + /*! \page config + - receiverversion Gets the software version of receiver. Only get! \c Returns \c (long int) in hexadecimal + */ + descrToFuncMap[i].m_pFuncName = "receiverversion"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSN; + ++i; + + /* r/w timers */ + + /*! \page timing + - timing [mode] sets/gets synchronization mode of the detector. Mode: auto, trigger, ro_trigger, gating, triggered_gating (string) + */ + descrToFuncMap[i].m_pFuncName = "timing"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTiming; + ++i; + + /*! \page timing + - exptime [i] sets/gets exposure time in s. \c Returns \c (double with 9 decimal digits) + */ + descrToFuncMap[i].m_pFuncName = "exptime"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimer; + ++i; + + /*! \page timing + - subexptime [i] sets/gets sub exposure time in s. Used in EIGER only in 32 bit mode. \c Returns \c (double with 9 decimal digits) + */ + descrToFuncMap[i].m_pFuncName = "subexptime"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimer; + ++i; + + /*! \page timing + - period [i] sets/gets frame period in s. \c Returns \c (double with 9 decimal digits) + */ + descrToFuncMap[i].m_pFuncName = "period"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimer; + ++i; + + /*! \page timing + - subdeadtime [i] sets/gets sub frame dead time in s. Subperiod is set in the detector = subexptime + subdeadtime. This value is normally a constant in the config file. Used in EIGER only in 32 bit mode. \c Returns \c (double with 9 decimal digits) + */ + descrToFuncMap[i].m_pFuncName = "subdeadtime"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimer; + ++i; + + /*! \page timing + - delay [i] sets/gets delay in s. Used in GOTTHARD only. \c Returns \c (double with 9 decimal digits) + */ + descrToFuncMap[i].m_pFuncName = "delay"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimer; + ++i; + + /*! \page timing + - gates [i] sets/gets number of gates. Used in GOTTHARD only. \c Returns \c (long long int) + */ + descrToFuncMap[i].m_pFuncName = "gates"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimer; + ++i; + + /*! \page timing + - frames [i] sets/gets number of frames. If \c timing is not \c auto, then it is the number of frames per cycle/trigger. \c Returns \c (long long int) + */ + descrToFuncMap[i].m_pFuncName = "frames"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimer; + ++i; + + /*! \page timing + - cycles [i] sets/gets number of triggers. Timing mode should be set appropriately. \c Returns \c (long long int) + */ + descrToFuncMap[i].m_pFuncName = "cycles"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimer; + ++i; + + /*! \page timing + - measurements [i] sets/gets number of measurements. \c Returns \c (long long int) + */ + descrToFuncMap[i].m_pFuncName = "measurements"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimer; + ++i; + + /*! \page timing + - samples [i] sets/gets number of samples expected from the jctb. Used in CHIP TEST BOARD only. \c Returns \c (long long int) + */ + descrToFuncMap[i].m_pFuncName = "samples"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimer; + ++i; + + /*! \page timing + - storagecells [i] sets/gets number of additional storage cells per acquisition. For very advanced users only! For JUNGFRAU only. Range: 0-15. The #images = #frames * #cycles * (#storagecells +1). \c Returns \c (long long int) + */ + descrToFuncMap[i].m_pFuncName = "storagecells"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimer; + ++i; + + /*! \page timing + - storagecell_start [i] sets/gets the storage cell that stores the first acquisition of the series. Default is 15(0xf).. For very advanced users only! For JUNGFRAU only. Range: 0-15. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "storagecell_start"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimer; + ++i; + + /*! \page timing + - storagecell_start [i] sets/gets the storage cell that stores the first acquisition of the series. Default is 15(0xf).. For very advanced users only! For JUNGFRAU only. Range: 0-15. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "storagecell_start"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimer; + ++i; + + /*! \page timing + - storagecell_delay [i] sets/gets additional time between 2 storage cells. For very advanced users only! For JUNGFRAU only. Range: 0-1638375 ns (resolution of 25ns). \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "storagecell_delay"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimer; + ++i; + + /* read only timers */ + + /*! \page timing + - exptimel gets exposure time left. Used in GOTTHARD only. Only get! \c Returns \c (double with 9 decimal digits) + */ + descrToFuncMap[i].m_pFuncName = "exptimel"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimeLeft; + ++i; + + /*! \page timing + - periodl gets frame period left. Used in GOTTHARD and Jungfrau only. Only get! \c Returns \c (double with 9 decimal digits) + */ + descrToFuncMap[i].m_pFuncName = "periodl"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimeLeft; + ++i; + + /*! \page timing + - delayl gets delay left. Used in GOTTHARD only. Only get! \c Returns \c (double with 9 decimal digits) + */ + descrToFuncMap[i].m_pFuncName = "delayl"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimeLeft; + ++i; + + /*! \page timing + - gatesl gets number of gates left. Used in GOTTHARD only. Only get! \c Returns \c (double with 9 decimal digits) + */ + descrToFuncMap[i].m_pFuncName = "gatesl"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimeLeft; + ++i; + + /*! \page config + - framesl gets number of frames left. Used in GOTTHARD and Jungfrau only. Only get! \c Returns \c (double with 9 decimal digits) + */ + descrToFuncMap[i].m_pFuncName = "framesl"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimeLeft; + ++i; + + /*! \page timing + - cyclesl gets number of cylces left. Used in GOTTHARD and Jungfrau only. Only get! \c Returns \c (double with 9 decimal digits) + */ + descrToFuncMap[i].m_pFuncName = "cyclesl"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimeLeft; + ++i; + + /*! \page timing + - now Getting actual time of the detector from start. For Jungfrau only. Only get! + */ + descrToFuncMap[i].m_pFuncName = "now"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimeLeft; + ++i; + + /*! \page timing + - timestamp Getting timestamp. For Jungfrau only. Only get! + */ + descrToFuncMap[i].m_pFuncName = "timestamp"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimeLeft; + ++i; + + /*! \page timing + - nframes Frames from start run control. Only Jungfrau. Only get! + */ + descrToFuncMap[i].m_pFuncName = "nframes"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimeLeft; + ++i; + + /*! \page timing + - measuredperiod gets the measured frame period (time between last frame and the previous one) in s. For Eiger only. Makes sense only for acquisitions of more than 1 frame. \c Returns \c (double with 9 decimal digits) + */ + descrToFuncMap[i].m_pFuncName = "measuredperiod"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimeLeft; + ++i; + + /*! \page timing + - measuredsubperiod gets the measured subframe period (time between last subframe and the previous one) in s. For Eiger only and in 32 bit mode. \c Returns \c (double with 9 decimal digits) + */ + descrToFuncMap[i].m_pFuncName = "measuredsubperiod"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTimeLeft; + ++i; + + /* speed */ + /*! \page config + \section configspeed Speed + commands to configure speed of detector + */ + + /*! \page config + - clkdivider [i] sets/gets the readout clock divider. EIGER, JUNGFRAU [0(fast speed), 1(half speed), 2(quarter speed)]. Jungfrau, full speed is not implemented and overwrites adcphase to recommended default. Not for Gotthard. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "clkdivider"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSpeed; + ++i; + + /*! \page config + - adcclk [i] sets/gets the ADC clock frequency in MHz. CTB & Moench only. It also resets adcphase. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "adcclk"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSpeed; + ++i; + + /*! \page config + - dbitclk [i] Sets/gets the clock frequency of the latching of the digital bits in MHz. CTB & Moench only. It also resets dbit phase. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "dbitclk"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSpeed; + ++i; + + /*! \page config + - adcphase [i] [deg] Sets/gets phase of the ADC clock to i. i is the shift or in degrees if deg is used. deg is optional & only for CTB, Moench and Jungfrau. For CTB & Moench, adcphase is reset if adcclk is changed. For Jungfrau, adcphase changed to defaults if clkdivider changed. Jungfrau, CTB & Moench, these are absolute values with limits. Gotthard, relative phase shift. Not for Eiger. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "adcphase"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSpeed; + ++i; + + /*! \page config + - dbitphase [i] [deg] Sets/gets phase of the clock for latching of the digital bits to i. i is the shift or in degrees if deg is used. deg is optional. dbitphase is also reset if dbitclk is changed. These are absolute values with limits. for CTB & Moench only.\c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "dbitphase"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSpeed; + ++i; + + /*! \page config + - maxadcphaseshift Gets maximum phase shift of the ADC clock. CTB, Moench and Jungfrau only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "maxadcphaseshift"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSpeed; + ++i; + + /*! \page config + - maxdbitphaseshift Gets the maximum phase shift of the clock for latching of the digital bits.\c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "maxdbitphaseshift"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSpeed; + ++i; + + /*! \page config + - adcpipeline [i] Sets/gets the pipeline of the ADC. For CTB & Moench only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "adcpipeline"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSpeed; + ++i; + + /*! \page config + - dbitpipeline [i] Sets/gets the pipeline of the latching of the digital bits. For CTB & Moench only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "dbitpipeline"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSpeed; + ++i; + + /* settings dump/retrieve */ + /*! \page config + \section configsettings Detector Parameters + commands to configure/retrieve configuration of detector + */ + + /*! \page config + - config [fname] sets/saves detector/receiver to configuration contained in fname. Same as executing sls_detector_put for every line. Normally a one time operation. \c Returns \c (string) fname + */ + descrToFuncMap[i].m_pFuncName = "config"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdConfiguration; + ++i; + + /* settings dump/retrieve */ + /*! \page config + - rx_printconfig prints the receiver configuration. Only get! \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "rx_printconfig"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdConfiguration; + ++i; + + /*! \page config + - parameters [fname] sets/saves detector parameters contained in fname. Normally once per different measurement. \c Returns \c (string) fname + */ + descrToFuncMap[i].m_pFuncName = "parameters"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdConfiguration; + ++i; + + /*! \page config + - setup [fname] sets/saves detector complete setup contained in fname (extensions automatically generated), including trimfiles, ff coefficients etc. \c Returns \c (string) fname + */ + descrToFuncMap[i].m_pFuncName = "setup"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdConfiguration; + ++i; + + /* data processing commands */ + + /*! \page data Data processing commands + Commands to setup the data processing + */ + + /*! \page data + - ratecorr [ns] Returns the dead time used for rate correections in ns (int). \c put sets the deadtime correction constant in ns, -1 will set it to default tau of settings (0 unset). \c Returns \c (int). For Eiger only. + */ + descrToFuncMap[i].m_pFuncName = "ratecorr"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdRateCorr; + ++i; + + /*! \page data + // - threaded [i] Sets/gets the data processing threaded flag. 1 is threaded, 0 unthreaded. + // */ + // descrToFuncMap[i].m_pFuncName="threaded"; + // descrToFuncMap[i].m_pFuncPtr=&slsDetectorCommand::cmdThreaded; + // ++i; + + /*! \page data + - darkimage fn Loads the dark image to the detector from file fn (pedestal image). Cannot get. For Gotthard only. + */ + descrToFuncMap[i].m_pFuncName = "darkimage"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdImage; + ++i; + + /*! \page data + - gainimage fn Loads the gain image to the detector from file fn (gain map for translation into number of photons of an analog detector). Cannot get. For Gotthard only. + */ + descrToFuncMap[i].m_pFuncName = "gainimage"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdImage; + ++i; + + /*! \page settings Detector settings commands + Commands to setup the settings of the detector + - \ref settingsdir "Settings, trim & cal Directories": commands to setup settings/trim/cal directories + - \ref settingssett "Settings and Threshold": commands to configure settings and threshold of detector + - \ref settingsdacs "DACs": commands to configure DACs of detector + - \ref settingsadcs "ADCs": commands to readout ADCs of detector + - \ref settingstmp "Temp Control": commands to monitor and handle temperature overshoot (only JUNGFRAU) + */ + + /* trim/cal directories */ + /*! \page settings + \section settingsdir Settings, trim & cal Directories + commands to setup settings/trim/cal directories + */ + /*! \page settings + - settingsdir [dir] Sets/gets the directory where the settings files are located. \c Returns \c (string) dir + */ + descrToFuncMap[i].m_pFuncName = "settingsdir"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSettingsDir; + ++i; + /*! \page settings + - trimdir [dir] obsolete \c settingsdir. \c Returns \c (string) dir + */ + descrToFuncMap[i].m_pFuncName = "trimdir"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSettingsDir; + ++i; + + /*! \page settings + - trimen [n e0 e1...e(n-1)] Sets/gets the number of energies n at which the detector has default trim file and their values in eV (int). \c Returns \c (int int...) n e0 e1...e(n-1) + */ + descrToFuncMap[i].m_pFuncName = "trimen"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTrimEn; + ++i; + + /* settings, threshold */ + /*! \page settings + \section settingssett Settings and Threshold + commands to configure settings and threshold of detector + */ + + /*! \page settings + - settings [s] sets/gets the settings of the detector. Options: \c standard, \c fast, \c highgain, \c dynamicgain, \c lowgain, \c mediumgain, \c veryhighgain, + \c lownoise, \c dynamichg0, \c fixgain1, \c fixgain2, \c forceswitchg1, \c forceswitchg2. + \n In Eiger, only sets in client shared memory. Use \c threshold or \c thresholdnotb to pass to detector. Gets from detector. \c Returns \c (string) s + */ + descrToFuncMap[i].m_pFuncName = "settings"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSettings; + ++i; + + /*! \page settings + - threshold [eV] [sett] sets/gets the detector threshold in eV. sett is optional and if provided also sets the settings. Use this for Eiger instead of \c settings. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "threshold"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSettings; + ++i; + + /*! \page settings + - thresholdnotb [eV] [sett] sets/gets the detector threshold in eV without loading trimbits. sett is optional and if provided also sets the settings. Use this for Eiger instead of \c settings. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "thresholdnotb"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSettings; + ++i; + + /*! \page settings + - trimbits [fname] loads/stores the trimbits to/from the detector. If no extension is specified, the serial number of each module will be attached. \c Returns \c (string) fname + */ + descrToFuncMap[i].m_pFuncName = "trimbits"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSettings; + ++i; + + /*! \page settings + - trimval [i] sets all trimbits to i. Used in EIGER only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "trimval"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdSettings; + ++i; + + /* pots */ + /*! \page settings + \section settingsdacs DACs + commands to configure DACs of detector + */ + + /*! \page settings + - vthreshold [i] [mv] Sets/gets detector threshold voltage for single photon counters. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vthreshold"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vcalibration [i] [mv] Sets/gets the voltage of the calibration pulses. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vcalibration"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vtrimbit [i] [mv] Sets/gets the voltage to set the width of the trimbits. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vtrimbit"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vpreamp [i] [mv] Sets/gets the voltage to define the preamplifier feedback resistance. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vpreamp"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vhaper1 [i] [mv] Sets/gets the voltage to define the feedback resistance of the first shaper. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vshaper1"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vshaper2 [i] [mv] Sets/gets the voltage to define the feedback resistance of the second shaper. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vshaper2"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vhighvoltage [i] Sets/gets the high voltage to the sensor in V. \c Returns \c (int ["mV"]). + */ + descrToFuncMap[i].m_pFuncName = "vhighvoltage"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vapower [i] Sets/gets the analog power supply for the old chiptest board in DAC units. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vapower"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vddpower [i] Sets/gets the digital power supply for the old chiptest board in DAC units. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vddpower"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vshpower [i] Sets/gets the comparator power supply for the old chiptest board in DAC units. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vshpower"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - viopower [i] Sets/gets the power supply of the FPGA I/Os for the old chiptest board in DAC units. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "viopower"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vrefds [i] [mv] Sets/gets vrefds. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vref_ds"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vcascn_pb [i] [mv] Sets/gets vcascn_pb. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vcascn_pb"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vcasc_pb [i] [mv] Sets/gets vcasc_pb. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vcascp_pb"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vout_cm [i] [mv] Sets/gets vout_cm. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vout_cm"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vcasc_out [i] [mv] Sets/gets vcasc_out. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vcasc_out"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vin_com [i] [mv] Sets/gets vin_com. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vin_cm"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vref_comp [i] [mv] Sets/gets vref_comp. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vref_comp"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - ib_test_c [i] [mv] Sets/gets ib_test_c. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "ib_test_c"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vsvp [i] [mv] Sets/gets vsvp. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vsvp"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vsvn [i] [mv] Sets/gets vsvn. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vsvn"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vtr [i] [mv] Sets/gets vtr. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vtr"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vrf [i] [mv] Sets/gets vrf. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vrf"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vrs [i] [mv] Sets/gets vrs. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vrs"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vtgstv [i] [mv] Sets/gets vtgstv. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vtgstv"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vcmp_ll [i] [mv] Sets/gets vcmp_ll. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vcmp_ll"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vcmp_lr [i] [mv] Sets/gets vcmp_lr. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vcmp_lr"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vcal_l [i] [mv] Sets/gets vcal_l. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vcall"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vcomp_rl [i] [mv] Sets/gets vcomp_rl. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vcmp_rl"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vcomp_rr [i] [mv] Sets/gets vcomp_rr. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vcmp_rr"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - rxb_rb [i] [mv] Sets/gets rxb_rb. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "rxb_rb"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - rxb_lb [i] [mv] Sets/gets rxb_lb. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "rxb_lb"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vcp [i] [mv] Sets/gets vcp. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vcp"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vcn [i] [mv] Sets/gets vcn. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vcn"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - vis [i] [mv] Sets/gets vis. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "vis"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - iodelay [i] [mv] Sets/gets iodelay. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "iodelay"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - dac:j [i] [mv] Sets/gets value for DAC number j for the new chiptestboard. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "dac"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - adcvpp [i] Sets/gets the Vpp of the ADC 0 -> 1V ; 1 -> 1.14V ; 2 -> 1.33V ; 3 -> 1.6V ; 4 -> 2V . \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "adcvpp"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - v_a [i] mv Sets/gets value for Va on the new chiptest board. Must be in mV. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "v_a"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - v_b [i] mv Sets/gets value for Vb on the new chiptest board. Must be in mV. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "v_b"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - v_c [i] mv Sets/gets value for Vc on the new chiptest board. Must be in mV. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "v_c"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - v_d [i] mv Sets/gets value for Vd on the new chiptest board. Must be in mV. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "v_d"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - v_io [i] mv Sets/gets value for Vio on the new chiptest board. Must be in mV. It should be minimum 1200 mV and must be the first power regulator to be set after server start up (fpga reset). To change again, reset fpga first. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "v_io"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - v_chip [i] mv Sets/gets value for Vchip on the new chiptest board. Must be in mV. \c Returns \c (int ["mV"]). Do NOT use it, unless you are completely sure you won't fry the board! + */ + descrToFuncMap[i].m_pFuncName = "v_chip"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - v_limit [i] mv Sets/gets a soft limit for the power supplies and the DACs on the new chiptest board. Must be in mV. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "v_limit"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /* MYTHEN 3.01 + all values are in DACu */ + + descrToFuncMap[i].m_pFuncName = "vIpre"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + descrToFuncMap[i].m_pFuncName = "VcdSh"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - Vth1 Sets/gets first detector threshold voltage for Mythen 3.01. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "Vth1"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - Vth1 Sets/gets second detector threshold voltage for Mythen 3.01. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "Vth2"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /*! \page settings + - Vth1 Sets/gets third detector threshold voltage for Mythen 3.01. Normally in DAC units unless \c mv is specified at the end of the command line. \c Returns \c (int ["mV"]) + */ + descrToFuncMap[i].m_pFuncName = "Vth3"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + descrToFuncMap[i].m_pFuncName = "VPL"; //baseline for analog pulsing + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + descrToFuncMap[i].m_pFuncName = "Vtrim"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + descrToFuncMap[i].m_pFuncName = "vIbias"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + descrToFuncMap[i].m_pFuncName = "vIinSh"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + descrToFuncMap[i].m_pFuncName = "cas"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + descrToFuncMap[i].m_pFuncName = "casSh"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + descrToFuncMap[i].m_pFuncName = "vIbiasSh"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + descrToFuncMap[i].m_pFuncName = "vIcin"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + descrToFuncMap[i].m_pFuncName = "vIpreOut"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDAC; + ++i; + + /* r/w timers */ + /*! \page settings + \section settingsadcs ADCs + commands to readout ADCs of detector + */ + + /*! \page settings + - temp_adc Gets the ADC temperature. \c Returns \c EIGER,JUNGFRAU(double"°C") Others \c (int"°C") + */ + descrToFuncMap[i].m_pFuncName = "temp_adc"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - temp_fpga Gets the FPGA temperature. \c Returns \c EIGER,JUNGFRAU(double"°C") Others \c (int"°C") + */ + descrToFuncMap[i].m_pFuncName = "temp_fpga"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - temp_fpgaext Gets the external FPGA temperature. Used in EIGER only. \c Returns \c EIGER(double"°C") + */ + descrToFuncMap[i].m_pFuncName = "temp_fpgaext"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - temp_10ge Gets the 10Gbe temperature. Used in EIGER only. \c Returns \c EIGER(double"°C") + */ + descrToFuncMap[i].m_pFuncName = "temp_10ge"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - temp_dcdc Gets the temperature of the DC/DC converter. Used in EIGER only. \c Returns \c EIGER(double"°C") + */ + descrToFuncMap[i].m_pFuncName = "temp_dcdc"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - temp_sodl Gets the temperature of the left so-dimm memory . Used in EIGER only. \c Returns \c EIGER(double"°C") + */ + descrToFuncMap[i].m_pFuncName = "temp_sodl"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - temp_sodr Gets the temperature of the right so-dimm memory. Used in EIGER only. \c Returns \c EIGER(double"°C") + */ + descrToFuncMap[i].m_pFuncName = "temp_sodr"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - adc:j Gets the values of the slow ADC number j for the new chiptest board. \c Returns \c (int"°C") + */ + descrToFuncMap[i].m_pFuncName = "adc"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - temp_fpgal Gets the temperature of the left frontend FPGA. Used in EIGER only. \c Returns \c EIGER(double"°C") + */ + descrToFuncMap[i].m_pFuncName = "temp_fpgafl"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - temp_fpgar Gets the temperature of the right frontend FPGA. Used in EIGER only. \c Returns \c EIGER(double"°C") + */ + descrToFuncMap[i].m_pFuncName = "temp_fpgafr"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - i_a Gets the current of the power supply a on the new chiptest board. \c Returns \c (int"mV") + */ + descrToFuncMap[i].m_pFuncName = "i_a"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - i_b Gets the current of the power supply b on the new chiptest board \c Returns \c (int"mV") + */ + descrToFuncMap[i].m_pFuncName = "i_b"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - i_c Gets the current of the power supply c on the new chiptest board \c Returns \c (int"mV") + */ + descrToFuncMap[i].m_pFuncName = "i_c"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - i_d Gets the current of the power supply d on the new chiptest board \c Returns \c (int"mV") + */ + descrToFuncMap[i].m_pFuncName = "i_d"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - i_io Gets the current of the power supply io on the new chiptest board \c Returns \c (int"mV") + */ + descrToFuncMap[i].m_pFuncName = "i_io"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - vm_a Gets the measured voltage of the power supply a on the new chiptest board \c Returns \c (int"mV") + */ + descrToFuncMap[i].m_pFuncName = "vm_a"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - vm_b Gets the measured voltage of the power supply b on the new chiptest board \c Returns \c (int"mV") + */ + descrToFuncMap[i].m_pFuncName = "vm_b"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - vm_c Gets the measured voltage of the power supply c on the new chiptest board \c Returns \c (int"mV") + */ + descrToFuncMap[i].m_pFuncName = "vm_c"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - vm_d Gets the measured voltage of the power supply d on the new chiptest board \c Returns \c (int"mV") + */ + descrToFuncMap[i].m_pFuncName = "vm_d"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /*! \page settings + - vm_io Gets the measured voltage of the power supply io on the new chiptest board \c Returns \c (int"mV") + */ + descrToFuncMap[i].m_pFuncName = "vm_io"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdADC; + ++i; + + /* temperature control */ + /*! \page settings + \section settingstmp Temp Control + commands to monitor and handle temperature overshoot (only JUNGFRAU) + */ + + /*! \page settings + - temp_threshold Sets/gets the threshold temperature. JUNGFRAU ONLY. \c Returns \c (double"°C") + */ + descrToFuncMap[i].m_pFuncName = "temp_threshold"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTempControl; + ++i; + + /*! \page settings + - temp_control Enables/Disables the temperature control. 1 enables, 0 disables. JUNGFRAU ONLY. \c Returns \c int + */ + descrToFuncMap[i].m_pFuncName = "temp_control"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTempControl; + ++i; + + /*! \page settings + - temp_event Resets/gets over-temperative event. Put only with option 0 to clear event. Gets 1 if temperature went over threshold and control is enabled, else 0. /Disables the temperature control. JUNGFRAU ONLY. \c Returns \c int + */ + descrToFuncMap[i].m_pFuncName = "temp_event"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdTempControl; + ++i; + + /* file name */ + + /*! \page output Output settings + Commands to setup the file destination and format + */ + + /*! \page output + - outdir [dir] Sets/gets the file output directory. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "outdir"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdOutDir; + ++i; + + /*! \page output + - fname [fn] Sets/gets the root of the output file name \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "fname"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdFileName; + ++i; + + /*! \page output + - index [i] Sets/gets the current file index. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "index"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdFileIndex; + ++i; + + /*! \page output + - enablefwrite [i] Enables/disables file writing. 1 enables, 0 disables. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "enablefwrite"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdEnablefwrite; + ++i; + + /*! \page output + - overwrite [i] enables(1) /disables(0) file overwriting. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "overwrite"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdOverwrite; + ++i; + + /*! \page output + - fileformat sets/gets the file format for data in receiver. Options: [binary, hdf5]. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "fileformat"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdFileName; + ++i; + + /* communication configuration */ + + /*! \page network Network + Commands to setup the network between client, detector and receiver + - rx_hostname [s] sets/gets the receiver hostname or IP address, configures detector mac with all network parameters and updates receiver with acquisition parameters. Normally used for single detectors (Can be multi-detector). \c none disables. If used, use as last network command in configuring detector MAC. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "rx_hostname"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - rx_udpip [ip] sets/gets the ip address of the receiver UDP interface where the data from the detector will be streamed to. Normally used for single detectors (Can be multi-detector). Used if different from eth0. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "rx_udpip"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - rx_udpip2 [ip] sets/gets the ip address of the second receiver UDP interface where the data from the bottom half module of the detector will be streamed to. Normally used for single detectors (Can be multi-detector). Used if different from eth0. JUNGFRAU only. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "rx_udpip2"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - rx_udpmac [mac] sets/gets the mac address of the receiver UDP interface where the data from the detector will be streamed to. Normally used for single detectors (Can be multi-detector). \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "rx_udpmac"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - rx_udpmac2 [mac] sets/gets the mac address of the second receiver UDP interface where the data from the bottom half module of the detector will be streamed to. Normally used for single detectors (Can be multi-detector). JUNGFRAU only.\c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "rx_udpmac2"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - rx_udpport [port] sets/gets the port of the receiver UDP interface where the data from the detector will be streamed to. Use single-detector command. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "rx_udpport"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - rx_udpport2 [port] sets/gets the second port of the receiver UDP interface where the data from the second half of the detector will be streamed to. Use single-detector command. Used for EIGERand JUNGFRAU only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "rx_udpport2"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - rx_udpsocksize [size] sets/gets the UDP socket buffer size. Already trying to set by default to 100mb, 2gb for Jungfrau. Does not remember in client shared memory, so must be initialized each time after setting receiver hostname in config file.\c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "rx_udpsocksize"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - rx_realudpsocksize [size] gets the actual UDP socket buffer size. Usually double the set udp socket buffer size due to kernel bookkeeping. Get only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "rx_realudpsocksize"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - detectormac [mac] sets/gets the mac address of the detector UDP interface from where the detector will stream data. Use single-detector command. Normally unused. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "detectormac"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - detectormac2 [mac] sets/gets the mac address of the second half of the detector UDP interface from where the bottom half module of the detector will stream data. Use single-detector command. Normally unused. JUNGFRAU only. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "detectormac2"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - detectorip [ip] sets/gets the ip address of the detector UDP interface from where the bottom half of the detector will stream data. Use single-detector command. Keep in same subnet as rx_udpip (if rx_udpip specified). \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "detectorip"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - detectorip2 [ip] sets/gets the ip address of the second half of the detector UDP interface from where the bottom half of the detector will stream data. Use single-detector command. Keep in same subnet as rx_udpip2 (if rx_udpip2 specified). JUNGFRAU only. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "detectorip2"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - numinterfaces [n] sets/gets the number of interfaces used to stream out from the detector. Options: 1, 2. JUNGFRAU only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "numinterfaces"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - selinterface [n] sets/gets the 1st or the 2nd interface to use to stream data out of the detector. Options: 1, 2. Effective only when \c numinterfaces is 1. JUNGFRAU only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "selinterface"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - txndelay_left [delay] sets/gets the transmission delay of first packet in an image being streamed out from the detector's left UDP port. Use single-detector command. Used for EIGER only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "txndelay_left"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - txndelay_right [delay] sets/gets the transmission delay of first packet in an image being streamed out from the detector's right UDP port. Use single-detector command. Used for EIGER only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "txndelay_right"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - txndelay_frame [delay] sets/gets the transmission frame period of entire frame being streamed out from the detector for both ports. Use single-detector command. Used for EIGER and JUNGFRAU only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "txndelay_frame"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - flowcontrol_10g [delay] Enables/disables 10 GbE flow control. 1 enables, 0 disables. Used for EIGER only. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "flowcontrol_10g"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - zmqport [port] sets/gets the 0MQ (TCP) port of the client to where final data is streamed to (eg. for GUI). The default already connects with rx_zmqport for the GUI. Use single-detector command to set individually or multi-detector command to calculate based on \c port for the rest. Must restart zmq client streaming in gui/external gui \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "zmqport"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - rx_zmqport [port] sets/gets the 0MQ (TCP) port of the receiver from where data is streamed from (eg. to GUI or another process for further processing). Use single-detector command to set individually or multi-detector command to calculate based on \c port for the rest. put restarts streaming in receiver with new port. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "rx_zmqport"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + ++i; + + /*! \page network + - rx_datastream enables/disables data streaming from receiver. 1 enables 0MQ data stream from receiver (creates streamer threads), while 0 disables (destroys streamer threads). Switching to Gui enables data streaming in receiver and switching back to command line acquire will require disabling data streaming in receiver for fast applications \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "rx_datastream"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdDataStream; + ++i; + + /*! \page network + - zmqip [ip] sets/gets the 0MQ (TCP) ip of the client to where final data is streamed to (eg. for GUI). For Experts only! Default is ip of rx_hostname and works for GUI. This command to change from default can be used from command line when sockets are not already open as the command line is not aware/create the 0mq sockets in the client side. This is usually used to stream in from an external process. . If no custom ip, empty until first time connect to receiver. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "zmqip"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + i++; + + /*! \page network + - rx_zmqip [ip] sets/gets the 0MQ (TCP) ip of the receiver from where data is streamed from (eg. to GUI or another process for further processing). For Experts only! Default is ip of rx_hostname and works for GUI. This is usually used to stream out to an external process for further processing. . If no custom ip, empty until first time connect to receiver. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "rx_zmqip"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdNetworkParameter; + i++; + + /*! \page network + - configuremac [i] configures the MAC of the detector with these parameters: detectorip, detectormac, rx_udpip, rx_udpmac, rx_udpport, rx_udpport2 (if applicable). This command is already included in \c rx_hsotname. Only put!. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "configuremac"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdConfigureMac; + ++i; + + /*! \page network + - rx_tcpport [port] sets/gets the port of the client-receiver TCP interface. Use single-detector command. Is different for each detector if same \c rx_hostname used. Must be first command to communicate with receiver. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "rx_tcpport"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPort; + ++i; + + /*! \page network + - port [port] sets/gets the port of the client-detector control server TCP interface. Use single-detector command. Default value is 1952 for all detectors. Normally not changed. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "port"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPort; + ++i; + + /*! \page network + - stopport [port] sets/gets the port of the client-detector stop server TCP interface. Use single-detector command. Default value is 1953 for all detectors. Normally not changed. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "stopport"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPort; + ++i; + + /*! \page network + - lock [i] Locks/Unlocks the detector to communicate with this client. 1 locks, 0 unlocks. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "lock"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdLock; + ++i; + + /*! \page network + - lastclient Gets the last client communicating with the detector. Cannot put!. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "lastclient"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdLastClient; + ++i; + + /* receiver functions */ + + /*! \page receiver Receiver commands + Commands to configure the receiver. + */ + + /*! \page receiver + - receiver [s] starts/stops the receiver to listen to detector packets. Options: [ \c start, \c stop]. \c Returns \c (string) status of receiver[ \c idle, \c running]. + */ + descrToFuncMap[i].m_pFuncName = "receiver"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdReceiver; + ++i; + + /*! \page receiver + - r_online [i] sets/gets the receiver in online/offline mode. 1 is online, 0 is offline. Get is from shared memory. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "r_online"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdOnline; + ++i; + + /*! \page receiver + - r_checkonline Checks the receiver if it is online/offline mode. Only get! \c Returns (string) "All online" or "[list of offline hostnames] : Not online". + */ + descrToFuncMap[i].m_pFuncName = "r_checkonline"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdOnline; + ++i; + + /*! \page receiver + - framescaught gets the number of frames caught by receiver. Average of all for multi-detector command. Only get! \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "framescaught"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdReceiver; + ++i; + + /*! \page receiver + - resetframescaught [i] resets the number of frames caught to 0. i can be any number. Use this if using status start, instead of acquire (this command is included). Only put! \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "resetframescaught"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdReceiver; + ++i; + + /*! \page receiver + - frameindex [i] gets the current frame index of receiver. Average of all for multi-detector command. Only get! \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "frameindex"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdReceiver; + ++i; + + /*! \page receiver + - r_lock [i] locks/unlocks the receiver to communicate with only this client. 1 locks, 0 unlocks. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "r_lock"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdLock; + ++i; + + /*! \page receiver + - r_lastclient gets the last client communicating with the receiver. Only get! \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "r_lastclient"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdLastClient; + ++i; + + /*! \page receiver + - r_readfreq [i] sets/gets the stream frequency of data from receiver to client. i > 0 is the nth frame being streamed. 0 sets frequency to a default timer (200ms). \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "r_readfreq"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdReceiver; + ++i; + + /*! \page receiver + - rx_fifodepth [i] sets/gets receiver fifo (between Listener and Writer Threads) depth to i number of frames. Can improve listener packet loss (loss due to packet processing time in Listener threads), not if limited by writing. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "rx_fifodepth"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdReceiver; + ++i; + + /*! \page receiver + - r_silent [i] sets/gets receiver in silent mode, ie. it will not print anything during real time acquisition. 1 sets, 0 unsets. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "r_silent"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdReceiver; + ++i; + + /*! \page receiver + - r_framesperfile [i] sets/gets the frames per file in receiver to i. 0 means infinite or all frames in a single file. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "r_framesperfile"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdReceiver; + ++i; + + /*! \page receiver + - r_discardpolicy sets/gets the frame discard policy in the receiver. nodiscard (default) - discards nothing, discardempty - discard only empty frames, discardpartial(fastest) - discards all partial frames. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "r_discardpolicy"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdReceiver; + ++i; + + /*! \page receiver + - r_padding sets/gets the frame padding in the receiver. 0 does not pad partial frames(fastest), 1 (default) pads partial frames. \c Returns \c (int) + */ + descrToFuncMap[i].m_pFuncName = "r_padding"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdReceiver; + ++i; + + /*! \page receiver + - rx_jsonaddheader [t] sets/gets additional json header to be streamed out with the zmq from receiver. Default is empty. \c t must be in the format "\"label1\":\"value1\",\"label2\":\"value2\"" etc. Use only if it needs to be processed by an intermediate process. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "rx_jsonaddheader"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdReceiver; + i++; + + /*! \page receiver + - rx_jsonpara [k] [v] sets/gets value v for additional json header parameter k to be streamed out with the zmq from receiver. If empty, then no parameter found Use only if it needs to be processed by an intermediate process. \c Returns \c (string) + */ + descrToFuncMap[i].m_pFuncName = "rx_jsonpara"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdReceiver; + i++; + + + /* pattern generator */ + + /*! \page prototype Chip Test Board / Moench + Commands specific for the chiptest board or moench + */ + + /*! \page prototype + - emin [i] Sets/gets detector minimum energy threshold for Moench (soft setting in processor) + */ + descrToFuncMap[i].m_pFuncName = "emin"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdProcessor; + ++i; + + /*! \page prototype + - emax [i] Sets/gets detector maximum energy threshold for Moench (soft setting in processor) + */ + descrToFuncMap[i].m_pFuncName = "emax"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdProcessor; + ++i; + + /*! \page prototype + - framemode [i] Sets/gets frame mode for Moench (soft setting in processor). Options: pedestal, newpedestal, flatfield, newflatfield + */ + descrToFuncMap[i].m_pFuncName = "framemode"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdProcessor; + ++i; + + /*! \page prototype + - detectormode [i] Sets/gets detector mode for Moench (soft setting in processor). Options: counting, interpolating, analog + */ + descrToFuncMap[i].m_pFuncName = "detectormode"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdProcessor; + ++i; + + /*! \page prototype + - adcinvert [mask] Sets/gets ADC inversion mask (8 digits hex format) + */ + descrToFuncMap[i].m_pFuncName = "adcinvert"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - adcdisable [mask] Sets/gets ADC disable mask (8 digits hex format) + */ + descrToFuncMap[i].m_pFuncName = "adcdisable"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - pattern fn loads binary pattern file fn + */ + descrToFuncMap[i].m_pFuncName = "pattern"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patword addr [word] sets/gets 64 bit word at address addr of pattern memory. Both address and word in hex format. Advanced! + */ + descrToFuncMap[i].m_pFuncName = "patword"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patioctrl [word] sets/gets 64 bit mask defining input (0) and output (1) signals. hex format. + */ + descrToFuncMap[i].m_pFuncName = "patioctrl"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patclkctrl [word] sets/gets 64 bit mask defining if output signal is a clock and runs. hex format. Unused at the moment. + */ + descrToFuncMap[i].m_pFuncName = "patclkctrl"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patlimits [addr1 addr2] sets/gets the start and stop limits of the pattern to be executed. hex format. Advanced! + */ + descrToFuncMap[i].m_pFuncName = "patlimits"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patloop0 [addr1 addr2] sets/gets the start and stop limits of the level 0 loop. hex format. Advanced! + */ + descrToFuncMap[i].m_pFuncName = "patloop0"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patnloop0 [n] sets/gets the number of cyclesof the level 0 loop (int). + */ + descrToFuncMap[i].m_pFuncName = "patnloop0"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patwait0 [addr] sets/gets the address of the level 0 wait point. hex format. Advanced! + */ + descrToFuncMap[i].m_pFuncName = "patwait0"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patwaittime0 [n] sets/gets the duration of the witing of the 0 waiting point in clock cycles (int). + */ + descrToFuncMap[i].m_pFuncName = "patwaittime0"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patloop1 [addr1 addr2] sets/gets the start and stop limits of the level 1 loop. hex format. Advanced! + */ + descrToFuncMap[i].m_pFuncName = "patloop1"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patnloop1 [n] sets/gets the number of cyclesof the level 1 loop (int). + */ + descrToFuncMap[i].m_pFuncName = "patnloop1"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patwait1 [addr] sets/gets the address of the level 1 wait point. hex format. Advanced! + */ + descrToFuncMap[i].m_pFuncName = "patwait1"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patwaittime1 [n] sets/gets the duration of the witing of the 1 waiting point in clock cycles (int). + */ + descrToFuncMap[i].m_pFuncName = "patwaittime1"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patloop2 [addr1 addr2] sets/gets the start and stop limits of the level 2 loop. hex format. Advanced! + */ + descrToFuncMap[i].m_pFuncName = "patloop2"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patnloop2 [n] sets/gets the number of cyclesof the level 2 loop (int). + */ + descrToFuncMap[i].m_pFuncName = "patnloop2"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patwait2 [addr] sets/gets the address of the level 2 wait point. hex format. Advanced! + */ + descrToFuncMap[i].m_pFuncName = "patwait2"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patwaittime2 [n] sets/gets the duration of the waiting of the 2 waiting point in clock cycles (int). + */ + descrToFuncMap[i].m_pFuncName = "patwaittime2"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patmask [m] sets/gets the 64 bit mask (hex) applied to every pattern. Only the bits from \c patsetbit are selected to mask for the corresponding bit value from \c m mask. Returns \c (uint64_t). + */ + descrToFuncMap[i].m_pFuncName = "patmask"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - patsetbit [m] selects/gets the 64 bits (hex) that the patmask will be applied to every pattern. Only the bits from \c m mask are selected to mask for the corresponding bit value from \c patmask. Returns \c (uint64_t). + */ + descrToFuncMap[i].m_pFuncName = "patsetbit"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + /*! \page prototype + - dut_clk [i] sets/gets the signal to be used as a clock for the digital data coming from the device under test. Advanced! + */ + descrToFuncMap[i].m_pFuncName = "dut_clk"; + descrToFuncMap[i].m_pFuncPtr = &slsDetectorCommand::cmdPattern; + ++i; + + numberOfCommands = i; + + // #ifdef VERBOSE + // std::cout << "Number of commands is " << numberOfCommands << std::endl; + // #endif +} + +//----------------------------------------------------------- + +/*! + */ + +//----------------------------------------------------------- + +std::string slsDetectorCommand::executeLine(int narg, char *args[], int action, int detPos) { + + if (action == READOUT_ACTION) + return cmdAcquire(narg, args, action, detPos); + + size_t s = std::string(args[0]).find(':'); + std::string key = std::string(args[0]).substr(0, s); // truncate at : + + if (action == PUT_ACTION && narg < 1) + action = HELP_ACTION; + + for (int i = 0; i < numberOfCommands; ++i) { + + /* this works only if the command completely matches the key */ + /* otherwise one could try if truncated key is unique */ + + if (key == descrToFuncMap[i].m_pFuncName) { +#ifdef VERBOSE + std::cout << i << " command=" << descrToFuncMap[i].m_pFuncName << " key=" << key << std::endl; +#endif + cmd = descrToFuncMap[i].m_pFuncName; + + MemFuncGetter memFunc = descrToFuncMap[i].m_pFuncPtr; + std::string dResult = (this->*memFunc)(narg, args, action, detPos); + + return dResult; + } + } + return cmdUnknown(narg, args, action, detPos); +} + +/*! \page advanced Advanced Usage +This page is for advanced users. +Make sure you have first read \ref intro "the introduction". + */ + +std::string slsDetectorCommand::cmdUnknown(int narg, char *args[], int action, int detPos) { + return std::string("Unknown command ") + std::string(args[0]) + std::string("\n") + helpLine(0, args, action, detPos); +} +std::string slsDetectorCommand::cmdUnderDevelopment(int narg, char *args[], int action, int detPos) { + return std::string("Must still develop ") + std::string(args[0]) + std::string(" ( ") + cmd + std::string(" )\n"); +} + +std::string slsDetectorCommand::helpLine(int narg, char *args[], int action, int detPos) { + + std::ostringstream os; + + if (action == READOUT_ACTION) { + return helpAcquire(HELP_ACTION); + } + + if (narg == 0) { + os << "Command can be: " << std::endl; + for (int i = 0; i < numberOfCommands; ++i) { + os << descrToFuncMap[i].m_pFuncName << "\n"; + } + os << std::endl; + return os.str(); + } + return executeLine(narg, args, HELP_ACTION, detPos); +} + +std::string slsDetectorCommand::cmdAcquire(int narg, char *args[], int action, int detPos) { +#ifdef VERBOSE + std::cout << std::string("Executing command ") + std::string(args[0]) + std::string(" ( ") + cmd + std::string(" )\n"); +#endif + + if (action == HELP_ACTION) { + return helpAcquire(HELP_ACTION); + } + if (!myDet->getNumberOfDetectors()) { + cprintf(RED, "Error: This shared memory has no detectors added. Aborting.\n"); + return std::string("acquire failed"); + } + if (detPos >= 0) { + cprintf(RED, "Error: Individual detectors not allowed for readout. Aborting.\n"); + return std::string("acquire failed"); + } + + myDet->setOnline(ONLINE_FLAG, detPos); + int r_online = myDet->setReceiverOnline(ONLINE_FLAG, detPos); + + + + if (myDet->acquire() == FAIL) + return std::string("acquire failed"); + if (r_online) { + char answer[100]; + sprintf(answer, "\nAcquired %d", myDet->getFramesCaughtByReceiver(detPos)); + return std::string(answer); + } + + return std::string(); +} + +std::string slsDetectorCommand::helpAcquire(int action) { + + if (action == PUT_ACTION) + return std::string(""); + std::ostringstream os; + os << "Usage is " << std::endl + << "sls_detector_acquire id " << std::endl; + os << "where id is the id of the detector " << std::endl; + os << "the detector will be started, the data acquired, processed and written to file according to the preferences configured " << std::endl; + return os.str(); +} + +std::string slsDetectorCommand::cmdData(int narg, char *args[], int action, int detPos) { + +#ifdef VERBOSE + std::cout << std::string("Executing command ") + std::string(args[0]) + std::string(" ( ") + cmd + std::string(" )\n"); +#endif + //int b; + if (action == PUT_ACTION) { + return std::string("cannot set"); + } else if (action == HELP_ACTION) { + return helpData(HELP_ACTION); + } else { + // b=myDet->setThreadedProcessing(-1); + // myDet->setThreadedProcessing(0); + // myDet->setOnline(ONLINE_FLAG, detPos); + // myDet->setReceiverOnline(ONLINE_FLAG, detPos); + // myDet->readAll(detPos); + // //processdata in receiver is useful only for gui purposes + // if(myDet->setReceiverOnline(detPos)==OFFLINE_FLAG) + // myDet->processData(); + // myDet->setThreadedProcessing(b); + return std::string(""); + } +} + +std::string slsDetectorCommand::helpData(int action) { + + if (action == PUT_ACTION) + return std::string(""); + else + return std::string("data \t gets all data from the detector (if any) processes them and writes them to file according to the preferences already setup\n"); +} + +std::string slsDetectorCommand::cmdStatus(int narg, char *args[], int action, int detPos) { + +#ifdef VERBOSE + std::cout << std::string("Executing command ") + std::string(args[0]) + std::string(" ( ") + cmd + std::string(" )\n"); +#endif + + if (action == HELP_ACTION) + return helpStatus(action); + + if (cmd == "status") { + myDet->setOnline(ONLINE_FLAG, detPos); + if (action == PUT_ACTION) { + //myDet->setThreadedProcessing(0); + if (std::string(args[1]) == "start") + myDet->startAcquisition(detPos); + else if (std::string(args[1]) == "stop") { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); //restream stop + myDet->stopAcquisition(detPos); + } else if (std::string(args[1]) == "trigger") { + myDet->sendSoftwareTrigger(detPos); + } else + return std::string("unknown action"); + } + runStatus s = myDet->getRunStatus(detPos); + return myDet->runStatusType(s); + } else if (cmd == "busy") { + if (action == PUT_ACTION) { + int i; + if (!sscanf(args[1], "%d", &i)) + return std::string("cannot parse busy mode"); + myDet->setAcquiringFlag(i); + } + char answer[100]; + sprintf(answer, "%d", myDet->getAcquiringFlag()); + return std::string(answer); + } else + return std::string("cannot scan command ") + std::string(cmd); +} + +std::string slsDetectorCommand::helpStatus(int action) { + + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) { + os << std::string("status \t gets the detector status - can be: running, error, transmitting, finished, waiting or idle\n"); + os << std::string("busy \t gets the status of acquire- can be: 0 or 1. 0 for idle, 1 for running\n"); + } + if (action == PUT_ACTION || action == HELP_ACTION) { + os << std::string("status \t controls the detector acquisition - can be start or stop or trigger(EIGER only). When using stop acquisition and if acquisition is done, it will restream the stop packet from receiver (if data streaming in receiver is on). Eiger can also provide an internal software trigger\n"); + os << std::string("busy i\t sets the status of acquire- can be: 0(idle) or 1(running).Command Acquire sets it to 1 at beignning of acquire and back to 0 at the end. Clear Flag for unexpected acquire terminations. \n"); + } + return os.str(); +} + +std::string slsDetectorCommand::cmdDataStream(int narg, char *args[], int action, int detPos) { + +#ifdef VERBOSE + std::cout << std::string("Executing command ") + std::string(args[0]) + std::string(" ( ") + cmd + std::string(" )\n"); +#endif + int ival = -1; + char ans[100] = ""; + + myDet->setOnline(ONLINE_FLAG, detPos); + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + + if (action == HELP_ACTION) + return helpDataStream(HELP_ACTION); + + if (action == PUT_ACTION) { + if (!sscanf(args[1], "%d", &ival)) + return std::string("cannot scan rx_datastream mode"); + myDet->enableDataStreamingFromReceiver(ival, detPos); + } + + sprintf(ans, "%d", myDet->enableDataStreamingFromReceiver(-1, detPos)); + return std::string(ans); +} + +std::string slsDetectorCommand::helpDataStream(int action) { + + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) + os << std::string("rx_datastream \t enables/disables data streaming from receiver. 1 is 0MQ data stream from receiver enabled, while 0 is 0MQ disabled. -1 for inconsistency between multiple receivers. \n"); + if (action == PUT_ACTION || action == HELP_ACTION) + os << std::string("rx_datastream i\t enables/disables data streaming from receiver. i is 1 enables 0MQ data stream from receiver (creates streamer threads), while 0 disables (destroys streamer threads). \n"); + return os.str(); +} + +std::string slsDetectorCommand::cmdFree(int narg, char *args[], int action, int detPos) { + +#ifdef VERBOSE + std::cout << std::string("Executing command ") + std::string(args[0]) + std::string(" ( ") + cmd + std::string(" )\n"); +#endif + if (action == HELP_ACTION) { + return helpFree(HELP_ACTION); + } + + return ("Error: Should have been freed before creating constructor\n"); +} + +std::string slsDetectorCommand::helpFree(int action) { + return std::string("free \t frees the shared memory\n"); +} + +std::string slsDetectorCommand::cmdHostname(int narg, char *args[], int action, int detPos) { +#ifdef VERBOSE + std::cout << std::string("Executing command ") + std::string(args[0]) + std::string(" ( ") + cmd + std::string(" )\n"); +#endif + + if (action == HELP_ACTION) { + return helpHostname(HELP_ACTION); + } + if (action == GET_ACTION) { + if ((cmd == "add") || (cmd == "replace")) + return std::string("cannot get"); + } + + if (action == PUT_ACTION) { + if (((cmd == "add") || (cmd == "hostname")) && + (detPos >= 0)) { + return std::string("Wrong usage - setting hostname/add only from " + "multiDetector level"); + } + if ((cmd == "replace") && (detPos < 0)) { + return std::string("Wrong usage - replace only from " + "single detector level"); + } + + char hostname[1000]; + strcpy(hostname, ""); + // if each argument is a hostname + for (int id = 1; id < narg; ++id) { + strcat(hostname, args[id]); + if (narg > 2) + strcat(hostname, "+"); + } + + if (cmd == "add") + myDet->addMultipleDetectors(hostname); + else + myDet->setHostname(hostname, detPos); + } + + return myDet->getHostname(detPos); +} + +std::string slsDetectorCommand::helpHostname(int action) { + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) { + os << std::string("hostname \t returns the hostname(s) of the multi detector structure.\n"); + os << std::string("add \t cannot get\n"); + os << std::string("replace \t cannot get\n"); + } + if (action == PUT_ACTION || action == HELP_ACTION) { + os << std::string("hostname name [name name]\t frees shared memory and " + "sets the hostname (or IP adress). Only allowed at multi detector level.\n"); + os << std::string("add det [det det]\t appends a hostname (or IP address) at " + "the end of the multi-detector structure. Only allowed at multi detector level." + "Returns hostnames in the multi detector structure\n"); + os << std::string("replace det \t Sets the hostname (or IP adress) for a " + "single detector. Only allowed at single detector level. " + "Returns the hostnames for that detector\n"); + } + return os.str(); +} + +std::string slsDetectorCommand::cmdUser(int narg, char *args[], int action, int detPos) { +#ifdef VERBOSE + std::cout << std::string("Executing command ") + std::string(args[0]) + std::string(" ( ") + cmd + std::string(" )\n"); +#endif + + if (action == HELP_ACTION) { + return helpHostname(HELP_ACTION); + } + if (action == PUT_ACTION) { + return std::string("cannot put"); + } + if (detPos >= 0) { + return std::string("Wrong usage - getting user details only from " + "multiDetector level"); + } + return myDet->getUserDetails(); +} + +std::string slsDetectorCommand::helpUser(int action) { + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) { + os << std::string("user \t returns user details from shared memory without updating shared memory. " + "Only allowed at multi detector level.\n"); + } + if (action == PUT_ACTION || action == HELP_ACTION) { + os << std::string("user \t cannot put\n"); + } + return os.str(); +} + +std::string slsDetectorCommand::cmdHelp(int narg, char *args[], int action, int detPos) { +#ifdef VERBOSE + std::cout << std::string("Executing command ") + std::string(args[0]) + std::string(" ( ") + cmd + std::string(" )\n"); +#endif + + std::cout << narg << std::endl; + + if (narg >= 1) + return helpLine(narg - 1, args, action, detPos); + else + return helpLine(0, args, action, detPos); +} + +std::string slsDetectorCommand::cmdExitServer(int narg, char *args[], int action, int detPos) { +#ifdef VERBOSE + std::cout << std::string("Executing command ") + std::string(args[0]) + std::string(" ( ") + cmd + std::string(" )\n"); +#endif + if (action == HELP_ACTION) { + return helpExitServer(action); + } + + if (action == PUT_ACTION) { + if (cmd == "exitserver") { + myDet->setOnline(ONLINE_FLAG, detPos); + if (myDet->exitServer(detPos) == OK) + return std::string("Server shut down."); + else + return std::string("Error closing server\n"); + } else if (cmd == "exitreceiver") { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + if (myDet->exitReceiver(detPos) == OK) + return std::string("Receiver shut down\n"); + else + return std::string("Error closing receiver\n"); + } else if (cmd == "execcommand") { + myDet->setOnline(ONLINE_FLAG, detPos); + if (myDet->execCommand(std::string(args[1]), detPos) == OK) + return std::string("Command executed successfully\n"); + else + return std::string("Command failed\n"); + } else if (cmd == "rx_execcommand") { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + if (myDet->execReceiverCommand(std::string(args[1]), detPos) == OK) + return std::string("Command executed successfully\n"); + else + return std::string("Command failed\n"); + } else + return ("cannot decode command\n"); + } else + return ("cannot get"); +} + +std::string slsDetectorCommand::helpExitServer(int action) { + std::ostringstream os; + os << std::string("exitserver \t shuts down all the detector servers. Don't use it!!!!\n"); + os << std::string("exitreceiver \t shuts down all the receiver servers.\n"); + os << std::string("execcommand \t executes command in detector server. Don't use it if you do not know what you are doing.\n"); + os << std::string("rx_execcommand \t executes command in receiver server. Don't use it if you do not know what you are doing.\n"); + return os.str(); +} + +std::string slsDetectorCommand::cmdSettingsDir(int narg, char *args[], int action, int detPos) { +#ifdef VERBOSE + std::cout << std::string("Executing command ") + std::string(args[0]) + std::string(" ( ") + cmd + std::string(" )\n"); +#endif + if (action == HELP_ACTION) { + return helpSettingsDir(action); + } + if (action == PUT_ACTION) { + myDet->setSettingsDir(std::string(args[1]), detPos); + } + if (myDet->getSettingsDir(detPos) == "") + return std::string("undefined"); + return myDet->getSettingsDir(detPos); +} + +std::string slsDetectorCommand::helpSettingsDir(int action) { + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) + os << std::string("settingsdir \t gets the directory where the settings files are located\n"); + if (action == PUT_ACTION || action == HELP_ACTION) + os << std::string("settingsdir dir \t sets the directory where the settings files are located\n"); + if (action == GET_ACTION || action == HELP_ACTION) + os << std::string("trimdir \t obsolete for settingsdir\n"); + if (action == PUT_ACTION || action == HELP_ACTION) + os << std::string("trimdir dir \t obsolete for settingsdir\n"); + return os.str(); +} + +std::string slsDetectorCommand::cmdTrimEn(int narg, char *args[], int action, int detPos) { + std::vector energies; + if (action == HELP_ACTION) + return helpTrimEn(action); + + if (action == PUT_ACTION) { + energies.reserve(narg-1); + for(int i=1; i!=narg; ++i){ + energies.push_back(std::stoi(args[i])); + } + myDet->setTrimEn(energies, detPos); + energies.clear(); + } + energies = myDet->getTrimEn(detPos); + std::ostringstream os; + for(const auto& en : energies){ + os << en << ' '; + } + return os.str(); +} + +std::string slsDetectorCommand::helpTrimEn(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) + os << "trimen ne [e0 e1...ene] \t sets the number of energies at which the detector has default trim files" << std::endl; + if (action == GET_ACTION || action == HELP_ACTION) + os << "trimen \t returns the number of energies at which the detector has default trim files and their values" << std::endl; + return os.str(); +} + +std::string slsDetectorCommand::cmdOutDir(int narg, char *args[], int action, int detPos) { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + if (action == HELP_ACTION) + return helpOutDir(action); + + else if (action == PUT_ACTION) + myDet->setFilePath(std::string(args[1]), detPos); + + return std::string(myDet->getFilePath(detPos)); +} + +std::string slsDetectorCommand::helpOutDir(int action) { + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) + os << std::string("outdir \t gets the directory where the output files will be written\n"); + if (action == PUT_ACTION || action == HELP_ACTION) + os << std::string("outdir dir \t sets the directory where the output files will be written\n"); + return os.str(); +} + +std::string slsDetectorCommand::cmdFileName(int narg, char *args[], int action, int detPos) { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + if (action == HELP_ACTION) + return helpFileName(action); + if (cmd == "fname") { + if (action == PUT_ACTION) + myDet->setFileName(std::string(args[1]), detPos); + + return std::string(myDet->getFileName(detPos)); + } else if (cmd == "fileformat") { + if (action == PUT_ACTION) { + if (std::string(args[1]) == "binary") + myDet->setFileFormat(BINARY, detPos); + else if (std::string(args[1]) == "hdf5") + myDet->setFileFormat(HDF5, detPos); + else + return std::string("could not scan file format mode\n"); + } + return myDet->fileFormats(myDet->getFileFormat(detPos)); + } + return std::string("unknown command") + cmd; +} + +std::string slsDetectorCommand::helpFileName(int action) { + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) { + os << std::string("fname \t gets the filename for the data without index and extension\n"); + os << std::string("fileformat \t gets the file format for data\n"); + } + if (action == PUT_ACTION || action == HELP_ACTION) { + os << std::string("fname s \t sets the filename for the data (index and extension will be automatically appended)\n"); + os << std::string("fileformat s \t sets the file format for the data (binary, hdf5)\n"); + } + return os.str(); +} + +std::string slsDetectorCommand::cmdEnablefwrite(int narg, char *args[], int action, int detPos) { + + int i; + char ans[100]; + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + if (action == HELP_ACTION) { + return helpEnablefwrite(action); + } + if (action == PUT_ACTION) { + if (sscanf(args[1], "%d", &i)) + myDet->setFileWrite(i, detPos); + else + return std::string("could not decode enable file write"); + } + sprintf(ans, "%d", myDet->getFileWrite(detPos)); + return std::string(ans); +} + +std::string slsDetectorCommand::helpEnablefwrite(int action) { + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) + os << std::string("enablefwrite \t When Enabled writes the data into the file\n"); + if (action == PUT_ACTION || action == HELP_ACTION) + os << std::string("enablefwrite i \t should be 1 or 0 or -1\n"); + return os.str(); +} + +std::string slsDetectorCommand::cmdOverwrite(int narg, char *args[], int action, int detPos) { + int i; + char ans[100]; + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + if (action == HELP_ACTION) { + return helpOverwrite(action); + } + if (action == PUT_ACTION) { + if (sscanf(args[1], "%d", &i)) + myDet->setFileOverWrite(i, detPos); + else + return std::string("could not decode overwrite"); + } + sprintf(ans, "%d", myDet->getFileOverWrite(detPos)); + return std::string(ans); +} + +std::string slsDetectorCommand::helpOverwrite(int action) { + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) + os << std::string("overwrite \t When Enabled overwrites files\n"); + if (action == PUT_ACTION || action == HELP_ACTION) + os << std::string("overwrite i \t should be 1 or 0 or -1\n"); + return os.str(); +} + +std::string slsDetectorCommand::cmdFileIndex(int narg, char *args[], int action, int detPos) { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + if (action == HELP_ACTION) { + return helpFileName(action); + } else if (action == PUT_ACTION) { + int i = std::stoi(args[1]); + myDet->setFileIndex(i, detPos); + } + return std::to_string(myDet->getFileIndex(detPos)); +} + +std::string slsDetectorCommand::helpFileIndex(int action) { + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) + os << std::string("index \t gets the file index for the next the data file\n"); + if (action == PUT_ACTION || action == HELP_ACTION) + os << std::string("index i \t sets the fileindex for the next data file\n"); + return os.str(); +} + +std::string slsDetectorCommand::cmdRateCorr(int narg, char *args[], int action, int detPos) { + + if (action == HELP_ACTION) { + return helpRateCorr(action); + } + int64_t ival; + char answer[1000]; + + myDet->setOnline(ONLINE_FLAG, detPos); + + if (action == PUT_ACTION) { + sscanf(args[1], "%ld", &ival); + myDet->setRateCorrection(ival, detPos); + } + sprintf(answer, "%ld", myDet->getRateCorrection(detPos)); + return std::string(answer); +} + +std::string slsDetectorCommand::helpRateCorr(int action) { + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) + os << std::string("ratecorr \t returns the dead time used for rate correections in ns \n"); + if (action == PUT_ACTION || action == HELP_ACTION) + os << std::string("ratecorr ns \t sets the deadtime correction constant in ns, -1 in Eiger will set it to default tau of settings\n"); + return os.str(); +} + +// std::string slsDetectorCommand::cmdThreaded(int narg, char *args[], int action, int detPos){ +// int ival; +// char answer[1000]; + +// if (action==HELP_ACTION) +// return helpThreaded(action); + +// if (action==PUT_ACTION) { +// if (sscanf(args[1],"%d",&ival)) +// myDet->setThreadedProcessing(ival); +// } +// sprintf(answer,"%d",myDet->setThreadedProcessing()); +// return std::string(answer); + +// } + +std::string slsDetectorCommand::helpThreaded(int action) { + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) + os << std::string("threaded \t returns wether the data processing is threaded. \n"); + if (action == PUT_ACTION || action == HELP_ACTION) + os << std::string("threaded t \t sets the threading flag ( 1sets, 0 unsets).\n"); + + return os.str(); +} + +std::string slsDetectorCommand::cmdImage(int narg, char *args[], int action, int detPos) { + std::string sval; + int retval = FAIL; + if (action == HELP_ACTION) + return helpImage(HELP_ACTION); + else if (action == GET_ACTION) + return std::string("Cannot get"); + + sval = std::string(args[1]); + myDet->setOnline(ONLINE_FLAG, detPos); + + if (std::string(args[0]) == std::string("darkimage")) + retval = myDet->loadImageToDetector(DARK_IMAGE, sval, detPos); + else if (std::string(args[0]) == std::string("gainimage")) + retval = myDet->loadImageToDetector(GAIN_IMAGE, sval, detPos); + + if (retval == OK) + return std::string("Image loaded succesfully"); + else + return std::string("Image load failed"); +} + +std::string slsDetectorCommand::helpImage(int action) { + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "darkimage f \t loads the image to detector from file f" << std::endl; + os << "gainimage f \t loads the image to detector from file f" << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "darkimage \t Cannot get" << std::endl; + os << "gainimage \t Cannot get" << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdCounter(int narg, char *args[], int action, int detPos) { + int ival; + char answer[100]; + std::string sval; + int retval = FAIL; + if (action == HELP_ACTION) + return helpCounter(HELP_ACTION); + else if (action == PUT_ACTION) + ival = atoi(args[1]); + + myDet->setOnline(ONLINE_FLAG, detPos); + + if (std::string(args[0]) == std::string("readctr")) { + if (action == PUT_ACTION) + return std::string("Cannot put"); + else { + if (narg < 3) + return std::string("should specify I/O file"); + sval = std::string(args[2]); + retval = myDet->writeCounterBlockFile(sval, ival, detPos); + } + } else if (std::string(args[0]) == std::string("resetctr")) { + if (action == GET_ACTION) + return std::string("Cannot get"); + else + retval = myDet->resetCounterBlock(ival, detPos); + } + + else if (std::string(args[0]) == std::string("resmat")) { + if (action == PUT_ACTION) { + if (!sscanf(args[1], "%d", &ival)) + return std::string("Could not scan resmat input ") + std::string(args[1]); + if (ival >= 0) + sprintf(answer, "%d", myDet->setCounterBit(ival, detPos)); + } else + sprintf(answer, "%d", myDet->setCounterBit(-1, detPos)); + return std::string(answer); + } + + if (retval == OK) + return std::string("Counter read/reset succesfully"); + else + return std::string("Counter read/reset failed"); +} + +std::string slsDetectorCommand::helpCounter(int action) { + std::ostringstream os; + os << std::endl; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "readctr \t Cannot put" << std::endl; + os << "resetctr i \t resets counter in detector, restarts acquisition if i=1" << std::endl; + os << "resmat i \t sets/resets counter bit in detector" << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "readctr i fname\t reads counter in detector to file fname, restarts acquisition if i=1" << std::endl; + os << "resetctr \t Cannot get" << std::endl; + os << "resmat i \t gets the counter bit in detector" << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdNetworkParameter(int narg, char *args[], int action, int detPos) { + + char ans[100] = {0}; + int i; + if (action == HELP_ACTION) + return helpNetworkParameter(action); + + myDet->setOnline(ONLINE_FLAG, detPos); + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + + if (cmd == "detectormac") { + if (action == PUT_ACTION) { + myDet->setDetectorMAC(args[1], detPos); + } + return myDet->getDetectorMAC(detPos); + } else if (cmd == "detectormac2") { + if (action == PUT_ACTION) { + myDet->setDetectorMAC2(args[1], detPos); + } + return myDet->getDetectorMAC2(detPos); + } else if (cmd == "detectorip") { + if (action == PUT_ACTION) { + myDet->setDetectorIP(args[1], detPos); + } + return myDet->getDetectorIP(detPos); + } else if (cmd == "detectorip2") { + if (action == PUT_ACTION) { + myDet->setDetectorIP2(args[1], detPos); + } + return myDet->getDetectorIP2(detPos); + } else if (cmd == "rx_hostname") { + if (action == PUT_ACTION) { + myDet->setReceiverHostname(args[1], detPos); + } + return myDet->getReceiverHostname(detPos); + } else if (cmd == "rx_udpip") { + if (action == PUT_ACTION) { + myDet->setReceiverUDPIP(args[1], detPos); + } + return myDet->getReceiverUDPIP(detPos); + } else if (cmd == "rx_udpip2") { + if (action == PUT_ACTION) { + myDet->setReceiverUDPIP2(args[1], detPos); + } + return myDet->getReceiverUDPIP(detPos); + } else if (cmd == "rx_udpmac") { + if (action == PUT_ACTION) { + myDet->setReceiverUDPMAC(args[1], detPos); + } + return myDet->getReceiverUDPMAC(detPos); + } else if (cmd == "rx_udpmac2") { + if (action == PUT_ACTION) { + myDet->setReceiverUDPMAC2(args[1], detPos); + } + return myDet->getReceiverUDPMAC(detPos); + } else if (cmd == "rx_udpport") { + if (action == PUT_ACTION) { + if (!(sscanf(args[1], "%d", &i))) { + return ("cannot parse argument") + std::string(args[1]); + } + myDet->setReceiverUDPPort(i, detPos); + } + sprintf(ans, "%d", myDet->getReceiverUDPPort(detPos)); + return ans; + } else if (cmd == "rx_udpport2") { + if (action == PUT_ACTION) { + if (!(sscanf(args[1], "%d", &i))) { + return ("cannot parse argument") + std::string(args[1]); + } + myDet->setReceiverUDPPort2(i, detPos); + } + sprintf(ans, "%d", myDet->getReceiverUDPPort2(detPos)); + return ans; + } else if (cmd == "numinterfaces") { + if (action == PUT_ACTION) { + if (!(sscanf(args[1], "%d", &i))) { + return ("cannot parse argument") + std::string(args[1]); + } + myDet->setNumberofUDPInterfaces(i, detPos); + } + sprintf(ans, "%d", myDet->getNumberofUDPInterfaces(detPos)); + return ans; + } else if (cmd == "selinterface") { + if (action == PUT_ACTION) { + if (!(sscanf(args[1], "%d", &i))) { + return ("cannot parse argument") + std::string(args[1]); + } + myDet->selectUDPInterface(i, detPos); + } + sprintf(ans, "%d", myDet->getSelectedUDPInterface(detPos)); + return ans; + } else if (cmd == "rx_udpsocksize") { + if (action == PUT_ACTION) { + int64_t ival = -1; + if (!(sscanf(args[1], "%ld", &ival))) { + return ("cannot parse argument") + std::string(args[1]); + } + myDet->setReceiverUDPSocketBufferSize(ival, detPos); + } + sprintf(ans, "%ld", myDet->getReceiverUDPSocketBufferSize(detPos)); + return ans; + } else if (cmd == "rx_realudpsocksize") { + if (action == PUT_ACTION) { + return ("cannot put!"); + } + sprintf(ans, "%ld", myDet->getReceiverRealUDPSocketBufferSize(detPos)); + return ans; + } else if (cmd == "txndelay_left") { + networkParameter t = DETECTOR_TXN_DELAY_LEFT; + if (action == PUT_ACTION) { + if (!(sscanf(args[1], "%d", &i))) { + return ("cannot parse argument") + std::string(args[1]); + } + myDet->setDetectorNetworkParameter(t, i, detPos); + } + sprintf(ans, "%d", myDet->setDetectorNetworkParameter(t, -1, detPos)); + return ans; + } else if (cmd == "txndelay_right") { + networkParameter t = DETECTOR_TXN_DELAY_RIGHT; + if (action == PUT_ACTION) { + if (!(sscanf(args[1], "%d", &i))) { + return ("cannot parse argument") + std::string(args[1]); + } + myDet->setDetectorNetworkParameter(t, i, detPos); + } + sprintf(ans, "%d", myDet->setDetectorNetworkParameter(t, -1, detPos)); + return ans; + } else if (cmd == "txndelay_frame") { + networkParameter t = DETECTOR_TXN_DELAY_FRAME; + if (action == PUT_ACTION) { + if (!(sscanf(args[1], "%d", &i))) { + return ("cannot parse argument") + std::string(args[1]); + } + myDet->setDetectorNetworkParameter(t, i, detPos); + } + sprintf(ans, "%d", myDet->setDetectorNetworkParameter(t, -1, detPos)); + return ans; + } else if (cmd == "flowcontrol_10g") { + networkParameter t = FLOW_CONTROL_10G; + if (action == PUT_ACTION) { + if (!(sscanf(args[1], "%d", &i))) { + return ("cannot parse argument") + std::string(args[1]); + } + myDet->setDetectorNetworkParameter(t, i, detPos); + } + sprintf(ans, "%d", myDet->setDetectorNetworkParameter(t, -1, detPos)); + return ans; + } else if (cmd == "zmqport") { + if (action == PUT_ACTION) { + if (!(sscanf(args[1], "%d", &i))) { + return ("cannot parse argument") + std::string(args[1]); + } + myDet->setClientDataStreamingInPort(i, detPos); + } + sprintf(ans, "%d", myDet->getClientStreamingPort(detPos)); + return ans; + } else if (cmd == "rx_zmqport") { + if (action == PUT_ACTION) { + if (!(sscanf(args[1], "%d", &i))) { + return ("cannot parse argument") + std::string(args[1]); + } + myDet->setReceiverDataStreamingOutPort(i, detPos); + } + sprintf(ans, "%d", myDet->getReceiverStreamingPort(detPos)); + return ans; + } else if (cmd == "zmqip") { + if (action == PUT_ACTION) { + myDet->setClientDataStreamingInIP(args[1], detPos); + } + return myDet->getClientStreamingIP(detPos); + } else if (cmd == "rx_zmqip") { + if (action == PUT_ACTION) { + myDet->setReceiverDataStreamingOutIP(args[1], detPos); + } + return myDet->getReceiverStreamingIP(detPos); + } + + return ("unknown network parameter") + cmd; +} + +std::string slsDetectorCommand::helpNetworkParameter(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "detectormac mac \n sets detector mac to mac" << std::endl; + os << "detectormac2 mac \n sets detector mac of 2nd udp interface to mac. Jungfrau only" << std::endl; + os << "detectorip ip \n sets detector ip to ip" << std::endl; + os << "detectorip2 ip \n sets detector ip of 2nd udp interface to ip. Jungfrau only" << std::endl; + os << "rx_hostname name \n sets receiver ip/hostname to name" << std::endl; + os << "rx_udpip ip \n sets receiver udp ip to ip" << std::endl; + os << "rx_udpip2 ip \n sets receiver udp ip of 2nd udp interface to ip. Jungfrau only" << std::endl; + os << "rx_udpmac mac \n sets receiver udp mac to mac" << std::endl; + os << "rx_udpmac2 mac \n sets receiver udp mac of 2nd udp interface to mac. Jungfrau only." << std::endl; + os << "rx_udpport port \n sets receiver udp port to port" << std::endl; + os << "rx_udpport2 port \n sets receiver udp port to port. For Eiger and Jungfrau, it is the second half module and for other detectors, same as rx_udpport" << std::endl; + os << "numinterfaces n \n sets the number of interfaces to n used to stream out from the detector. Options: 1, 2. JUNGFRAU only. " << std::endl; + os << "selinterface n \n sets the 1st or the 2nd interface to use to stream data out of the detector. Options: 1, 2. Effective only when numinterfaces is 1. JUNGFRAU only. " << std::endl; + os << "txndelay_left port \n sets detector transmission delay of the left port" << std::endl; + os << "txndelay_right port \n sets detector transmission delay of the right port" << std::endl; + os << "txndelay_frame port \n sets detector transmission delay of the entire frame" << std::endl; + os << "flowcontrol_10g port \n sets flow control for 10g for eiger" << std::endl; + os << "zmqport port \n sets the 0MQ (TCP) port of the client to where final data is streamed to (eg. for GUI). The default already connects with rx_zmqport for the GUI. " + "Use single-detector command to set individually or multi-detector command to calculate based on port for the rest." + "Must restart streaming in client with new port from gui/external gui" + << std::endl; + os << "rx_zmqport port \n sets the 0MQ (TCP) port of the receiver from where data is streamed from (eg. to GUI or another process for further processing). " + "Use single-detector command to set individually or multi-detector command to calculate based on port for the rest." + "Restarts streaming in receiver with new port" + << std::endl; + os << "zmqip ip \n sets the 0MQ (TCP) ip of the client to where final data is streamed to (eg. for GUI). Default is ip of rx_hostname and works for GUI. " + "This is usually used to stream in from an external process." + "Must restart streaming in client with new port from gui/external gui. " + << std::endl; + os << "rx_zmqip ip \n sets/gets the 0MQ (TCP) ip of the receiver from where data is streamed from (eg. to GUI or another process for further processing). " + "Default is ip of rx_hostname and works for GUI. This is usually used to stream out to an external process for further processing." + "restarts streaming in receiver with new port" + << std::endl; + os << "rx_udpsocksize [t]\n sets the UDP socket buffer size. Different defaults for Jungfrau. " + "Does not remember in client shared memory, " + "so must be initialized each time after setting receiver " + "hostname in config file." + << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "detectormac \n gets detector mac " << std::endl; + os << "detectormac2 \n gets detector mac of 2nd udp interface. Jungfrau only" << std::endl; + os << "detectorip \n gets detector ip " << std::endl; + os << "detectorip2 \n gets detector ip of 2nd udp interface. Jungfrau only" << std::endl; + os << "rx_hostname \n gets receiver ip " << std::endl; + os << "rx_udpmac \n gets receiver udp mac " << std::endl; + os << "rx_udpmac2 \n gets receiver udp mac of 2nd udp interface. Jungfrau only" << std::endl; + os << "rx_udpip \n gets receiver udp mac " << std::endl; + os << "rx_udpip2 \n gets receiver udp mac of 2nd udp interface. Jungfrau only" << std::endl; + os << "rx_udpport \n gets receiver udp port " << std::endl; + os << "rx_udpport2 \n gets receiver udp port of 2nd udp interface. For Eiger and Jungfrau, it is the second half module and for other detectors, same as rx_udpport" << std::endl; + os << "numinterfaces \n gets the number of interfaces to n used to stream out from the detector. Options: 1, 2. JUNGFRAU only. " << std::endl; + os << "selinterface \n gets the interface selected to use to stream data out of the detector. Options: 1, 2. Effective only when numinterfaces is 1. JUNGFRAU only. " << std::endl; + os << "txndelay_left \n gets detector transmission delay of the left port" << std::endl; + os << "txndelay_right \n gets detector transmission delay of the right port" << std::endl; + os << "txndelay_frame \n gets detector transmission delay of the entire frame" << std::endl; + os << "flowcontrol_10g \n gets flow control for 10g for eiger" << std::endl; + os << "zmqport \n gets the 0MQ (TCP) port of the client to where final data is streamed to" << std::endl; + os << "rx_zmqport \n gets the 0MQ (TCP) port of the receiver from where data is streamed from" << std::endl; + os << "zmqip \n gets the 0MQ (TCP) ip of the client to where final data is streamed to.If no custom ip, empty until first time connect to receiver" << std::endl; + os << "rx_zmqip \n gets/gets the 0MQ (TCP) ip of the receiver from where data is streamed from. If no custom ip, empty until first time connect to receiver" << std::endl; + os << "rx_udpsocksize \n gets the UDP socket buffer size." << std::endl; + os << "rx_realudpsocksize \n gets the actual UDP socket buffer size. Usually double the set udp socket buffer size due to kernel bookkeeping." << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdPort(int narg, char *args[], int action, int detPos) { + + if (action == HELP_ACTION) + return helpPort(action); + int val; //ret, + char ans[MAX_STR_LENGTH]; + if (action == PUT_ACTION) { + if (sscanf(args[1], "%d", &val)) + ; + else + return std::string("could not scan port number") + std::string(args[1]); + } + + myDet->setOnline(ONLINE_FLAG, detPos); + if (cmd == "port") { + if (action == PUT_ACTION) + myDet->setControlPort(val, detPos); + sprintf(ans, "%d", myDet->setControlPort(-1, detPos)); + } else if (cmd == "rx_tcpport") { + if (action == PUT_ACTION) + myDet->setReceiverPort(val, detPos); + sprintf(ans, "%d", myDet->setReceiverPort(-1, detPos)); + } else if (cmd == "stopport") { + if (action == PUT_ACTION) + myDet->setStopPort(val, detPos); + sprintf(ans, "%d", myDet->setStopPort(-1, detPos)); + } else + return std::string("unknown port type ") + cmd; + + return std::string(ans); +} + +std::string slsDetectorCommand::helpPort(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "port i \n sets the communication control port" << std::endl; + os << "rx_tcpport i \n sets the communication receiver port" << std::endl; + os << "stopport i \n sets the communication stop port " << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "port \n gets the communication control port" << std::endl; + os << "rx_tcpport \n gets the communication receiver port" << std::endl; + os << "stopport \n gets the communication stop port " << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdLock(int narg, char *args[], int action, int detPos) { + + if (action == HELP_ACTION) + return helpLock(action); + + int val; //, ret; + char ans[1000]; + + if (cmd == "lock") { + myDet->setOnline(ONLINE_FLAG, detPos); + if (action == PUT_ACTION) { + if (sscanf(args[1], "%d", &val)) + myDet->lockServer(val, detPos); + else + return std::string("could not lock status") + std::string(args[1]); + } + + sprintf(ans, "%d", myDet->lockServer(-1, detPos)); + } + + else if (cmd == "r_lock") { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + if (action == PUT_ACTION) { + if (sscanf(args[1], "%d", &val)) + myDet->lockReceiver(val, detPos); + else + return std::string("could not decode lock status") + std::string(args[1]); + } + sprintf(ans, "%d", myDet->lockReceiver(-1, detPos)); + } + + else + return std::string("could not decode command"); + + return std::string(ans); +} + +std::string slsDetectorCommand::helpLock(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "lock i \n locks (1) or unlocks (0) the detector to communicate to this client" << std::endl; + os << "r_lock i \n locks (1) or unlocks (0) the receiver to communicate to this client" << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "lock \n returns the detector lock status" << std::endl; + os << "r_lock \n returns the receiver lock status" << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdLastClient(int narg, char *args[], int action, int detPos) { + + if (action == HELP_ACTION) + return helpLastClient(action); + + if (action == PUT_ACTION) + return std::string("cannot set"); + + if (cmd == "lastclient") { + myDet->setOnline(ONLINE_FLAG, detPos); + return myDet->getLastClientIP(detPos); + } + + else if (cmd == "r_lastclient") { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + return myDet->getReceiverLastClientIP(detPos); + } + + return std::string("cannot decode command"); +} + +std::string slsDetectorCommand::helpLastClient(int action) { + + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) { + os << "lastclient \n returns the last client communicating with the detector" << std::endl; + os << "r_lastclient \n returns the last client communicating with the receiver" << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdOnline(int narg, char *args[], int action, int detPos) { + + if (action == HELP_ACTION) { + return helpOnline(action); + } + int ival; + char ans[1000]; + + if (cmd == "online") { + if (action == PUT_ACTION) { + if (sscanf(args[1], "%d", &ival)) + myDet->setOnline(ival, detPos); + else + return std::string("Could not scan online mode ") + std::string(args[1]); + } + sprintf(ans, "%d", myDet->setOnline(-1, detPos)); + } else if (cmd == "checkonline") { + if (action == PUT_ACTION) + return std::string("cannot set"); + strcpy(ans, myDet->checkOnline(detPos).c_str()); + if (!strlen(ans)) + strcpy(ans, "All online"); + else + strcat(ans, " :Not online"); + } else if (cmd == "activate") { + myDet->setOnline(ONLINE_FLAG, detPos); + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + if (action == PUT_ACTION) { + if (!sscanf(args[1], "%d", &ival)) + return std::string("Could not scan activate mode ") + std::string(args[1]); + myDet->activate(ival, detPos); + bool padding = true; + if (narg > 2) { + if (std::string(args[2]) == "padding") + padding = true; + else if (std::string(args[2]) == "nopadding") + padding = false; + else + return std::string("Could not scan activate mode's padding option " + std::string(args[2])); + myDet->setDeactivatedRxrPaddingMode(padding, detPos); + } + } + int ret = myDet->setDeactivatedRxrPaddingMode(-1, detPos); + sprintf(ans, "%d %s", myDet->activate(-1, detPos), ret == 1 ? "padding" : (ret == 0 ? "nopadding" : "unknown")); + } else if (cmd == "r_online") { + if (action == PUT_ACTION) { + if (sscanf(args[1], "%d", &ival)) + myDet->setReceiverOnline(ival, detPos); + else + return std::string("Could not scan online mode ") + std::string(args[1]); + } + sprintf(ans, "%d", myDet->setReceiverOnline(-1, detPos)); + } else { + if (action == PUT_ACTION) + return std::string("cannot set"); + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + strcpy(ans, myDet->checkReceiverOnline(detPos).c_str()); + if (!strlen(ans)) + strcpy(ans, "All receiver online"); + else + strcat(ans, " :Not all receiver online"); + } + + return ans; +} + +std::string slsDetectorCommand::helpOnline(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "online i \n sets the detector in online (1) or offline (0) mode" << std::endl; + os << "r_online i \n sets the receiver in online (1) or offline (0) mode" << std::endl; + os << "activate i [p]\n sets the detector in activated (1) or deactivated (0) mode (does not send data). p is optional and can be padding (default) or nonpadding for receivers for deactivated detectors. Only for Eiger." << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "online \n gets the detector online (1) or offline (0) mode" << std::endl; + os << "checkonline \n returns the hostnames of all detectors in offline mode" << std::endl; + os << "r_online \n gets the receiver online (1) or offline (0) mode" << std::endl; + os << "r_checkonline \n returns the hostnames of all receiver in offline mode" << std::endl; + os << "activate \n gets the detector activated (1) or deactivated (0) mode. And padding or nonpadding for the deactivated receiver. Only for Eiger." << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdConfigureMac(int narg, char *args[], int action, int detPos) { + + if (action == HELP_ACTION) { + return helpConfigureMac(action); + } + int ret; + char ans[1000]; + + if (action == PUT_ACTION) { + myDet->setOnline(ONLINE_FLAG, detPos); + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + ret = myDet->configureMAC(detPos); + } else + return std::string("Cannot get ") + cmd; + + sprintf(ans, "%d", ret); + return ans; +} + +std::string slsDetectorCommand::helpConfigureMac(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) + os << "configuremac i \n configures the MAC of the detector." << std::endl; + if (action == GET_ACTION || action == HELP_ACTION) + os << "configuremac " + << "Cannot get " << std::endl; + + return os.str(); +} + +std::string slsDetectorCommand::cmdDetectorSize(int narg, char *args[], int action, int detPos) { + + if (action == HELP_ACTION) + return helpDetectorSize(action); + int ret, val = -1, pos = -1, i; + char ans[1000]; + + myDet->setOnline(ONLINE_FLAG, detPos); + + if (cmd == "roi") + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + + if (action == PUT_ACTION) { + if (!sscanf(args[1], "%d", &val)) + return std::string("could not scan ") + std::string(args[0]) + std::string(" ") + std::string(args[1]); + + if (cmd == "roi") { + //debug number of arguments + if ((val < 0) || (narg != ((val * 4) + 2))) + return helpDetectorSize(action); + ROI allroi[val]; + pos = 2; + for (i = 0; i < val; ++i) { + if ((!sscanf(args[pos++], "%d", &allroi[i].xmin)) || + (!sscanf(args[pos++], "%d", &allroi[i].xmax)) || + (!sscanf(args[pos++], "%d", &allroi[i].ymin)) || + (!sscanf(args[pos++], "%d", &allroi[i].ymax))) + return std::string("cannot parse arguments for roi"); + } + myDet->setROI(val, allroi, detPos); + } + + if (cmd == "detsizechan") { + if ((sscanf(args[1], "%d", &val)) && (val > 0)) + myDet->setMaxNumberOfChannelsPerDetector(X, val); + if ((narg > 2) && (sscanf(args[2], "%d", &val)) && (val > 0)) + myDet->setMaxNumberOfChannelsPerDetector(Y, val); + } + + if (cmd == "flippeddatax") { + if ((!sscanf(args[1], "%d", &val)) || (val != 0 && val != 1)) + return std::string("cannot scan flippeddata x mode: must be 0 or 1"); + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + myDet->setFlippedData(X, val, detPos); + } + + if (cmd == "flippeddatay") { + return std::string("Not required for this detector\n"); + if ((!sscanf(args[1], "%d", &val)) || (val != 0 && val != 1)) + return std::string("cannot scan flippeddata y mode: must be 0 or 1"); + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + myDet->setFlippedData(Y, val, detPos); + } + + if (cmd == "gappixels") { + if ((!sscanf(args[1], "%d", &val)) || (val != 0 && val != 1)) + return std::string("cannot scan gappixels mode: must be 0 or 1"); + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + if (detPos < 0) // only in multi detector level to update offsets etc. + myDet->enableGapPixels(val, detPos); + } + } + + if (cmd == "dr") { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + ret = myDet->setDynamicRange(val, detPos); + } else if (cmd == "roi") { + const ROI* r = myDet->getROI(ret, detPos); + if (r != NULL) + delete [] r; + } else if (cmd == "detsizechan") { + sprintf(ans, "%d %d", myDet->getMaxNumberOfChannelsPerDetector(X), myDet->getMaxNumberOfChannelsPerDetector(Y)); + return std::string(ans); + } else if (cmd == "flippeddatax") { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + ret = myDet->getFlippedData(X, detPos); + } else if (cmd == "flippeddatay") { + return std::string("Not required for this detector\n"); + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + ret = myDet->getFlippedData(Y, detPos); + } else if (cmd == "gappixels") { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + if (detPos >= 0) // only in multi detector level to update offsets etc. + return std::string("Cannot execute this command from slsDetector level. Please use multiSlsDetector level.\n"); + ret = myDet->enableGapPixels(-1, detPos); + } + + else + return std::string("unknown command ") + cmd; + + sprintf(ans, "%d", ret); + + return std::string(ans); +} + +std::string slsDetectorCommand::helpDetectorSize(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "dr i \n sets the dynamic range of the detector" << std::endl; + os << "roi i xmin xmax ymin ymax \n sets region of interest where i is number of rois;i=0 to clear rois" << std::endl; + os << "detsizechan x y \n sets the maximum number of channels for complete detector set in both directions; -1 is no limit" << std::endl; + os << "flippeddatax x \n sets if the data should be flipped on the x axis" << std::endl; + os << "flippeddatay y \n sets if the data should be flipped on the y axis" << std::endl; + os << "gappixels i \n enables/disables gap pixels in system (detector & receiver). 1 sets, 0 unsets. Used in EIGER only and multidetector level." << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "dr \n gets the dynamic range of the detector" << std::endl; + os << "roi \n gets region of interest" << std::endl; + os << "detsizechan \n gets the maximum number of channels for complete detector set in both directions; -1 is no limit" << std::endl; + os << "flippeddatax\n gets if the data will be flipped on the x axis" << std::endl; + os << "flippeddatay\n gets if the data will be flipped on the y axis" << std::endl; + os << "gappixels\n gets if gap pixels is enabled in system. Used in EIGER only and multidetector level." << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdSettings(int narg, char *args[], int action, int detPos) { + + if (action == HELP_ACTION) + return helpSettings(action); + int val = -1; //ret, + char ans[1000]; + + // portType index; + // if (sscanf(args[1],"%d",&val)) + // ; + // else + // return std::string("could not scan port number")+std::string (args[1]); + // } + + myDet->setOnline(ONLINE_FLAG, detPos); + + if (cmd == "settings") { + detectorSettings sett = GET_SETTINGS; + if (action == PUT_ACTION) { + sett = myDet->getDetectorSettings(std::string(args[1])); + if (sett == -1) + return std::string("unknown settings scanned " + std::string(args[1])); + sett = myDet->setSettings(sett, detPos); + if (myDet->getDetectorTypeAsEnum(detPos) == EIGER) { + return myDet->getDetectorSettings(sett); + } + } + return myDet->getDetectorSettings(myDet->getSettings(detPos)); + } else if (cmd == "threshold") { + if (action == PUT_ACTION) { + if (!sscanf(args[1], "%d", &val)) { + return std::string("invalid threshold value"); + } + detectorType type = myDet->getDetectorTypeAsEnum(detPos); + if (type != EIGER || (type == EIGER && narg <= 2)) { + myDet->setThresholdEnergy(val, GET_SETTINGS, 1, detPos); + } else { + detectorSettings sett = myDet->getDetectorSettings(std::string(args[2])); + if (sett == -1) + return std::string("invalid settings value"); + myDet->setThresholdEnergy(val, sett, 1, detPos); + } + } + sprintf(ans, "%d", myDet->getThresholdEnergy(detPos)); + return std::string(ans); + } else if (cmd == "thresholdnotb") { + if (action == PUT_ACTION) { + if (!sscanf(args[1], "%d", &val)) { + return std::string("invalid threshold value"); + } + detectorType type = myDet->getDetectorTypeAsEnum(detPos); + if (type != EIGER) + return std::string("not implemented for this detector"); + if (narg <= 2) { + myDet->setThresholdEnergy(val, GET_SETTINGS, 0, detPos); + } else { + detectorSettings sett = myDet->getDetectorSettings(std::string(args[2])); + if (sett == -1) + return std::string("invalid settings value"); + myDet->setThresholdEnergy(val, sett, 0, detPos); + } + } + sprintf(ans, "%d", myDet->getThresholdEnergy(detPos)); + return std::string(ans); + } else if (cmd == "trimbits") { + if (narg >= 2) { + std::string sval = std::string(args[1]); +#ifdef VERBOSE + std::cout << " trimfile " << sval << std::endl; +#endif + int ret = OK; + if (action == GET_ACTION) { + //create file names + ret = myDet->saveSettingsFile(sval, detPos); + } else if (action == PUT_ACTION) { + ret = myDet->loadSettingsFile(sval, detPos); + } + if (ret == OK) + return sval; + else + return std::string("failed"); + } + return std::string("Specify file name for geting settings file"); + } else if (cmd == "trimval") { + if (action == PUT_ACTION) { + if (sscanf(args[1], "%d", &val)) + myDet->setAllTrimbits(val, detPos); + else + return std::string("invalid trimbit value ") + cmd; + } + sprintf(ans, "%d", myDet->setAllTrimbits(-1, detPos)); + return ans; + } + return std::string("unknown settings command ") + cmd; +} + +std::string slsDetectorCommand::helpSettings(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "settings s \n sets the settings of the detector - can be standard, fast, highgain, dynamicgain, lowgain, mediumgain, veryhighgain" + "lownoise, dynamichg0,fixgain1,fixgain2,forceswitchg1, forceswitchg2" + << std::endl; + os << "threshold eV [sett]\n sets the detector threshold in eV. If sett is provided for eiger, uses settings sett" << std::endl; + os << "thresholdnotb eV [sett]\n sets the detector threshold in eV without loading trimbits. If sett is provided for eiger, uses settings sett" << std::endl; + os << "trimbits fname\n loads the trimfile fname to the detector. If no extension is specified, the serial number of each module will be attached." << std::endl; + os << "trimval i \n sets all the trimbits to i" << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "settings \n gets the settings of the detector" << std::endl; + os << "threshold V\n gets the detector threshold" << std::endl; + os << "thresholdnotb V\n gets the detector threshold" << std::endl; + os << "trimbits [fname]\n returns the trimfile loaded on the detector. If fname is specified the trimbits are saved to file. If no extension is specified, the serial number of each module will be attached." << std::endl; + os << "trimval \n returns the value all trimbits are set to. If they are different, returns -1." << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdSN(int narg, char *args[], int action, int detPos) { + + char answer[1000]; + + if (action == PUT_ACTION) + return std::string("cannot set"); + + if (action == HELP_ACTION) + return helpSN(action); + + if (cmd == "thisversion") { + int64_t retval = myDet->getClientSoftwareVersion(); + if (retval < 0) + sprintf(answer, "%d", -1); + else + sprintf(answer, "0x%lx", retval); + return std::string(answer); + } + + myDet->setOnline(ONLINE_FLAG, detPos); + + if (cmd == "detectornumber") { + int64_t retval = myDet->getId(DETECTOR_SERIAL_NUMBER, detPos); + if (retval < 0) + sprintf(answer, "%d", -1); + else + sprintf(answer, "0x%lx", retval); + return std::string(answer); + } + + if (cmd == "detectorversion") { + int64_t retval = myDet->getId(DETECTOR_FIRMWARE_VERSION, detPos); + if (retval < 0) + sprintf(answer, "%d", -1); + else + sprintf(answer, "0x%lx", retval); + return std::string(answer); + } + + if (cmd == "softwareversion") { + int64_t retval = myDet->getId(DETECTOR_SOFTWARE_VERSION, detPos); + if (retval < 0) + sprintf(answer, "%d", -1); + else + sprintf(answer, "0x%lx", retval); + return std::string(answer); + } + + if (cmd == "receiverversion") { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + int64_t retval = myDet->getReceiverSoftwareVersion(detPos); + if (retval < 0) + sprintf(answer, "%d", -1); + else + sprintf(answer, "0x%lx", retval); + return std::string(answer); + } + + if (cmd == "checkdetversion") { + int retval = myDet->checkDetectorVersionCompatibility(detPos); + if (retval < 0) + sprintf(answer, "%d", -1); + sprintf(answer, "%s", retval == OK ? "compatible" : "incompatible"); + return std::string(answer); + } + + if (cmd == "checkrecversion") { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + int retval = myDet->checkReceiverVersionCompatibility(detPos); + if (retval < 0) + sprintf(answer, "%d", -1); + sprintf(answer, "%s", retval == OK ? "compatible" : "incompatible"); + return std::string(answer); + } + + return std::string("unknown id mode ") + cmd; +} + +std::string slsDetectorCommand::helpSN(int action) { + + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) { + os << "checkdetversion \n gets the version compatibility with detector server (if hostname is in shared memory). Only for Eiger, Jungfrau & Gotthard. Prints compatible/ incompatible." << std::endl; + os << "checkrecversion \n gets the version compatibility with receiver server (if rx_hostname is in shared memory). Only for Eiger, Jungfrau & Gotthard. Prints compatible/ incompatible." << std::endl; + os << "detectornumber \n gets the serial number of the detector (MAC)" << std::endl; + os << "detectorversion \n gets the firmware version of the detector" << std::endl; + os << "softwareversion \n gets the software version of the detector" << std::endl; + os << "thisversion \n gets the version of this software" << std::endl; + os << "receiverversion \n gets the version of the receiver" << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdDigiTest(int narg, char *args[], int action, int detPos) { + + char answer[1000]; + + if (action == HELP_ACTION) + return helpSN(action); + + myDet->setOnline(ONLINE_FLAG, detPos); + + if (cmd == "bustest") { + if (action == PUT_ACTION) + return std::string("cannot set ") + cmd; + sprintf(answer, "%d", myDet->digitalTest(DETECTOR_BUS_TEST)); + return std::string(answer); + } + + else if (cmd == "firmwaretest") { + if (action == PUT_ACTION) + return std::string("cannot set ") + cmd; + sprintf(answer, "%d", myDet->digitalTest(DETECTOR_FIRMWARE_TEST)); + return std::string(answer); + } + + else if (cmd == "digibittest") { + if (action == GET_ACTION) + return std::string("cannot get ") + cmd; + int ival = -1; + if (sscanf(args[1], "%d", &ival)) { + if ((ival == 0) || (ival == 1)) { + sprintf(answer, "%d", myDet->digitalTest(DIGITAL_BIT_TEST, ival, detPos)); + return std::string(answer); + } else + return std::string("Use only 0 or 1 to set/clear digital test bit\n"); + } else + return std::string("undefined number"); + } + + return std::string("unknown test mode ") + cmd; +} + +std::string slsDetectorCommand::helpDigiTest(int action) { + + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) { + os << "digibittest:i \t performs digital test of the module i. Returns 0 if succeeded, otherwise error mask.Gotthard only." << std::endl; + os << "bustest \t performs test of the bus interface between FPGA and embedded Linux system. Can last up to a few minutes. Jungfrau only." << std::endl; + os << "firmwaretest \t performs the firmware test. Jungfrau only." << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdRegister(int narg, char *args[], int action, int detPos) { + + if (action == HELP_ACTION) + return helpRegister(action); + + int addr, val, n; + char answer[1000]; + + myDet->setOnline(ONLINE_FLAG, detPos); + + // "reg" // + + // "setbit" // + + // "clearbit" // + + // "getbit" // + + if (action == PUT_ACTION) { + if (cmd == "getbit") + return std::string("Cannot put"); + + if (narg < 3) { + if (cmd == "reg") + return std::string("wrong usage: should specify both address and value (hexadecimal fomat) "); + else + return std::string("wrong usage: should specify both address (hexadecimal fomat) and bit number"); + } + + if (sscanf(args[1], "%x", &addr)) + ; + else + return std::string("Could not scan address (hexadecimal fomat) ") + std::string(args[1]); + + if (cmd == "reg") { + if (sscanf(args[2], "%x", &val)) + ; + else + return std::string("Could not scan value (hexadecimal fomat) ") + std::string(args[2]); + sprintf(answer, "0x%x", myDet->writeRegister(addr, val, detPos)); + } else if (cmd == "adcreg") { + if (sscanf(args[2], "%x", &val)) + ; + else + return std::string("Could not scan value (hexadecimal fomat) ") + std::string(args[2]); + sprintf(answer, "%s", (myDet->writeAdcRegister(addr, val, detPos) == OK) ? "successful" : "failed"); + } else { + + if (sscanf(args[2], "%d", &n)) + ; + else + return std::string("Could not scan bit number ") + std::string(args[2]); + + if (n < 0 || n > 31) + return std::string("Bit number out of range") + std::string(args[2]); + + if (cmd == "setbit") + sprintf(answer, "0x%x", myDet->setBit(addr, n, detPos)); + if (cmd == "clearbit") + sprintf(answer, "0x%x", myDet->clearBit(addr, n, detPos)); + } + + } else { + if (cmd == "setbit") + return std::string("Cannot get"); + if (cmd == "clearbit") + return std::string("Cannot get"); + if (cmd == "adcreg") + return std::string("Cannot get"); + + if (cmd == "reg") { + if (narg < 2) + return std::string("wrong usage: should specify address (hexadecimal fomat) "); + if (sscanf(args[1], "%x", &addr)) + ; + else + return std::string("Could not scan address (hexadecimal fomat) ") + std::string(args[1]); + + sprintf(answer, "0x%x", myDet->readRegister(addr, detPos)); + } + + if (cmd == "getbit") { + + if (narg < 3) + return std::string("wrong usage: should specify both address (hexadecimal fomat) and bit number"); + + if (sscanf(args[1], "%x", &addr)) + ; + else + return std::string("Could not scan address (hexadecimal fomat) ") + std::string(args[1]); + + if (sscanf(args[2], "%d", &n)) + ; + else + return std::string("Could not scan bit number ") + std::string(args[2]); + + if (n < 0 || n > 31) + return std::string("Bit number out of range") + std::string(args[2]); + + sprintf(answer, "%d", (myDet->readRegister(addr, detPos) >> n) & 1); + } + } + + return std::string(answer); +} + +std::string slsDetectorCommand::helpRegister(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "reg addr val \n writes the register addr with the value val (hexadecimal format)" << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "reg addr \n reads the register addr" << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdDAC(int narg, char *args[], int action, int detPos) { + + if (action == HELP_ACTION) + return helpDAC(action); + + dacIndex dac; + int val = -1; + char answer[1000]; + int mode = 0; + + int idac = -1; + if (sscanf(args[0], "dac:%d", &idac) == 1) { + //printf("chiptestboard!\n"); + dac = (dacIndex)idac; + } else if (cmd == "adcvpp") + dac = ADC_VPP; + else if (cmd == "vthreshold") + dac = THRESHOLD; + else if (cmd == "vcalibration") + dac = CALIBRATION_PULSE; + else if (cmd == "vtrimbit") + dac = TRIMBIT_SIZE; + else if (cmd == "vpreamp") + dac = PREAMP; + else if (cmd == "vshaper1") + dac = SHAPER1; + else if (cmd == "vshaper2") + dac = SHAPER2; + else if (cmd == "vhighvoltage") + dac = HIGH_VOLTAGE; + else if (cmd == "vapower") + dac = VA_POT; + else if (cmd == "vddpower") + dac = VDD_POT; + else if (cmd == "vshpower") + dac = VSH_POT; + else if (cmd == "viopower") + dac = VIO_POT; + else if (cmd == "vref_ds") + dac = G_VREF_DS; + else if (cmd == "vcascn_pb") + dac = G_VCASCN_PB; + else if (cmd == "vcascp_pb") + dac = G_VCASCP_PB; + else if (cmd == "vout_cm") + dac = G_VOUT_CM; + else if (cmd == "vcasc_out") + dac = G_VCASC_OUT; + else if (cmd == "vin_cm") + dac = G_VIN_CM; + else if (cmd == "vref_comp") + dac = G_VREF_COMP; + else if (cmd == "ib_test_c") + dac = G_IB_TESTC; + + else if (cmd == "vsvp") + dac = E_SvP; + else if (cmd == "vsvn") + dac = E_SvN; + else if (cmd == "vtr") + dac = E_Vtr; + else if (cmd == "vrf") + dac = E_Vrf; + else if (cmd == "vrs") + dac = E_Vrs; + else if (cmd == "vtgstv") + dac = E_Vtgstv; + else if (cmd == "vcmp_ll") + dac = E_Vcmp_ll; + else if (cmd == "vcmp_lr") + dac = E_Vcmp_lr; + else if (cmd == "vcall") + dac = E_cal; + else if (cmd == "vcmp_rl") + dac = E_Vcmp_rl; + else if (cmd == "vcmp_rr") + dac = E_Vcmp_rr; + else if (cmd == "rxb_rb") + dac = E_rxb_rb; + else if (cmd == "rxb_lb") + dac = E_rxb_lb; + else if (cmd == "vcp") + dac = E_Vcp; + else if (cmd == "vcn") + dac = E_Vcn; + else if (cmd == "vis") + dac = E_Vis; + else if (cmd == "iodelay") + dac = IO_DELAY; + else if (cmd == "v_a") { + dac = V_POWER_A; + mode = 1; + } else if (cmd == "v_b") { + dac = V_POWER_B; + mode = 1; + } else if (cmd == "v_c") { + dac = V_POWER_C; + mode = 1; + } else if (cmd == "v_d") { + dac = V_POWER_D; + mode = 1; + } else if (cmd == "v_io") { + dac = V_POWER_IO; + mode = 1; + } else if (cmd == "v_chip") { + dac = V_POWER_CHIP; + mode = 1; + } else if (cmd == "v_limit") + dac = V_LIMIT; + else if (cmd == "vIpre") + dac = M_vIpre; + else if (cmd == "vIbias") + dac = M_vIbias; + else if (cmd == "vIinSh") + dac = M_vIinSh; + else if (cmd == "VcdSh") + dac = M_VdcSh; + else if (cmd == "Vth1") + dac = THRESHOLD; + else if (cmd == "Vth2") + dac = M_Vth2; + else if (cmd == "Vth3") + dac = M_Vth3; + else if (cmd == "VPL") + dac = M_VPL; + else if (cmd == "Vtrim") + dac = TRIMBIT_SIZE; + else if (cmd == "casSh") + dac = M_casSh; + else if (cmd == "cas") + dac = M_cas; + else if (cmd == "vIcin") + dac = M_vIcin; + else if (cmd == "vIbiasSh") + dac = M_vIbiasSh; + else if (cmd == "vIpreOut") + dac = M_vIpreOut; + + else + return std::string("cannot decode dac ") + cmd; + + myDet->setOnline(ONLINE_FLAG, detPos); + + if (action == PUT_ACTION) { + + if (narg >= 3) + if (!strcasecmp(args[2], "mv")) + mode = 1; + + if (sscanf(args[1], "%d", &val)) + ; + else + return std::string("cannot scan DAC value ") + std::string(args[1]); + + myDet->setDAC(val, dac, mode, detPos); + } + // get (dacs in dac units or mV) + else if ((narg >= 2) && (!strcasecmp(args[1], "mv"))) { + mode = 1; + } + + sprintf(answer, "%d", myDet->setDAC(-1, dac, mode, detPos)); + if (mode) + strcat(answer, " mV"); + return std::string(answer); +} + +std::string slsDetectorCommand::helpDAC(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "vthreshold dacu\t sets the detector threshold in dac units (0-1024) or mV. The energy is approx 800-15*keV" << std::endl; + os << std::endl; + + os << "vcalibration " + << "dacu\t sets the calibration pulse amplitude in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vtrimbit " + << "dacu\t sets the trimbit amplitude in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vpreamp " + << "dacu\t sets the preamp feedback voltage in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vshaper1 " + << "dacu\t sets the shaper1 feedback voltage in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vshaper2 " + << "dacu\t sets the shaper2 feedback voltage in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vhighvoltage " + << "dacu\t CHIPTEST BOARD ONLY - sets the detector HV in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vapower " + << "dacu\t CHIPTEST BOARD ONLY - sets the analog power supply in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vddpower " + << "dacu\t CHIPTEST BOARD ONLY - sets the digital power supply in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vshpower " + << "dacu\t CHIPTEST BOARD ONLY - sets the comparator power supply in dac units (0-1024)." << std::endl; + os << std::endl; + os << "viopower " + << "dacu\t CHIPTEST BOARD ONLY - sets the FPGA I/O power supply in dac units (0-1024)." << std::endl; + + os << "vrefds " + << "dacu\t sets vrefds" << std::endl; + os << "vcascn_pb " + << "dacu\t sets vcascn_pb" << std::endl; + os << "vcascp_pb " + << "dacu\t sets vcascp_pb" << std::endl; + os << "vout_cm " + << "dacu\t sets vout_cm" << std::endl; + os << "vin_cm " + << "dacu\t sets vin_cm" << std::endl; + os << "vcasc_out " + << "dacu\t sets vcasc_out" << std::endl; + os << "vref_comp " + << "dacu\t sets vref_comp" << std::endl; + os << "ib_test_c " + << "dacu\t sets ib_test_c" << std::endl; + + os << "vsvp" + << "dacu\t sets vsvp" << std::endl; + os << "vsvn" + << "dacu\t sets vsvn" << std::endl; + os << "vtr" + << "dacu\t sets vtr" << std::endl; + os << "vrf" + << "dacu\t sets vrf" << std::endl; + os << "vrs" + << "dacu\t sets vrs" << std::endl; + os << "vtgstv" + << "dacu\t sets vtgstv" << std::endl; + os << "vcmp_ll" + << "dacu\t sets vcmp_ll" << std::endl; + os << "vcmp_lr" + << "dacu\t sets vcmp_lr" << std::endl; + os << "vcall" + << "dacu\t sets vcall" << std::endl; + os << "vcmp_rl" + << "dacu\t sets vcmp_rl" << std::endl; + os << "vcmp_rr" + << "dacu\t sets vcmp_rr" << std::endl; + os << "rxb_rb" + << "dacu\t sets rxb_rb" << std::endl; + os << "rxb_lb" + << "dacu\t sets rxb_lb" << std::endl; + os << "vcp" + << "dacu\t sets vcp " << std::endl; + os << "vcn" + << "dacu\t sets vcn " << std::endl; + os << "vis" + << "dacu\t sets vis " << std::endl; + + os << " mv if you want in mV else in dac units " << std::endl; + } + + if (action == GET_ACTION || action == HELP_ACTION) { + + os << "vthreshold \t Gets the detector threshold in dac units (0-1024). The energy is approx 800-15*keV" << std::endl; + os << std::endl; + + os << "vcalibration " + << "dacu\t gets the calibration pulse amplitude in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vtrimbit " + << "dacu\t gets the trimbit amplitude in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vpreamp " + << "dacu\t gets the preamp feedback voltage in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vshaper1 " + << "dacu\t gets the shaper1 feedback voltage in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vshaper2 " + << "dacu\t gets the shaper2 feedback voltage in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vhighvoltage " + << "dacu\t CHIPTEST BOARD ONLY - gets the detector HV in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vapower " + << "dacu\t CHIPTEST BOARD ONLY - gets the analog power supply in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vddpower " + << "dacu\t CHIPTEST BOARD ONLY - gets the digital power supply in dac units (0-1024)." << std::endl; + os << std::endl; + os << "vshpower " + << "dacu\t CHIPTEST BOARD ONLY - gets the comparator power supply in dac units (0-1024)." << std::endl; + os << std::endl; + os << "viopower " + << "dacu\t CHIPTEST BOARD ONLY - gets the FPGA I/O power supply in dac units (0-1024)." << std::endl; + os << std::endl; + + os << "vrefds " + << "\t gets vrefds" << std::endl; + os << "vcascn_pb " + << "\t gets vcascn_pb" << std::endl; + os << "vcascp_pb " + << "\t gets vcascp_pb" << std::endl; + os << "vout_cm " + << "\t gets vout_cm" << std::endl; + os << "vin_cm " + << "\t gets vin_cm" << std::endl; + os << "vcasc_out " + << "\t gets vcasc_out" << std::endl; + os << "vref_comp " + << "\t gets vref_comp" << std::endl; + os << "ib_test_c " + << "\t gets ib_test_c" << std::endl; + + os << "vsvp" + << "dacu\t gets vsvp" << std::endl; + os << "vsvn" + << "dacu\t gets vsvn" << std::endl; + os << "vtr" + << "dacu\t gets vtr" << std::endl; + os << "vrf" + << "dacu\t gets vrf" << std::endl; + os << "vrs" + << "dacu\t gets vrs" << std::endl; + os << "vtgstv" + << "dacu\t gets vtgstv" << std::endl; + os << "vcmp_ll" + << "dacu\t gets vcmp_ll" << std::endl; + os << "vcmp_lr" + << "dacu\t gets vcmp_lr" << std::endl; + os << "vcall" + << "dacu\t gets vcall" << std::endl; + os << "vcmp_rl" + << "dacu\t gets vcmp_rl" << std::endl; + os << "vcmp_rr" + << "dacu\t gets vcmp_rr" << std::endl; + os << "rxb_rb" + << "dacu\t gets rxb_rb" << std::endl; + os << "rxb_lb" + << "dacu\t gets rxb_lb" << std::endl; + os << "vcp" + << "dacu\t gets vcp " << std::endl; + os << "vcn" + << "dacu\t gets vcn " << std::endl; + os << "vis" + << "dacu\t gets vis " << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdADC(int narg, char *args[], int action, int detPos) { + + dacIndex adc; + int idac; + // double val=-1; + char answer[1000]; + + if (action == HELP_ACTION) + return helpADC(action); + else if (action == PUT_ACTION) + return std::string("cannot set ") + cmd; + + if (sscanf(args[0],"adc:%d",&idac)==1) { + // printf("chiptestboard!\n"); + adc=(dacIndex)(idac+SLOW_ADC0); + if (idac < 0 || idac > SLOW_ADC_TEMP - SLOW_ADC0) + return (std::string ("cannot set adc, must be between ") + std::to_string(0) + + std::string (" and ") + std::to_string(SLOW_ADC_TEMP - SLOW_ADC0)); + } else if (cmd=="temp_adc") + adc=TEMPERATURE_ADC; + else if (cmd=="temp_fpga") + adc=TEMPERATURE_FPGA; + else if (cmd=="temp_fpgaext") + adc=TEMPERATURE_FPGAEXT; + else if (cmd=="temp_10ge") + adc=TEMPERATURE_10GE; + else if (cmd=="temp_dcdc") + adc=TEMPERATURE_DCDC; + else if (cmd=="temp_sodl") + adc=TEMPERATURE_SODL; + else if (cmd=="temp_sodr") + adc=TEMPERATURE_SODR; + else if (cmd=="temp_fpgafl") + adc=TEMPERATURE_FPGA2; + else if (cmd=="temp_fpgafr") + adc=TEMPERATURE_FPGA3; + else if (cmd=="i_a") + adc=I_POWER_A; + else if (cmd=="i_b") + adc=I_POWER_B; + else if (cmd=="i_c") + adc=I_POWER_C; + else if (cmd=="i_d") + adc=I_POWER_D; + else if (cmd=="vm_a") + adc=V_POWER_A; + else if (cmd=="vm_b") + adc=V_POWER_B; + else if (cmd=="vm_c") + adc=V_POWER_C; + else if (cmd=="vm_d") + adc=V_POWER_D; + else if (cmd=="vm_io") + adc=V_POWER_IO; + else if (cmd=="i_io") + adc=I_POWER_IO; + else + return std::string("cannot decode adc ")+cmd; + + myDet->setOnline(ONLINE_FLAG, detPos); + if (myDet->getDetectorTypeAsEnum(detPos) == EIGER || myDet->getDetectorTypeAsEnum(detPos) == JUNGFRAU){ + int val = myDet->getADC(adc, detPos); + if (val == -1) + sprintf(answer,"%d",val); + else + sprintf(answer,"%.2f", (double)val/1000.000); + } + else sprintf(answer,"%d",myDet->getADC(adc, detPos)); + + //if ((adc == TEMPERATURE_ADC) || (adc == TEMPERATURE_FPGA)) + if (adc < 100 || adc == SLOW_ADC_TEMP) + strcat(answer,"°C"); + else if (adc == I_POWER_A || adc == I_POWER_B || adc == I_POWER_C || adc == I_POWER_D || adc == I_POWER_IO) + strcat(answer," mA"); + else + strcat(answer," mV"); + + return std::string(answer); + +} + +std::string slsDetectorCommand::helpADC(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "temp_adc " + << "Cannot be set" << std::endl; + os << "temp_fpga " + << "Cannot be set" << std::endl; + os << "temp_fpgaext " + << "Cannot be set" << std::endl; + os << "temp_10ge " + << "Cannot be set" << std::endl; + os << "temp_dcdc " + << "Cannot be set" << std::endl; + os << "temp_sodl " + << "Cannot be set" << std::endl; + os << "temp_sodr " + << "Cannot be set" << std::endl; + os << "temp_fpgafl " + << "Cannot be set" << std::endl; + os << "temp_fpgafr " + << "Cannot be set" << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "temp_adc " + << "\t gets the temperature of the adc" << std::endl; + os << "temp_fpga " + << "\t gets the temperature of the fpga" << std::endl; + os << "temp_fpgaext " + << "\t gets the temperature close to the fpga" << std::endl; + os << "temp_10ge " + << "\t gets the temperature close to the 10GE" << std::endl; + os << "temp_dcdc " + << "\t gets the temperature close to the dc dc converter" << std::endl; + os << "temp_sodl " + << "\t gets the temperature close to the left so-dimm memory" << std::endl; + os << "temp_sodr " + << "\t gets the temperature close to the right so-dimm memory" << std::endl; + os << "temp_fpgafl " + << "\t gets the temperature of the left front end board fpga" << std::endl; + os << "temp_fpgafr " + << "\t gets the temperature of the left front end board fpga" << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdTempControl(int narg, char *args[], int action, int detPos) { + char answer[1000] = ""; + int val = -1; + + if (action == HELP_ACTION) + return helpTempControl(action); + + myDet->setOnline(ONLINE_FLAG, detPos); + + if (cmd == "temp_threshold") { + if (action == PUT_ACTION) { + double fval = 0.0; + if (!sscanf(args[1], "%lf", &fval)) + return std::string("cannot scan temp control value ") + std::string(args[1]); + val = fval * 1000; + myDet->setThresholdTemperature(val, detPos); + } + val = myDet->setThresholdTemperature(-1, detPos); + if (val == -1) + sprintf(answer, "%d", val); + else + sprintf(answer, "%.2f°C", (double)val / 1000.000); + } + + else if (cmd == "temp_control") { + if (action == PUT_ACTION) { + if (!sscanf(args[1], "%d", &val)) + return std::string("cannot scan temp control value ") + std::string(args[1]); + if ((val != 0) && (val != 1)) + return std::string("temp_control option must be 0 or 1"); + myDet->setTemperatureControl(val, detPos); + } + sprintf(answer, "%d", myDet->setTemperatureControl(-1, detPos)); + } + + else if (cmd == "temp_event") { + if (action == PUT_ACTION) { + if (!sscanf(args[1], "%d", &val)) + return std::string("cannot scan temp control value ") + std::string(args[1]); + if (val != 0) + return std::string("temp_event option must be 0 to clear event"); + myDet->setTemperatureEvent(val, detPos); + } + sprintf(answer, "%d", myDet->setTemperatureEvent(-1, detPos)); + } + + else + return std::string("cannot scan command " + cmd); + + return std::string(answer); +} + +std::string slsDetectorCommand::helpTempControl(int action) { + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "temp_threshold t \t sets the threshold temperature. Jungfrau only" << std::endl; + os << "temp_control t \t Enables/Disables the temperature control. 1 enables, 0 disables. JUNGFRAU ONLY" << std::endl; + os << "temp_event t \t Resets over-temperative event. Put only with option 0 to clear event. JUNGFRAU ONLY." << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "temp_threshold \t gets the threshold temperature. Jungfrau only." << std::endl; + os << "temp_control \t gets temperature control enable. 1 enabled, 0 disabled. JUNGFRAU ONLY" << std::endl; + os << "temp_event \t gets over-temperative event. Gets 1 if temperature went over threshold and control is enabled, else 0. /Disables the temperature control. JUNGFRAU ONLY." << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdTiming(int narg, char *args[], int action, int detPos) { +#ifdef VERBOSE + std::cout << std::string("Executing command ") + std::string(args[0]) + std::string(" ( ") + cmd + std::string(" )\n"); +#endif + + if (action == HELP_ACTION) { + return helpTiming(HELP_ACTION); + } + myDet->setOnline(ONLINE_FLAG, detPos); + if (action == PUT_ACTION) { + if (myDet->externalCommunicationType(std::string(args[1])) == GET_EXTERNAL_COMMUNICATION_MODE) + return helpTiming(action); + myDet->setExternalCommunicationMode(myDet->externalCommunicationType(std::string(args[1])), detPos); + } + return myDet->externalCommunicationType(myDet->setExternalCommunicationMode(GET_EXTERNAL_COMMUNICATION_MODE, detPos)); +} +std::string slsDetectorCommand::helpTiming(int action) { + + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) + os << std::string("timing \t gets the timing mode of the detector (auto, trigger, ro_trigger, gating, triggered_gating)\n"); + if (action == PUT_ACTION || action == HELP_ACTION) + os << std::string("timing mode \t sets synchronization mode of the detector. Can be auto, trigger, ro_trigger, gating, triggered_gating \n"); + return os.str(); +} + +std::string slsDetectorCommand::cmdTimer(int narg, char *args[], int action, int detPos) { + timerIndex index; + int64_t t = -1, ret; + double val, rval; + + char answer[1000]; + + if (action == HELP_ACTION) + return helpTimer(action); + + if (cmd == "exptime") + index = ACQUISITION_TIME; + else if (cmd == "subexptime") + index = SUBFRAME_ACQUISITION_TIME; + else if (cmd == "period") + index = FRAME_PERIOD; + else if (cmd == "subdeadtime") + index = SUBFRAME_DEADTIME; + else if (cmd == "delay") + index = DELAY_AFTER_TRIGGER; + else if (cmd == "gates") + index = GATES_NUMBER; + else if (cmd == "frames") + index = FRAME_NUMBER; + else if (cmd == "cycles") + index = CYCLES_NUMBER; + else if (cmd == "measurements") + index = MEASUREMENTS_NUMBER; + else if (cmd == "samples") + index = SAMPLES; + else if (cmd == "storagecells") + index = STORAGE_CELL_NUMBER; + else if (cmd == "storagecell_delay") + index = STORAGE_CELL_DELAY; + else if (cmd == "storagecell_start") { + myDet->setOnline(ONLINE_FLAG, detPos); + if (action == PUT_ACTION) { + int ival = -1; + if (!sscanf(args[1], "%d", &ival)) + return std::string("cannot scan storage cell start value ") + std::string(args[1]); + myDet->setStoragecellStart(ival, detPos); + } + sprintf(answer, "%d", myDet->setStoragecellStart(-1, detPos)); + return std::string(answer); + } else + return std::string("could not decode timer ") + cmd; + + if (action == PUT_ACTION) { + if (sscanf(args[1], "%lf", &val)) + ; //printf("value:%0.9lf\n",val); + else + return std::string("cannot scan timer value ") + std::string(args[1]); + + // timer + if (index == ACQUISITION_TIME || index == SUBFRAME_ACQUISITION_TIME || + index == FRAME_PERIOD || index == DELAY_AFTER_TRIGGER || + index == SUBFRAME_DEADTIME || index == STORAGE_CELL_DELAY) { + // +0.5 for precision of eg.0.0000325 + t = (val * 1E9 + 0.5); + } else + t = (int64_t)val; + } + + myDet->setOnline(ONLINE_FLAG, detPos); + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + + ret = myDet->setTimer(index, t, detPos); + + if ((ret != -1) && (index == ACQUISITION_TIME || index == SUBFRAME_ACQUISITION_TIME || + index == FRAME_PERIOD || index == DELAY_AFTER_TRIGGER || + index == SUBFRAME_DEADTIME || index == STORAGE_CELL_DELAY)) { + rval = (double)ret * 1E-9; + sprintf(answer, "%0.9f", rval); + } else + sprintf(answer, "%lld", (long long int)ret); + + return std::string(answer); +} + +std::string slsDetectorCommand::helpTimer(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "exptime t \t sets the exposure time in s" << std::endl; + os << "subexptime t \t sets the exposure time of subframe in s" << std::endl; + os << "period t \t sets the frame period in s" << std::endl; + os << "delay t \t sets the delay after trigger in s" << std::endl; + os << "frames t \t sets the number of frames per cycle (e.g. after each trigger)" << std::endl; + os << "cycles t \t sets the number of cycles (e.g. number of triggers)" << std::endl; + os << "samples t \t sets the number of samples expected from the jctb" << std::endl; + os << "storagecells t \t sets number of storage cells per acquisition. For very advanced users only! For JUNGFRAU only. Range: 0-15. The #images = #frames * #cycles * (#storagecells+1)." << std::endl; + os << "storagecell_start t \t sets the storage cell that stores the first acquisition of the series. Default is 15(0xf). For very advanced users only! For JUNGFRAU only. Range: 0-15." << std::endl; + os << "storagecell_delay t \t sets additional time to t between 2 storage cells. For very advanced users only! For JUNGFRAU only. Range: 0-1638375 ns (resolution of 25ns).. " << std::endl; + os << "subdeadtime t \t sets sub frame dead time in s. Subperiod is set in the detector = subexptime + subdeadtime. This value is normally a constant in the config file. Used in EIGER only in 32 bit mode. " << std::endl; + os << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + + os << "exptime \t gets the exposure time in s" << std::endl; + os << "subexptime \t gets the exposure time of subframe in s" << std::endl; + os << "period \t gets the frame period in s" << std::endl; + os << "delay \t gets the delay after trigger in s" << std::endl; + os << "frames \t gets the number of frames per cycle (e.g. after each trigger)" << std::endl; + os << "cycles \t gets the number of cycles (e.g. number of triggers)" << std::endl; + os << "samples \t gets the number of samples expected from the jctb" << std::endl; + os << "storagecells \t gets number of storage cells per acquisition.For JUNGFRAU only." << std::endl; + os << "storagecell_start \t gets the storage cell that stores the first acquisition of the series." << std::endl; + os << "storagecell_delay \tgets additional time between 2 storage cells. " << std::endl; + os << "subperiod \t gets sub frame dead time in s. Used in EIGER in 32 bit only." << std::endl; + os << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdTimeLeft(int narg, char *args[], int action, int detPos) { + timerIndex index; + int64_t ret; + double rval; + + char answer[1000]; + + if (action == HELP_ACTION) + return helpTimeLeft(action); + + if (cmd == "exptimel") + index = ACQUISITION_TIME; + else if (cmd == "periodl") + index = FRAME_PERIOD; + else if (cmd == "delayl") + index = DELAY_AFTER_TRIGGER; + else if (cmd == "gatesl") + index = GATES_NUMBER; + else if (cmd == "framesl") + index = FRAME_NUMBER; + else if (cmd == "cyclesl") + index = CYCLES_NUMBER; + else if (cmd == "now") + index = ACTUAL_TIME; + else if (cmd == "timestamp") + index = MEASUREMENT_TIME; + else if (cmd == "nframes") + index = FRAMES_FROM_START; + else if (cmd == "measuredperiod") + index = MEASURED_PERIOD; + else if (cmd == "measuredsubperiod") + index = MEASURED_SUBPERIOD; + else + return std::string("could not decode timer ") + cmd; + + if (action == PUT_ACTION) { + return std::string("cannot set ") + std::string(args[1]); + } + + myDet->setOnline(ONLINE_FLAG, detPos); + + ret = myDet->getTimeLeft(index, detPos); + + if ((ret != -1) && (index == ACQUISITION_TIME || index == FRAME_PERIOD || index == DELAY_AFTER_TRIGGER || index == ACTUAL_TIME || index == MEASUREMENT_TIME || + index == MEASURED_PERIOD || index == MEASURED_SUBPERIOD)) + rval = (double)ret * 1E-9; + else + rval = ret; + + sprintf(answer, "%0.9f", rval); + return std::string(answer); +} + +std::string slsDetectorCommand::helpTimeLeft(int action) { + + std::ostringstream os; + if (action == GET_ACTION || action == HELP_ACTION) { + + os << "exptimel \t gets the exposure time left" << std::endl; + os << "periodl \t gets the frame period left" << std::endl; + os << "delayl \t gets the delay left" << std::endl; + os << "framesl \t gets the number of frames left" << std::endl; + os << "cyclesl \t gets the number of cycles left" << std::endl; + os << "measuredperiod \t gets the measured frame period (time between last frame and the previous one) in s. For Eiger only. Makes sense only for acquisitions of more than 1 frame." << std::endl; + os << "measuredsubperiod \t gets the measured subframe period (time between last subframe and the previous one) in s. For Eiger only and in 32 bit mode." << std::endl; + os << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdSpeed(int narg, char *args[], int action, int detPos) { + + speedVariable index; + int t = -1, ret = 0, mode = 0; + + char answer[1000]; + + if (action == HELP_ACTION) + return helpSpeed(action); + + if (cmd == "clkdivider") { + index = CLOCK_DIVIDER; + } + else if (cmd == "adcclk") { + index = ADC_CLOCK; + } + else if (cmd == "dbitclk") { + index = DBIT_CLOCK; + } + else if (cmd == "adcphase") { + index = ADC_PHASE; + if ((action == PUT_ACTION && narg > 2 && std::string(args[2]) == "deg") || + (action == GET_ACTION && narg > 1 && std::string(args[1]) == "deg")) { + mode = 1; + } + } + else if (cmd == "dbitphase") { + index = DBIT_PHASE; + if ((action == PUT_ACTION && narg > 2 && std::string(args[2]) == "deg") || + (action == GET_ACTION && narg > 1 && std::string(args[1]) == "deg")) { + mode = 1; + } + } + else if (cmd == "maxadcphaseshift") { + index = MAX_ADC_PHASE_SHIFT; + if (action == PUT_ACTION) { + return std::string("cannot put"); + } + } + else if (cmd == "maxdbitphaseshift") { + index = MAX_DBIT_PHASE_SHIFT; + if (action == PUT_ACTION) { + return std::string("cannot put"); + } + } + else if (cmd == "adcpipeline") { + index = ADC_PIPELINE; + } + else if (cmd == "dbitpipeline") { + index = DBIT_PIPELINE; + } + else + return std::string("could not decode speed variable ") + cmd; + + if (action == PUT_ACTION) { + if (sscanf(args[1], "%d", &t)) + ; + else + return std::string("cannot scan speed value ") + std::string(args[1]); + } + + myDet->setOnline(ONLINE_FLAG, detPos); + + ret = myDet->setSpeed(index, t, mode, detPos); + + sprintf(answer, "%d", ret); + return std::string(answer); +} + +std::string slsDetectorCommand::helpSpeed(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "clkdivider c \t sets readout clock divider. EIGER, JUNGFRAU [0(fast speed), 1(half speed), 2(quarter speed)]. Jungfrau, full speed is not implemented and overwrites adcphase to recommended default. Not for Gotthard." << std::endl; + os << "adcclk c \tSets ADC clock frequency in MHz. CTB & Moench only. It also resets adcphase." << std::endl; + os << "dbitclk c \tSets the clock frequency of the latching of the digital bits in MHz. CTB & Moench only. It also resets dbit phase." << std::endl; + os << "adcphase c [deg]\t Sets phase of the ADC clock to i. i is the shift or in degrees if deg is used. deg is optional & only for CTB, Moench & Jungfrau. For CTB & Moench, adcphase is reset if adcclk is changed. For Jungfrau, adcphase changed to defaults if clkdivider changed. Jungfrau, CTB & Moench, these are absolute values with limits. Gotthard, relative phase shift. Not for Eiger." << std::endl; + os << "dbitphase c [deg]\t Sets the phase of the clock for latching of the digital bits to i. i is the shift or in degrees if deg is used. deg is optional. dbitphase is also reset if dbitclk is changed. These are absolute values with limits. for CTB & Moench only." << std::endl; + os << "adcpipeline c \t Sets the pipeline of the ADC. For CTB & Moench only." << std::endl; + os << "dbitpipeline c \t Sets the pipeline of the latching of the digital bits. For CTB & Moench only." << std::endl; + os << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "clkdivider \t Gets readout clock divider. EIGER, JUNGFRAU [0(fast speed), 1(half speed), 2(quarter speed)]. Jungfrau, full speed is not implemented and overwrites adcphase to recommended default. Not for Gotthard." << std::endl; + os << "adcclk \tGets ADC clock frequency in MHz. CTB & Moench only. It also resets adcphase." << std::endl; + os << "dbitclk \tGets the clock frequency of the latching of the digital bits in MHz. CTB & Moench only. It also resets dbit phase." << std::endl; + os << "adcphase [deg]\t Gets phase of the ADC clock. unit is number of shifts or in degrees if deg is used. deg is optional & only for CTB, Moench & Jungfrau. For CTB & Moench, adcphase is reset if adcclk is changed. For Jungfrau, adcphase changed to defaults if clkdivider changed. Jungfrau, CTB & Moench, these are absolute values with limits. Gotthard, relative phase shift. Not for Eiger." << std::endl; + os << "dbitphase [deg]\t Gets the phase of the clock for latching of the digital bits. unit is number of shifts or in degrees if deg is used. deg is optional. dbitphase is also reset if dbitclk is changed. These are absolute values with limits. for CTB & Moench only." << std::endl; + os << "adcpipeline \t Gets the pipeline of the ADC. For CTB & Moench only." << std::endl; + os << "dbitpipeline \t Gets the pipeline of the latching of the digital bits. For CTB & Moench only." << std::endl; + os << "maxadcphaseshift \t Gets maximum phase shift of the ADC clock. CTB,Moench and Jungfrau only." << std::endl; + os << "maxdbitphaseshift \t Gets maximum phase shift of the clock for latching of the digital bits. CTB & Moench only." << std::endl; + os << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdAdvanced(int narg, char *args[], int action, int detPos) { + + + char answer[1000] = ""; + + if (action == HELP_ACTION) + return helpAdvanced(action); + + if (cmd == "flags") { + + readOutFlags flag = GET_READOUT_FLAGS; + + if (action == PUT_ACTION) { + std::string sval = std::string(args[1]); + if (sval == "none") + flag = NORMAL_READOUT; + else if (sval == "storeinram") + flag = STORE_IN_RAM; + else if (sval == "tot") + flag = TOT_MODE; + else if (sval == "continous") + flag = CONTINOUS_RO; + else if (sval == "parallel") + flag = PARALLEL; + else if (sval == "nonparallel") + flag = NONPARALLEL; + else if (sval == "safe") + flag = SAFE; + else if (sval == "digital") + flag = DIGITAL_ONLY; + else if (sval == "analog_digital") + flag = ANALOG_AND_DIGITAL; + else if (sval == "overflow") + flag = SHOW_OVERFLOW; + else if (sval == "nooverflow") + flag = NOOVERFLOW; + else + return std::string("could not scan flag ") + std::string(args[1]); + } + + myDet->setOnline(ONLINE_FLAG, detPos); + int retval = myDet->setReadOutFlags(flag, detPos); + + // std::cout << std::hex << flag << " " << retval << std::endl; + + if (retval == NORMAL_READOUT) + return std::string("none"); + + if (retval & STORE_IN_RAM) + strcat(answer, "storeinram "); + if (retval & TOT_MODE) + strcat(answer, "tot "); + if (retval & CONTINOUS_RO) + strcat(answer, "continous "); + if (retval & PARALLEL) + strcat(answer, "parallel "); + if (retval & NONPARALLEL) + strcat(answer, "nonparallel "); + if (retval & SAFE) + strcat(answer, "safe "); + if (retval & DIGITAL_ONLY) + strcat(answer, "digital "); + if (retval & ANALOG_AND_DIGITAL) + strcat(answer, "analog_digital "); + if (retval & SHOW_OVERFLOW) + strcat(answer, "overflow "); + if (retval & NOOVERFLOW) + strcat(answer, "nooverflow "); + if (strlen(answer)) + return std::string(answer); + + return std::string("unknown"); + + } else if (cmd == "extsig") { + externalSignalFlag flag = GET_EXTERNAL_SIGNAL_FLAG; + int is = -1; + if (sscanf(args[0], "extsig:%d", &is)) + ; + else + return std::string("could not scan signal number ") + std::string(args[0]); + + if (action == PUT_ACTION) { + flag = myDet->externalSignalType(args[1]); + if (flag == GET_EXTERNAL_SIGNAL_FLAG) + return std::string("could not scan external signal mode ") + std::string(args[1]); + } + myDet->setOnline(ONLINE_FLAG, detPos); + + return myDet->externalSignalType(myDet->setExternalSignalFlags(flag, is, detPos)); + + } else if (cmd == "programfpga") { + if (action == GET_ACTION) + return std::string("cannot get"); + if (strstr(args[1], ".pof") == nullptr) + return std::string("wrong usage: programming file should have .pof extension"); + std::string sval = std::string(args[1]); + myDet->setOnline(ONLINE_FLAG, detPos); + if (myDet->programFPGA(sval, detPos) == OK) + return std::string("successful"); + return std::string("failed"); + } + + else if (cmd == "resetfpga") { + if (action == GET_ACTION) + return std::string("cannot get"); + myDet->setOnline(ONLINE_FLAG, detPos); + if (myDet->resetFPGA(detPos) == OK) + return std::string("successful"); + return std::string("failed"); + } + + else if (cmd == "copydetectorserver") { + if (action == GET_ACTION) + return std::string("cannot get"); + if (narg < 3) + return ("wrong usage." + helpAdvanced(PUT_ACTION)); + std::string sval = std::string(args[1]); + std::string pval = std::string(args[2]); + myDet->setOnline(ONLINE_FLAG, detPos); + if (myDet->copyDetectorServer(sval, pval, detPos) == OK) + return std::string("successful"); + return std::string("failed"); + } + + else if (cmd == "rebootcontroller") { + if (action == GET_ACTION) + return std::string("cannot get"); + myDet->setOnline(ONLINE_FLAG, detPos); + if (myDet->rebootController(detPos) == OK) + return std::string("successful"); + return std::string("failed"); + } + + else if (cmd == "update") { + if (action == GET_ACTION) + return std::string("cannot get"); + if (narg < 4) + return ("wrong usage." + helpAdvanced(PUT_ACTION)); + // pof + if (strstr(args[3], ".pof") == nullptr) + return std::string("wrong usage: programming file should have .pof extension"); + std::string sval = std::string(args[1]); + std::string pval = std::string(args[2]); + std::string fval = std::string(args[3]); + myDet->setOnline(ONLINE_FLAG, detPos); + if (myDet->update(sval, pval, fval, detPos) == OK) + return std::string("successful"); + return std::string("failed"); + } + + else if (cmd == "powerchip") { + char ans[100]; + myDet->setOnline(ONLINE_FLAG, detPos); + if (action == PUT_ACTION) { + int ival = -1; + if (!sscanf(args[1], "%d", &ival)) + return std::string("could not scan powerchip parameter " + std::string(args[1])); + myDet->powerChip(ival, detPos); + } + sprintf(ans, "%d", myDet->powerChip(-1, detPos)); + return std::string(ans); + } + + else if (cmd == "led") { + myDet->setOnline(ONLINE_FLAG, detPos); + if (action == PUT_ACTION) { + int ival = -1; + if (!sscanf(args[1], "%d", &ival)) + return std::string("could not scan led parameter " + std::string(args[1])); + myDet->setLEDEnable(ival, detPos); + } + return std::to_string(myDet->setLEDEnable(-1, detPos)); + } + + else if (cmd == "diodelay") { + if (action == GET_ACTION) { + return std::string("Cannot get"); + } + myDet->setOnline(ONLINE_FLAG, detPos); + + uint64_t pinMask = -1; + if (!sscanf(args[1], "%lx", &pinMask)) + return std::string("could not scan diodelay pin mask(in hex) " + std::string(args[1])); + int delay = -1; + if (!sscanf(args[2], "%d", &delay)) + return std::string("could not scan diodelay delay " + std::string(args[2])); + + int retval = myDet->setDigitalIODelay(pinMask, delay, detPos); + if (retval == -1) + return std::to_string(-1); + return std::string((retval == OK) ? "successful" : "failed"); + } + + else if (cmd == "auto_comp_disable") { + char ans[100]; + myDet->setOnline(ONLINE_FLAG, detPos); + if (action == PUT_ACTION) { + int ival = -1; + if (!sscanf(args[1], "%d", &ival)) + return std::string("could not scan auto_comp_control parameter " + std::string(args[1])); + myDet->setAutoComparatorDisableMode(ival, detPos); + } + sprintf(ans, "%d", myDet->setAutoComparatorDisableMode(-1, detPos)); + return std::string(ans); + } else + return std::string("unknown command ") + cmd; +} + +std::string slsDetectorCommand::helpAdvanced(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + + os << "extsig:i mode \t sets the mode of the external signal i. can be \n \t \t \t off, \n \t \t \t gate_in_active_high, \n \t \t \t gate_in_active_low, \n \t \t \t trigger_in_rising_edge, \n \t \t \t trigger_in_falling_edge, \n \t \t \t ro_trigger_in_rising_edge, \n \t \t \t ro_trigger_in_falling_edge, \n \t \t \t gate_out_active_high, \n \t \t \t gate_out_active_low, \n \t \t \t trigger_out_rising_edge, \n \t \t \t trigger_out_falling_edge, \n \t \t \t ro_trigger_out_rising_edge, \n \t \t \t ro_trigger_out_falling_edge" << std::endl; + os << "flags mode \t sets the readout flags to mode. can be none, storeinram, tot, continous, parallel, nonparallel, safe, digital, analog_digital, overlow, nooverflow, unknown." << std::endl; + + os << "programfpga f \t programs the fpga with file f (with .pof extension)." << std::endl; + os << "resetfpga f \t resets fpga, f can be any value" << std::endl; + os << "copydetectorserver s p \t copies the detector server s via tftp from pc with hostname p and changes respawn server. Not for Eiger. " << std::endl; + os << "rebootcontroller \t reboot controler blackfin of the detector. Not for Eiger." << std::endl; + os << "update s p f \t updates the firmware to f and detector server to f from host p via tftp and then reboots controller (blackfin). Not for Eiger. " << std::endl; + os << "led s \t sets led status (0 off, 1 on)" << std::endl; + os << "diodelay m v \tsets the delay for the digital IO pins selected by mask m and delay set by v. mask is upto 64 bits in hex, delay max is 775ps, and set in steps of 25 ps. Used for MOENCH/CTB only." << std::endl; + os << "powerchip i \t powers on or off the chip. i = 1 for on, i = 0 for off" << std::endl; + os << "auto_comp_disable i \t Currently not implemented. this mode disables the on-chip gain switching comparator automatically after 93.75% of exposure time (only for longer than 100us). 1 enables mode, 0 disables mode. By default, mode is disabled (comparator is enabled throughout). (JUNGFRAU only). " << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + + os << "extsig:i \t gets the mode of the external signal i. can be \n \t \t \t off, \n \t \t \t gate_in_active_high, \n \t \t \t gate_in_active_low, \n \t \t \t trigger_in_rising_edge, \n \t \t \t trigger_in_falling_edge, \n \t \t \t ro_trigger_in_rising_edge, \n \t \t \t ro_trigger_in_falling_edge, \n \t \t \t gate_out_active_high, \n \t \t \t gate_out_active_low, \n \t \t \t trigger_out_rising_edge, \n \t \t \t trigger_out_falling_edge, \n \t \t \t ro_trigger_out_rising_edge, \n \t \t \t ro_trigger_out_falling_edge" << std::endl; + + os << "flags \t gets the readout flags. can be none, storeinram, tot, continous, parallel, nonparallel, safe, digital, analog_digital, overflow, nooverflow, unknown" << std::endl; + os << "led \t returns led status (0 off, 1 on)" << std::endl; + os << "powerchip \t gets if the chip has been powered on or off" << std::endl; + os << "auto_comp_disable \t Currently not implemented. gets if the automatic comparator diable mode is enabled/disabled" << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdConfiguration(int narg, char *args[], int action, int detPos) { + + if (action == HELP_ACTION) + return helpConfiguration(action); + + std::string sval; + + if (narg < 2 && cmd != "rx_printconfig") + return std::string("should specify I/O file"); + + myDet->setOnline(ONLINE_FLAG, detPos); + + if (cmd == "config") { + if (action == PUT_ACTION) { + sval = std::string(args[1]); + myDet->readConfigurationFile(sval); + } else if (action == GET_ACTION) { + sval = std::string(args[1]); + myDet->writeConfigurationFile(sval); + } + return sval; + } else if (cmd == "rx_printconfig") { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + if (action == PUT_ACTION) + return std::string("cannot put"); + myDet->printReceiverConfiguration(logINFO, detPos); + return std::string(""); + } else if (cmd == "parameters") { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + if (action == PUT_ACTION) { + sval = std::string(args[1]); + myDet->retrieveDetectorSetup(sval, 0); + } else if (action == GET_ACTION) { + sval = std::string(args[1]); + myDet->dumpDetectorSetup(sval, 0); + } + return sval; + } else if (cmd == "setup") { + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + if (action == PUT_ACTION) { + sval = std::string(args[1]); + myDet->retrieveDetectorSetup(sval, 2); + } else if (action == GET_ACTION) { + sval = std::string(args[1]); + myDet->dumpDetectorSetup(sval, 2); + } + return sval; + } + return std::string("could not decode conf mode"); +} + +std::string slsDetectorCommand::helpConfiguration(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + + os << "config fname \t sets the detector to the configuration contained in fname" << std::endl; + os << "parameters fname \t sets the detector parameters to those contained in fname" << std::endl; + os << "setup fname \t sets the detector complete detector setup to that contained in fname (extensions automatically generated), including trimfiles, ff coefficients etc." << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "rx_printconfig \t prints the receiver configuration" << std::endl; + os << "config fname \t saves the detector to the configuration to fname" << std::endl; + os << "parameters fname \t saves the detector parameters to fname" << std::endl; + os << "setup fname \t saves the detector complete detector setup to fname (extensions automatically generated), including trimfiles, ff coefficients etc." << std::endl; + } + + return os.str(); +} + +std::string slsDetectorCommand::cmdReceiver(int narg, char *args[], int action, int detPos) { + char answer[100]; + int ival = -1; + + if (action == HELP_ACTION) + return helpReceiver(action); + + myDet->setOnline(ONLINE_FLAG, detPos); + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + + if (cmd == "receiver") { + if (action == PUT_ACTION) { + if (!strcasecmp(args[1], "start")) + myDet->startReceiver(detPos); + else if (!strcasecmp(args[1], "stop")) + myDet->stopReceiver(detPos); + else + return helpReceiver(action); + } + return myDet->runStatusType(myDet->getReceiverStatus(detPos)); + } + + else if (cmd == "framescaught") { + if (action == PUT_ACTION) + return std::string("cannot put"); + else { + sprintf(answer, "%d", myDet->getFramesCaughtByReceiver(detPos)); + return std::string(answer); + } + } + + else if (cmd == "resetframescaught") { + if (action == GET_ACTION) + return std::string("cannot get"); + else { + if (myDet->resetFramesCaught(detPos) == OK) + strcpy(answer, "successful"); + else + strcpy(answer, "failed"); + return std::string(answer); + } + } + + else if (cmd == "frameindex") { + if (action == PUT_ACTION) + return std::string("cannot put"); + else { + sprintf(answer, "%d", myDet->getReceiverCurrentFrameIndex(detPos)); + return std::string(answer); + } + } else if (cmd == "r_readfreq") { + if (action == PUT_ACTION) { + if (!sscanf(args[1], "%d", &ival)) + return std::string("Could not scan read frequency mode ") + std::string(args[1]); + if (ival >= 0) + myDet->setReceiverStreamingFrequency(ival, detPos); + } + sprintf(answer, "%d", myDet->setReceiverStreamingFrequency(-1, detPos)); + return std::string(answer); + + } + + else if (cmd == "tengiga") { + if (action == PUT_ACTION) { + if (!sscanf(args[1], "%d", &ival)) + return std::string("Could not scan tengiga input ") + std::string(args[1]); + if (ival >= 0) + sprintf(answer, "%d", myDet->enableTenGigabitEthernet(ival, detPos)); + } else + sprintf(answer, "%d", myDet->enableTenGigabitEthernet(-1, detPos)); + return std::string(answer); + + } + + else if (cmd == "rx_fifodepth") { + if (action == PUT_ACTION) { + if (!sscanf(args[1], "%d", &ival)) + return std::string("Could not scan rx_fifodepth input ") + std::string(args[1]); + if (ival >= 0) + sprintf(answer, "%d", myDet->setReceiverFifoDepth(ival, detPos)); + } else + sprintf(answer, "%d", myDet->setReceiverFifoDepth(-1, detPos)); + return std::string(answer); + + } + + else if (cmd == "r_silent") { + if (action == PUT_ACTION) { + if (!sscanf(args[1], "%d", &ival)) + return std::string("Could not scan r_online input ") + std::string(args[1]); + if (ival >= 0) + sprintf(answer, "%d", myDet->setReceiverSilentMode(ival, detPos)); + } else + sprintf(answer, "%d", myDet->setReceiverSilentMode(-1, detPos)); + return std::string(answer); + + } + + else if (cmd == "r_framesperfile") { + if (action == PUT_ACTION) { + if (sscanf(args[1], "%d", &ival)) { + myDet->setFramesPerFile(ival, detPos); + } else + return std::string("could not scan max frames per file\n"); + } + memset(answer, 0, 100); + sprintf(answer, "%d", myDet->getFramesPerFile(detPos)); + return std::string(answer); + } + + else if (cmd == "r_discardpolicy") { + if (action == PUT_ACTION) { + frameDiscardPolicy f = myDet->getReceiverFrameDiscardPolicy(std::string(args[1])); + if (f == GET_FRAME_DISCARD_POLICY) + return std::string("could not scan frame discard policy. Options: nodiscard, discardempty, discardpartial\n"); + myDet->setReceiverFramesDiscardPolicy(f); + } + return myDet->getReceiverFrameDiscardPolicy(myDet->setReceiverFramesDiscardPolicy(GET_FRAME_DISCARD_POLICY, detPos)); + } + + else if (cmd == "r_padding") { + if (action == PUT_ACTION) { + if (sscanf(args[1], "%d", &ival)) { + myDet->setPartialFramesPadding(ival, detPos); + } else + return std::string("could not scan receiver padding enable\n"); + } + memset(answer, 0, 100); + sprintf(answer, "%d", myDet->getPartialFramesPadding(detPos)); + return std::string(answer); + } + + else if (cmd == "rx_jsonaddheader") { + if (action == PUT_ACTION) { + myDet->setAdditionalJsonHeader(args[1], detPos); + } + return myDet->getAdditionalJsonHeader(detPos); + } + + else if (cmd == "rx_jsonpara") { + if (action == PUT_ACTION) { + myDet->setAdditionalJsonParameter(args[1], args[2], detPos); + } + return myDet->getAdditionalJsonParameter(args[1], detPos); + } + + return std::string("could not decode command"); +} + +std::string slsDetectorCommand::helpReceiver(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "receiver [status] \t starts/stops the receiver to listen to detector packets. - can be start, stop." << std::endl; + os << "resetframescaught [any value] \t resets frames caught by receiver" << std::endl; + os << "r_readfreq \t sets the gui read frequency of the receiver, 0 if gui requests frame, >0 if receiver sends every nth frame to gui" << std::endl; + os << "tengiga \t sets system to be configure for 10Gbe if set to 1, else 1Gbe if set to 0" << std::endl; + os << "rx_fifodepth [val]\t sets receiver fifo depth to val" << std::endl; + os << "r_silent [i]\t sets receiver in silent mode, ie. it will not print anything during real time acquisition. 1 sets, 0 unsets." << std::endl; + os << "r_framesperfile s\t sets the number of frames per file in receiver. 0 means infinite or all frames in a single file." << std::endl; + os << "r_discardpolicy s\t sets the frame discard policy in the receiver. nodiscard (default) - discards nothing, discardempty - discard only empty frames, discardpartial(fastest) - discards all partial frames." << std::endl; + os << "r_padding s\t enables/disables partial frames to be padded in the receiver. 0 does not pad partial frames(fastest), 1 (default) pads partial frames." << std::endl; + os << "rx_jsonaddheader [t]\n sets additional json header to be streamed " + "out with the zmq from receiver. Default is empty. t must be in the format '\"label1\":\"value1\",\"label2\":\"value2\"' etc." + "Use only if it needs to be processed by an intermediate process." << std::endl; + os << "rx_jsonpara [k] [v]\n sets value to v for additional json header parameter k to be streamed out with the zmq from receiver." << std::endl; + + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "receiver \t returns the status of receiver - can be running or idle" << std::endl; + os << "framescaught \t returns the number of frames caught by receiver(average for multi)" << std::endl; + os << "frameindex \t returns the current frame index of receiver(average for multi)" << std::endl; + os << "r_readfreq \t returns the gui read frequency of the receiver" << std::endl; + os << "tengiga \t returns 1 if the system is configured for 10Gbe else 0 for 1Gbe" << std::endl; + os << "rx_fifodepth \t returns receiver fifo depth" << std::endl; + os << "r_silent \t returns receiver silent mode enable. 1 is silent, 0 not silent." << std::endl; + os << "r_framesperfile \t gets the number of frames per file in receiver. 0 means infinite or all frames in a single file." << std::endl; + os << "r_discardpolicy \t gets the frame discard policy in the receiver. nodiscard (default) - discards nothing, discardempty - discard only empty frames, discardpartial(fastest) - discards all partial frames." << std::endl; + os << "r_padding \t gets partial frames padding enable in the receiver. 0 does not pad partial frames(fastest), 1 (default) pads partial frames." << std::endl; + os << "rx_jsonaddheader \n gets additional json header to be streamed " + "out with the zmq from receiver." << std::endl; + os << "rx_jsonpara [k] \n gets value of additional json header parameter k to be streamed out with the zmq from receiver. If empty, then no parameter found." << std::endl; + + } + return os.str(); +} + +std::string slsDetectorCommand::helpPattern(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "pattern fname \t loads pattern file" << std::endl; + os << "patword addr word \t writes pattern word - only very advanced users!" << std::endl; + os << "patioctrl reg\t configures inputs/outputs of the chiptest board - only advanced users!" << std::endl; + os << "patclkctrl reg\t configures output clk enable of the chiptest board- only advanced users! " << std::endl; + os << "patlimits addr1 addr2\t defines pattern limits between addr1 and addr2" << std::endl; + os << "patloop0 addr1 adrr2 \t configures the limits of the 0 loop " << std::endl; + os << "patloop1 addr1 adrr2 \t configures the limits of the 1 loop " << std::endl; + os << "patloop2 addr1 adrr2 \t configures the limits of the 2 loop " << std::endl; + os << "patnloop0 n \t sets number of cycles of the 0 loop " << std::endl; + os << "patnloop1 n \t sets number of cycles of the 1 loop " << std::endl; + os << "patnloop2 n \t sets number of cycles of the 2 loop " << std::endl; + os << "patwait0 addr \t configures pattern wait 0 address " << std::endl; + os << "patwait1 addr \t configures pattern wait 1 address " << std::endl; + os << "patwait2 addr \t configures pattern wait 2 address " << std::endl; + os << "patwaittime0 nclk \t sets wait 0 waiting time in clock number " << std::endl; + os << "patwaittime1 nclk \t sets wait 1 waiting time in clock number " << std::endl; + os << "patwaittime2 nclk \t sets wait 2 waiting time in clock number " << std::endl; + os << "patmask m \t sets the 64 bit mask (hex) applied to every pattern. Only the bits from patsetbit are selected to mask for the corresponding bit value from m mask" << std::endl; + os << "patsetbit m \t selects bits (hex) of the 64 bits that the patmask will be applied to every pattern. Only the bits from m mask are selected to mask for the corresponding bit value from patmask." << std::endl; + os << "adcinvert mask\t sets the adcinversion mask (hex)" << std::endl; + os << "adcdisable mask\t sets the adcdisable mask (hex)" << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "pattern \t cannot get" << std::endl; + os << "patword \t cannot get" << std::endl; + os << "patioctrl \t returns inputs/outputs of the chiptest board - only advanced users!" << std::endl; + os << "patclkctrl\t returns output clk enable of the chiptest board- only advanced users! " << std::endl; + os << "patlimits \t returns pattern limits between addr1 and addr2" << std::endl; + os << "patloop0 \t returns the limits of the 0 loop " << std::endl; + os << "patloop1 \t returns the limits of the 1 loop " << std::endl; + os << "patloop2 \t returns the limits of the 2 loop " << std::endl; + os << "patnloop0 \t returns the number of cycles of the 0 loop " << std::endl; + os << "patnloop1 \t returns the number of cycles of the 1 loop " << std::endl; + os << "patnloop2 \t returns the number of cycles of the 2 loop " << std::endl; + os << "patwait0 \t returns the pattern wait 0 address " << std::endl; + os << "patwait1 \t returns the pattern wait 1 address " << std::endl; + os << "patwait2 \t returns the pattern wait 2 address " << std::endl; + os << "patwaittime0 \t returns the wait 0 waiting time in clock number " << std::endl; + os << "patwaittime1 \t returns the wait 1 waiting time in clock number " << std::endl; + os << "patwaittime2 \t returns the wait 2 waiting time in clock number " << std::endl; + os << "patmask \t gets the 64 bit mask (hex) applied to every pattern." << std::endl; + os << "patsetbit \t gets 64 bit mask (hex) of the selected bits that the patmask will be applied to every pattern. " << std::endl; + os << "adcinvert \t returns the adcinversion mask " << std::endl; + + os << "adcdisable \t returns the adcdisable mask " << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdPattern(int narg, char *args[], int action, int detPos) { + + if (action == HELP_ACTION) + return helpPattern(action); + /******** + + Must implement set ctb functions in slsDetector and multiSlsDetector + + **********/ + std::string fname; + int addr, start, stop, n; + uint64_t word, t; + + myDet->setOnline(ONLINE_FLAG, detPos); + + std::ostringstream os; + if (cmd == "pattern") { + //get fname fron stdin + + if (action == PUT_ACTION) { + fname = std::string(args[1]); + os << myDet->setPattern(fname, detPos); + } else if (action == GET_ACTION) + os << "Cannot get"; + } else if (cmd == "patword") { + + if (action == PUT_ACTION) { + //get addr, word from stdin + + if (narg < 3) + return std::string("wrong usage: should specify both address and value (hexadecimal fomat) "); + + if (sscanf(args[1], "%x", &addr)) + ; + else + return std::string("Could not scan address (hexadecimal fomat) ") + std::string(args[1]); + + if (sscanf(args[2], "%lx", &word)) + ; + else + return std::string("Could not scan value (hexadecimal fomat) ") + std::string(args[2]); + + os << std::hex << myDet->setPatternWord(addr, word, detPos) << std::dec; + } else if (action == GET_ACTION) + os << "Cannot get"; + + } else if (cmd == "patioctrl") { + //get word from stdin + + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%lx", &word)) + ; + else + return std::string("Could not scan value (hexadecimal fomat) ") + std::string(args[1]); + + myDet->setPatternWord(-1, word, detPos); + } + + os << std::hex << myDet->setPatternWord(-1, -1, detPos) << std::dec; + } else if (cmd == "patclkctrl") { + //get word from stdin + + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%lx", &word)) + ; + else + return std::string("Could not scan value (hexadecimal fomat) ") + std::string(args[1]); + + myDet->setPatternWord(-2, word, detPos); + } + + os << std::hex << myDet->setPatternWord(-2, -1, detPos) << std::dec; + + } else if (cmd == "patlimits") { + //get start, stop from stdin + if (action == PUT_ACTION) { + if (narg < 3) + return std::string("wrong usage: should specify both start and stop address (hexadecimal fomat) "); + n = -1; + if (sscanf(args[1], "%x", &start)) + ; + else + return std::string("Could not scan start address (hexadecimal fomat) ") + std::string(args[1]); + + if (sscanf(args[2], "%x", &stop)) + ; + else + return std::string("Could not scan stop address (hexadecimal fomat) ") + std::string(args[2]); + + myDet->setPatternLoops(-1, start, stop, n, detPos); + } + + start = -1; + stop = -1; + n = -1; + myDet->setPatternLoops(-1, start, stop, n, detPos); + os << std::hex << start << " " << stop; // << " "<< std::dec << n ; + } else if (cmd == "patloop0") { + //get start, stop from stdin + + //get start, stop from stdin + if (action == PUT_ACTION) { + if (narg < 3) + return std::string("wrong usage: should specify both start and stop address (hexadecimal fomat) "); + n = -1; + if (sscanf(args[1], "%x", &start)) + ; + else + return std::string("Could not scan start address (hexadecimal fomat) ") + std::string(args[1]); + + if (sscanf(args[2], "%x", &stop)) + ; + else + return std::string("Could not scan stop address (hexadecimal fomat) ") + std::string(args[2]); + + myDet->setPatternLoops(0, start, stop, n, detPos); + } + + start = -1; + stop = -1; + n = -1; + myDet->setPatternLoops(0, start, stop, n, detPos); + os << std::hex << start << " " << stop; // << " "<< std::dec << n ; + + } else if (cmd == "patloop1") { + + //get start, stop from stdin + if (action == PUT_ACTION) { + if (narg < 3) + return std::string("wrong usage: should specify both start and stop address (hexadecimal fomat) "); + n = -1; + if (sscanf(args[1], "%x", &start)) + ; + else + return std::string("Could not scan start address (hexadecimal fomat) ") + std::string(args[1]); + + if (sscanf(args[2], "%x", &stop)) + ; + else + return std::string("Could not scan stop address (hexadecimal fomat) ") + std::string(args[2]); + + myDet->setPatternLoops(1, start, stop, n, detPos); + } + + start = -1; + stop = -1; + n = -1; + myDet->setPatternLoops(1, start, stop, n, detPos); + os << std::hex << start << " " << stop; // << " "<< std::dec << n ; + + } else if (cmd == "patloop2") { + + //get start, stop from stdin + if (action == PUT_ACTION) { + if (narg < 3) + return std::string("wrong usage: should specify both start and stop address (hexadecimal fomat) "); + n = -1; + if (sscanf(args[1], "%x", &start)) + ; + else + return std::string("Could not scan start address (hexadecimal fomat) ") + std::string(args[1]); + + if (sscanf(args[2], "%x", &stop)) + ; + else + return std::string("Could not scan stop address (hexadecimal fomat) ") + std::string(args[2]); + + myDet->setPatternLoops(2, start, stop, n, detPos); + } + + start = -1; + stop = -1; + n = -1; + myDet->setPatternLoops(2, start, stop, n, detPos); + os << std::hex << start << " " << stop << std::dec; // << " "<< std::dec << n ; + + } else if (cmd == "patnloop0") { + start = -1; + stop = -1; + + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%d", &n)) + ; + else + return std::string("Could not scan number of loops ") + std::string(args[1]); + + myDet->setPatternLoops(0, start, stop, n, detPos); + } + + start = -1; + stop = -1; + n = -1; + myDet->setPatternLoops(0, start, stop, n, detPos); + os << n; + } else if (cmd == "patnloop1") { + + start = -1; + stop = -1; + + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%d", &n)) + ; + else + return std::string("Could not scan number of loops ") + std::string(args[1]); + + myDet->setPatternLoops(1, start, stop, n, detPos); + } + + start = -1; + stop = -1; + n = -1; + myDet->setPatternLoops(1, start, stop, n, detPos); + os << n; + + } else if (cmd == "patnloop2") { + + start = -1; + stop = -1; + + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%d", &n)) + ; + else + return std::string("Could not scan number of loops ") + std::string(args[1]); + + myDet->setPatternLoops(2, start, stop, n, detPos); + } + + start = -1; + stop = -1; + n = -1; + myDet->setPatternLoops(2, start, stop, n, detPos); + os << n; + + } else if (cmd == "patwait0") { + + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%x", &addr)) + ; + else + return std::string("Could not scan wait address (hex format)") + std::string(args[1]); + + myDet->setPatternWaitAddr(0, addr, detPos); + } + + os << std::hex << myDet->setPatternWaitAddr(0, -1, detPos) << std::dec ; + + } else if (cmd == "patwait1") { + + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%x", &addr)) + ; + else + return std::string("Could not scan wait address (hex format)") + std::string(args[1]); + + myDet->setPatternWaitAddr(1, addr, detPos); + } + + os << std::hex << myDet->setPatternWaitAddr(1, -1, detPos) << std::dec ; + + } else if (cmd == "patwait2") { + + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%x", &addr)) + ; + else + return std::string("Could not scan wait address (hex format)") + std::string(args[1]); + + myDet->setPatternWaitAddr(2, addr, detPos); + } + + os << std::hex << myDet->setPatternWaitAddr(2, -1, detPos) << std::dec ; + + } else if (cmd == "patwaittime0") { + + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%ld", &t)) + ; + else + return std::string("Could not scan wait time") + std::string(args[1]); + + myDet->setPatternWaitTime(0, t, detPos); + } + + os << myDet->setPatternWaitTime(0, -1, detPos); + + } else if (cmd == "patwaittime1") { + + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%ld", &t)) + ; + else + return std::string("Could not scan wait time ") + std::string(args[1]); + + myDet->setPatternWaitTime(1, t, detPos); + } + + os << myDet->setPatternWaitTime(1, -1, detPos); + + } else if (cmd == "patwaittime2") { + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%ld", &t)) + ; + else + return std::string("Could not scan wait time ") + std::string(args[1]); + + myDet->setPatternWaitTime(2, t, detPos); + } + + os << myDet->setPatternWaitTime(2, -1, detPos); + + } else if (cmd == "patmask") { + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%lx", &word)) + ; + else + return std::string("Could not scan patmask argument (should be in hex) ") + std::string(args[1]); + + myDet->setPatternMask(word, detPos); + } + + os << "0x" << std::hex << myDet->getPatternMask(detPos) << std::dec; + + } else if (cmd == "patsetbit") { + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%lx", &word)) + ; + else + return std::string("Could not scan patsetbit argument (should be in hex) ") + std::string(args[1]); + + myDet->setPatternBitMask(word, detPos); + } + + os << "0x" << std::hex << myDet->getPatternBitMask(detPos) << std::dec; + + } else if (cmd == "adcinvert") { + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%x", &addr)) + ; + else + return std::string("Could not scan adcinvert reg ") + std::string(args[1]); + + myDet->writeRegister(67, addr, detPos); + } + + os << std::hex << myDet->readRegister(67, detPos) << std::dec ; + + } else if (cmd == "dut_clk") { + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%x", &addr)) + ; + else + return std::string("Could not scan dut_clk reg ") + std::string(args[1]); + + myDet->writeRegister(123, addr, detPos); //0x7b + } + + os << std::hex << myDet->readRegister(123, detPos) << std::dec ; //0x7b + } else if (cmd == "adcdisable") { + + int nroi = 0; + ROI roiLimits[MAX_ROIS]; + + if (action == PUT_ACTION) { + + if (sscanf(args[1], "%x", &addr)) + ; + else + return std::string("Could not scan adcdisable reg ") + std::string(args[1]); + + /******USE ROI?!?!?!?*********/ + // roiLimits[i].xmin;roiLimits[i].xmax;roiLimits[i].ymin;roiLimits[i].ymin;roiLimits[i].ymax + //int mask=1; + int ii = 0; + while (ii < 32) { + ++nroi; + roiLimits[nroi - 1].xmin = ii; + roiLimits[nroi - 1].ymin = 0; + roiLimits[nroi - 1].ymax = 0; + while ((addr & (1 << ii))) { + ++ii; + if (ii >= 32) + break; + } + if (ii >= 32) { + break; + std::cout << "ROI " << nroi << " xmin " << roiLimits[nroi - 1].xmin << " xmax " << roiLimits[nroi - 1].xmax << std::endl; + roiLimits[nroi - 1].xmax = 31; + break; + } + roiLimits[nroi - 1].xmin = ii; + while ((addr & (1 << ii)) == 0) { + ++ii; + if (ii >= 32) + break; + } + roiLimits[nroi - 1].xmax = ii - 1; + if (ii >= 32) { + std::cout << "ROI " << nroi << " xmin " << roiLimits[nroi - 1].xmin << " xmax " << roiLimits[nroi - 1].xmax << std::endl; + ++nroi; + break; + } + std::cout << "ROI " << nroi << " xmin " << roiLimits[nroi - 1].xmin << " xmax " << roiLimits[nroi - 1].xmax << std::endl; + } + std::cout << "********ROI " << nroi << std::endl; + myDet->setROI(nroi - 1, roiLimits, detPos); + // myDet->writeRegister(94,addr, detPos); + // myDet->writeRegister(120,addr, detPos); + } + + const ROI *aa = myDet->getROI(nroi, detPos); + + int reg = 0xffffffff; + if (nroi < 1) + reg = 0; + else { + for (int iroi = 0; iroi < nroi; ++iroi) { + std::cout << iroi << " xmin " << (aa + iroi)->xmin << " xmax " << (aa + iroi)->xmax << std::endl; + for (int ich = (aa + iroi)->xmin; ich <= (aa + iroi)->xmax; ++ich) { + reg &= ~(1 << ich); + } + } + } + os << std::hex << reg << std::dec ; + if (aa != NULL) + delete [] aa; + //os <<" "<< std::hex << myDet->readRegister(120, detPos) << std::dec ; + + } + + else + return helpPattern(action); + + return os.str(); +} + +std::string slsDetectorCommand::helpPulse(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "pulse [n] [x] [y] \t pulses pixel at coordinates (x,y) n number of times" << std::endl; + os << "pulsenmove [n] [x] [y]\t pulses pixel n number of times and moves relatively by x value (x axis) and y value(y axis)" << std::endl; + os << "pulsechip [n] \t pulses chip n number of times, while n=-1 will reset it to normal mode" << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "pulse \t cannot get" << std::endl; + os << "pulsenmove \t cannot get" << std::endl; + os << "pulsechip \t cannot get" << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdPulse(int narg, char *args[], int action, int detPos) { + int retval = FAIL; + + if (action == HELP_ACTION) + return helpPulse(action); + else if (action == GET_ACTION) + return std::string("cannot get ") + cmd; + + myDet->setOnline(ONLINE_FLAG, detPos); + + int ival1 = -1; + if (!sscanf(args[1], "%d", &ival1)) + return std::string("Could not scan 1st argument ") + std::string(args[1]); + + if (std::string(args[0]) == std::string("pulsechip")) + retval = myDet->pulseChip(ival1, detPos); + + else { + //next commands requires 3 addnl. arguments + int ival2 = -1, ival3 = -1; + if (narg < 4) + return std::string("insufficient arguments:\n" + helpPulse(action)); + if (!sscanf(args[2], "%d", &ival2)) + return std::string("Could not scan 2nd argument ") + std::string(args[2]); + if (!sscanf(args[3], "%d", &ival3)) + return std::string("Could not scan 3rd argument ") + std::string(args[3]); + + if (std::string(args[0]) == std::string("pulse")) + retval = myDet->pulsePixel(ival1, ival2, ival3, detPos); + + else if (std::string(args[0]) == std::string("pulsenmove")) + retval = myDet->pulsePixelNMove(ival1, ival2, ival3, detPos); + + else + return std::string("could not decode command") + cmd; + } + + if (retval == OK) + return std::string(" successful"); + else + return std::string(" failed"); +} + + +std::string slsDetectorCommand::helpProcessor(int action) { + + std::ostringstream os; + if (action == PUT_ACTION || action == HELP_ACTION) { + os << "emin [n] \t Sets detector minimum energy threshold to x for Moench (soft setting in processor)" << std::endl; + os << "emax [n] \t Sets detector maximum energy threshold to x for Moench (soft setting in processor)" << std::endl; + os << "framemode [n] \t Sets frame mode for Moench (soft setting in processor). Options: pedestal, newpedestal, flatfield, newflatfield" << std::endl; + os << "detectormode [n] \t Sets detector mode for Moench (soft setting in processor). Options: counting, interpolating, analog" << std::endl; + } + if (action == GET_ACTION || action == HELP_ACTION) { + os << "emin [n] \t Gets detector minimum energy threshold to x for Moench (soft setting in processor)" << std::endl; + os << "emax [n] \t Gets detector maximum energy threshold to x for Moench (soft setting in processor)" << std::endl; + os << "framemode [n] \t Gets frame mode for Moench (soft setting in processor). Options: pedestal, newpedestal, flatfield, newflatfield" << std::endl; + os << "detectormode [n] \t Gets detector mode for Moench (soft setting in processor). Options: counting, interpolating, analog" << std::endl; + } + return os.str(); +} + +std::string slsDetectorCommand::cmdProcessor(int narg, char *args[], int action, int detPos) { + if (action == HELP_ACTION) + return helpProcessor(action); + + myDet->setOnline(ONLINE_FLAG, detPos); + myDet->setReceiverOnline(ONLINE_FLAG, detPos); + + if (cmd == "emin" || cmd == "emax") { + if (action == PUT_ACTION) { + int ival = -1; + if(!sscanf(args[1],"%d",&ival)) + return std::string("cannot parse emin/emax value"); + myDet->setDetectorMinMaxEnergyThreshold((cmd == "emin" ? 0 : 1), ival, detPos); + } + return std::to_string(myDet->setDetectorMinMaxEnergyThreshold(0, -1, detPos)); + } + + else if (cmd == "framemode") { + if (action == PUT_ACTION) { + frameModeType ival = getFrameModeType(args[1]); + if (ival == GET_FRAME_MODE) + return std::string("cannot parse frame mode value"); + myDet->setFrameMode(ival, detPos); + } + return getFrameModeType(frameModeType(myDet->setFrameMode(GET_FRAME_MODE, detPos))); + } + + else if (cmd == "detectormode") { + if (action == PUT_ACTION) { + detectorModeType ival = getDetectorModeType(args[1]); + if (ival == GET_DETECTOR_MODE) + return std::string("cannot parse detector mode value"); + myDet->setDetectorMode(ival, detPos); + } + return getDetectorModeType(detectorModeType(myDet->setDetectorMode(GET_DETECTOR_MODE, detPos))); + } + return std::string("unknown command"); +} + + + diff --git a/slsDetectorSoftware/src/slsDetectorUsers.cpp b/slsDetectorSoftware/src/slsDetectorUsers.cpp new file mode 100755 index 000000000..6a37dc0b7 --- /dev/null +++ b/slsDetectorSoftware/src/slsDetectorUsers.cpp @@ -0,0 +1,431 @@ +#include "slsDetectorUsers.h" +#include "detectorData.h" +#include "multiSlsDetectorClient.h" + + + +int slsDetectorUsers::getNumberOfDetectors() const { + return detector.getNumberOfDetectors(); +} + +int slsDetectorUsers::getMaximumDetectorSize(int &nx, int &ny){ + nx=detector.getMaxNumberOfChannelsPerDetector(slsDetectorDefs::X); + ny=detector.getMaxNumberOfChannelsPerDetector(slsDetectorDefs::Y); + return nx*ny; +} + +int slsDetectorUsers::getDetectorSize(int &x, int &y, int &nx, int &ny, int detPos){ + if (detPos < 0) { + x = 0; + y = 0; + } else { + x = detector.getDetectorOffset(slsDetectorDefs::X, detPos); + y = detector.getDetectorOffset(slsDetectorDefs::Y, detPos); + } + nx=detector.getTotalNumberOfChannels(slsDetectorDefs::X, detPos); + ny=detector.getTotalNumberOfChannels(slsDetectorDefs::Y, detPos); + return nx*ny; +} + +std::string slsDetectorUsers::getDetectorType(int detPos){ + return detector.getDetectorTypeAsString(detPos); +} +int slsDetectorUsers::setOnline(int const online, int detPos){ + return detector.setOnline(online, detPos); +} + +int slsDetectorUsers::setReceiverOnline(int const online, int detPos){ + return detector.setReceiverOnline(online, detPos); +} + +int slsDetectorUsers::readConfigurationFile(const std::string& fname){ + try{ + detector.readConfigurationFile(fname); + return slsDetectorDefs::OK; + } catch (...) { + return slsDetectorDefs::FAIL; + } +} + +int slsDetectorUsers::writeConfigurationFile(const std::string& fname){ + return detector.writeConfigurationFile(fname); +} + +int slsDetectorUsers::retrieveDetectorSetup(const std::string& fname){ + return detector.retrieveDetectorSetup(fname); +} + +int slsDetectorUsers::dumpDetectorSetup(const std::string& fname){ + return detector.dumpDetectorSetup(fname); +} + +int64_t slsDetectorUsers::getDetectorFirmwareVersion(int detPos){ + return detector.getId(slsDetectorDefs::DETECTOR_FIRMWARE_VERSION, detPos); +} + +int64_t slsDetectorUsers::getDetectorSerialNumber(int detPos){ + return detector.getId(slsDetectorDefs::DETECTOR_SERIAL_NUMBER, detPos); +} + +int64_t slsDetectorUsers::getDetectorSoftwareVersion(int detPos){ + return detector.getId(slsDetectorDefs::DETECTOR_SOFTWARE_VERSION, detPos); +} + +int64_t slsDetectorUsers::getClientSoftwareVersion(){ + return detector.getClientSoftwareVersion(); +} + +int64_t slsDetectorUsers::getReceiverSoftwareVersion(int detPos){ + return detector.getId(slsDetectorDefs::RECEIVER_VERSION, detPos); +} + +bool slsDetectorUsers::isDetectorVersionCompatible(int detPos) { + return (detector.checkDetectorVersionCompatibility(detPos) == slsDetectorDefs::OK); +} + +bool slsDetectorUsers::isReceiverVersionCompatible(int detPos) { + return (detector.checkReceiverVersionCompatibility(detPos) == slsDetectorDefs::OK); +} + +int slsDetectorUsers::startMeasurement(){ + return detector.acquire(); +} + +int slsDetectorUsers::stopMeasurement(int detPos){ + return detector.stopAcquisition(detPos); +} + +int slsDetectorUsers::getDetectorStatus(int detPos){ + return (int)detector.getRunStatus(detPos); +} + +int slsDetectorUsers::startAcquisition(int detPos) { + return detector.startAcquisition(detPos); +} + +int slsDetectorUsers::stopAcquisition(int detPos) { + return detector.stopAcquisition(detPos); +} + +int slsDetectorUsers::sendSoftwareTrigger(int detPos) { + return detector.sendSoftwareTrigger(detPos); +} + +int slsDetectorUsers::enableCountRateCorrection(int i, int detPos){ + if (i == 0) + detector.setRateCorrection(0, detPos); + else + detector.setRateCorrection(-1, detPos); + + return detector.getRateCorrection(detPos); +} + +int slsDetectorUsers::setBitDepth(int i, int detPos){ + return detector.setDynamicRange(i, detPos); +} + +int slsDetectorUsers::setSettings(int isettings, int detPos){ + return detector.setSettings((slsDetectorDefs::detectorSettings)isettings, detPos); +} + +int slsDetectorUsers::getThresholdEnergy(int detPos){ + return detector.getThresholdEnergy(detPos); +} + +int slsDetectorUsers::setThresholdEnergy(int e_ev, int tb, int isettings, int detPos) { + return detector.setThresholdEnergy(e_ev, + (isettings == -1) ? slsDetectorDefs::GET_SETTINGS : (slsDetectorDefs::detectorSettings)isettings, + tb, detPos); +} + +double slsDetectorUsers::setExposureTime(double t, bool inseconds, int detPos){ + return detector.setExposureTime(t, inseconds, detPos); +} + +double slsDetectorUsers::setExposurePeriod(double t, bool inseconds, int detPos){ + return detector.setExposurePeriod(t, inseconds, detPos); +} + +double slsDetectorUsers::setDelayAfterTrigger(double t, bool inseconds, int detPos){ + return detector.setDelayAfterTrigger(t, inseconds, detPos); +} + +double slsDetectorUsers::setSubFrameExposureTime(double t, bool inseconds, int detPos){ + return detector.setSubFrameExposureTime(t, inseconds, detPos); +} + +double slsDetectorUsers::setSubFrameExposureDeadTime(double t, bool inseconds, int detPos){ + return detector.setSubFrameExposureDeadTime(t, inseconds, detPos); +} + +int64_t slsDetectorUsers::setNumberOfFrames(int64_t t, int detPos){ + return detector.setNumberOfFrames(t, detPos); +} + +int64_t slsDetectorUsers::setNumberOfCycles(int64_t t, int detPos){ + return detector.setNumberOfCycles(t, detPos); +} + +int64_t slsDetectorUsers::setNumberOfGates(int64_t t, int detPos){ + return detector.setNumberOfGates(t, detPos); +} + +int64_t slsDetectorUsers::setNumberOfStorageCells(int64_t t, int detPos) { + return detector.setNumberOfStorageCells(t, detPos); +} + +double slsDetectorUsers::getMeasuredPeriod(bool inseconds, int detPos) { + return detector.getMeasuredPeriod(inseconds, detPos); +} + +double slsDetectorUsers::getMeasuredSubFramePeriod(bool inseconds, int detPos) { + return detector.getMeasuredSubFramePeriod(inseconds, detPos); +} + +int slsDetectorUsers::setTimingMode(int pol, int detPos){ + return detector.setExternalCommunicationMode(slsDetectorDefs::externalCommunicationMode(pol), detPos); +} + +int slsDetectorUsers::setClockDivider(int value, int detPos) { + return detector.setSpeed(slsDetectorDefs::CLOCK_DIVIDER, value, detPos); +} + +int slsDetectorUsers::setParallelMode(int value, int detPos) { + if(value >= 0) + detector.setReadOutFlags(slsDetectorDefs::readOutFlags(value), detPos); + return detector.setReadOutFlags(slsDetectorDefs::GET_READOUT_FLAGS, detPos); +} + +int slsDetectorUsers::setOverflowMode(int value, int detPos) { + if(value >= 0) { + if (value == 1) + detector.setReadOutFlags(slsDetectorDefs::SHOW_OVERFLOW, detPos); + else + detector.setReadOutFlags(slsDetectorDefs::NOOVERFLOW, detPos); + } + int ret = detector.setReadOutFlags(slsDetectorDefs::GET_READOUT_FLAGS, detPos); + if (ret == -1) + return -1; + return ((ret & slsDetectorDefs::SHOW_OVERFLOW) ? 1 : 0); +} + +int slsDetectorUsers::setAllTrimbits(int val, int detPos) { + return detector.setAllTrimbits(val, detPos); +} + +int slsDetectorUsers::setDAC(int val, int index , int detPos) { + return detector.setDAC(val, slsDetectorDefs::dacIndex(index), 0, detPos); +} + +int slsDetectorUsers::getADC(int index, int detPos) { + return detector.getADC(slsDetectorDefs::dacIndex(index),detPos); +} + +int slsDetectorUsers::setTenGigabitEthernet(int i, int detPos) { + return detector.enableTenGigabitEthernet(i, detPos); +} + +int slsDetectorUsers::setStoragecellStart(int pos, int detPos) { + return detector.setStoragecellStart(pos, detPos); +} + +int slsDetectorUsers::setHighVoltage(int i, int detPos) { + return detector.setDAC(i, slsDetectorDefs::HIGH_VOLTAGE, 0, detPos); +} + +int slsDetectorUsers::setFlowControl10G(int i, int detPos) { + return detector.setFlowControl10G(i, detPos); +} + +int slsDetectorUsers::setROI(int n, slsDetectorDefs::ROI roiLimits[], int detPos) { + return detector.setROI(n, roiLimits, detPos); +} + +const slsDetectorDefs::ROI* slsDetectorUsers::getROI(int &n, int detPos) { + return detector.getROI(n, detPos); +} + +/************************************************************************ + + RECEIVER FUNCTIONS + + *********************************************************************/ + + +int slsDetectorUsers::startReceiver(int detPos) { + return detector.startReceiver(detPos); +} + +int slsDetectorUsers::stopReceiver(int detPos) { + return detector.stopReceiver(detPos); +} + +int slsDetectorUsers::setReceiverSilentMode(int i, int detPos) { + return detector.setReceiverSilentMode(i, detPos); +} + +int slsDetectorUsers::resetFramesCaughtInReceiver(int detPos) { + return detector.resetFramesCaught(detPos); +} + +int slsDetectorUsers::setReceiverFifoDepth(int i, int detPos) { + return detector.setReceiverFifoDepth(i, detPos); +} + +std::string slsDetectorUsers::getFilePath(int detPos){ + return detector.getFilePath(detPos); +} + +std::string slsDetectorUsers::setFilePath(const std::string& s, int detPos){ + return detector.setFilePath(s, detPos); +} + +std::string slsDetectorUsers::getFileName(int detPos){ + return detector.getFileName(detPos); +} + +std::string slsDetectorUsers::setFileName(const std::string& s, int detPos){ + return detector.setFileName(s, detPos); +} + +int slsDetectorUsers::getFileIndex(int detPos){ + return detector.getFileIndex(detPos); +} + +int slsDetectorUsers::setFileIndex(int i, int detPos){ + return detector.setFileIndex(i, detPos); +} + +int slsDetectorUsers::enableWriteToFile(int enable, int detPos){ + if (enable >0) + return detector.setFileWrite(enable, detPos); + else + return detector.getFileWrite(detPos); + +} + +int slsDetectorUsers::enableOverwriteFile(int enable, int detPos) { + if (enable > 0) + return detector.setFileOverWrite(enable, detPos); + else + return detector.getFileOverWrite(detPos); +} + +int slsDetectorUsers::setReceiverStreamingFrequency(int freq, int detPos){ + return detector.setReceiverStreamingFrequency(freq, detPos); +} + +int slsDetectorUsers::setReceiverStreamingTimer(int time_in_ms, int detPos){ + return detector.setReceiverStreamingTimer(time_in_ms, detPos); +} + +int slsDetectorUsers::enableDataStreamingToClient(int i){ + return detector.enableDataStreamingToClient(i); +} + +int slsDetectorUsers::enableDataStreamingFromReceiver(int i, int detPos){ + return detector.enableDataStreamingFromReceiver(i, detPos); +} + +int slsDetectorUsers::setReceiverDataStreamingOutPort(int i, int detPos){ + if (i >= 0) { + detector.setReceiverDataStreamingOutPort(i, detPos); + } + return detector.getReceiverStreamingPort(detPos); +} + +int slsDetectorUsers::setClientDataStreamingInPort(int i, int detPos){ + if (i >= 0) { + detector.setClientDataStreamingInPort(i, detPos); + } + return detector.getClientStreamingPort(detPos); +} + +std::string slsDetectorUsers::setReceiverDataStreamingOutIP(const std::string& ip, int detPos){ + if (ip.length()) { + detector.setReceiverDataStreamingOutIP(ip, detPos); + } + return detector.getReceiverStreamingIP(detPos); +} + +std::string slsDetectorUsers::setClientDataStreamingInIP(const std::string& ip, int detPos){ + if (ip.length()) { + detector.setClientDataStreamingInIP(ip, detPos); + } + return detector.getClientStreamingIP(detPos); +} + +int slsDetectorUsers::enableGapPixels(int enable, int detPos) { + return detector.enableGapPixels(enable, detPos); +} + +int slsDetectorUsers::setReceiverFramesDiscardPolicy(int f, int detPos) { + return detector.setReceiverFramesDiscardPolicy(slsDetectorDefs::frameDiscardPolicy(f), detPos); +} + +int slsDetectorUsers::setReceiverPartialFramesPadding(int f, int detPos) { + if (f>=0) + return detector.setPartialFramesPadding(f, detPos); + else + return detector.getPartialFramesPadding(detPos); +} + +int slsDetectorUsers::setReceiverFramesPerFile(int f, int detPos) { + if (f > 0) { + return detector.setFramesPerFile(f, detPos); + } + else { + return detector.getFramesPerFile(detPos); + } +} + +int slsDetectorUsers::setDetectorMinMaxEnergyThreshold(const int index, int v, int detPos) { + return detector.setDetectorMinMaxEnergyThreshold(index, v, detPos); +} + +int slsDetectorUsers::setFrameMode(int value, int detPos) { + return detector.setFrameMode(slsDetectorDefs::frameModeType(value), detPos); +} + +int slsDetectorUsers::setDetectorMode(int value, int detPos) { + return detector.setDetectorMode(slsDetectorDefs::detectorModeType(value), detPos); +} + + +/************************************************************************ + + CALLBACKS & COMMAND LINE PARSING + + *********************************************************************/ + +void slsDetectorUsers::registerDataCallback(int( *userCallback)(detectorData*, int, int, void*), void *pArg) { + detector.registerDataCallback(userCallback,pArg); +} + +void slsDetectorUsers::registerAcquisitionFinishedCallback(int( *func)(double,int, void*), void *pArg) { + detector.registerAcquisitionFinishedCallback(func,pArg); +} + +void slsDetectorUsers::registerMeasurementFinishedCallback(int( *func)(int,int, void*), void *pArg) { + detector.registerMeasurementFinishedCallback(func,pArg); +} + +void slsDetectorUsers::registerProgressCallback(int( *func)(double,void*), void *pArg) { + detector.registerProgressCallback(func,pArg); +} + +void slsDetectorUsers::putCommand(const std::string& command){ + multiSlsDetectorClient(command, slsDetectorDefs::PUT_ACTION, &detector); +} + + + + + + + + + + + + diff --git a/slsDetectorSoftware/src/sls_detector_client.cpp b/slsDetectorSoftware/src/sls_detector_client.cpp new file mode 100755 index 000000000..875950978 --- /dev/null +++ b/slsDetectorSoftware/src/sls_detector_client.cpp @@ -0,0 +1,33 @@ +#include "versionAPI.h" +#include "multiSlsDetectorClient.h" +#include + +int main(int argc, char *argv[]) { + for (int i = 1; i < argc; ++i) { + if (!(strcmp(argv[i], "--version")) || !(strcmp(argv[i], "-v"))) { + int64_t tempval = APILIB; + std::cout << argv[0] << " " << GITBRANCH << " (0x" << std::hex << tempval << ")" << std::endl; + return 0; + } + } + +#ifdef PUT + int action = slsDetectorDefs::PUT_ACTION; +#endif + +#ifdef GET + int action = slsDetectorDefs::GET_ACTION; +#endif + +#ifdef READOUT + int action = slsDetectorDefs::READOUT_ACTION; +#endif + +#ifdef HELP + int action = slsDetectorDefs::HELP_ACTION; +#endif + + // if (argc > 1) + // argv++; + multiSlsDetectorClient(argc, argv, action); +} diff --git a/slsDetectorSoftware/tests/CMakeLists.txt b/slsDetectorSoftware/tests/CMakeLists.txt new file mode 100755 index 000000000..a30e9f3ac --- /dev/null +++ b/slsDetectorSoftware/tests/CMakeLists.txt @@ -0,0 +1,5 @@ +target_sources(tests PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/test-SharedMemory.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test-slsDetector.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test-multiSlsDetector.cpp +) \ No newline at end of file diff --git a/slsDetectorSoftware/tests/test-SharedMemory.cpp b/slsDetectorSoftware/tests/test-SharedMemory.cpp new file mode 100755 index 000000000..c42e9986f --- /dev/null +++ b/slsDetectorSoftware/tests/test-SharedMemory.cpp @@ -0,0 +1,135 @@ + +#include "SharedMemory.h" +#include "catch.hpp" +#include "string_utils.h" + +#include + +struct Data { + int x; + double y; + char mess[50]; +}; + +using namespace sls; + +constexpr int shm_id = 10; + +TEST_CASE("Create SharedMemory read and write", "[detector]") { + + SharedMemory shm(shm_id, -1); + shm.CreateSharedMemory(); + CHECK(shm.GetName() == + std::string("/slsDetectorPackage_multi_") + std::to_string(shm_id)); + + shm()->x = 3; + shm()->y = 5.7; + sls::strcpy_safe(shm()->mess, "Some string"); + + CHECK(shm()->x == 3); + CHECK(shm()->y == 5.7); + CHECK(std::string(shm()->mess) == "Some string"); + + shm.UnmapSharedMemory(); + shm.RemoveSharedMemory(); + + CHECK(shm.IsExisting() == false); +} + +TEST_CASE("Open existing SharedMemory and read", "[detector]") { + + { + SharedMemory shm(shm_id, -1); + shm.CreateSharedMemory(); + *shm() = 5.3; + } + + SharedMemory shm2(shm_id, -1); + shm2.OpenSharedMemory(); + CHECK(*shm2() == 5.3); + + shm2.RemoveSharedMemory(); +} + +TEST_CASE("Creating a second shared memory with the same name throws", + "[detector]") { + + SharedMemory shm0(shm_id, -1); + SharedMemory shm1(shm_id, -1); + + shm0.CreateSharedMemory(); + CHECK_THROWS(shm1.CreateSharedMemory()); + shm0.RemoveSharedMemory(); +} + +TEST_CASE("Open two shared memories to the same place", "[detector]") { + + //Create the first shared memory + SharedMemory shm(shm_id, -1); + shm.CreateSharedMemory(); + shm()->x = 5; + CHECK(shm()->x == 5); + + //Open the second shared memory with the same name + SharedMemory shm2(shm_id, -1); + shm2.OpenSharedMemory(); + CHECK(shm2()->x == 5); + CHECK(shm.GetName() == shm2.GetName()); + + //Check that they still point to the same place + shm2()->x = 7; + CHECK(shm()->x == 7); + + //Remove only needs to be done once since they refer + //to the same memory + shm2.RemoveSharedMemory(); + CHECK(shm.IsExisting() == false); + CHECK(shm2.IsExisting() == false); +} + +TEST_CASE("Move SharedMemory", "[detector]") { + + SharedMemory shm(shm_id, -1); + CHECK(shm.GetName() == + std::string("/slsDetectorPackage_multi_") + std::to_string(shm_id)); + shm.CreateSharedMemory(); + shm()->x = 9; + + CHECK(shm.size()== sizeof(Data)); + + SharedMemory shm2(shm_id+1, -1); + shm2 = std::move(shm); //shm is now a moved from object! + + CHECK(shm2()->x == 9); + CHECK(shm() == nullptr); + CHECK(shm.size() == 0); + + CHECK(shm2.GetName() == std::string("/slsDetectorPackage_multi_") + + std::to_string(shm_id)); + shm2.RemoveSharedMemory(); + +} + +TEST_CASE("Create several shared memories", "[detector]") { + constexpr int N = 5; + std::vector> v; + v.reserve(N); + for (int i = 0; i != N; ++i) { + v.emplace_back(shm_id+i, -1); + CHECK(v[i].IsExisting() == false); + v[i].CreateSharedMemory(); + *v[i]() = i; + CHECK(*v[i]() == i); + } + + for (int i = 0; i != N; ++i) { + CHECK(*v[i]() == i); + CHECK(v[i].GetName() == std::string("/slsDetectorPackage_multi_") + + std::to_string(i + shm_id)); + } + + for (int i = 0; i != N; ++i) { + v[i].RemoveSharedMemory(); + CHECK(v[i].IsExisting() == false); + } +} diff --git a/slsDetectorSoftware/tests/test-multiSlsDetector.cpp b/slsDetectorSoftware/tests/test-multiSlsDetector.cpp new file mode 100755 index 000000000..f4e40e726 --- /dev/null +++ b/slsDetectorSoftware/tests/test-multiSlsDetector.cpp @@ -0,0 +1,84 @@ + +#include "catch.hpp" +#include "container_utils.h" +#include "multiSlsDetector.h" +#include "slsDetector.h" +#include "string_utils.h" + +#include + +using namespace sls; + +SCENARIO("Multi detector operation", "[detector]") { + + multiSlsDetector::freeSharedMemory(20, -1); + + GIVEN("An empty multi detector") { + multiSlsDetector m(20); + THEN("the size is zero") { + CHECK(m.getNumberOfDetectors() == 0); + CHECK(m.getDataBytes() == 0); + CHECK(m.getTotalNumberOfChannels() == 0); + } + + WHEN("we add a detector") { + m.addSlsDetector(sls::make_unique( + slsDetectorDefs::detectorType::EIGER, 20, 0)); + THEN("the size and number of detector changes") { + CHECK(m.getNumberOfDetectors() == 1); + CHECK(m.getTotalNumberOfChannels() == 256 * 1024); + } + + WHEN("we add another detector") { + m.addSlsDetector(sls::make_unique( + slsDetectorDefs::detectorType::EIGER, 20, 1)); + THEN("the size and number of detector changes") { + CHECK(m.getNumberOfDetectors() == 2); + CHECK(m.getTotalNumberOfChannels() == 2 * 256 * 1024); + } + + WHEN("We set the trimen") { + std::vector energies{5000, 6000, 7000, 8000, 9000}; + m.setTrimEn(energies); + THEN("we read back the same values") { + CHECK(m.getTrimEn() == energies); + } + } + WHEN("We set the trimen to different values") { + std::vector en0{5000, 6000, 7000, 8000, 9000}; + std::vector en1{6000, 7000, 8000, 9000}; + m.setTrimEn(en0, 0); + m.setTrimEn(en1, 1); + THEN("we read back the same values") { + CHECK(m.getTrimEn(0) == en0); + CHECK(m.getTrimEn(1) == en1); + CHECK(m.getTrimEn() == std::vector{-1}); + } + } + } + } + + m.freeSharedMemory(); + } +} + +TEST_CASE("Set and get partialFramesPadding", "[detector]"){ + + multiSlsDetector::freeSharedMemory(20, -1); + multiSlsDetector m(20); + m.addSlsDetector(sls::make_unique( + slsDetectorDefs::detectorType::EIGER, 20, 0)); + m.addSlsDetector(sls::make_unique( + slsDetectorDefs::detectorType::EIGER, 20, 1)); + + m.setPartialFramesPadding(0); + CHECK(m.getPartialFramesPadding() == 0); + + m.setPartialFramesPadding(1); + CHECK(m.getPartialFramesPadding() == 1); + + m.setPartialFramesPadding(0, 0); + CHECK(m.getPartialFramesPadding() == -1); + + m.freeSharedMemory(); +} diff --git a/slsDetectorSoftware/tests/test-slsDetector.cpp b/slsDetectorSoftware/tests/test-slsDetector.cpp new file mode 100755 index 000000000..8a3d44ed0 --- /dev/null +++ b/slsDetectorSoftware/tests/test-slsDetector.cpp @@ -0,0 +1,194 @@ + +#include "catch.hpp" +#include "container_utils.h" +#include "slsDetector.h" +#include "sls_detector_defs.h" +#include "string_utils.h" +#include +#include + +using namespace sls; + +TEST_CASE("Set and get trimen", "[detector]") { + // Free shared memory to be sure that we start in a clean state + slsDetector::freeSharedMemory(20, 20); + + // Create a detector and check that the type is set correctly + slsDetector d(slsDetectorDefs::detectorType::EIGER, 20, 20); + CHECK(d.getDetectorTypeAsEnum() == slsDetectorDefs::detectorType::EIGER); + + // At the beginning there should be no trimen set + auto res = d.getTrimEn(); + CHECK(res.empty()); + + std::vector energies{5200, 6400, 8500, 9900, 12000}; + d.setTrimEn(energies); + auto res2 = d.getTrimEn(); + + // Check that the size and every element matches what we set + CHECK(res2.size() == energies.size()); + for (size_t i = 0; i != res2.size(); ++i) + CHECK(res2[i] == energies[i]); + + // Setting trimen with too many vales throws an exception and keeps the + // old values + std::vector too_many(150, 1000); + CHECK_THROWS(d.setTrimEn(too_many)); + auto res3 = d.getTrimEn(); + CHECK(res3.size() == energies.size()); + for (size_t i = 0; i != res3.size(); ++i) + CHECK(res3[i] == energies[i]); + + // Setting trimen without arguments resets to zero + d.setTrimEn(); + CHECK(d.getTrimEn().empty()); + + // Clean up before next test + d.freeSharedMemory(); +} + +TEST_CASE("Set additional JSON header", "[detector]") { + slsDetector::freeSharedMemory(20, 20); + slsDetector d(slsDetectorDefs::detectorType::EIGER, 20, 20); + auto header = d.getAdditionalJsonHeader(); + CHECK(header.empty()); + + // The header set is not validated + d.setAdditionalJsonHeader("any header"); + header = d.getAdditionalJsonHeader(); + CHECK(header == "any header"); + + // make sure reset works + d.setAdditionalJsonHeader(""); + CHECK(d.getAdditionalJsonHeader().empty()); + + // Setting and getting one parameter + d.setAdditionalJsonParameter("exptime", "5"); + CHECK(d.getAdditionalJsonParameter("exptime") == "5"); + CHECK(d.getAdditionalJsonHeader() == "\"exptime\":5"); + + // Making sure setting another paramer does not mess up + // the first + d.setAdditionalJsonParameter("gain", "low"); + CHECK(d.getAdditionalJsonParameter("exptime") == "5"); + CHECK(d.getAdditionalJsonParameter("gain") == "low"); + CHECK(d.getAdditionalJsonHeader() == "\"exptime\":5,\"gain\":\"low\""); + + // Change a value + d.setAdditionalJsonParameter("exptime", "90"); + CHECK(d.getAdditionalJsonParameter("exptime") == "90"); + CHECK(d.getAdditionalJsonHeader() == "\"exptime\":90,\"gain\":\"low\""); + + // Ask for a key that does not exists + // TODO!(Erik) Is an empty string the right return or should we throw + CHECK(d.getAdditionalJsonParameter("somerandomkey").empty()); + + // Throws if value or key is empty + CHECK_THROWS(d.setAdditionalJsonParameter("somekey", "")); + CHECK_THROWS(d.setAdditionalJsonParameter("", "parameter")); + CHECK_THROWS(d.setAdditionalJsonParameter("", "")); + + // Throws if key or value has illegal char + CHECK_THROWS(d.setAdditionalJsonParameter("mykey,", "5")); + CHECK_THROWS(d.setAdditionalJsonParameter("some:key", "9")); + CHECK_THROWS(d.setAdditionalJsonParameter("some\"key", "1")); + CHECK_THROWS(d.setAdditionalJsonParameter("key", "value:")); + CHECK_THROWS(d.setAdditionalJsonParameter("key", "va,lue")); + CHECK_THROWS(d.setAdditionalJsonParameter("key", "va\"l\"ue")); + + d.freeSharedMemory(); +} + +TEST_CASE("Set ROI", "[detector]") { + using ROI = slsDetectorDefs::ROI; + + slsDetector::freeSharedMemory(20,20); + slsDetector d(slsDetectorDefs::detectorType::EIGER, 20, 20); + + int n{0}; + d.getROI(n); + CHECK(n == 0); + CHECK(d.getNRoi() == 0); + + // set one ROI + ROI r; + r.xmin = 5; + r.xmax = 100; + r.ymin = 10; + r.ymax = 300; + d.setROI(1, &r); + + auto res2 = d.getROI(n); + CHECK(n == 1); + CHECK(d.getNRoi() == 1); + + CHECK(res2->xmin == 5); + CHECK(res2->xmax == 100); + CHECK(res2->ymin == 10); + CHECK(res2->ymax == 300); + + d.freeSharedMemory(); +} + +TEST_CASE("Set multiple ROIs", "[detector]") { + using ROI = slsDetectorDefs::ROI; + + slsDetector::freeSharedMemory(20, 20); + slsDetector d(slsDetectorDefs::detectorType::EIGER, 20, 20); + + // set one ROI + constexpr int n = 3; + ROI r[n]; + r[0].xmin = 500; + r[0].xmax = 60000; + r[0].ymin = 100; + r[0].ymax = 800; + + r[1].xmin = 2; + r[1].xmax = 100; + r[1].ymin = 1; + r[1].ymax = 300; + + r[2].xmin = 200; + r[2].xmax = 300; + r[2].ymin = 15; + r[2].ymax = 307; + d.setROI(n, r); + + int n_roi{0}; + auto res = d.getROI(n_roi); + CHECK(n_roi == n); + CHECK(d.getNRoi() == n); + + CHECK(res[0].xmin == 2); + CHECK(res[0].xmax == 100); + CHECK(res[0].ymin == 1); + CHECK(res[0].ymax == 300); + + CHECK(res[1].xmin == 200); + CHECK(res[1].xmax == 300); + CHECK(res[1].ymin == 15); + CHECK(res[1].ymax == 307); + + CHECK(res[2].xmin == 500); + CHECK(res[2].xmax == 60000); + CHECK(res[2].ymin == 100); + CHECK(res[2].ymax == 800); + + d.freeSharedMemory(); +} + +TEST_CASE("Padding and discard policy", "[detector][new]"){ + slsDetector::freeSharedMemory(20, 20); + slsDetector d(slsDetectorDefs::detectorType::EIGER, 20, 20); + + // + d.setPartialFramesPadding(false); + CHECK(d.getPartialFramesPadding() == false); + d.setPartialFramesPadding(true); + CHECK(d.getPartialFramesPadding() == true); + + + d.freeSharedMemory(); + +} \ No newline at end of file diff --git a/slsDetectorSoftware/threadFiles/CondVar.cpp b/slsDetectorSoftware/threadFiles/CondVar.cpp deleted file mode 100644 index 2feff962f..000000000 --- a/slsDetectorSoftware/threadFiles/CondVar.cpp +++ /dev/null @@ -1,17 +0,0 @@ -#include "CondVar.h" - -CondVar::CondVar() { - pthread_cond_init(&m_cond_var, NULL); -} -CondVar::~CondVar() { - pthread_cond_destroy(&m_cond_var); -} -void CondVar::wait(pthread_mutex_t* mutex) { - pthread_cond_wait(&m_cond_var, mutex); -} -void CondVar::signal() { - pthread_cond_signal(&m_cond_var); -} -void CondVar::broadcast() { - pthread_cond_broadcast(&m_cond_var); -} diff --git a/slsDetectorSoftware/threadFiles/CondVar.h b/slsDetectorSoftware/threadFiles/CondVar.h deleted file mode 100644 index 3bf69d146..000000000 --- a/slsDetectorSoftware/threadFiles/CondVar.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include - -#include "Global.h" - - -class CondVar { -public: - - CondVar(); - ~CondVar(); - void wait(pthread_mutex_t* mutex); - void signal(); - void broadcast(); - -private: - pthread_cond_t m_cond_var; -}; diff --git a/slsDetectorSoftware/threadFiles/Global.h b/slsDetectorSoftware/threadFiles/Global.h deleted file mode 100644 index 2596df0c0..000000000 --- a/slsDetectorSoftware/threadFiles/Global.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once - -const int DEFAULT_POOL_SIZE = 10; -const int MAX_SINGLES = 5; -const int STARTED = 0; -const int STOPPED = 1; diff --git a/slsDetectorSoftware/threadFiles/Makefile b/slsDetectorSoftware/threadFiles/Makefile deleted file mode 100644 index a1eb27d29..000000000 --- a/slsDetectorSoftware/threadFiles/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -OBJPATH=bin/obj -EXAMPLEPATH=bin/example - -all: - g++ CondVar.cpp -pthread -c -g -o $(OBJPATH)/CondVar.o - g++ Mutex.cpp -pthread -c -g -o $(OBJPATH)/Mutex.o - #g++ Task.cpp -pthread -c -g -o $(OBJPATH)/Task.o - g++ ThreadPool.cpp -pthread -c -g -o $(OBJPATH)/ThreadPool.o - g++ Multi.cpp -pthread -c -g -o $(OBJPATH)/Multi.o - #g++ $(OBJPATH)/CondVar.o $(OBJPATH)/Mutex.o $(OBJPATH)/Task.o $(OBJPATH)/ThreadPool.o threadpool_test.cpp Single.cpp Multi.cpp -pthread -I . -g -o $(EXAMPLEPATH)threadpool_test - g++ $(OBJPATH)/CondVar.o $(OBJPATH)/Mutex.o $(OBJPATH)/ThreadPool.o threadpool_test.cpp Single.cpp Multi.cpp -pthread -I . -g -o $(EXAMPLEPATH)threadpool_test - -#all: -# g++ threadpool.cpp -pthread -fpic -c -o bin/obj/threadpool.o -# g++ -L./bin bin/obj/threadpool.o -pthread threadpool_test.cpp -o bin/example/threadpool_test - -#threadpool: -# g++ threadpool.cpp -pthread -fpic -c -o bin/obj/threadpool.o -# g++ -shared -fPIC bin/obj/threadpool.o -o bin/lib/libthreadpool.so -#example: -# g++ -L./bin/lib -lthreadpool threadpool_test.cpp -o threadpool_test diff --git a/slsDetectorSoftware/threadFiles/Multi.cpp b/slsDetectorSoftware/threadFiles/Multi.cpp deleted file mode 100644 index 02e34438e..000000000 --- a/slsDetectorSoftware/threadFiles/Multi.cpp +++ /dev/null @@ -1,197 +0,0 @@ -#include "Multi.h" -#include "Single.h" -#include "ThreadPool.h" - - - -#include -#include -#include -#include -using namespace std; - -char ans[1000]; -int threadflag = 1; - -Multi::Multi() { - numSingles = 1; - threadpool = 0; - for(int i=0;idestroy_threadpool(); - threadpool=0; - } - if(numSingles > 0) - threadpool = new ThreadPool(numSingles); - switch(threadpool->initialize_threadpool()){ - case -1: - cerr << "Failed to initialize thread pool!" << endl; - return 0; - case 0: - cout << "Not initializing threads, only one detector" << endl; - break; - default: - cout << "Initialized Threadpool" << endl; - break; - } - return 1; -} - -int Multi::destroyThreadPool(){ - if(threadpool){ - threadpool->destroy_threadpool(); - threadpool=0; - cout<<"Destroyed Threadpool"<* binder = - // new func_t(&Single::printNumber,singles[i],inum,iret[i]); - Task* task = new Task(new func1_t(&Single::printNumber,singles[i],inum,iret[i])); - threadpool->add_task(task); - } - threadpool->wait_for_tasks_to_complete(); - - - for(int i=0;i1){ - string* sret[numSingles]; - - - for(int i=0;i* binder = - new func1_t(&Single::printString,singles[i],s,sret[i]); - Task* task = new Task(binder); - threadpool->add_task(task); - } - threadpool->wait_for_tasks_to_complete(); - for(int i=0;iprintString(s); - if(ret=="error") - ret = ret1; - else if (ret != ret1) - ret = "sss"; - } - } - return ret; -} - -char* Multi::printCharArray(char a[]){ - string ret="error", ret1="sss"; - - if(numSingles>1){ - string* sret[numSingles]; - - for(int i=0;i* binder = - new func1_t (&Single::printCharArray,singles[i],a,sret[i]); - Task* task = new Task(binder); - threadpool->add_task(task); - } - threadpool->wait_for_tasks_to_complete(); - - for(int i=0;iprintCharArray(a); - if(ret=="error") - ret = ret1; - else if (ret != ret1) - ret = "sss"; - } - } - strcpy(ans,ret.c_str()); - return ans; -} diff --git a/slsDetectorSoftware/threadFiles/Multi.h b/slsDetectorSoftware/threadFiles/Multi.h deleted file mode 100644 index cf34396a8..000000000 --- a/slsDetectorSoftware/threadFiles/Multi.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once - - -#include "Global.h" - -#include - -class Single; -class ThreadPool; - -class Multi { -public: - - Multi(); - ~Multi(); - - std::string executeCommand(int argc,char* argv[]); - - int printNumber(int inum); - std::string printString(std::string s); - char* printCharArray(char a[]); - - int createThreadPool(); - int destroyThreadPool(); - -protected: - Single* singles[MAX_SINGLES]; - int numSingles; - ThreadPool* threadpool; - - - -}; - - diff --git a/slsDetectorSoftware/threadFiles/Mutex.cpp b/slsDetectorSoftware/threadFiles/Mutex.cpp deleted file mode 100644 index 4aefec723..000000000 --- a/slsDetectorSoftware/threadFiles/Mutex.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include "Mutex.h" - -Mutex::Mutex() { - pthread_mutex_init(&m_lock, NULL); - is_locked = false; -} - -Mutex::~Mutex() { - while(is_locked); - //unlock(); // Unlock Mutex after shared resource is safe - pthread_mutex_destroy(&m_lock); -} - -void Mutex::lock() { - pthread_mutex_lock(&m_lock); - is_locked = true; -} - -void Mutex::unlock() { - is_locked = false; // do it BEFORE unlocking to avoid race condition - pthread_mutex_unlock(&m_lock); -} - -pthread_mutex_t* Mutex::get_mutex_ptr(){ - return &m_lock; -} diff --git a/slsDetectorSoftware/threadFiles/Mutex.h b/slsDetectorSoftware/threadFiles/Mutex.h deleted file mode 100644 index 33e108777..000000000 --- a/slsDetectorSoftware/threadFiles/Mutex.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include "Global.h" - -// - -class Mutex -{ -public: - Mutex(); - ~Mutex(); - void lock(); - void unlock(); - pthread_mutex_t* get_mutex_ptr(); - -private: - pthread_mutex_t m_lock; - volatile bool is_locked; -}; diff --git a/slsDetectorSoftware/threadFiles/Single.cpp b/slsDetectorSoftware/threadFiles/Single.cpp deleted file mode 100644 index 43b0ca14b..000000000 --- a/slsDetectorSoftware/threadFiles/Single.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "Single.h" - -#include -#include -using namespace std; - -char local_ans[1000]; - -Single::Single(int id) { - detID = id; - // cout<<"detID:"< -// - -class Single { -public: - Single(int id); - ~Single(); - int getID(); - - int printNumber(int i); - string printString(string s); - char* printCharArray(char a[]); - -private: - int detID; - - int* someValue; - -}; - diff --git a/slsDetectorSoftware/threadFiles/Task.h b/slsDetectorSoftware/threadFiles/Task.h deleted file mode 100644 index 585f4a119..000000000 --- a/slsDetectorSoftware/threadFiles/Task.h +++ /dev/null @@ -1,221 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Global.h" -#include "sls_detector_defs.h" - -class slsDetector; - -template -class func00_t{ -public: - func00_t(_Ret (slsDetector::*fn)(),slsDetector* ptr): - m_fn(fn),m_ptr(ptr){} - ~func00_t() {} - void operator()() const {((m_ptr->*m_fn)());} -private: - _Ret (slsDetector::*m_fn)(); - slsDetector* m_ptr; -}; - -template -class func0_t{ -public: - func0_t(_Ret (slsDetector::*fn)(),slsDetector* ptr, _Ret* sto): - m_fn(fn),m_ptr(ptr),m_store(sto){} - ~func0_t() {} - void operator()() const {*m_store = ((m_ptr->*m_fn)());} -private: - _Ret (slsDetector::*m_fn)(); - slsDetector* m_ptr; - _Ret* m_store; -}; - -template -class func1_t{ -public: - func1_t(_Ret (slsDetector::*fn)(_Arg1),slsDetector* ptr,_Arg1 arg1, _Ret* sto): - m_fn(fn),m_ptr(ptr),m_arg1(arg1),m_store(sto){} - ~func1_t() {} - void operator()() const {*m_store = ((m_ptr->*m_fn)(m_arg1));} -private: - _Ret (slsDetector::*m_fn)(_Arg1); - slsDetector* m_ptr; - _Arg1 m_arg1; - _Ret* m_store; -}; - -template -class func2_t{ -public: - func2_t(_Ret (slsDetector::*fn)(_Arg1,_Arg2),slsDetector* ptr,_Arg1 arg1,_Arg2 arg2,_Ret* sto): - m_fn(fn),m_ptr(ptr),m_arg1(arg1),m_arg2(arg2),m_store(sto){} - ~func2_t() {} - void operator()() const {*m_store = ((m_ptr->*m_fn)(m_arg1,m_arg2));} -private: - _Ret (slsDetector::*m_fn)(_Arg1,_Arg2); - slsDetector* m_ptr; - _Arg1 m_arg1; - _Arg2 m_arg2; - _Ret* m_store; -}; - -template -class func3_t{ -public: - func3_t(_Ret (slsDetector::*fn)(_Arg1,_Arg2,_Arg3),slsDetector* ptr,_Arg1 arg1,_Arg2 arg2,_Arg3 arg3,_Ret* sto): - m_fn(fn),m_ptr(ptr),m_arg1(arg1),m_arg2(arg2),m_arg3(arg3),m_store(sto){} - ~func3_t() {} - void operator()() const {*m_store = ((m_ptr->*m_fn)(m_arg1,m_arg2,m_arg3));} -private: - _Ret (slsDetector::*m_fn)(_Arg1,_Arg2,_Arg3); - slsDetector* m_ptr; - _Arg1 m_arg1; - _Arg2 m_arg2; - _Arg3 m_arg3; - _Ret* m_store; -}; - -template -class func4_t{ -public: - func4_t(_Ret (slsDetector::*fn)(_Arg1,_Arg2,_Arg3,_Arg4),slsDetector* ptr,_Arg1 arg1,_Arg2 arg2,_Arg3 arg3,_Arg4 arg4,_Ret* sto): - m_fn(fn),m_ptr(ptr),m_arg1(arg1),m_arg2(arg2),m_arg3(arg3),m_arg4(arg4),m_store(sto){} - ~func4_t() {} - void operator()() const {*m_store = ((m_ptr->*m_fn)(m_arg1,m_arg2,m_arg3,m_arg4));} -private: - _Ret (slsDetector::*m_fn)(_Arg1,_Arg2,_Arg3,_Arg4); - slsDetector* m_ptr; - _Arg1 m_arg1; - _Arg2 m_arg2; - _Arg3 m_arg3; - _Arg4 m_arg4; - _Ret* m_store; -}; - - -class SuperTask: public virtual slsDetectorDefs { -public: - SuperTask(): - m1(0),m2(0),m3(0),m4(0),m5(0),m6(0),m7(0),m8(0),m9(0),m10(0),m11(0),m12(0),m13(0),m14(0),m15(0),m16(0),m17(0),m18(0),m19(0){}; - virtual ~SuperTask(){}; -protected: - /** Function signature defined - * First argument is Return type, the remaining are arguments - */ - func00_t * m1; - func0_t * m2; - func0_t * m3; - func0_t * m4; - func1_t * m5; - func1_t * m6; - func1_t * m7; - func1_t * m8; - func2_t * m9; - func2_t * m10; - func2_t * m11; - func2_t * m12; - func3_t * m13; - func2_t * m14; - func3_t * m15; - func4_t * m16; - func4_t * m17; - func4_t * m18; - func1_t * m19; -}; - -class Task: public virtual SuperTask { -public: - /** Task Constructors using appropriate function signature - * First argument is Return type, the remaining are arguments - */ - Task(func00_t * t): SuperTask(),fnum(1){m1 = t;}; - Task(func0_t * t): SuperTask(),fnum(2){m2 = t;}; - Task(func0_t * t): SuperTask(),fnum(3){m3 = t;}; - Task(func0_t * t): SuperTask(),fnum(4){m4 = t;}; - Task(func1_t * t): SuperTask(),fnum(5){m5 = t;}; - Task(func1_t * t): SuperTask(),fnum(6){m6 = t;}; - Task(func1_t * t): SuperTask(),fnum(7){m7 = t;}; - Task(func1_t * t): SuperTask(),fnum(8){m8 = t;}; - Task(func2_t * t): SuperTask(),fnum(9){m9 = t;}; - Task(func2_t * t): SuperTask(),fnum(10){m10 = t;}; - Task(func2_t * t): SuperTask(),fnum(11){m11 = t;}; - Task(func2_t * t): SuperTask(),fnum(12){m12 = t;}; - Task(func3_t * t): SuperTask(),fnum(13){m13 = t;}; - Task(func2_t * t): SuperTask(),fnum(14){m14 = t;}; - Task(func3_t * t): SuperTask(),fnum(15){m15 = t;}; - Task(func4_t * t): SuperTask(),fnum(16){m16 = t;}; - Task(func4_t * t): SuperTask(),fnum(17){m17 = t;}; - Task(func4_t * t): SuperTask(),fnum(18){m18 = t;}; - Task(func1_t * t): SuperTask(),fnum(19){m19 = t;}; - - virtual ~Task(){ - switch(fnum) { - case 1: delete m1; break; - case 2: delete m2; break; - case 3: delete m3; break; - case 4: delete m4; break; - case 5: delete m5; break; - case 6: delete m6; break; - case 7: delete m7; break; - case 8: delete m8; break; - case 9: delete m9; break; - case 10: delete m10; break; - case 11: delete m11; break; - case 12: delete m12; break; - case 13: delete m13; break; - case 14: delete m14; break; - case 15: delete m15; break; - case 16: delete m16; break; - case 17: delete m17; break; - case 18: delete m18; break; - case 19: delete m19; break; - default: - cprintf(RED, "Error: Task not defined. Abort!\n"); - break; - } - - }; - - void operator()(){ - switch(fnum) { - case 1: (*m1)(); break; - case 2: (*m2)(); break; - case 3: (*m3)(); break; - case 4: (*m4)(); break; - case 5: (*m5)(); break; - case 6: (*m6)(); break; - case 7: (*m7)(); break; - case 8: (*m8)(); break; - case 9: (*m9)(); break; - case 10: (*m10)(); break; - case 11: (*m11)(); break; - case 12: (*m12)(); break; - case 13: (*m13)(); break; - case 14: (*m14)(); break; - case 15: (*m15)(); break; - case 16: (*m16)(); break; - case 17: (*m17)(); break; - case 18: (*m18)(); break; - case 19: (*m19)(); break; - default: - cprintf(RED, "Error: Task not defined. Abort!\n"); - break; - } - } - -private: - /** function number */ - int fnum; - -}; - - diff --git a/slsDetectorSoftware/threadFiles/ThreadPool.cpp b/slsDetectorSoftware/threadFiles/ThreadPool.cpp deleted file mode 100644 index 224038f5c..000000000 --- a/slsDetectorSoftware/threadFiles/ThreadPool.cpp +++ /dev/null @@ -1,191 +0,0 @@ -#include "ThreadPool.h" -#include -using namespace std; -ThreadPool::ThreadPool(int pool_size) : m_pool_size(pool_size){ -#ifdef VERBOSE - cout << "Constructed ThreadPool of size " << m_pool_size << endl; -#endif - m_tasks_loaded = false; - thread_started = false; - current_thread_number = -1; - number_of_ongoing_tasks = 0; - number_of_total_tasks = 0; -} - -ThreadPool::~ThreadPool(){ - // Release resources - if (m_pool_state != STOPPED) { - destroy_threadpool(); - } -} - - -extern "C" -void* start_thread(void* arg) -{ - ThreadPool* tp = (ThreadPool*) arg; - tp->execute_thread(); - return NULL; -} - -int ThreadPool::initialize_threadpool(){ - if(m_pool_size == 1) - return m_pool_size; - - m_pool_state = STARTED; - int ret = -1; - sem_init(&semStart,1,0); - sem_init(&semDone,1,0); - for (int i = 0; i < m_pool_size; i++) { - pthread_t tid; - thread_started = false; - current_thread_number = i; - ret = pthread_create(&tid, NULL, start_thread, (void*) this); - if (ret != 0) { - cerr << "pthread_create() failed: " << ret << endl; - return 0; - } - m_threads.push_back(tid); - while(!thread_started); - } -#ifdef VERBOSE - cout << m_pool_size << " threads created by the thread pool" << endl; -#endif - return m_pool_size; -} - -int ThreadPool::destroy_threadpool(){ - if(m_pool_size == 1) - return 0; - /*cout << "in destroying threadpool" << endl;*/ - // thread communication- modified m_pool_state may not show up - //to other threads until its modified in a lock! - m_task_mutex.lock(); - m_pool_state = STOPPED; - /*cout << "Broadcasting STOP signal to all threads..." << endl;*/ - m_task_cond_var.broadcast(); // notify all threads we are shttung down - m_task_mutex.unlock(); - -// int ret = -1; - for (int i = 0; i < m_pool_size; i++) { - sem_post(&semStart); - sem_post(&semDone); - - void* result; - pthread_join(m_threads[i], &result); - /*cout << "pthread_join() returned " << ret << ": " << strerror(errno) << endl;*/ - m_task_mutex.lock(); - m_task_cond_var.broadcast(); // try waking up a bunch of threads that are still waiting - m_task_mutex.unlock(); - } - - - sem_destroy(&semStart); - sem_destroy(&semDone); - number_of_ongoing_tasks = 0; - number_of_total_tasks = 0; - - /* cout << m_pool_size << " threads exited from the thread pool" << endl;*/ - return 0; -} - -void* ThreadPool::execute_thread(){ -//for debugging seting ithread value -// int ithread = current_thread_number; - thread_started = true; - Task* task = NULL; - m_tasks_loaded = false; - /*cout << "Starting thread " << pthread_self() << endl;*/ - while(true) { - // Try to pick a task - /*cout << "Locking: " << pthread_self() << endl;*/ - m_task_mutex.lock(); - - while ((m_pool_state != STOPPED) && (m_tasks.empty())) { - // Wait until there is a task in the queue - // Unlock mutex while wait, then lock it back when signaled - /* cout << "Unlocking and waiting: " << pthread_self() << endl;*/ - m_task_cond_var.wait(m_task_mutex.get_mutex_ptr()); - /* cout << "Signaled and locking: " << pthread_self() << endl;*/ - } - - // If the thread was woken up to notify process shutdown, return from here - if (m_pool_state == STOPPED) { - /* cout << "Unlocking and exiting: " << pthread_self() << endl;*/ - m_task_mutex.unlock(); - pthread_exit(NULL); - } - - task = m_tasks.front(); - m_tasks.pop_front(); - /*cout << "Unlocking: " << pthread_self() << endl;*/ - m_task_mutex.unlock(); - - sem_wait(&semStart); - - //cout<<"***"<run(arg); - /*cout << ithread <<" Done executing thread " << pthread_self() << endl;*/ - - delete task; - /*cout << ithread << " task deleted" << endl;*/ - - m_task_mutex.lock(); - number_of_ongoing_tasks--; - m_task_mutex.unlock(); - - //last task and check m_tasks_loaded to ensure done only once - if((!number_of_ongoing_tasks) && m_tasks_loaded){ - m_tasks_loaded = false; - } - - sem_post(&semDone); - //removed deleteing task to earlier - } - return NULL; -} - -int ThreadPool::add_task(Task* task){ - if(m_pool_size == 1){ - (*task)(); - return 0; - } - m_task_mutex.lock(); - - // TODO: put a limit on how many tasks can be added at most - m_tasks.push_back(task); - number_of_ongoing_tasks++; - number_of_total_tasks++; - m_task_cond_var.signal(); // wake up one thread that is waiting for a task to be available - m_task_mutex.unlock(); - return 0; -} - -void ThreadPool::startExecuting(){ - if(m_pool_size == 1) - return; - - /*cout << "waiting for tasks: locked. gonna wait" << endl;*/ - m_tasks_loaded = true; - - //giving all threads permission to start as all tasks have been added - for(int i=0;i -#include -#include -#include -#include -#include -#include -#include - -#include "Mutex.h" -#include "Task.h" -#include "CondVar.h" -#include "Global.h" -#include -// - - -class ThreadPool -{ -public: - ThreadPool(int pool_size); - ~ThreadPool(); - int initialize_threadpool(); - int destroy_threadpool(); - void* execute_thread(); - int add_task(Task* task); - void startExecuting(); - void wait_for_tasks_to_complete(); - -private: - int m_pool_size; - Mutex m_task_mutex; - CondVar m_task_cond_var; - std::vector m_threads; // storage for threads - std::deque m_tasks; - volatile int m_pool_state; - - volatile bool m_tasks_loaded; - volatile bool thread_started; - int current_thread_number; - - //volatile uint64_t tasks_done_mask; - volatile int number_of_ongoing_tasks; - volatile int number_of_total_tasks; - - sem_t semStart; - sem_t semDone; -}; - diff --git a/slsDetectorSoftware/threadFiles/bin/examplethreadpool_test b/slsDetectorSoftware/threadFiles/bin/examplethreadpool_test deleted file mode 100755 index 621d57a47..000000000 Binary files a/slsDetectorSoftware/threadFiles/bin/examplethreadpool_test and /dev/null differ diff --git a/slsDetectorSoftware/threadFiles/threadpool_test.cpp b/slsDetectorSoftware/threadFiles/threadpool_test.cpp deleted file mode 100644 index 2dbd2c416..000000000 --- a/slsDetectorSoftware/threadFiles/threadpool_test.cpp +++ /dev/null @@ -1,61 +0,0 @@ -//#include "ThreadPool.h" - -//#include "threadpool.h" - -#include -#include - -#include "Multi.h" -using namespace std; - -//const int MAX_TASKS = 4; - -/* -void hello(void* arg) -{ - string* x = (string*) arg; - cout << "Hello: " << *x << endl; -// cout << "\n"; -} -*/ -int main(int argc, char* argv[]) -{ - - Multi* m = new Multi(); - cout<<"Answer:"<< m->executeCommand(argc,argv) << endl; - delete m; - /* - ThreadPool tp(2); - int ret = tp.initialize_threadpool(); - if (ret == -1) { - cerr << "Failed to initialize thread pool!" << endl; - return 0; - } -*/ - - -/* - for (int i = 0; i < MAX_TASKS; i++) { - cout<<"adding task:" < gitInfo.txt - cd .. - ./genVersionHeader.sh $SPECDIR/gitInfo.txt $SPECDIR/$TMPFILE $SPECDIR/$INCLFILE - cd $WD -#fi \ No newline at end of file diff --git a/slsDetectorSoftware/usersFunctions/angleFunction.h b/slsDetectorSoftware/usersFunctions/angleFunction.h deleted file mode 100644 index d06adaf3b..000000000 --- a/slsDetectorSoftware/usersFunctions/angleFunction.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef DEFAULT_ANGLE_FUNCTION_H -#define DEFAULT_ANGLE_FUNCTION_H -#include - -/* - contains the conversion channel-angle for a module channel - conv_r=pitch/radius -*/ -#define PI 3.14159265358979323846 -#include - -double defaultAngleFunction(double ichan, double encoder, double totalOffset, double conv_r, double center, double offset, double tilt, int direction) {\ - (void) tilt; - double ang; - - ang=180./PI*(center*conv_r+direction*atan((double)(ichan-center)*conv_r))+encoder+totalOffset+offset; - - - //#ifdef VERBOSE - // printf("%d %f %f %f %f %f %f %d\n", ichan, ang, center, encoder, totalOffset, conv_r, offset, direction); - //#endif - - return ang; \ - return 180./PI*(center*conv_r+direction*atan((double)(ichan-center)*conv_r))+encoder+totalOffset+offset; }; - -#endif diff --git a/slsDetectorSoftware/usersFunctions/usersFunctions.cpp b/slsDetectorSoftware/usersFunctions/usersFunctions.cpp deleted file mode 100644 index 0d7b5318a..000000000 --- a/slsDetectorSoftware/usersFunctions/usersFunctions.cpp +++ /dev/null @@ -1,347 +0,0 @@ -#include "usersFunctions.h" -#include -#include - - -float pos; -float i0=0; -#ifdef EPICS - -#include -#include - -static double timeout = 3.0; - -chid ch_pos,ch_i0, ch_getpos; - - - - -/* connect to a PV */ -int connect_channel(const char *name, chid *ch_id) { - int status = ECA_NORMAL; - status = ca_create_channel(name, NULL, NULL, CA_PRIORITY_DEFAULT, ch_id); - if (status != ECA_NORMAL) - return status; - - status = ca_pend_io(timeout); - return status; -} - -/* disconnect to a PV */ -int disconnect_channel(chid ch_id) -{ - ca_clear_channel(ch_id); - ca_flush_io(); -} - -int caget(chid ch_id, double *value) { - - int status = ECA_NORMAL; - - status = ca_get(DBR_DOUBLE, ch_id, value); - if (status != ECA_NORMAL) { - return status; - } - - status = ca_pend_io(timeout); - if (status != ECA_NORMAL) { - return status; - } - - return status; -} - -int caputq(chid ch_id, double value) { - // does not wait! - int status = ECA_NORMAL; - - status = ca_put(DBR_DOUBLE, ch_id, &value); - if (status != ECA_NORMAL) - return status; - - status = ca_pend_io(timeout); - if (status != ECA_NORMAL) { - return status; - } - - return status; -} - -void put_callback(struct event_handler_args args) -{ - epicsEventId eid = (epicsEventId)args.usr; - epicsEventSignal(eid); -} - -int caput(chid ch_id, double value) { - - // waits! - int status = ECA_NORMAL; - epicsEventId eid = epicsEventCreate(epicsEventEmpty); - - status = ca_put_callback(DBR_DOUBLE, - ch_id, - &value, - put_callback, - eid); - status = ca_pend_io(timeout); - if (status != ECA_NORMAL) - return status; - - if (epicsEventWait(eid) != epicsEventWaitOK) - status = ECA_TIMEOUT; - - return status; -} - -//int main(int argc, char *argv[]) { - - - - - - - - -#endif - - - - - - - -// /* -// contains the conversion channel-angle for a module channel -// conv_r=pitch/radius -// */ - - -// double defaultAngleFunction(double ichan, double encoder, double totalOffset, double conv_r, double center, double offset, double tilt, int direction) { - - -// (void) tilt; /* to avoid warning: unused parameter */ -// double ang; - -// ang=180./PI*(center*conv_r+direction*atan((double)(ichan-center)*conv_r))+encoder+totalOffset+offset; - - -// //#ifdef VERBOSE -// printf("%d %f \n", ichan, ang); -// //#endif - -// return ang; - -// } - -/* reads the encoder and returns the position */ - -double defaultGetPosition(void*) { -#ifdef VERBOSE - printf("Getting motor position \n"); -#endif - // caget X04SA-ES2-TH2:RO.RBV - -#ifdef EPICS - int status; - - double value = 256; - if (ch_getpos<0) return -1; - -/* /\* caget *\/ */ - if (caget(ch_getpos, &value) == ECA_NORMAL) { -#ifdef VERBOSE - printf("caget: %f\n", value); -#endif - pos=value; - } else - printf(ca_message(status)); -#endif - - - - return pos; -} - -/* moves the encoder to position p */ - - -int defaultGoToPosition(double p, void*) { -#ifdef VERBOSE - printf("Setting motor position \n"); -#endif - -#ifdef EPICS - int status; - if (ch_pos<0) return -1; - /* /\* caput and wait until done *\/ */ - if ((status = caput(ch_pos, p)) == ECA_NORMAL) { - ; -#ifdef VERBOSE - printf("caput %f: success\n", p); -#endif - } else - printf(ca_message(status)); -#else - pos=p; -#endif - //"caputq X04SA-ES2-TH2:RO p" - //cawait -nounit -timeout 3600 X04SA-ES2-TH2:RO.DMOV '==1' - - return (int)p; -} - -/* moves the encoder to position p without waiting */ - -int defaultGoToPositionNoWait(double p, void*) { -#ifdef VERBOSE - printf("Setting motor position no wait \n"); -#endif - - -#ifdef EPICS - int status; - if (ch_pos<0) return -1; - /* /\* caput and wait until done *\/ */ - if ((status = caputq(ch_pos, p)) == ECA_NORMAL) { - ; -#ifdef VERBOSE - printf("caputq: success\n"); -#endif - } else - printf(ca_message(status)); -#else - pos=p; -#endif - //"caputq X04SA-ES2-TH2:RO p" - - return (int)p; - - pos=p; - return (int)pos; -} - - -/* reads I0 and returns the intensity */ - -double defaultGetI0(int t, void*) { -#ifdef VERBOSE - printf("Getting I0 readout \n"); -#endif - -#ifdef EPICS - int status; - - double value = 256; -/* /\* caget *\/ */ - if (ch_i0<0) return -1; - if (caget(ch_i0, &value) == ECA_NORMAL) { -#ifdef VERBOSE - printf("caget: %f\n", value); -#endif - - - if (t==0) - i0=value; - else - i0=value-i0; - - - - } else - printf(ca_message(status)); -#else - i0++; -#endif - - //"ca_get X04SA-ES2-SC:CH6" - return i0; - -} - - -int defaultConnectChannels(void *) { -#ifdef EPICS - //double value = 256; - /* channel name */ - //const char *name = "ARIDI-PCT:CURRENT"; - /* channel id */ - /* status code */ - int status; - -#ifdef VERBOSE - printf("starting...\n"); -#endif - - /* init channel access context before any caget/put */ - ca_context_create(ca_enable_preemptive_callback); -#ifdef VERBOSE - printf("context created\n"); -#endif - //"caputq X04SA-ES2-TH2:RO p" - - //"ca_get X04SA-ES2-SC:CH6" - - /* open the channel by name and return ch_id */ - status = connect_channel("X04SA-ES2-SC:CH6", &ch_i0); - if (status == ECA_NORMAL) { -#ifdef VERBOSE - printf("I0 channel connected \n"); -#endif - ; - } else { - printf(ca_message(status)); - //ch_i0=-1;; - } - status = connect_channel("X04SA-ES2-TH2:RO", &ch_pos); - if (status == ECA_NORMAL) { -#ifdef VERBOSE - printf("Detector position channel connected \n"); -#endif - ; - } else { - printf(ca_message(status)); - //ch_i0=-1;; - } - status = connect_channel("X04SA-ES2-TH2:RO.RBV", &ch_getpos); - if (status == ECA_NORMAL) { -#ifdef VERBOSE - printf("Detector get position channel connected \n"); -#endif - ; - } else { - printf(ca_message(status)); - //ch_getpos=-1;; - } - - // caget X04SA-ES2-TH2:RO.RBV - - //cawait -nounit -timeout 3600 X04SA-ES2-TH2:RO.DMOV '==1' -#endif - return 0; -} - -int defaultDisconnectChannels(void*) { -#ifdef EPICS - /* close channel connect */ - disconnect_channel(ch_i0); - disconnect_channel(ch_pos); - disconnect_channel(ch_getpos); - - /* delete channel access context before program exits */ - ca_context_destroy(); -#endif - return 0; -} - - - -int defaultDataReadyFunc(detectorData* d) { -#ifdef VERBOSE - printf("UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU Data received \n"); -#endif - return 0; -} - - diff --git a/slsDetectorSoftware/usersFunctions/usersFunctions.h b/slsDetectorSoftware/usersFunctions/usersFunctions.h deleted file mode 100644 index d2cc60f71..000000000 --- a/slsDetectorSoftware/usersFunctions/usersFunctions.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef USERS_FUNCTIONS_H -#define USERS_FUNCTIONS_H -/****************************************************************** - -Functions depending on the experimental setup should be defined here - -******************************************************************/ - -#define PI 3.14159265358979323846 - - -#ifdef EPICS -#include -#include -#endif -#include "detectorData.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#ifdef EPICS - int connect_channel(const char *name, chid *ch_id); - int disconnect_channel(chid ch_id); - int caget(chid ch_id, double *value); - int caputq(chid ch_id, double value); - void put_callback(struct event_handler_args args); - int caput(chid ch_id, double value); -#endif - - - // double defaultAngleFunction(double ichan, double encoder, double totalOffset, double conv_r, double center, double offset, double tilt, int direction); - double defaultGetPosition(void*); - int defaultGoToPosition(double p, void*); - int defaultGoToPositionNoWait(double p, void*); - int defaultConnectChannels(void*); - int defaultDisconnectChannels(void*); - double defaultGetI0(int t, void*); - - int defaultDataReadyFunc(detectorData* d, void*); - - - -#ifdef __cplusplus -}; -#endif - - -#endif diff --git a/slsReceiverSoftware/.gitignore b/slsReceiverSoftware/.gitignore deleted file mode 100644 index a515bd3e6..000000000 --- a/slsReceiverSoftware/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -*~ -*.o -build/* -GPATH -GRTAGS -GSYMS -GTAGS -.project diff --git a/slsReceiverSoftware/CMakeLists.txt b/slsReceiverSoftware/CMakeLists.txt old mode 100644 new mode 100755 index 63311c5ef..f02689010 --- a/slsReceiverSoftware/CMakeLists.txt +++ b/slsReceiverSoftware/CMakeLists.txt @@ -1,12 +1,8 @@ set(SOURCES - src/MySocketTCP.cpp - src/UDPInterface.cpp - src/UDPBaseImplementation.cpp - src/UDPStandardImplementation.cpp + src/slsReceiverImplementation.cpp src/slsReceiverTCPIPInterface.cpp src/slsReceiver.cpp src/slsReceiverUsers.cpp - src/utilities.cpp src/File.cpp src/BinaryFile.cpp src/ThreadObject.cpp @@ -33,34 +29,29 @@ if (SLS_USE_HDF5) endif (SLS_USE_HDF5) -add_definitions( - -DDACS_INT -DSLS_RECEIVER_UDP_FUNCTIONS -) - -include_directories( - include -) - -add_library(zmq STATIC IMPORTED GLOBAL) - -set(ZMQ_STATIC_ARCHIVE ${CMAKE_CURRENT_SOURCE_DIR}/include/libzmq.a) -set_target_properties(zmq PROPERTIES - IMPORTED_LOCATION ${ZMQ_STATIC_ARCHIVE} -) - add_library(slsReceiverShared SHARED ${SOURCES} ${HEADERS} ) +check_ipo_supported(RESULT result) +if(result) + set_property(TARGET slsReceiverShared PROPERTY INTERPROCEDURAL_OPTIMIZATION True) +endif() + +target_link_libraries(slsReceiverShared PUBLIC + slsProjectOptions + slsProjectWarnings + slsSupportLib +) + +target_include_directories(slsReceiverShared PUBLIC + "$" + "$") + +#What is included in slsReceiverLib? set(PUBLICHEADERS - include/sls_receiver_defs.h - include/ansi.h - include/sls_receiver_funcs.h - include/MySocketTCP.h - include/genericSocket.h - include/logger.h - include/sls_receiver_exceptions.h + include/slsReceiverUsers.h ) @@ -76,25 +67,31 @@ add_executable(slsReceiver set_target_properties(slsReceiver PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin ) -target_link_libraries(slsReceiver + +target_link_libraries(slsReceiver PUBLIC + slsProjectOptions + slsProjectWarnings + slsSupportLib slsReceiverShared pthread - zmq + ${ZeroMQ_LIBRARIES} rt ) if (HDF5_FOUND) - target_link_libraries(slsReceiver ${HDF5_LIBRARIES}) + target_link_libraries(slsReceiver PUBLIC ${HDF5_LIBRARIES}) endif () +if (SLS_USE_TESTS) + add_subdirectory(tests) +endif(SLS_USE_TESTS) - -install(TARGETS slsReceiverShared slsReceiver +install(TARGETS slsReceiverShared EXPORT "${TARGETS_EXPORT_NAME}" - RUNTIME DESTINATION bin - LIBRARY DESTINATION lib - ARCHIVE DESTINATION lib - PUBLIC_HEADER DESTINATION include) + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(FILES ${ZMQ_STATIC_ARCHIVE} -DESTINATION lib) +DESTINATION lib) diff --git a/slsReceiverSoftware/Makefile b/slsReceiverSoftware/Makefile deleted file mode 100644 index 655d0c1dc..000000000 --- a/slsReceiverSoftware/Makefile +++ /dev/null @@ -1,126 +0,0 @@ -include ../Makefile.include - -DESTDIR ?= ../bin -LIBDIR ?= ../bin -DOCDIR ?= docs -SRCDIR = src -INCDIR = include -TESTDIR = test -BUILDDIR = build -PROGS = $(DESTDIR)/slsReceiver - - -CFLAGS= -g -DC_ONLY -fPIC -#FLAGS+= #-DVERBOSE -DVERYVERBOSE - -DFLAGS= -g -DDACS_INT -DSLS_RECEIVER_UDP_FUNCTIONS #-DVERBOSE - -INCLUDES?= $(INCLUDESRXR) -I include/ - -############################################################## -# ZMQ specific: in this case, you need ZMQ libraries already included in this package -########################################################### -LIBZMQDIR = include -LIBZMQ = -L$(LIBZMQDIR) -Wl,-rpath=$(LIBZMQDIR) -lzmq - - - -SRC_CLNT = MySocketTCP.cpp ThreadObject.cpp Listener.cpp DataProcessor.cpp DataStreamer.cpp Fifo.cpp File.cpp BinaryFile.cpp UDPInterface.cpp UDPBaseImplementation.cpp UDPStandardImplementation.cpp slsReceiverTCPIPInterface.cpp slsReceiver.cpp slsReceiverUsers.cpp utilities.cpp -DEPSINCLUDES = $(INCDIR)/ansi.h $(INCDIR)/sls_receiver_defs.h $(INCDIR)/sls_receiver_funcs.h $(INCDIR)/GeneralData.h $(INCDIR)/circularFifo.h $(INCDIR)/genericSocket.h $(INCDIR)/logger.h $(INCDIR)/receiver_defs.h $(INCDIR)/UDPInterface.h $(INCDIR)/utilities.h $(INCDIR)/ZmqSocket.h $(INCDIR)/BinaryFileStatic.h $(INCDIR)/HDF5FileStatic.h $(INCDIR)/sls_receiver_exceptions.h - - -ifeq ($(HDF5),yes) - SRC_CLNT += HDF5File.cpp -endif - -MAIN_SRC = main.cpp - - -OBJS=$(SRC_CLNT:%.cpp=$(BUILDDIR)/%.o) - -$(info ) -$(info #######################################) -$(info # In slsReceiverSoftware Makefile #) -$(info #######################################) -$(info ) - - -.PHONY: all intdoc package eigerReceiver clean - -all: builddir lib receiver - -dummy: $(DESTDIR)/dummyReceiver - -intdoc: $(SRC_H) $(SRC_CLNT) - doxygen doxy.config - -$(BUILDDIR)/%.o : $(SRCDIR)/%.cpp $(INCDIR)/%.h $(DEPSINCLUDES) Makefile -ifeq ($(ROOTSLS),yes) - $(CXX) -DROOTSLS -o $@ -c $< $(INCLUDES) $(DFLAGS) $(ROOTFLAGS) -fPIC $(EPICSFLAGS) $(LDFLAGRXR) -L/usr/lib64/ $(FLAGS) -else -# $(call colorecho,`./updateGitVersion.sh`) - $(CXX) -o $@ -c $< $(INCLUDES) $(DFLAGS) -fPIC $(EPICSFLAGS) $(LDFLAGRXR) -pthread $(FLAGS) $(LIBZMQ) -lrt -endif - -versioning: - $(call colorecho,`./updateGitVersion.sh`) - -lib: versioning $(OBJS) $(DESTDIR)/libSlsReceiver.so $(DESTDIR)/libSlsReceiver.a - -receiver: $(DESTDIR)/slsReceiver - -$(DESTDIR)/libSlsReceiver.so: $(OBJS) - $(call colorecho,"#######################################") - $(call colorecho,"# Compiling slsReceiver Library #") - $(call colorecho,"#######################################") - $(CXX) -shared -Wl,-soname,libSlsReceiver.so -o libSlsReceiver.so $(OBJS) -lc $(INCLUDES) $(DFLAGS) $(FLAGS) $(EPICSFLAGS) -L/usr/lib64 -pthread $(LIBZMQ) -lrt - $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) - mv libSlsReceiver.so $(DESTDIR) - -$(DESTDIR)/libSlsReceiver.a: $(OBJS) - ar rcs libSlsReceiver.a $(OBJS) - mv libSlsReceiver.a $(DESTDIR) - - -$(DESTDIR)/slsReceiver: $(SRCDIR)/$(MAIN_SRC) $(DESTDIR)/libSlsReceiver.so $(DESTDIR)/libSlsReceiver.a - $(call colorecho,"#######################################") - $(call colorecho,"# Compiling slsReceiver #") - $(call colorecho,"#######################################") - $(CXX) -o $@ $(SRCDIR)/$(MAIN_SRC) $(FLAGS) $(INCLUDES) $(CFLAGS) $(LIBS) $(LDFLAGRXR) -fPIC $(LIBZMQ) -lrt -#$(EIGERFLAGS) - - -$(DESTDIR)/dummyReceiver: $(SRCDIR)/$(DUMMY_MAIN_SRC) $(DESTDIR)/libSlsReceiver.so $(DESTDIR)/libSlsReceiver.a - $(call colorecho,"#######################################") - $(call colorecho,"# Compiling Dummy slsReceiver #") - $(call colorecho,"#######################################") - $(CXX) -o $@ $(SRCDIR)/$(DUMMY_MAIN_SRC) $(FLAGS) $(INCLUDES) $(CFLAGS) $(LIBS) $(LDFLAGRXR) -fPIC $(LIBZMQ) -lrt -#$(EIGERFLAGS) - - -clean: buildclean - make testclean - if test -e $(DESTDIR)/libSlsReceiver.a; then rm $(DESTDIR)/libSlsReceiver.a;fi - if test -e $(DESTDIR)/libSlsReceiver.so; then rm $(DESTDIR)/libSlsReceiver.so;fi - if test -e $(PROGS); then rm $(PROGS);fi - -builddir: - mkdir -p $(BUILDDIR) -# if [ ! -d $(BUILDDIR) ]; then mkdir $(BUILDDIR); fi - -buildclean: - rm -rf $(OBJS) - -testclean: - if [ -f $(TESTDIR)/rec ]; then \ - cd $(TESTDIR) && rm *.o rec send; \ - fi - - -#------------------------------------------------------------------------------- - -install: package - -install_inc: - $(shell test -d $(DESTDIR) || mkdir -p $(DESTDIR)) - cp -P slsReceiver/slsReceiverUsers.h $(DESTDIR) diff --git a/slsReceiverSoftware/gitInfo.txt b/slsReceiverSoftware/gitInfo.txt deleted file mode 100644 index 96759d264..000000000 --- a/slsReceiverSoftware/gitInfo.txt +++ /dev/null @@ -1,9 +0,0 @@ -Path: slsDetectorsPackage/slsReceiverSoftware -URL: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repository Root: origin git@github.com:slsdetectorgroup/slsDetectorPackage.git -Repsitory UUID: 907d1655d1f6cf2bb8cf6ccd7e91e82f479dd2ca -Revision: 859 -Branch: developer -Last Changed Author: Dhanya_Thattil -Last Changed Rev: 4101 -Last Changed Date: 2019-02-11 14:04:47.000000002 +0100 ./src/slsReceiverTCPIPInterface.cpp diff --git a/slsReceiverSoftware/include/BinaryFile.h b/slsReceiverSoftware/include/BinaryFile.h old mode 100644 new mode 100755 index 9cb585396..8d9324df7 --- a/slsReceiverSoftware/include/BinaryFile.h +++ b/slsReceiverSoftware/include/BinaryFile.h @@ -14,7 +14,7 @@ #include -class BinaryFile : private virtual slsReceiverDefs, public File, public BinaryFileStatic { +class BinaryFile : private virtual slsDetectorDefs, public File, public BinaryFileStatic { public: /** @@ -47,7 +47,7 @@ class BinaryFile : private virtual slsReceiverDefs, public File, public BinaryFi /** * Print all member values */ - void PrintMembers(); + void PrintMembers(TLogLevel level = logDEBUG1); /** * Create file diff --git a/slsReceiverSoftware/include/BinaryFileStatic.h b/slsReceiverSoftware/include/BinaryFileStatic.h old mode 100644 new mode 100755 index 348453b82..b528f8d73 --- a/slsReceiverSoftware/include/BinaryFileStatic.h +++ b/slsReceiverSoftware/include/BinaryFileStatic.h @@ -123,12 +123,14 @@ class BinaryFileStatic { { if(!owenable){ if (NULL == (fd = fopen((const char *) fname.c_str(), "wx"))){ - cprintf(RED,"Error in creating binary master file %s\n",fname.c_str()); + FILE_LOG(logERROR) << "Could not create binary master file " + "(without overwrite enable) " << fname; fd = 0; return 1; } }else if (NULL == (fd = fopen((const char *) fname.c_str(), "w"))){ - cprintf(RED,"Error in creating binary master file %s\n",fname.c_str()); + FILE_LOG(logERROR) << "Could not create binary master file " + "(with overwrite enable) " << fname; fd = 0; return 1; } @@ -179,8 +181,8 @@ class BinaryFileStatic { (long long int)acquisitionPeriod, ctime(&t)); if (strlen(message) > MAX_MASTER_FILE_LENGTH) { - cprintf(RED,"Master File Size %d is greater than max str size %d\n", - (int)strlen(message), MAX_MASTER_FILE_LENGTH); + FILE_LOG(logERROR) << "Master File Size " << strlen(message) << + " is greater than max str size " << MAX_MASTER_FILE_LENGTH; return 1; } diff --git a/slsReceiverSoftware/include/DataProcessor.h b/slsReceiverSoftware/include/DataProcessor.h old mode 100644 new mode 100755 index 6b7692430..fd8a62b0a --- a/slsReceiverSoftware/include/DataProcessor.h +++ b/slsReceiverSoftware/include/DataProcessor.h @@ -18,7 +18,7 @@ class DataStreamer; #include -class DataProcessor : private virtual slsReceiverDefs, public ThreadObject { +class DataProcessor : private virtual slsDetectorDefs, public ThreadObject { public: /** @@ -38,17 +38,11 @@ class DataProcessor : private virtual slsReceiverDefs, public ThreadObject { * @param act pointer to activated * @param depaden pointer to deactivated padding enable * @param sm pointer to silent mode - * @param dataReadycb pointer to data ready call back function - * @param dataModifyReadycb pointer to data ready call back function with modified - * @param pDataReadycb pointer to arguments of data ready call back function. To write/stream a smaller size of processed data, change this value (only smaller value is allowed). */ - DataProcessor(int ind, detectorType dtype, Fifo*& f, fileFormat* ftype, + DataProcessor(int ind, detectorType dtype, Fifo* f, fileFormat* ftype, bool fwenable, bool* dsEnable, bool* gpEnable, uint32_t* dr, uint32_t* freq, uint32_t* timer, - bool* fp, bool* act, bool* depaden, bool* sm, - void (*dataReadycb)(char*, char*, uint32_t, void*), - void (*dataModifyReadycb)(char*, char*, uint32_t &, void*), - void *pDataReadycb); + bool* fp, bool* act, bool* depaden, bool* sm); /** * Destructor @@ -121,7 +115,7 @@ class DataProcessor : private virtual slsReceiverDefs, public ThreadObject { * Set Fifo pointer to the one given * @param f address of Fifo pointer */ - void SetFifo(Fifo*& f); + void SetFifo(Fifo* f); /** * Reset parameters for new acquisition (including all scans) @@ -203,6 +197,27 @@ class DataProcessor : private virtual slsReceiverDefs, public ThreadObject { */ void SetPixelDimension(); + /** + * Call back for raw data + * args to raw data ready callback are + * sls_receiver_header frame metadata + * dataPointer is the pointer to the data + * dataSize in bytes is the size of the data in bytes. + */ + void registerCallBackRawDataReady(void (*func)(char* , + char*, uint32_t, void*),void *arg); + + /** + * Call back for raw data (modified) + * args to raw data ready callback are + * sls_receiver_header frame metadata + * dataPointer is the pointer to the data + * revDatasize is the reference of data size in bytes. + * Can be modified to the new size to be written/streamed. (only smaller value). + */ + void registerCallBackRawDataModifyReady(void (*func)(char* , + char*, uint32_t &,void*),void *arg); + diff --git a/slsReceiverSoftware/include/DataStreamer.h b/slsReceiverSoftware/include/DataStreamer.h old mode 100644 new mode 100755 index 8857102c7..18490565f --- a/slsReceiverSoftware/include/DataStreamer.h +++ b/slsReceiverSoftware/include/DataStreamer.h @@ -16,7 +16,7 @@ class ZmqSocket; #include -class DataStreamer : private virtual slsReceiverDefs, public ThreadObject { +class DataStreamer : private virtual slsDetectorDefs, public ThreadObject { public: /** @@ -29,10 +29,9 @@ class DataStreamer : private virtual slsReceiverDefs, public ThreadObject { * @param fi pointer to file index * @param fd flipped data enable for x and y dimensions * @param ajh additional json header - * @param sm pointer to silent mode */ - DataStreamer(int ind, Fifo*& f, uint32_t* dr, std::vector* r, - uint64_t* fi, int* fd, char* ajh, bool* sm); + DataStreamer(int ind, Fifo* f, uint32_t* dr, std::vector* r, + uint64_t* fi, int* fd, char* ajh); /** * Destructor @@ -63,7 +62,7 @@ class DataStreamer : private virtual slsReceiverDefs, public ThreadObject { * Set Fifo pointer to the one given * @param f address of Fifo pointer */ - void SetFifo(Fifo*& f); + void SetFifo(Fifo* f); /** * Reset parameters for new acquisition (including all scans) @@ -73,7 +72,7 @@ class DataStreamer : private virtual slsReceiverDefs, public ThreadObject { /** * Reset parameters for new measurement (eg. for each scan) */ - void ResetParametersforNewMeasurement(char* fname); + void ResetParametersforNewMeasurement(const std::string& fname); /** * Set GeneralData pointer to the one given @@ -202,7 +201,7 @@ class DataStreamer : private virtual slsReceiverDefs, public ThreadObject { uint64_t firstMeasurementIndex; /* File name to stream */ - char fileNametoStream[MAX_STR_LENGTH]; + std::string fileNametoStream; /** Complete buffer used for roi, eg. shortGotthard */ char* completeBuffer; diff --git a/slsReceiverSoftware/include/Fifo.h b/slsReceiverSoftware/include/Fifo.h old mode 100644 new mode 100755 index 5fad6a3cc..082357168 --- a/slsReceiverSoftware/include/Fifo.h +++ b/slsReceiverSoftware/include/Fifo.h @@ -9,12 +9,12 @@ *@short constructs the fifo structure */ -#include "sls_receiver_defs.h" +#include "sls_detector_defs.h" #include "logger.h" #include "circularFifo.h" -class Fifo : private virtual slsReceiverDefs { +class Fifo : private virtual slsDetectorDefs { public: /** diff --git a/slsReceiverSoftware/include/File.h b/slsReceiverSoftware/include/File.h old mode 100644 new mode 100755 index cb403c2b1..750c2296e --- a/slsReceiverSoftware/include/File.h +++ b/slsReceiverSoftware/include/File.h @@ -8,13 +8,13 @@ *@short sets/gets properties for the file, creates/closes the file and writes data to it */ -#include "sls_receiver_defs.h" +#include "sls_detector_defs.h" #include "logger.h" #include -class File : private virtual slsReceiverDefs { +class File : private virtual slsDetectorDefs { public: /** @@ -53,7 +53,7 @@ class File : private virtual slsReceiverDefs { /** * Print all member values */ - virtual void PrintMembers(); + virtual void PrintMembers(TLogLevel level = logDEBUG1); /** * Get Type @@ -85,8 +85,8 @@ class File : private virtual slsReceiverDefs { * @returns OK or FAIL */ virtual int CreateFile(uint64_t fnum){ - cprintf(RED,"This is a generic function CreateFile that should be " - "overloaded by a derived class\n"); + FILE_LOG(logERROR) << "This is a generic function CreateFile that should be " + "overloaded by a derived class"; return OK; } @@ -94,16 +94,16 @@ class File : private virtual slsReceiverDefs { * Close Current File */ virtual void CloseCurrentFile() { - cprintf(RED,"This is a generic function CloseCurrentFile that should be " - "overloaded by a derived class\n"); + FILE_LOG(logERROR) << "This is a generic function CloseCurrentFile that should be " + "overloaded by a derived class"; } /** * Close Files */ virtual void CloseAllFiles() { - cprintf(RED,"This is a generic function that should be overloaded " - "by a derived class\n"); + FILE_LOG(logERROR) << "This is a generic function that should be overloaded " + "by a derived class"; } /** @@ -114,8 +114,8 @@ class File : private virtual slsReceiverDefs { * @param OK or FAIL */ virtual int WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t nump) { - cprintf(RED,"This is a generic function WriteToFile that " - "should be overloaded by a derived class\n"); + FILE_LOG(logERROR) << "This is a generic function WriteToFile that " + "should be overloaded by a derived class"; return FAIL; } @@ -134,8 +134,8 @@ class File : private virtual slsReceiverDefs { virtual int CreateMasterFile(bool en, uint32_t size, uint32_t nx, uint32_t ny, uint64_t at, uint64_t st, uint64_t sp, uint64_t ap) { - cprintf(RED,"This is a generic function CreateMasterFile that " - "should be overloaded by a derived class\n"); + FILE_LOG(logERROR) << "This is a generic function CreateMasterFile that " + "should be overloaded by a derived class"; return OK; } @@ -146,8 +146,8 @@ class File : private virtual slsReceiverDefs { * @param ny number of pixels in y direction */ virtual void SetNumberofPixels(uint32_t nx, uint32_t ny) { - cprintf(RED,"This is a generic function SetNumberofPixels that " - "should be overloaded by a derived class\n"); + FILE_LOG(logERROR) << "This is a generic function SetNumberofPixels that " + "should be overloaded by a derived class"; } /** @@ -156,8 +156,8 @@ class File : private virtual slsReceiverDefs { * @param numf number of images caught */ virtual void EndofAcquisition(bool anyPacketsCaught, uint64_t numf) { - cprintf(RED,"This is a generic function EndofAcquisition that " - "should be overloaded by a derived class\n"); + FILE_LOG(logERROR) << "This is a generic function EndofAcquisition that " + "should be overloaded by a derived class"; } protected: diff --git a/slsReceiverSoftware/include/GeneralData.h b/slsReceiverSoftware/include/GeneralData.h old mode 100644 new mode 100755 index c9276a778..a6513bae8 --- a/slsReceiverSoftware/include/GeneralData.h +++ b/slsReceiverSoftware/include/GeneralData.h @@ -7,10 +7,10 @@ *@short abstract for setting/getting properties of detector data */ -#include "sls_receiver_defs.h" +#include "sls_detector_defs.h" #include "receiver_defs.h" - -#include //ceil +#include "logger.h" +#include //ceil #include @@ -19,7 +19,7 @@ class GeneralData { public: /** DetectorType */ - slsReceiverDefs::detectorType myDetectorType; + slsDetectorDefs::detectorType myDetectorType; /** Number of Pixels in x axis */ uint32_t nPixelsX; @@ -89,9 +89,10 @@ public: + /** Cosntructor */ GeneralData(): - myDetectorType(slsReceiverDefs::GENERIC), + myDetectorType(slsDetectorDefs::GENERIC), nPixelsX(0), nPixelsY(0), emptyHeader(0), @@ -145,8 +146,8 @@ public: * Set ROI * @param i ROI */ - virtual void SetROI(std::vector i) { - cprintf(RED,"This is a generic function that should be overloaded by a derived class\n"); + virtual void SetROI(std::vector i) { + FILE_LOG(logERROR) << "SetROI is a generic function that should be overloaded by a derived class"; }; /** @@ -155,8 +156,8 @@ public: * @param i pointer to a vector of ROI pointers * @returns adc configured */ - virtual int GetAdcConfigured(int index, std::vector* i) const{ - cprintf(RED,"This is a generic function that should be overloaded by a derived class\n"); + virtual int GetAdcConfigured(int index, std::vector* i) const{ + FILE_LOG(logERROR) << "GetAdcConfigured is a generic function that should be overloaded by a derived class"; return 0; }; @@ -166,7 +167,7 @@ public: * @param tgEnable true if 10GbE is enabled, else false */ virtual void SetDynamicRange(int dr, bool tgEnable) { - cprintf(RED,"This is a generic function that should be overloaded by a derived class\n"); + FILE_LOG(logERROR) << "SetDynamicRange is a generic function that should be overloaded by a derived class"; }; /** @@ -175,16 +176,15 @@ public: * @param dr dynamic range */ virtual void SetTenGigaEnable(bool tgEnable, int dr) { - cprintf(RED,"This is a generic function that should be overloaded by a derived class\n"); + FILE_LOG(logERROR) << "SetTenGigaEnable is a generic function that should be overloaded by a derived class"; }; /** * Setting packets per frame changes member variables * @param ns number of samples - * @param nroich number of channels in roi */ - virtual void setNumberofSamples(const uint64_t ns, uint32_t nroich) { - cprintf(RED,"This is a generic function that should be overloaded by a derived class\n"); + virtual void setNumberofSamples(const uint64_t ns) { + FILE_LOG(logERROR) << "setNumberofSamples is a generic function that should be overloaded by a derived class"; }; /** @@ -192,49 +192,67 @@ public: * @param enable true if gap pixels enable, else false */ virtual void SetGapPixelsEnable(bool b, int dr) { - cprintf(RED,"This is a generic function that should be overloaded by a derived class\n"); + FILE_LOG(logERROR) << "SetGapPixelsEnable is a generic function that should be overloaded by a derived class"; }; - /** - * Set odd starting packet (gotthard) - * @param index thread index for debugging purposes - * @param packetData pointer to data - * @returns true or false for odd starting packet number - */ - virtual bool SetOddStartingPacket(int index, char* packetData) { - cprintf(RED,"This is a generic function that should be overloaded by a derived class\n"); - return false; - }; + /** + * Set odd starting packet (gotthard) + * @param index thread index for debugging purposes + * @param packetData pointer to data + * @returns true or false for odd starting packet number + */ + virtual bool SetOddStartingPacket(int index, char* packetData) { + cprintf(RED,"SetOddStartingPacket is a generic function that should be overloaded by a derived class\n"); + return false; + }; + /** + * Set databytes (ctb, moench) + * @param f readout flags + * @param r roi + * @param s number of samples + * @param t tengiga enable + */ + virtual void setImageSize(std::vector r, int s, bool t, slsDetectorDefs::readOutFlags f = slsDetectorDefs::GET_READOUT_FLAGS) { + cprintf(RED,"setImageSize is a generic function that should be overloaded by a derived class\n"); + }; + + /** + * set number of interfaces (jungfrau) + * @param number of interfaces + */ + virtual void SetNumberofInterfaces(const int n) { + cprintf(RED,"SetNumberofInterfaces is a generic function that should be overloaded by a derived class\n"); + } /** * Print all variables */ - virtual void Print() const { - FILE_LOG(logDEBUG) << "\n\nDetector Data Variables:"; - FILE_LOG(logDEBUG) << "myDetectorType: " << slsReceiverDefs::getDetectorType(myDetectorType); - FILE_LOG(logDEBUG) << "Pixels X: " << nPixelsX; - FILE_LOG(logDEBUG) << "Pixels Y: " << nPixelsY; - FILE_LOG(logDEBUG) << "Empty Header: " << emptyHeader; - FILE_LOG(logDEBUG) << "Header Size in Packet: " << headerSizeinPacket; - FILE_LOG(logDEBUG) << "Data Size: " << dataSize; - FILE_LOG(logDEBUG) << "Packet Size: " << packetSize; - FILE_LOG(logDEBUG) << "Packets per Frame: " << packetsPerFrame; - FILE_LOG(logDEBUG) << "Image Size: " << imageSize; - FILE_LOG(logDEBUG) << "Frame Index Mask: " << frameIndexMask; - FILE_LOG(logDEBUG) << "Frame Index Offset: " << frameIndexOffset; - FILE_LOG(logDEBUG) << "Packet Index Mask: " << packetIndexMask; - FILE_LOG(logDEBUG) << "Packet Index Offset: " << packetIndexOffset; - FILE_LOG(logDEBUG) << "Max Frames Per File: " << maxFramesPerFile; - FILE_LOG(logDEBUG) << "Fifo Buffer Header Size: " << fifoBufferHeaderSize; - FILE_LOG(logDEBUG) << "Default Fifo Depth: " << defaultFifoDepth; - FILE_LOG(logDEBUG) << "Threads Per Receiver: " << threadsPerReceiver; - FILE_LOG(logDEBUG) << "Header Packet Size: " << headerPacketSize; - FILE_LOG(logDEBUG) << "Complete Pixels X: " << nPixelsXComplete; - FILE_LOG(logDEBUG) << "Complete Pixels Y: " << nPixelsYComplete; - FILE_LOG(logDEBUG) << "Complete Image Size: " << imageSizeComplete; - FILE_LOG(logDEBUG) << "Standard Header: " << standardheader; - FILE_LOG(logDEBUG) << "UDP Socket Buffer Size: " << defaultUdpSocketBufferSize; + virtual void Print(TLogLevel level = logDEBUG1) const { + FILE_LOG(level) << "\n\nDetector Data Variables:"; + FILE_LOG(level) << "myDetectorType: " << slsDetectorDefs::detectorTypeToString(myDetectorType); + FILE_LOG(level) << "Pixels X: " << nPixelsX; + FILE_LOG(level) << "Pixels Y: " << nPixelsY; + FILE_LOG(level) << "Empty Header: " << emptyHeader; + FILE_LOG(level) << "Header Size in Packet: " << headerSizeinPacket; + FILE_LOG(level) << "Data Size: " << dataSize; + FILE_LOG(level) << "Packet Size: " << packetSize; + FILE_LOG(level) << "Packets per Frame: " << packetsPerFrame; + FILE_LOG(level) << "Image Size: " << imageSize; + FILE_LOG(level) << "Frame Index Mask: " << frameIndexMask; + FILE_LOG(level) << "Frame Index Offset: " << frameIndexOffset; + FILE_LOG(level) << "Packet Index Mask: " << packetIndexMask; + FILE_LOG(level) << "Packet Index Offset: " << packetIndexOffset; + FILE_LOG(level) << "Max Frames Per File: " << maxFramesPerFile; + FILE_LOG(level) << "Fifo Buffer Header Size: " << fifoBufferHeaderSize; + FILE_LOG(level) << "Default Fifo Depth: " << defaultFifoDepth; + FILE_LOG(level) << "Threads Per Receiver: " << threadsPerReceiver; + FILE_LOG(level) << "Header Packet Size: " << headerPacketSize; + FILE_LOG(level) << "Complete Pixels X: " << nPixelsXComplete; + FILE_LOG(level) << "Complete Pixels Y: " << nPixelsYComplete; + FILE_LOG(level) << "Complete Image Size: " << imageSizeComplete; + FILE_LOG(level) << "Standard Header: " << standardheader; + FILE_LOG(level) << "UDP Socket Buffer Size: " << defaultUdpSocketBufferSize; }; }; @@ -242,14 +260,14 @@ public: class GotthardData : public GeneralData { private: - const static int nChip = 10; - const static int nChan = 128; - const static int nChipsPerAdc = 2; + const int nChip = 10; + const int nChan = 128; + const int nChipsPerAdc = 2; public: /** Constructor */ GotthardData(){ - myDetectorType = slsReceiverDefs::GOTTHARD; + myDetectorType = slsDetectorDefs::GOTTHARD; nPixelsX = 1280; nPixelsY = 1; headerSizeinPacket = 4; @@ -261,7 +279,7 @@ private: frameIndexOffset = 1; packetIndexMask = 1; maxFramesPerFile = MAX_FRAMES_PER_FILE; - fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsReceiverDefs::sls_receiver_header); + fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsDetectorDefs::sls_receiver_header); defaultFifoDepth = 50000; }; @@ -283,7 +301,7 @@ private: if (nPixelsX == 1280) { subFrameNumber = -1; bunchId = -1; - frameNumber = ((uint32_t)(*((uint32_t*)(packetData)))); + frameNumber = *reinterpret_cast(packetData); if (oddStartingPacket) frameNumber++; packetNumber = frameNumber&packetIndexMask; @@ -291,8 +309,8 @@ private: } else { subFrameNumber = -1; bunchId = -1; - frameNumber = ((uint32_t)(*((uint32_t*)(packetData)))); - packetNumber = 0; + frameNumber = *reinterpret_cast(packetData); + packetNumber = 0; } } @@ -301,7 +319,7 @@ private: * Set ROI * @param i ROI */ - void SetROI(std::vector i) { + void SetROI(std::vector i) { // all adcs if(!i.size()) { nPixelsX = 1280; @@ -313,7 +331,7 @@ private: frameIndexOffset = 1; packetIndexMask = 1; maxFramesPerFile = MAX_FRAMES_PER_FILE; - fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsReceiverDefs::sls_receiver_header); + fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsDetectorDefs::sls_receiver_header); defaultFifoDepth = 50000; nPixelsXComplete = 0; nPixelsYComplete = 0; @@ -331,7 +349,7 @@ private: frameIndexOffset = 0; packetIndexMask = 0; maxFramesPerFile = SHORT_MAX_FRAMES_PER_FILE; - fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsReceiverDefs::sls_receiver_header); + fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsDetectorDefs::sls_receiver_header); defaultFifoDepth = 25000; nPixelsXComplete = 1280; nPixelsYComplete = 1; @@ -345,7 +363,7 @@ private: * @param i pointer to a vector of ROI * @returns adc configured */ - int GetAdcConfigured(int index, std::vector* i) const{ + int GetAdcConfigured(int index, std::vector* i) const{ int adc = -1; // single adc if(i->size()) { @@ -376,8 +394,8 @@ private: * @param packetData pointer to data * @returns true or false for odd starting packet number */ - bool SetOddStartingPacket(int index, char* packetData) { - bool oddStartingPacket = true; + bool SetOddStartingPacket(int index, char* packetData) { + bool oddStartingPacket = true; // care only if no roi if (nPixelsX == 1280) { uint32_t fnum = ((uint32_t)(*((uint32_t*)(packetData)))); @@ -404,197 +422,6 @@ private: return oddStartingPacket; }; - -}; - - -class PropixData : public GeneralData { - - private: - - /**bytes per pixel for calculating image size */ - const static uint32_t bytesPerPixel = 2; - - public: - - /** Constructor */ - PropixData(){ - myDetectorType = slsReceiverDefs::PROPIX; - nPixelsX = 22; - nPixelsY = 22; - headerSizeinPacket = 4; - dataSize = 1280; - packetSize = 1286; - packetsPerFrame = 2; //not really - imageSize = nPixelsX*nPixelsY*bytesPerPixel; - frameIndexMask = 0xFFFFFFFE; - frameIndexOffset = 1; - packetIndexMask = 1; - maxFramesPerFile = MAX_FRAMES_PER_FILE; - fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsReceiverDefs::sls_receiver_header); - defaultFifoDepth = 50000; - }; -}; - - -class Moench02Data : public GeneralData { - - public: - - /** Bytes Per Adc */ - const static uint32_t bytesPerAdc = (40*2); - - /** Constructor */ - Moench02Data(){ - myDetectorType = slsReceiverDefs::MOENCH; - nPixelsX = 160; - nPixelsY = 160; - headerSizeinPacket = 4; - dataSize = 1280; - packetSize = 1286; - packetsPerFrame = 40; - imageSize = dataSize*packetsPerFrame; - frameIndexMask = 0xFFFFFF00; - frameIndexOffset = 8; - packetIndexMask = 0xFF; - maxFramesPerFile = MOENCH_MAX_FRAMES_PER_FILE; - fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsReceiverDefs::sls_receiver_header); - defaultFifoDepth = 2500; - }; - - /** - * Print all variables - */ - void Print() const { - GeneralData::Print(); - FILE_LOG(logINFO) << "Bytes Per Adc: " << bytesPerAdc; - } -}; - - -class Moench03Data : public GeneralData { - - public: - - /** Constructor */ - Moench03Data(){ - myDetectorType = slsReceiverDefs::MOENCH; - nPixelsX = 400; - nPixelsY = 400; - headerSizeinPacket = 22; - dataSize = 8192; - packetSize = headerSizeinPacket + dataSize; - packetsPerFrame = 40; - imageSize = dataSize*packetsPerFrame; - frameIndexMask = 0xFFFFFFFF; - frameIndexOffset = (6+8); - packetIndexMask = 0xFFFFFFFF; - maxFramesPerFile = JFRAU_MAX_FRAMES_PER_FILE; - fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsReceiverDefs::sls_receiver_header); - defaultFifoDepth = 2500; - }; -}; - - -class JCTBData : public GeneralData { - - -private: - /** Structure of an jungfrau ctb packet header */ - typedef struct { - unsigned char emptyHeader[6]; - unsigned char reserved[4]; - unsigned char packetNumber[1]; - unsigned char frameNumber[3]; - unsigned char bunchid[8]; - } jfrauctb_packet_header_t; - - public: - - - - /** Bytes Per Adc */ - const static uint32_t bytesPerAdc = 2; - - /** Constructor */ - JCTBData(){ - myDetectorType = slsReceiverDefs::JUNGFRAUCTB; - nPixelsX = 400; - nPixelsY = 400; - headerSizeinPacket = 22; - dataSize = 8192; - packetSize = headerSizeinPacket + dataSize; - packetsPerFrame = 1; - imageSize = nPixelsX * nPixelsY * 2; - frameIndexMask = 0xFFFFFF; - maxFramesPerFile = JFCTB_MAX_FRAMES_PER_FILE; - fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsReceiverDefs::sls_receiver_header); - defaultFifoDepth = 2500; - }; - - - /** - * Get Header Infomation (frame number, packet number) - * @param index thread index for debugging purposes - * @param packetData pointer to data - * @param dynamicRange dynamic range to assign subframenumber if 32 bit mode - * @param oddStartingPacket odd starting packet (gotthard) - * @param frameNumber frame number * @param packetNumber packet number - * @param subFrameNumber sub frame number if applicable - * @param bunchId bunch id - */ - void GetHeaderInfo(int index, char* packetData, uint32_t dynamicRange, bool oddStartingPacket, - uint64_t& frameNumber, uint32_t& packetNumber, uint32_t& subFrameNumber, uint64_t& bunchId) const { - subFrameNumber = -1; - jfrauctb_packet_header_t* header = (jfrauctb_packet_header_t*)(packetData); - frameNumber = (uint64_t)((*( (uint32_t*) header->frameNumber)) & frameIndexMask); - packetNumber = (uint32_t)(*( (uint8_t*) header->packetNumber)); - bunchId = (*((uint64_t*) header->bunchid)); - } - - /** - * Setting packets per frame changes member variables - * @param ns number of samples - * @param nroich number of channels in roi - */ - void setNumberofSamples(const uint64_t ns, uint32_t nroich) { - packetsPerFrame = ceil(double(2 * (nroich ? nroich : 32) * ns) / dataSize); - nPixelsY = (ns * 2) / 25;/* depends on nroich also?? */ - imageSize = nPixelsX * nPixelsY * 2; - }; - - /** - * Print all variables - */ - void Print() const { - GeneralData::Print(); - FILE_LOG(logINFO) << "Bytes Per Adc: " << bytesPerAdc; - } -}; - - -class JungfrauData : public GeneralData { - - public: - - /** Constructor */ - JungfrauData(){ - myDetectorType = slsReceiverDefs::JUNGFRAU; - nPixelsX = (256*4); - nPixelsY = 512; - emptyHeader = 6; - headerSizeinPacket = emptyHeader + sizeof(slsReceiverDefs::sls_detector_header); - dataSize = 8192; - packetSize = headerSizeinPacket + dataSize; - packetsPerFrame = 128; - imageSize = dataSize*packetsPerFrame; - maxFramesPerFile = JFRAU_MAX_FRAMES_PER_FILE; - fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsReceiverDefs::sls_receiver_header); - defaultFifoDepth = 2500; - standardheader = true; - defaultUdpSocketBufferSize = (2000 * 1024 * 1024); - }; - }; @@ -604,16 +431,16 @@ class EigerData : public GeneralData { /** Constructor */ EigerData(){ - myDetectorType = slsReceiverDefs::EIGER; + myDetectorType = slsDetectorDefs::EIGER; nPixelsX = (256*2); nPixelsY = 256; - headerSizeinPacket = sizeof(slsReceiverDefs::sls_detector_header); + headerSizeinPacket = sizeof(slsDetectorDefs::sls_detector_header); dataSize = 1024; packetSize = headerSizeinPacket + dataSize; packetsPerFrame = 256; imageSize = dataSize*packetsPerFrame; maxFramesPerFile = EIGER_MAX_FRAMES_PER_FILE; - fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsReceiverDefs::sls_receiver_header); + fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsDetectorDefs::sls_receiver_header); defaultFifoDepth = 100; threadsPerReceiver = 2; headerPacketSize = 40; @@ -673,3 +500,227 @@ class EigerData : public GeneralData { }; + + +class JungfrauData : public GeneralData { + + public: + + /** Constructor */ + JungfrauData(){ + myDetectorType = slsDetectorDefs::JUNGFRAU; + nPixelsX = (256*4); + nPixelsY = 512; + emptyHeader = 6; + headerSizeinPacket = emptyHeader + sizeof(slsDetectorDefs::sls_detector_header); + dataSize = 8192; + packetSize = headerSizeinPacket + dataSize; + packetsPerFrame = 128; + imageSize = dataSize * packetsPerFrame; + maxFramesPerFile = JFRAU_MAX_FRAMES_PER_FILE; + fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsDetectorDefs::sls_receiver_header); + defaultFifoDepth = 2500; + standardheader = true; + defaultUdpSocketBufferSize = (1000 * 1024 * 1024); + }; + + + /** + * set number of interfaces (jungfrau) + * @param number of interfaces + */ + void SetNumberofInterfaces(const int n) { + // 2 interfaces + if (n == 2) { + nPixelsY = 256; + packetsPerFrame = 64; + imageSize = dataSize * packetsPerFrame; + threadsPerReceiver = 2; + defaultUdpSocketBufferSize = (500 * 1024 * 1024); + + } + // 1 interface + else { + nPixelsY = 512; + packetsPerFrame = 128; + imageSize = dataSize * packetsPerFrame; + threadsPerReceiver = 1; + defaultUdpSocketBufferSize = (1000 * 1024 * 1024); + } + } +}; + + + +class ChipTestBoardData : public GeneralData { +private: + /** Number of analog channels */ + const int NCHAN_ANALOG = 32; + /** Number of digital channels */ + const int NCHAN_DIGITAL = 4; +public: + + + /** Constructor */ + ChipTestBoardData(){ + myDetectorType = slsDetectorDefs::CHIPTESTBOARD; + nPixelsX = 36; // total number of channels + nPixelsY = 1; // number of samples + headerSizeinPacket = sizeof(slsDetectorDefs::sls_detector_header); + dataSize = UDP_PACKET_DATA_BYTES; + packetSize = headerSizeinPacket + dataSize; + //packetsPerFrame = 1; + imageSize = nPixelsX * nPixelsY * 2; + packetsPerFrame = ceil((double)imageSize / (double)UDP_PACKET_DATA_BYTES); + maxFramesPerFile = CTB_MAX_FRAMES_PER_FILE; + fifoBufferHeaderSize= FIFO_HEADER_NUMBYTES + sizeof(slsDetectorDefs::sls_receiver_header); + defaultFifoDepth = 2500; + standardheader = true; + }; + + /** + * Set databytes (ctb, moench) + * @param f readout flags + * @param r roi + * @param s number of samples + * @param t tengiga enable + */ + void setImageSize(std::vector r, int s, bool t, slsDetectorDefs::readOutFlags f = slsDetectorDefs::GET_READOUT_FLAGS) { + int nchans = 0; + if (f != slsDetectorDefs::GET_READOUT_FLAGS) { + // analog channels + if (f == slsDetectorDefs::NORMAL_READOUT || f & slsDetectorDefs::ANALOG_AND_DIGITAL) { + nchans += NCHAN_ANALOG; + // if roi + if (r.size()) { + nchans = 0; + for (auto &roi : r) { + nchans += (roi.xmax - roi.xmin + 1); + } + } + } + // digital channels + if (f & slsDetectorDefs::DIGITAL_ONLY || f & slsDetectorDefs::ANALOG_AND_DIGITAL) { + nchans += NCHAN_DIGITAL; + } + } + nPixelsX = nchans; + nPixelsY = s; + // 10G + if (t) { + headerSizeinPacket = 22; + dataSize = 8192; + packetSize = headerSizeinPacket + dataSize; + imageSize = nPixelsX * nPixelsY * 2; + packetsPerFrame = ceil((double)imageSize / (double)packetSize); + standardheader = false; } + // 1g udp (via fifo readout) + else { + headerSizeinPacket = sizeof(slsDetectorDefs::sls_detector_header); + dataSize = UDP_PACKET_DATA_BYTES; + packetSize = headerSizeinPacket + dataSize; + imageSize = nPixelsX * nPixelsY * 2; + packetsPerFrame = ceil((double)imageSize / (double)UDP_PACKET_DATA_BYTES); + standardheader = true; + } + } + +}; + + +class MoenchData : public GeneralData { + + +private: + /** Structure of an jungfrau ctb packet header (10G Udp) */ + struct jfrauctb_packet_header { + unsigned char emptyHeader[6]; + unsigned char reserved[4]; + uint32_t packetFrameNumber; + uint64_t bunchid; + } __attribute__((packed)); + +public: + /** Constructor */ + MoenchData() { + myDetectorType = slsDetectorDefs::MOENCH; + nPixelsX = 32; // total number of channels + nPixelsY = 1; // number of samples + headerSizeinPacket = sizeof(slsDetectorDefs::sls_detector_header); + dataSize = UDP_PACKET_DATA_BYTES; + packetSize = headerSizeinPacket + dataSize; + // packetsPerFrame = 1; + imageSize = nPixelsX * nPixelsY * 2; + packetsPerFrame = ceil((double)imageSize / (double)UDP_PACKET_DATA_BYTES); + frameIndexMask = 0xFFFFFF; + maxFramesPerFile = CTB_MAX_FRAMES_PER_FILE; + fifoBufferHeaderSize = + FIFO_HEADER_NUMBYTES + sizeof(slsDetectorDefs::sls_receiver_header); + defaultFifoDepth = 2500; + standardheader = true; + }; + + /** + * Get Header Infomation (frame number, packet number) + * @param index thread index for debugging purposes + * @param packetData pointer to data + * @param dynamicRange dynamic range to assign subframenumber if 32 bit mode + * @param oddStartingPacket odd starting packet (gotthard) + * @param frameNumber frame number * @param packetNumber packet number + * @param subFrameNumber sub frame number if applicable + * @param bunchId bunch id + */ + void GetHeaderInfo(int index, char* packetData, uint32_t dynamicRange, bool oddStartingPacket, + uint64_t& frameNumber, uint32_t& packetNumber, uint32_t& subFrameNumber, uint64_t& bunchId) const { + subFrameNumber = -1; + auto header = reinterpret_cast(packetData); + frameNumber = (header->packetFrameNumber >> 8) & frameIndexMask; + packetNumber = header->packetFrameNumber & 0xFF; + bunchId = header->bunchid; + } + + + /** + * Set databytes (ctb, moench) + * @param f readout flags + * @param r roi + * @param s number of samples + * @param t tengiga enable + */ + void setImageSize(std::vector r, int s, bool t, + slsDetectorDefs::readOutFlags f = slsDetectorDefs::GET_READOUT_FLAGS) { + int nchans = 32; + // if roi + if (r.size()) { + nchans = 0; + for (auto &roi : r) { + nchans += abs(roi.xmax - roi.xmin) + 1; + } + } + + nPixelsX = nchans; + nPixelsY = s; + // 10G + if (t) { + headerSizeinPacket = 22; + dataSize = 8192; + packetSize = headerSizeinPacket + dataSize; + imageSize = nPixelsX * nPixelsY * 2; + packetsPerFrame = (imageSize + packetSize - 1) / packetSize; + standardheader = false; + } + // 1g udp (via fifo readout) + else { + headerSizeinPacket = sizeof(slsDetectorDefs::sls_detector_header); + dataSize = UDP_PACKET_DATA_BYTES; + packetSize = headerSizeinPacket + dataSize; + imageSize = nPixelsX * nPixelsY * 2; + packetsPerFrame = (imageSize + UDP_PACKET_DATA_BYTES - 1) / UDP_PACKET_DATA_BYTES; + standardheader = true; + } + } +}; + + + +; \ No newline at end of file diff --git a/slsReceiverSoftware/include/HDF5File.h b/slsReceiverSoftware/include/HDF5File.h old mode 100644 new mode 100755 index ff5146e50..81390c542 --- a/slsReceiverSoftware/include/HDF5File.h +++ b/slsReceiverSoftware/include/HDF5File.h @@ -19,7 +19,7 @@ #endif -class HDF5File : private virtual slsReceiverDefs, public File, public HDF5FileStatic { +class HDF5File : private virtual slsDetectorDefs, public File, public HDF5FileStatic { public: /** @@ -55,7 +55,7 @@ class HDF5File : private virtual slsReceiverDefs, public File, public HDF5FileSt /** * Print all member values */ - void PrintMembers(); + void PrintMembers(TLogLevel level = logDEBUG1); /** * Set Number of pixels diff --git a/slsReceiverSoftware/include/HDF5FileStatic.h b/slsReceiverSoftware/include/HDF5FileStatic.h old mode 100644 new mode 100755 index 1fff667da..7f89a3348 --- a/slsReceiverSoftware/include/HDF5FileStatic.h +++ b/slsReceiverSoftware/include/HDF5FileStatic.h @@ -13,7 +13,7 @@ #ifndef H5_NO_NAMESPACE using namespace H5; #endif -#include "sls_receiver_defs.h" +#include "sls_detector_defs.h" #include "logger.h" #include @@ -24,7 +24,7 @@ using namespace H5; #include #include //memset -class HDF5FileStatic: public virtual slsReceiverDefs { +class HDF5FileStatic: public virtual slsDetectorDefs { public: @@ -112,7 +112,7 @@ public: fd = 0; } } catch(Exception error) { - cprintf(RED,"Error in closing HDF5 handles of index %d\n", ind); + FILE_LOG(logERROR) << "Could not close HDF5 handles of index " << ind; error.printErrorStack(); } } @@ -130,7 +130,7 @@ public: fd = 0; } } catch(Exception error) { - cprintf(RED,"Error in closing master HDF5 handles\n"); + FILE_LOG(logERROR) << "Could not close master HDF5 handles"; error.printErrorStack(); } } @@ -143,8 +143,9 @@ public: static void CloseVirtualDataFile(hid_t& fd) { if(fd) { - if (H5Fclose(fd) < 0 ) - cprintf(RED,"Error in closing virtual HDF5 handles\n"); + if (H5Fclose(fd) < 0 ) { + FILE_LOG(logERROR) << "Could not close virtual HDF5 handles"; + } fd = 0; } } @@ -177,7 +178,7 @@ public: memspace.close(); } catch(Exception error){ - cprintf(RED,"Error in writing to file in object %d\n",ind); + FILE_LOG(logERROR) << "Could not write to file in object " << ind; error.printErrorStack(); return 1; } @@ -239,7 +240,7 @@ public: }i=14; } catch(Exception error){ - cprintf(RED,"Error in writing parameters (index:%d) to file in object %d\n", i, ind); + FILE_LOG(logERROR) << "Could not write parameters (index:" << i << ") to file in object " << ind; error.printErrorStack(); return 1; } @@ -282,7 +283,7 @@ public: } catch(Exception error){ - cprintf(RED,"Error in extending dataset in object %d\n",ind); + FILE_LOG(logERROR) << "Could not extend dataset in object " << ind; error.printError(); return 1; } @@ -417,7 +418,7 @@ public: fd->close(); } catch(Exception error) { - cprintf(RED,"Error in creating master HDF5 handles\n"); + FILE_LOG(logERROR) << "Could not create master HDF5 handles"; error.printErrorStack(); if (fd) fd->close(); return 1; @@ -521,7 +522,7 @@ public: } } catch(Exception error){ - cprintf(RED,"Error in creating HDF5 handles in object %d\n",ind); + FILE_LOG(logERROR) << "Could not create HDF5 handles in object " << ind; error.printErrorStack(); if (fd) fd->close(); return 1; @@ -571,36 +572,36 @@ public: hid_t dfal = H5Pcreate (H5P_FILE_ACCESS); if (dfal < 0) return CloseFileOnError(fd, - std::string("Error in creating file access property for virtual file ") + std::string("Could not create file access property for virtual file ") + virtualFileName + std::string("\n")); if (H5Pset_fclose_degree (dfal, H5F_CLOSE_STRONG) < 0) return CloseFileOnError(fd, - std::string("Error in setting strong file close degree for virtual file ") + std::string("Could not set strong file close degree for virtual file ") + virtualFileName + std::string("\n")); fd = H5Fcreate( virtualFileName.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, dfal); if (fd < 0) return CloseFileOnError(fd, - std::string("Error in creating virtual file ") + virtualFileName + std::string("\n")); + std::string("Could not create virtual file ") + virtualFileName + std::string("\n")); //attributes - version hid_t dataspace_attr = H5Screate (H5S_SCALAR); if (dataspace_attr < 0) return CloseFileOnError(fd, - std::string("Error in creating dataspace for attribute in virtual file ") + std::string("Could not create dataspace for attribute in virtual file ") + virtualFileName + std::string("\n")); hid_t attrid = H5Acreate2 (fd, "version", H5T_NATIVE_DOUBLE, dataspace_attr, H5P_DEFAULT, H5P_DEFAULT); if (attrid < 0) return CloseFileOnError(fd, - std::string("Error in creating attribute in virtual file ") + std::string("Could not create attribute in virtual file ") + virtualFileName + std::string("\n")); double attr_data = version; if (H5Awrite (attrid, H5T_NATIVE_DOUBLE, &attr_data) < 0) return CloseFileOnError(fd, - std::string("Error in writing attribute in virtual file ") + std::string("Could not write attribute in virtual file ") + virtualFileName + std::string("\n")); if (H5Aclose (attrid) < 0) return CloseFileOnError(fd, - std::string("Error in closing attribute in virtual file ") + std::string("Could not close attribute in virtual file ") + virtualFileName + std::string("\n")); @@ -609,13 +610,13 @@ public: hid_t vdsDataspace = H5Screate_simple(3, vdsdims ,NULL); if (vdsDataspace < 0) return CloseFileOnError(fd, - std::string("Error in creating virtual dataspace in virtual file ") + std::string("Could not create virtual dataspace in virtual file ") + virtualFileName + std::string("\n")); hsize_t vdsdims_para[2] = {numf, (unsigned int) numDety * numDetz}; hid_t vdsDataspace_para = H5Screate_simple(2, vdsdims_para, NULL); if (vdsDataspace_para < 0) return CloseFileOnError(fd, - std::string("Error in creating virtual dataspace (parameters) in virtual file ") + std::string("Could not create virtual dataspace (parameters) in virtual file ") + virtualFileName + std::string("\n")); @@ -623,23 +624,23 @@ public: hid_t dcpl = H5Pcreate (H5P_DATASET_CREATE); if (dcpl < 0) return CloseFileOnError(fd, - std::string("Error in creating file creation properties in virtual file ") + std::string("Could not create file creation properties in virtual file ") + virtualFileName + std::string("\n")); int fill_value = -1; if (H5Pset_fill_value (dcpl, GetDataTypeinC(dataType), &fill_value) < 0) return CloseFileOnError(fd, - std::string("Error in creating fill value in virtual file ") + std::string("Could not create fill value in virtual file ") + virtualFileName + std::string("\n")); hid_t dcpl_para[parameterNames.size()]; for (unsigned int i = 0; i < parameterNames.size(); ++i) { dcpl_para[i] = H5Pcreate (H5P_DATASET_CREATE); if (dcpl_para[i] < 0) return CloseFileOnError(fd, - std::string("Error in creating file creation properties (parameters) in virtual file ") + std::string("Could not create file creation properties (parameters) in virtual file ") + virtualFileName + std::string("\n")); if (H5Pset_fill_value (dcpl_para[i], GetDataTypeinC(parameterDataTypes[i]), &fill_value) < 0) return CloseFileOnError(fd, - std::string("Error in creating fill value (parameters) in virtual file ") + std::string("Could not create fill value (parameters) in virtual file ") + virtualFileName + std::string("\n")); } @@ -661,13 +662,13 @@ public: //setect hyperslabs if (H5Sselect_hyperslab (vdsDataspace, H5S_SELECT_SET, offset, NULL, count, NULL) < 0) { - cprintf(RED,"could not select hyperslab\n"); + FILE_LOG(logERROR) << "Could not select hyperslab"; error = true; break; } if (H5Sselect_hyperslab (vdsDataspace_para, H5S_SELECT_SET, offset_para, NULL, count_para, NULL) < 0) { - cprintf(RED,"could not select hyperslab for parameters\n"); + FILE_LOG(logERROR) << "Could not select hyperslab for parameters"; error = true; break; } @@ -696,20 +697,20 @@ public: hid_t srcDataspace = H5Screate_simple(3, srcdims, srcdimsmax); if (srcDataspace < 0) return CloseFileOnError(fd, - std::string("Error in creating source dataspace in virtual file ") + std::string("Could not create source dataspace in virtual file ") + virtualFileName + std::string("\n")); hsize_t srcdims_para[1] = {nDimx}; hsize_t srcdimsmax_para[1] = {H5S_UNLIMITED}; hid_t srcDataspace_para = H5Screate_simple(1, srcdims_para, srcdimsmax_para); if (srcDataspace_para < 0) return CloseFileOnError(fd, - std::string("Error in creating source dataspace (parameters) in virtual file ") + std::string("Could not create source dataspace (parameters) in virtual file ") + virtualFileName + std::string("\n")); //mapping if (H5Pset_virtual(dcpl, vdsDataspace, relative_srcFileName.c_str(), srcDatasetName.c_str(), srcDataspace) < 0) { - cprintf(RED,"could not set mapping for paramter 1\n"); + FILE_LOG(logERROR) << "Could not set mapping for paramter 1"; error = true; break; } @@ -717,7 +718,7 @@ public: for (unsigned int k = 0; k < parameterNames.size(); ++k) { if (H5Pset_virtual(dcpl_para[k], vdsDataspace_para, relative_srcFileName.c_str(), parameterNames[k], srcDataspace_para) < 0) { - cprintf(RED,"could not set mapping for paramter %d\n", k); + FILE_LOG(logERROR) << "Could not set mapping for paramter " << k; error = true; break; } @@ -736,7 +737,7 @@ public: } if (error) return CloseFileOnError(fd, - std::string("Error in mapping files in virtual file ") + std::string("Could not map files in virtual file ") + virtualFileName + std::string("\n")); //dataset @@ -745,7 +746,7 @@ public: GetDataTypeinC(dataType), vdsDataspace, H5P_DEFAULT, dcpl, H5P_DEFAULT); if (vdsdataset < 0) return CloseFileOnError(fd, - std::string("Error in creating virutal dataset in virtual file ") + std::string("Could not create virutal dataset in virtual file ") + virtualFileName + std::string("\n")); @@ -757,7 +758,7 @@ public: H5P_DEFAULT, dcpl_para[i], H5P_DEFAULT); if (vdsdataset_para < 0) return CloseFileOnError(fd, - std::string("Error in creating virutal dataset (parameters) in virtual file ") + std::string("Could not create virutal dataset (parameters) in virtual file ") + virtualFileName + std::string("\n")); } @@ -798,7 +799,7 @@ public: data_out = (T*)malloc(sizeof(T)*(nDimx*nDimy*nDimz)); break; default: - cprintf(RED,"invalid rank. Options: 2 or 3\n"); + FILE_LOG(logERROR) << "Invalid rank. Options: 2 or 3"; return 0; } if (datatype == PredType::STD_U16LE) { @@ -810,7 +811,7 @@ public: } else if (datatype == PredType::STD_U8LE) { FILE_LOG(logINFO) << "datatype:8"; } else { - FILE_LOG(logERROR) << "unknown datatype"; + FILE_LOG(logERROR) << "Unknown datatype: " << datatype; return 1; } FILE_LOG(logINFO) << "owenable:" << (owenable?1:0) << std::endl @@ -861,7 +862,7 @@ public: newfd->close(); oldfd->close(); } catch(Exception error){ - cprintf(RED,"Error in copying virtual files\n"); + FILE_LOG(logERROR) << "Could not copy virtual files"; error.printErrorStack(); free(data_out); oldfd->close(); @@ -890,20 +891,20 @@ public: hid_t dfal = H5Pcreate (H5P_FILE_ACCESS); if (dfal < 0) - return CloseFileOnError( vfd, std::string("Error in creating file access property for link\n")); + return CloseFileOnError( vfd, std::string("Could not create file access property for link\n")); if (H5Pset_fclose_degree (dfal, H5F_CLOSE_STRONG) < 0) - return CloseFileOnError( vfd, std::string("Error in setting strong file close degree for link\n")); + return CloseFileOnError( vfd, std::string("Could not set strong file close degree for link\n")); //open master file hid_t mfd = H5Fopen( masterFileName.c_str(), H5F_ACC_RDWR, dfal); if (mfd < 0) - return CloseFileOnError( vfd, std::string("Error in opening master file\n")); + return CloseFileOnError( vfd, std::string("Could not open master file\n")); //open virtual file vfd = H5Fopen( virtualfname.c_str(), H5F_ACC_RDWR, dfal); if (vfd < 0) { H5Fclose(mfd); mfd = 0; - return CloseFileOnError( vfd, std::string("Error in opening virtual file\n")); + return CloseFileOnError( vfd, std::string("Could not open virtual file\n")); } // find relative path @@ -918,13 +919,13 @@ public: hid_t vdset = H5Dopen2( vfd, virtualDatasetname.c_str(), H5P_DEFAULT); if (vdset < 0) { H5Fclose(mfd); - return CloseFileOnError( vfd, std::string("Error in opening virtual data dataset\n")); + return CloseFileOnError( vfd, std::string("Could not open virtual data dataset\n")); } sprintf(linkname, "/entry/data/%s",virtualDatasetname.c_str()); if(H5Lcreate_external( relative_virtualfname.c_str(), virtualDatasetname.c_str(), mfd, linkname, H5P_DEFAULT, H5P_DEFAULT) < 0) { H5Fclose(mfd); mfd = 0; - return CloseFileOnError( vfd, std::string("Error in creating link to data dataset\n")); + return CloseFileOnError( vfd, std::string("Could not create link to data dataset\n")); } H5Dclose(vdset); @@ -933,14 +934,14 @@ public: hid_t vdset_para = H5Dopen2( vfd, (std::string (parameterNames[i])).c_str(), H5P_DEFAULT); if (vdset_para < 0) { H5Fclose(mfd); mfd = 0; - return CloseFileOnError( vfd, std::string("Error in opening virtual parameter dataset to create link\n")); + return CloseFileOnError( vfd, std::string("Could not open virtual parameter dataset to create link\n")); } sprintf(linkname, "/entry/data/%s",(std::string (parameterNames[i])).c_str()); if(H5Lcreate_external( relative_virtualfname.c_str(), (std::string (parameterNames[i])).c_str(), mfd, linkname, H5P_DEFAULT, H5P_DEFAULT) < 0) { H5Fclose(mfd); mfd = 0; - return CloseFileOnError( vfd, std::string("Error in creating link to virtual parameter dataset\n")); + return CloseFileOnError( vfd, std::string("Could not create link to virtual parameter dataset\n")); } } @@ -956,7 +957,7 @@ public: * @returns 1 for fail */ static int CloseFileOnError(hid_t& fd, const std::string msg) { - cprintf(RED, "%s", msg.c_str()); + FILE_LOG(logERROR) << msg; if(fd > 0) H5Fclose(fd); fd = 0; diff --git a/slsReceiverSoftware/include/Listener.h b/slsReceiverSoftware/include/Listener.h old mode 100644 new mode 100755 index 366b4cdc1..2ee15c75a --- a/slsReceiverSoftware/include/Listener.h +++ b/slsReceiverSoftware/include/Listener.h @@ -9,13 +9,15 @@ *@short creates & manages a listener thread each */ +#include + #include "ThreadObject.h" class GeneralData; class Fifo; class genericSocket; -class Listener : private virtual slsReceiverDefs, public ThreadObject { +class Listener : private virtual slsDetectorDefs, public ThreadObject { public: /** @@ -37,9 +39,9 @@ class Listener : private virtual slsReceiverDefs, public ThreadObject { * @param depaden pointer to deactivated padding enable * @param sm pointer to silent mode */ - Listener(int ind, detectorType dtype, Fifo*& f, runStatus* s, + Listener(int ind, detectorType dtype, Fifo* f, runStatus* s, uint32_t* portno, char* e, uint64_t* nf, uint32_t* dr, - uint32_t* us, uint32_t* as, uint32_t* fpf, + int64_t* us, int64_t* as, uint32_t* fpf, frameDiscardPolicy* fdp, bool* act, bool* depaden, bool* sm); /** @@ -54,7 +56,7 @@ class Listener : private virtual slsReceiverDefs, public ThreadObject { * Returns if the thread is currently running * @returns true if thread is running, else false */ - bool IsRunning(); + bool IsRunning() override; /** * Get acquisition started flag @@ -96,7 +98,7 @@ class Listener : private virtual slsReceiverDefs, public ThreadObject { * Set Fifo pointer to the one given * @param f address of Fifo pointer */ - void SetFifo(Fifo*& f); + void SetFifo(Fifo* f); /** * Reset parameters for new acquisition (including all scans) @@ -112,7 +114,7 @@ class Listener : private virtual slsReceiverDefs, public ThreadObject { * Set GeneralData pointer to the one given * @param g address of GeneralData (Detector Data) pointer */ - void SetGeneralData(GeneralData*& g); + void SetGeneralData(GeneralData* g); /** * Set thread priority @@ -138,7 +140,7 @@ class Listener : private virtual slsReceiverDefs, public ThreadObject { * @param s UDP socket buffer size to be set * @return OK or FAIL of dummy socket creation */ - int CreateDummySocketForUDPSocketBufferSize(uint32_t s); + int CreateDummySocketForUDPSocketBufferSize(int64_t s); /** * Set hard coded (calculated but not from detector) row and column @@ -156,7 +158,7 @@ class Listener : private virtual slsReceiverDefs, public ThreadObject { * Get Type * @return type */ - std::string GetType(); + std::string GetType() override; /** * Record First Indices (firstAcquisitionIndex, firstMeasurementIndex) @@ -169,7 +171,7 @@ class Listener : private virtual slsReceiverDefs, public ThreadObject { * Pop free addresses, listen to udp socket, * write to memory & push the address into fifo */ - void ThreadExecution(); + void ThreadExecution() override; /** * Pushes non empty buffers into fifo/ frees empty buffer, @@ -207,7 +209,6 @@ class Listener : private virtual slsReceiverDefs, public ThreadObject { /** Fifo structure */ Fifo* fifo; - // individual members /** Detector Type */ detectorType myDetectorType; @@ -216,7 +217,7 @@ class Listener : private virtual slsReceiverDefs, public ThreadObject { runStatus* status; /** UDP Socket - Detector to Receiver */ - genericSocket* udpSocket; + std::unique_ptr udpSocket; /** UDP Port Number */ uint32_t* udpPortNumber; @@ -231,10 +232,10 @@ class Listener : private virtual slsReceiverDefs, public ThreadObject { uint32_t* dynamicRange; /** UDP Socket Buffer Size */ - uint32_t* udpSocketBufferSize; + int64_t* udpSocketBufferSize; /** actual UDP Socket Buffer Size (double due to kernel bookkeeping) */ - uint32_t* actualUDPSocketBufferSize; + int64_t* actualUDPSocketBufferSize; /** frames per file */ uint32_t* framesPerFile; @@ -293,10 +294,10 @@ class Listener : private virtual slsReceiverDefs, public ThreadObject { bool carryOverFlag; /** Carry over packet buffer */ - char* carryOverPacket; + std::unique_ptr carryOverPacket; /** Listening buffer for one packet - might be removed when we can peek and eiger fnum is in header */ - char* listeningPacket; + std::unique_ptr listeningPacket; /** if the udp socket is connected */ bool udpSocketAlive; @@ -312,10 +313,10 @@ class Listener : private virtual slsReceiverDefs, public ThreadObject { /** number of images for statistic */ uint32_t numFramesStatistic; - /** - * starting packet number is odd or evern, accordingly increment frame number - * to get first packet number as 0 - * (pecific to gotthard, can vary between modules, hence defined here) */ - bool oddStartingPacket; + /** + * starting packet number is odd or evern, accordingly increment frame number + * to get first packet number as 0 + * (pecific to gotthard, can vary between modules, hence defined here) */ + bool oddStartingPacket; }; diff --git a/slsReceiverSoftware/include/ThreadObject.h b/slsReceiverSoftware/include/ThreadObject.h old mode 100644 new mode 100755 index 5b5639cea..932dc2630 --- a/slsReceiverSoftware/include/ThreadObject.h +++ b/slsReceiverSoftware/include/ThreadObject.h @@ -7,14 +7,14 @@ *@short creates/destroys a thread */ -#include "sls_receiver_defs.h" +#include "sls_detector_defs.h" #include "logger.h" #include #include #include -class ThreadObject : private virtual slsReceiverDefs { +class ThreadObject : private virtual slsDetectorDefs { public: /** diff --git a/slsReceiverSoftware/include/UDPInterface.h b/slsReceiverSoftware/include/UDPInterface.h deleted file mode 100644 index 3879abd7e..000000000 --- a/slsReceiverSoftware/include/UDPInterface.h +++ /dev/null @@ -1,801 +0,0 @@ -#pragma once -/*********************************************** - * @file UDPInterface.h - * @short Base class with all the functions for the UDP inteface of the receiver - ***********************************************/ -/** - * \mainpage Base class with all the functions for the UDP inteface of the receiver - */ - -/** - * @short Base class with all the functions for the UDP inteface of the receiver - */ - -#include "sls_receiver_defs.h" -#include "receiver_defs.h" -#include "utilities.h" -#include "logger.h" - -#include -#include - -class UDPInterface { - - /* abstract class that defines the UDP interface of an sls detector data receiver. - * - * Use the factory method UDPInterface::create() to get an instance: - * - * UDPInterface *udp_interface = UDPInterface::create() - * - * Sequence of Calls from client (upon setting receiver) - * -setDetectorType - * -setMultiDetectorSize - * -setDetectorPositionId - * -initialize - * -setUDPPortNumber,setUDPPortNumber2,setEthernetInterface - * -setFilePath - * -setFileName - * -setFileIndex - * -setFileFormat - * -setFileWriteEnable - * -setOverwriteEnable - * -setAcquisitionPeriod - * -setNumberOfFrames - * -setAcquisitionTime - * -setSubExpTime (if eiger) - * -setNumberofSamples (if chip test board) - * -setDynamicRange - * -setFlippedData (if eiger) - * -setActivate (if eiger) - * -setDeactivatedPadding (if eiger) - * -setTenGigaEnable (if eiger) - * -setGapPixelsEnable - * -setStreamingPort - * -setStreamingSourceIP - * -setAdditionalJsonHeader - * -setDataStreamEnable - * -setROI - * - * - * - * supported sequence of method-calls: - * - * initialize() : once and only once after create() - * - * get*() : anytime after initialize(), multiples times - * - * set*() : anytime after initialize(), multiple times - * - * startReceiver(): anytime after initialize(). Will fail in TCPIP itself if state already is 'running': - * - * Only startReceiver() does change the data receiver configuration, it does pass the whole configuration cache to the data receiver. - * - * abort(), //FIXME: needed? - * - * stopReceiver() : anytime after initialize(). Will do nothing if state already is idle. - * Otherwise, sets status to transmitting when shutting down sockets - * then to run_finished when all data obtained - * then to idle when returning from this function - * - * - * getStatus() returns the actual state of the data receiver - idle, running or error, enum defined in include/sls_receiver_defs.h - * - * - * - * get*() and set*() methods access the local cache of configuration values only and *do not* modify the data receiver settings. - * - * set methods return nothing, use get methods to validate a set method success - * - * get-methods that return a char array (char *) allocate a new array at each call. The caller is responsible to free the allocated space: - * - * char *c = receiver->getFileName(); - * Or - * FIXME: so that the pointers are not shared external to the class, do the following way in the calling method? - * char *c = new char[MAX_STR_LENGTH]; - * strcpy(c,receiver->getFileName()); - * .... - * - * delete[] c; - * - * All pointers passed in externally will be allocated and freed by the calling function - * - * OK and FAIL are defined in include/sls_receiver_defs.h for functions implementing behavior - * - */ - - public: - - /************************************************************************* - * Constructor & Destructor ********************************************** - * They access local cache of configuration or detector parameters ******* - *************************************************************************/ - /** - * Constructor - * Only non virtual function implemented in this class - * Factory create method to create a standard or custom object - * @param [in] receiver_type type can be standard or custom (must be derived from base class) - * @return a UDPInterface reference to object depending on receiver type - */ - static UDPInterface *create(std::string receiver_type = "standard"); - - /** - * Destructor - */ - virtual ~UDPInterface() {}; - - - - /************************************************************************* - * Getters *************************************************************** - * They access local cache of configuration or detector parameters ******* - *************************************************************************/ - - //**initial/detector parameters*** - - /* - * Get multi detector size - * @return pointer to array of multi detector size in every dimension - */ - virtual int* getMultiDetectorSize() const = 0; - - /* - * Get detector position id - * @return detector position id - */ - virtual int getDetectorPositionId() const = 0; - - /* - * Get detector hostname - * @return hostname or NULL if uninitialized, must be released by calling function (max of 1000 characters) - */ - virtual char *getDetectorHostname() const = 0; - - /* - * Get flipped data across 'axis' - * @return if data is flipped across 'axis' - */ - virtual int getFlippedData(int axis=0) const = 0; - - /** - * Get Gap Pixels Enable (eiger specific) - * @return true if gap pixels enabled, else false - */ - virtual bool getGapPixelsEnable() const = 0; - - - //***file parameters*** - /** - * Get File Format - * @return file format - */ - virtual slsReceiverDefs::fileFormat getFileFormat() const = 0; - - /** - * Get File Name Prefix (without frame index, file index and extension (_d0_f000000000000_8.raw)) - * @return NULL or pointer to file name prefix, must be released by calling function (max of 1000 characters) - */ - virtual char *getFileName() const = 0; - - /** - * Get File Path - * @return NULL or pointer to file path, must be released by calling function (max of 1000 characters) - */ - virtual char *getFilePath() const = 0; - - /** - * Get File Index - * @return file index of acquisition - */ - virtual uint64_t getFileIndex() const = 0; - - /** - * Get Frames per File (0 means infinite) - * @return Frames per File - */ - virtual uint32_t getFramesPerFile() const = 0; - - /** - * Get Frame Discard Policy - * @return Frame Discard Policy - */ - virtual slsReceiverDefs::frameDiscardPolicy getFrameDiscardPolicy() const = 0; - - /** - * Get Partial Frame Padding Enable - * @return Partial Frame Padding Enable - */ - virtual bool getFramePaddingEnable() const = 0; - - /** - * Get Scan Tag - * @return scan tag //FIXME: needed? (unsigned integer?) - */ - virtual int getScanTag() const = 0; - - /** - * Get File Write Enable - * @return true if file write enabled, else false - */ - virtual bool getFileWriteEnable() const = 0; - - /** - * Get File Over Write Enable - * @return true if file over write enabled, else false - */ - virtual bool getOverwriteEnable() const = 0; - - /** - * Get data compression, by saving only hits (so far implemented only for Moench and Gotthard) - * @return true if data compression enabled, else false - */ - virtual bool getDataCompressionEnable() const = 0; - - - //***acquisition count parameters*** - /** - * Get Total Frames Caught for an entire acquisition (including all scans) - * @return total number of frames caught for entire acquisition - */ - virtual uint64_t getTotalFramesCaught() const = 0; - - /** - * Get Frames Caught for each real time acquisition (eg. for each scan) - * @return number of frames caught for each scan - */ - virtual uint64_t getFramesCaught() const = 0; - - /** - * Get Current Frame Index for an entire acquisition (including all scans) - * @return -1 if no frames have been caught, else current frame index (represents all scans too) or -1 if no packets caught - */ - virtual int64_t getAcquisitionIndex() const = 0; - - - //***connection parameters*** - /** - * Get UDP Port Number - * @return udp port number - */ - virtual uint32_t getUDPPortNumber() const = 0; - - /** - * Get Second UDP Port Number (eiger specific) - * @return second udp port number - */ - virtual uint32_t getUDPPortNumber2() const = 0; - - /** - * Get Ehernet Interface - * @return ethernet interface. eg. eth0 (max of 1000 characters) - */ - virtual char *getEthernetInterface() const = 0; - - - //***acquisition parameters*** - /** - * Get ROI - * @return index of adc enabled, else -1 if all enabled - */ - virtual std::vector getROI() const = 0; - - /** - * Get the Frequency of Frames Sent to GUI - * @return 0 for random frame requests, n for nth frame frequency - */ - virtual uint32_t getFrameToGuiFrequency() const = 0; - - /** - * Gets the timer between frames streamed when frequency is set to 0 - * @return timer between frames streamed - */ - virtual uint32_t getFrameToGuiTimer() const = 0; - - - /** - * Get the data stream enable - * @return data stream enable - */ - virtual bool getDataStreamEnable() const = 0; - - /** - * Get Acquisition Period - * @return acquisition period - */ - virtual uint64_t getAcquisitionPeriod() const = 0; - - /** - * Get Acquisition Time - * @return acquisition time - */ - virtual uint64_t getAcquisitionTime() const = 0; - - /** - * Get Sub Exposure Time - * @return Sub Exposure Time - */ - virtual uint64_t getSubExpTime() const = 0; - - /** - * Get Sub Period - * @return Sub Period - */ - virtual uint64_t getSubPeriod() const = 0; - - /* - * Get Number of Frames expected by receiver from detector - * The data receiver status will change from running to idle when it gets this number of frames FIXME: (for Leo? Not implemented) - * @return number of samples expected - */ - virtual uint64_t getNumberOfFrames() const = 0; - - /* - * Get Number of Samples expected by receiver from detector (for chip test board only) - * @return number of samples expected - */ - virtual uint64_t getNumberofSamples() const = 0; - - /** - * Get Dynamic Range or Number of Bits Per Pixel - * @return dynamic range that is 4, 8, 16 or 32 - */ - virtual uint32_t getDynamicRange() const = 0; - - /** - * Get Ten Giga Enable - * @return true if 10Giga enabled, else false (1G enabled) - */ - virtual bool getTenGigaEnable() const = 0; - - /** - * Get Fifo Depth - * @return fifo depth - */ - virtual uint32_t getFifoDepth() const = 0; - - //***receiver status*** - /** - * Get Listening Status of Receiver - * @return can be idle, listening or error depending on if the receiver is listening or not - */ - virtual slsReceiverDefs::runStatus getStatus() const = 0; - - /** (not saved in client shared memory) - * Get Silent Mode - * @return silent mode - */ - virtual bool getSilentMode() const = 0; - - /** - * Get activate - * If deactivated, receiver will create dummy data if deactivated padding is enabled - * (as it will receive nothing from detector) - * @return false for deactivated, true for activated - */ - virtual bool getActivate() const = 0; - - /** - * Get deactivated padding enable - * If enabled, receiver will create dummy packets (0xFF), else it will create nothing - * (as it will receive nothing from detector) - * @return false for disabled, true for enabled - */ - virtual bool getDeactivatedPadding() const = 0; - - /** - * Get Streaming Port - * @return streaming port - */ - virtual uint32_t getStreamingPort() const = 0; - - /** - * Get streaming source ip - * @return streaming source ip - */ - virtual char *getStreamingSourceIP() const = 0; - - /** - * Get additional json header - * @return additional json header - */ - virtual char *getAdditionalJsonHeader() const = 0; - - - /** (not saved in client shared memory) - * Get UDP Socket Buffer Size - * @return UDP Socket Buffer Size - */ - virtual uint32_t getUDPSocketBufferSize() const = 0; - - /** (not saved in client shared memory) - * Get actual UDP Socket Buffer Size - * @return actual UDP Socket Buffer Size - */ - virtual uint32_t getActualUDPSocketBufferSize() const = 0; - - /************************************************************************* - * Setters *************************************************************** - * They modify the local cache of configuration or detector parameters *** - *************************************************************************/ - - //**initial parameters*** - /** - * Configure command line parameters - * @param config_map mapping of config parameters passed from command line arguments - */ - virtual void configure(std::map config_map) = 0; - - /* - * Set multi detector size - * @param pointer to array of multi detector size in every dimension - */ - virtual void setMultiDetectorSize(const int* size) = 0; - - /* - * Get flipped data across 'axis' - * @return if data is flipped across 'axis' - */ - virtual void setFlippedData(int axis=0, int enable=-1) = 0; - - - /** - * Set Gap Pixels Enable (eiger specific) - * @param b true for gap pixels enable, else false - * @return OK or FAIL - */ - virtual int setGapPixelsEnable(const bool b) = 0; - - - //***file parameters*** - /** - * Set File Format - * @param f fileformat binary or hdf5 - */ - virtual void setFileFormat(slsReceiverDefs::fileFormat f) = 0; - - /** - * Set File Name Prefix (without frame index, file index and extension (_d0_f000000000000_8.raw)) - * Does not check for file existence since it is created only at startReceiver - * @param c file name (max of 1000 characters) - */ - virtual void setFileName(const char c[]) = 0; - - /** - * Set File Path - * Checks for file directory existence before setting file path - * @param c file path (max of 1000 characters) - */ - virtual void setFilePath(const char c[]) = 0; - - /** - * Set File Index of acquisition - * @param i file index of acquisition - */ - virtual void setFileIndex(const uint64_t i) = 0; - - /** - * Set Frames per File (0 means infinite) - * @param i Frames per File - */ - virtual void setFramesPerFile(const uint32_t i) = 0; - - /** - * Set Frame Discard Policy - * @param i Frame Discard Policy - */ - virtual void setFrameDiscardPolicy(const slsReceiverDefs::frameDiscardPolicy i) = 0; - - /** - * Set Partial Frame Padding Enable - * @param i Partial Frame Padding Enable - */ - virtual void setFramePaddingEnable(const bool i) = 0; - - /** - * Set Scan Tag - * @param i scan tag //FIXME: needed? (unsigned integer?) - */ - virtual void setScanTag(const int i) = 0; - - /** - * Set File Write Enable - * @param b true for file write enable, else false - */ - virtual void setFileWriteEnable(const bool b) = 0; - - /** - * Set File Overwrite Enable - * @param b true for file overwrite enable, else false - */ - virtual void setOverwriteEnable(const bool b) = 0; - - /** - * Set data compression, by saving only hits (so far implemented only for Moench and Gotthard) - * @param b true for data compression enable, else false - * @return OK or FAIL - */ - virtual int setDataCompressionEnable(const bool b) = 0; - - //***connection parameters*** - /** - * Set UDP Port Number - * @param i udp port number - */ - virtual void setUDPPortNumber(const uint32_t i) = 0; - - /** - * Set Second UDP Port Number (eiger specific) - * @return second udp port number - */ - virtual void setUDPPortNumber2(const uint32_t i) = 0; - - /** - * Set Ethernet Interface to listen to - * @param c ethernet inerface eg. eth0 (max of 1000 characters) - */ - virtual void setEthernetInterface(const char* c) = 0; - - - //***acquisition parameters*** - /** - * Set ROI - * @param i ROI - * @return OK or FAIL - */ - virtual int setROI(const std::vector i) = 0; - - /** - * Set the Frequency of Frames Sent to GUI - * @param freq 0 for random frame requests, n for nth frame frequency - * @return OK or FAIL - */ - virtual int setFrameToGuiFrequency(const uint32_t freq) = 0; - - /** - * Sets the timer between frames streamed when frequency is set to 0 - * @param time_in_ms timer between frames streamed - */ - virtual void setFrameToGuiTimer(const uint32_t time_in_ms) = 0; - - /** - * Set the data stream enable - * @param enable data stream enable - * @return OK or FAIL - */ - virtual int setDataStreamEnable(const bool enable) = 0; - - /** - * Set Acquisition Period - * @param i acquisition period - * @return OK or FAIL - */ - virtual int setAcquisitionPeriod(const uint64_t i) = 0; - - /** - * Set Acquisition Time - * @param i acquisition time - * @return OK or FAIL - */ - virtual int setAcquisitionTime(const uint64_t i) = 0; - - /** - * Set Sub Exposure Time - * @param i Sub Exposure Time - * @return OK or FAIL - */ - virtual void setSubExpTime(const uint64_t i) = 0; - - /** - * Set Sub Period - * @param i Period - * @return OK or FAIL - */ - virtual void setSubPeriod(const uint64_t i) = 0; - - /** - * Set Number of Frames expected by receiver from detector - * The data receiver status will change from running to idle when it gets this number of frames FIXME: (for Leo? Not implemented) - * @param i number of frames expected - * @return OK or FAIL - */ - virtual int setNumberOfFrames(const uint64_t i) = 0; - - /** - * Set Number of Samples expected by receiver from detector - * @param i number of Samples expected - * @return OK or FAIL - */ - virtual int setNumberofSamples(const uint64_t i) = 0; - - /** - * Set Dynamic Range or Number of Bits Per Pixel - * @param i dynamic range that is 4, 8, 16 or 32 - * @return OK or FAIL - */ - virtual int setDynamicRange(const uint32_t i) = 0; - - /** - * Set Ten Giga Enable - * @param b true if 10Giga enabled, else false (1G enabled) - * @return OK or FAIL - */ - virtual int setTenGigaEnable(const bool b) = 0; - - /** - * Set Fifo Depth - * @param i fifo depth value - * @return OK or FAIL - */ - virtual int setFifoDepth(const uint32_t i) = 0; - - - //***receiver parameters*** - /** - * Set Silent Mode - * @param i silent mode. true sets, false unsets - */ - virtual void setSilentMode(const bool i) = 0; - - - /************************************************************************* - * Behavioral functions*************************************************** - * They may modify the status of the receiver **************************** - *************************************************************************/ - - - //***initial functions*** - /** - * Set receiver type (and corresponding detector variables in derived STANDARD class) - * It is the first function called by the client when connecting to receiver - * @param d detector type - * @return OK or FAIL - */ - virtual int setDetectorType(const slsReceiverDefs::detectorType d) = 0; - - /** - * Set detector position id - * @param i position id - */ - virtual void setDetectorPositionId(const int i) = 0; - - /** - * Sets detector hostname - * It is second function called by the client when connecting to receiver. - * you can call this function only once. - * @param c detector hostname - */ - virtual void initialize(const char *c) = 0; - - - //***acquisition functions*** - /** - * Reset acquisition parameters such as total frames caught for an entire acquisition (including all scans) - */ - virtual void resetAcquisitionCount() = 0; - - /** - * Start Listening for Packets by activating all configuration settings to receiver - * @param c error message if FAIL - * @return OK or FAIL - */ - virtual int startReceiver(char *c=NULL) = 0; - - /** - * Stop Listening for Packets - * Calls startReadout(), which stops listening and sets status to Transmitting - * When it has read every frame in buffer,it returns with the status Run_Finished - */ - virtual void stopReceiver() = 0; - - /** - * Stop Listening to Packets - * and sets status to Transmitting - */ - virtual void startReadout() = 0; - - /** - * Shuts down and deletes UDP Sockets - */ - virtual void shutDownUDPSockets() = 0; - - /** - * abort acquisition with minimum damage: close open files, cleanup. - * does nothing if state already is 'idle' - */ - virtual void abort() = 0; //FIXME: needed, isnt stopReceiver enough? - - /** - * Activate / Deactivate Receiver - * If deactivated, receiver will create dummy data if deactivated padding is enabled - * (as it will receive nothing from detector) - * @param enable enable - * @return false for disabled, true for enabled - */ - virtual bool setActivate(const bool enable) = 0; - - /** - * Set deactivated padding enable - * If enabled, receiver will create dummy packets (0xFF), else it will create nothing - * (as it will receive nothing from detector) - * @param enable enable - * @return false for disabled, true for enabled - */ - virtual bool setDeactivatedPadding(const bool enable) = 0; - - /** - * Set streaming port - * @param i streaming port - */ - virtual void setStreamingPort(const uint32_t i) = 0; - - /** - * Set streaming source ip - * @param c streaming source ip - */ - virtual void setStreamingSourceIP(const char* c) = 0; - - /** - * Set additional json header - */ - virtual void setAdditionalJsonHeader(const char* c) = 0; - - /** (not saved in client shared memory) - * Set UDP Socket Buffer Size - * @param s UDP Socket Buffer Size - * @return OK or FAIL if dummy socket could be created - */ - virtual int setUDPSocketBufferSize(const uint32_t s) = 0; - - /* - * Restream stop dummy packet from receiver - * @return OK or FAIL - */ - virtual int restreamStop() = 0; - - - //***callback functions*** - /** - * Call back for start acquisition - * callback arguments are - * filepath - * filename - * fileindex - * datasize - * - * return value is insignificant at the moment - * we write depending on file write enable - * users get data to write depending on call backs registered - */ - virtual void registerCallBackStartAcquisition(int (*func)(char*, char*, uint64_t, uint32_t, void*),void *arg) = 0; - - /** - * Call back for acquisition finished - * callback argument is - * total frames caught - */ - virtual void registerCallBackAcquisitionFinished(void (*func)(uint64_t, void*),void *arg) = 0; - - /** - * Call back for raw data - * args to raw data ready callback are - * sls_receiver_header frame metadata - * dataPointer is the pointer to the data - * dataSize in bytes is the size of the data in bytes. - */ - virtual void registerCallBackRawDataReady(void (*func)(char* , - char*, uint32_t, void*),void *arg) = 0; - - /** - * Call back for raw data (modified) - * args to raw data ready callback are - * sls_receiver_header frame metadata - * dataPointer is the pointer to the data - * revDatasize is the reference of data size in bytes. Can be modified to the new size to be written/streamed. (only smaller value). - */ - virtual void registerCallBackRawDataModifyReady(void (*func)(char* , - char*, uint32_t &,void*),void *arg) = 0; - - - protected: - private: - -}; diff --git a/slsReceiverSoftware/include/UDPStandardImplementation.h b/slsReceiverSoftware/include/UDPStandardImplementation.h deleted file mode 100644 index 30f19a596..000000000 --- a/slsReceiverSoftware/include/UDPStandardImplementation.h +++ /dev/null @@ -1,282 +0,0 @@ -#pragma once -/********************************************//** - * @file UDPBaseImplementation.h - * @short does all the functions for a receiver, set/get parameters, start/stop etc. - ***********************************************/ -/** - * @short does all the functions for a receiver, set/get parameters, start/stop etc. - */ -#include "UDPBaseImplementation.h" - -class GeneralData; -class Listener; -class DataProcessor; -class DataStreamer; -class Fifo; - - - -class UDPStandardImplementation: private virtual slsReceiverDefs, public UDPBaseImplementation { - public: - - - //*** cosntructor & destructor *** - /** - * Constructor - */ - UDPStandardImplementation(); - - /** - * Destructor - */ - virtual ~UDPStandardImplementation(); - - - - //*** Overloaded Functions called by TCP Interface *** - - /** - * Get Total Frames Caught for an entire acquisition (including all scans) - * @return total number of frames caught for entire acquisition - */ - uint64_t getTotalFramesCaught() const; - - /** - * Get Frames Caught for each real time acquisition (eg. for each scan) - * @return number of frames caught for each scan - */ - uint64_t getFramesCaught() const; - - /** - * Get Current Frame Index for an entire acquisition (including all scans) - * @return -1 if no frames have been caught, else current frame index (represents all scans too) - */ - int64_t getAcquisitionIndex() const; - - /** - * Set Gap Pixels Enable (eiger specific) - * @param b true for gap pixels enable, else false - * @return OK or FAIL - */ - int setGapPixelsEnable(const bool b); - - /** - * Set File Format - * @param f fileformat binary or hdf5 - */ - void setFileFormat(slsReceiverDefs::fileFormat f); - - /** - * Set File Write Enable - * @param b true for file write enable, else false - */ - void setFileWriteEnable(const bool b); - - /** - * Set ROI - * @param i ROI - * @return OK or FAIL - */ - int setROI(const std::vector i); - - /** - * Set the Frequency of Frames Sent to GUI - * @param freq 0 for random frame requests, n for nth frame frequency - * @return OK or FAIL - */ - int setFrameToGuiFrequency(const uint32_t freq); - - /** - * Set the data stream enable - * @param enable data stream enable - * @return OK or FAIL - */ - int setDataStreamEnable(const bool enable); - - /** - * Set Number of Samples expected by receiver from detector - * @param i number of Samples expected - * @return OK or FAIL - */ - int setNumberofSamples(const uint64_t i); - - /** - * Set Dynamic Range or Number of Bits Per Pixel - * @param i dynamic range that is 4, 8, 16 or 32 - * @return OK or FAIL - */ - int setDynamicRange(const uint32_t i); - - /** - * Set Ten Giga Enable - * @param b true if 10GbE enabled, else false (1G enabled) - * @return OK or FAIL - */ - int setTenGigaEnable(const bool b); - - /** - * Set Fifo Depth - * @param i fifo depth value - * @return OK or FAIL - */ - int setFifoDepth(const uint32_t i); - - - /** - * Set receiver type (and corresponding detector variables in derived STANDARD class) - * It is the first function called by the client when connecting to receiver - * @param d detector type - * @return OK or FAIL - */ - int setDetectorType(const detectorType d); - - /** - * Set detector position id and construct filewriter - * @param i position id - */ - void setDetectorPositionId(const int i); - - /** - * Reset acquisition parameters such as total frames caught for an entire acquisition (including all scans) - */ - void resetAcquisitionCount(); - - /** - * Start Listening for Packets by activating all configuration settings to receiver - * When this function returns, it has status RUNNING(upon SUCCESS) or IDLE (upon failure) - * @param c error message if FAIL - * @return OK or FAIL - */ - int startReceiver(char *c=NULL); - - /** - * Stop Listening for Packets - * Calls startReadout(), which stops listening and sets status to Transmitting - * When it has read every frame in buffer, the status changes to Run_Finished - * When this function returns, receiver has status IDLE - * Pre: status is running, semaphores have been instantiated, - * Post: udp sockets shut down, status is idle, semaphores destroyed - */ - void stopReceiver(); - - /** - * Stop Listening to Packets - * and sets status to Transmitting - * Next step would be to get all data and stop receiver completely and return with idle state - * Pre: status is running, udp sockets have been initialized, stop receiver initiated - * Post:udp sockets closed, status is transmitting - */ - void startReadout(); - - /** - * Shuts down and deletes UDP Sockets - * also called in case of illegal shutdown of receiver - */ - void shutDownUDPSockets(); - - /** - * Closes file / all files(data compression involves multiple files) - */ - void closeFiles(); - - /** (not saved in client shared memory) - * Set UDP Socket Buffer Size - * @param s UDP Socket Buffer Size - * @return OK or FAIL if dummy socket could be created - */ - int setUDPSocketBufferSize(const uint32_t s); - - /** - * Restream stop dummy packet from receiver - * @return OK or FAIL - */ - int restreamStop(); - - -private: - - /** - * Delete and free member parameters - */ - void DeleteMembers(); - - /** - * Initialize member parameters - */ - void InitializeMembers(); - - /** - * Sets local network parameters, but requires permissions - */ - void SetLocalNetworkParameters(); - - /** - * Set Thread Priorities - */ - void SetThreadPriorities(); - - /** - * Set up the Fifo Structure for processing buffers - * between listening and dataprocessor threads - * @return OK or FAIL - */ - int SetupFifoStructure(); - - /** - * Reset parameters for new measurement (eg. for each scan) - */ - void ResetParametersforNewMeasurement(); - - /** - * Creates UDP Sockets - * @return OK or FAIL - */ - int CreateUDPSockets(); - - /** - * Creates the first file - * also does the startAcquisitionCallBack - * @return OK or FAIL - */ - int SetupWriter(); - - /** - * Start Running - * Set running mask and post semaphore of the threads - * to start the inner loop in execution thread - */ - void StartRunning(); - - - - //*** Class Members *** - - - //*** receiver parameters *** - /** Number of Threads */ - int numThreads; - - /** Number of Jobs */ - int numberofJobs; - - /** Number of channels in roi for jungfrauctb */ - uint32_t nroichannels; - - //** class objects *** - /** General Data Properties */ - GeneralData* generalData; - - /** Listener Objects that listen to UDP and push into fifo */ - std::vector listener; - - /** DataProcessor Objects that pull from fifo and process data */ - std::vector dataProcessor; - - /** DataStreamer Objects that stream data via ZMQ */ - std::vector dataStreamer; - - /** Fifo Structure to store addresses of memory writes */ - std::vector fifo; - -}; - diff --git a/slsReceiverSoftware/include/circularFifo.h b/slsReceiverSoftware/include/circularFifo.h old mode 100644 new mode 100755 index f0b4eeb34..d85c0fac7 --- a/slsReceiverSoftware/include/circularFifo.h +++ b/slsReceiverSoftware/include/circularFifo.h @@ -7,17 +7,10 @@ * modified by the sls detetor group * */ -//#include "sls_receiver_defs.h" #include #include #include -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; - - - /** Circular Fifo (a.k.a. Circular Buffer) * Thread safe for one reader, and one writer */ template diff --git a/slsReceiverSoftware/include/gitInfoReceiver.h b/slsReceiverSoftware/include/gitInfoReceiver.h deleted file mode 100644 index 3c32a944b..000000000 --- a/slsReceiverSoftware/include/gitInfoReceiver.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "git@github.com:slsdetectorgroup/slsDetectorPackage.git" -#define GITREPUUID "907d1655d1f6cf2bb8cf6ccd7e91e82f479dd2ca" -#define GITAUTH "Dhanya_Thattil" -#define GITREV 0x4101 -#define GITDATE 0x20190211 -#define GITBRANCH "developer" diff --git a/slsReceiverSoftware/include/gitInfoReceiverTmp.h b/slsReceiverSoftware/include/gitInfoReceiverTmp.h deleted file mode 100644 index dfd9bb246..000000000 --- a/slsReceiverSoftware/include/gitInfoReceiverTmp.h +++ /dev/null @@ -1,6 +0,0 @@ -#define GITURL "" -#define GITREPUUID "" -#define GITAUTH "" -#define GITREV "" -#define GITDATE "" -#define GITBRANCH "" diff --git a/slsReceiverSoftware/include/libzmq.a b/slsReceiverSoftware/include/libzmq.a deleted file mode 100644 index 0bc273d00..000000000 Binary files a/slsReceiverSoftware/include/libzmq.a and /dev/null differ diff --git a/slsReceiverSoftware/include/receiver_defs.h b/slsReceiverSoftware/include/receiver_defs.h index 7d34bef05..5f623e16f 100755 --- a/slsReceiverSoftware/include/receiver_defs.h +++ b/slsReceiverSoftware/include/receiver_defs.h @@ -1,6 +1,6 @@ #pragma once -#include "sls_receiver_defs.h" +#include "sls_detector_defs.h" #include #define MAX_DIMENSIONS 2 diff --git a/slsReceiverSoftware/include/slsReceiver.h b/slsReceiverSoftware/include/slsReceiver.h old mode 100644 new mode 100755 index 896f63817..7c5647d39 --- a/slsReceiverSoftware/include/slsReceiver.h +++ b/slsReceiverSoftware/include/slsReceiver.h @@ -4,21 +4,17 @@ * @short creates the UDP and TCP class objects ***********************************************/ - +#include #include "slsReceiverTCPIPInterface.h" -#include "UDPInterface.h" - -#include "receiver_defs.h" -#include "MySocketTCP.h" -//#include "utilities.h" +#include "sls_detector_defs.h" /** *@short creates the UDP and TCP class objects */ -class slsReceiver : private virtual slsReceiverDefs { +class slsReceiver : private virtual slsDetectorDefs { public: /** @@ -30,11 +26,15 @@ class slsReceiver : private virtual slsReceiverDefs { * @param argv from command line */ slsReceiver(int argc, char *argv[]); - + /** - * Destructor + * Constructor + * Starts up a Receiver server. Reads configuration file, options, and + * assembles a Receiver using TCP and UDP detector interfaces + * throws an exception in case of failure + * @param tcpip_port_no TCP/IP port number */ - ~slsReceiver(); + slsReceiver(int tcpip_port_no = 1954); /** * starts listening on the TCP port for client comminication @@ -98,6 +98,5 @@ class slsReceiver : private virtual slsReceiverDefs { private: - slsReceiverTCPIPInterface* tcpipInterface; + std::unique_ptr tcpipInterface; }; - diff --git a/slsReceiverSoftware/include/UDPBaseImplementation.h b/slsReceiverSoftware/include/slsReceiverImplementation.h old mode 100644 new mode 100755 similarity index 74% rename from slsReceiverSoftware/include/UDPBaseImplementation.h rename to slsReceiverSoftware/include/slsReceiverImplementation.h index cafcd33bb..9eb8740ec --- a/slsReceiverSoftware/include/UDPBaseImplementation.h +++ b/slsReceiverSoftware/include/slsReceiverImplementation.h @@ -1,39 +1,41 @@ #pragma once /********************************************//** - * @file UDPBaseImplementation.h + * @file slsReceiverImplementation.h * @short does all the functions for a receiver, set/get parameters, start/stop etc. ***********************************************/ - -//#include "sls_receiver_defs.h" -#include "UDPInterface.h" -//#include - /** - * @short does all the base functions for a receiver, set/get parameters, start/stop etc. + * @short does all the functions for a receiver, set/get parameters, start/stop etc. */ +// #include "sls_detector_defs.h" +#include "receiver_defs.h" +#include "logger.h" +#include "container_utils.h" +class GeneralData; +class Listener; +class DataProcessor; +class DataStreamer; +class Fifo; +class slsDetectorDefs; -class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInterface { - +#include +#include +#include + +class slsReceiverImplementation: private virtual slsDetectorDefs { public: - /************************************************************************* - * Constructor & Destructor ********************************************** - * They access local cache of configuration or detector parameters ******* - *************************************************************************/ + + //*** cosntructor & destructor *** /** * Constructor */ - UDPBaseImplementation(); + slsReceiverImplementation(); /** * Destructor */ - virtual ~UDPBaseImplementation(); + virtual ~slsReceiverImplementation(); - /* - * Initialize class members - */ - void initializeMembers(); /************************************************************************* * Getters *************************************************************** @@ -47,7 +49,6 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter */ int* getMultiDetectorSize() const; - /* * Get detector position id * @return detector position id @@ -56,9 +57,9 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter /* * Get detector hostname - * @return NULL or hostname or NULL if uninitialized (max of 1000 characters) + * @return hostname (max of 1000 characters) */ - char *getDetectorHostname() const; + std::string getDetectorHostname() const; /* * Get flipped data across 'axis' @@ -72,6 +73,12 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter */ bool getGapPixelsEnable() const; + /** + * Get readout flags (Eiger, chiptestboard, moench) + * @return readout flags + */ + readOutFlags getReadOutFlags() const; + //***file parameters*** /** @@ -81,15 +88,15 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter fileFormat getFileFormat() const; /** * Get File Name Prefix (without frame index, file index and extension (_d0_f000000000000_8.raw)) - * @return NULL or file name prefix (max of 1000 characters) + * @return file name prefix */ - char *getFileName() const; + std::string getFileName() const; /** * Get File Path - * @return NULL or file path (max of 1000 characters) + * @return file path */ - char *getFilePath() const; + std::string getFilePath() const; /** * Get File Index @@ -115,12 +122,6 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter */ bool getFramePaddingEnable() const; - /** - * Get Scan Tag - * @return scan tag //FIXME: needed? (unsigned integer?) - */ - int getScanTag() const; - /** * Get File Write Enable * @return true if file write enabled, else false @@ -133,12 +134,6 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter */ bool getOverwriteEnable() const; - /** - * Get data compression, by saving only hits (so far implemented only for Moench and Gotthard) - * @return true if data compression enabled, else false - */ - bool getDataCompressionEnable() const; - //***acquisition count parameters*** /** @@ -168,16 +163,28 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter uint32_t getUDPPortNumber() const; /** - * Get Second UDP Port Number (eiger specific) + * Get Second UDP Port Number (eiger/jungfrau specific) * @return second udp port number */ uint32_t getUDPPortNumber2() const; /** * Get Ehernet Interface - * @ethernet interface. eg. eth0 or "" if listening to all (max of 1000 characters) + * @return ethernet interface. eg. eth0 or "" if listening to all */ - char *getEthernetInterface() const; + std::string getEthernetInterface() const; + + /** + * Get Ehernet Interface 2 (jungfrau specific) + * @return ethernet interface 2. eg. eth0 or "" if listening to all + */ + std::string getEthernetInterface2() const; + + /** + * Get number of UDP Interfaces (jungfrau specific) + * @return number of udp interfaces. Options (1-2) + */ + int getNumberofUDPInterfaces() const; //***acquisition parameters*** @@ -188,16 +195,16 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter std::vector getROI() const; /** - * Get the Frequency of Frames Sent to GUI - * @return 0 for random frame requests, n for nth frame frequency + * Get the streaming frequency + * @return 0 for timer, n for nth frame frequency */ - uint32_t getFrameToGuiFrequency() const; + uint32_t getStreamingFrequency() const; /** * Gets the timer between frames streamed when frequency is set to 0 * @return timer between frames streamed */ - uint32_t getFrameToGuiTimer() const; + uint32_t getStreamingTimer() const; /** * Get the data stream enable @@ -301,26 +308,26 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter * Get streaming source ip * @return streaming source ip */ - char *getStreamingSourceIP() const; + std::string getStreamingSourceIP() const; /** * Get additional json header * @return additional json header */ - char *getAdditionalJsonHeader() const; + std::string getAdditionalJsonHeader() const; /** (not saved in client shared memory) * Get UDP Socket Buffer Size * @return UDP Socket Buffer Size */ - uint32_t getUDPSocketBufferSize() const; + int64_t getUDPSocketBufferSize() const; /** (not saved in client shared memory) * Get actual UDP Socket Buffer Size * @return actual UDP Socket Buffer Size */ - uint32_t getActualUDPSocketBufferSize() const; + int64_t getActualUDPSocketBufferSize() const; /************************************************************************* * Setters *************************************************************** @@ -329,10 +336,10 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter //**initial parameters*** /** - * Configure command line parameters - * @param config_map mapping of config parameters passed from command line arguments + * Sets detector hostname + * @param c detector hostname */ - void configure(std::map config_map); + void setDetectorHostname(const char *c); /* * Set multi detector size @@ -353,13 +360,20 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter */ int setGapPixelsEnable(const bool b); + /** + * Set readout flags (eiger, chiptestboard, moench) + * @param f readout flag + * @return OK or FAIL + */ + int setReadOutFlags(const readOutFlags f); + //***file parameters*** /** * Set File Format * @param f fileformat binary or hdf5 */ - void setFileFormat(slsReceiverDefs::fileFormat f); + void setFileFormat(slsDetectorDefs::fileFormat f); /** * Set File Name Prefix (without frame index, file index and extension (_d0_f000000000000_8.raw)) @@ -400,12 +414,6 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter */ void setFramePaddingEnable(const bool i); - /** - * Set Scan Tag - * @param i scan tag //FIXME: needed? (unsigned integer?) - */ - void setScanTag(const int i); - /** * Set File Write Enable * @param b true for file write enable, else false @@ -418,14 +426,6 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter */ void setOverwriteEnable(const bool b); - /** - * Set data compression, by saving only hits (so far implemented only for Moench and Gotthard) - * @param b true for data compression enable, else false - * @return OK or FAIL - */ - int setDataCompressionEnable(const bool b); - - //***connection parameters*** /** * Set UDP Port Number @@ -434,7 +434,7 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter void setUDPPortNumber(const uint32_t i); /** - * Set Second UDP Port Number (eiger specific) + * Set Second UDP Port Number (eiger/jungfrau specific) * @return second udp port number */ void setUDPPortNumber2(const uint32_t i); @@ -445,6 +445,26 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter */ void setEthernetInterface(const char* c); + /** + * Set second Ethernet Interface to listen to (jungfrau specific) + * @param c second ethernet inerface eg. eth0 (max of 1000 characters) + */ + void setEthernetInterface2(const char* c); + + /** + * Set number of UDP Interfaces (jungfrau specific) + * @param n number of udp interfaces. Options (1-2) + * @return OK or FAIL for fifo structure creation + */ + int setNumberofUDPInterfaces(const int n); + + /** (not saved in client shared memory) + * Set UDP Socket Buffer Size + * @param s UDP Socket Buffer Size + * @return OK or FAIL if dummy socket could be created + */ + int setUDPSocketBufferSize(const int64_t s); + //***acquisition parameters*** /** @@ -452,27 +472,43 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter * @param i ROI * @return OK or FAIL */ - int setROI(const std::vector i); + int setROI(const std::vector new_roi); - /** - * Set the Frequency of Frames Sent to GUI - * @param freq 0 for random frame requests, n for nth frame frequency - * @return OK or FAIL - */ - int setFrameToGuiFrequency(const uint32_t freq); + /** + * Set the streaming frequency + * @param freq 0 for timer, n for nth frame frequency + * @return OK or FAIL + */ + int setStreamingFrequency(const uint32_t freq); - /** - * Sets the timer between frames streamed when frequency is set to 0 - * @param time_in_ms timer between frames streamed - */ - void setFrameToGuiTimer(const uint32_t time_in_ms); + /** + * Sets the timer between frames streamed when frequency is set to 0 + * @param time_in_ms timer between frames streamed + */ + void setStreamingTimer(const uint32_t time_in_ms); + /** + * Set the data stream enable + * @param enable data stream enable + * @return OK or FAIL + */ + int setDataStreamEnable(const bool enable); - /** - * Set the data stream enable - * @param enable data stream enable - * @return OK or FAIL - */ - int setDataStreamEnable(const bool enable); + /** + * Set streaming port + * @param i streaming port + */ + void setStreamingPort(const uint32_t i); + + /** + * Set streaming source ip + * @param c streaming source ip + */ + void setStreamingSourceIP(const char *c); + + /** + * Set additional json header + */ + void setAdditionalJsonHeader(const char* c); /** * Set Acquisition Period @@ -525,7 +561,7 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter /** * Set Ten Giga Enable - * @param b true if 10Giga enabled, else false (1G enabled) + * @param b true if 10GbE enabled, else false (1G enabled) * @return OK or FAIL */ int setTenGigaEnable(const bool b); @@ -537,80 +573,8 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter */ int setFifoDepth(const uint32_t i); + //***receiver parameters*** - /** - * Set Silent Mode - * @param i silent mode. true sets, false unsets - */ - void setSilentMode(const bool i); - - /************************************************************************* - * Behavioral functions*************************************************** - * They may modify the status of the receiver **************************** - *************************************************************************/ - - - //***initial functions*** - /** - * Set receiver type (and corresponding detector variables in derived STANDARD class) - * It is the first function called by the client when connecting to receiver - * @param d detector type - * @return OK or FAIL - */ - int setDetectorType(const detectorType d); - - /** - * Set detector position id - * @param i position id - */ - void setDetectorPositionId(const int i); - - /** - * Sets detector hostname - * It is second function called by the client when connecting to receiver. - * you can call this function only once. - * @param c detector hostname - */ - void initialize(const char *c); - - - //***acquisition functions*** - /** - * Reset acquisition parameters such as total frames caught for an entire acquisition (including all scans) - */ - void resetAcquisitionCount(); - - /** - * Start Listening for Packets by activating all configuration settings to receiver - * @param c error message if FAIL - * @return OK or FAIL - */ - int startReceiver(char *c=NULL); - - /** - * Stop Listening for Packets - * Calls startReadout(), which stops listening and sets status to Transmitting - * When it has read every frame in buffer,it returns with the status Run_Finished - */ - void stopReceiver(); - - /** - * Stop Listening to Packets - * and sets status to Transmitting - */ - void startReadout(); - - /** - * Shuts down and deletes UDP Sockets - */ - void shutDownUDPSockets(); - - /** - * abort acquisition with minimum damage: close open files, cleanup. - * does nothing if state already is 'idle' - */ - void abort(); //FIXME: needed, isn't stopReceiver enough? - /** * Activate / Deactivate Receiver * If deactivated, receiver will create dummy data if deactivated padding is enabled @@ -630,30 +594,77 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter bool setDeactivatedPadding(const bool enable); /** - * Set streaming port - * @param i streaming port + * Set Silent Mode + * @param i silent mode. true sets, false unsets */ - void setStreamingPort(const uint32_t i); + void setSilentMode(const bool i); + + + /************************************************************************* + * Behavioral functions*************************************************** + * They may modify the status of the receiver **************************** + *************************************************************************/ + + //***initial functions*** + /** + * Set receiver type (and corresponding detector variables in derived STANDARD class) + * It is the first function called by the client when connecting to receiver + * @param d detector type + * @return OK or FAIL + */ + int setDetectorType(const detectorType d); /** - * Set streaming source ip - * @param c streaming source ip + * Set detector position id and construct filewriter + * @param id position id */ - void setStreamingSourceIP(const char* c); + void setDetectorPositionId(const int id); - /** - * Set additional json header - */ - void setAdditionalJsonHeader(const char* c); + //***acquisition functions*** + /** + * Reset acquisition parameters such as total frames caught for an entire acquisition (including all scans) + */ + void resetAcquisitionCount(); - /** (not saved in client shared memory) - * Set UDP Socket Buffer Size - * @param s UDP Socket Buffer Size - * @return OK or FAIL if dummy socket could be created - */ - int setUDPSocketBufferSize(const uint32_t s); + /** + * Start Listening for Packets by activating all configuration settings to receiver + * When this function returns, it has status RUNNING(upon SUCCESS) or IDLE (upon failure) + * @param c error message if FAIL + * @return OK or FAIL + */ + int startReceiver(char *c=NULL); - /* + /** + * Stop Listening for Packets + * Calls startReadout(), which stops listening and sets status to Transmitting + * When it has read every frame in buffer, the status changes to Run_Finished + * When this function returns, receiver has status IDLE + * Pre: status is running, semaphores have been instantiated, + * Post: udp sockets shut down, status is idle, semaphores destroyed + */ + void stopReceiver(); + + /** + * Stop Listening to Packets + * and sets status to Transmitting + * Next step would be to get all data and stop receiver completely and return with idle state + * Pre: status is running, udp sockets have been initialized, stop receiver initiated + * Post:udp sockets closed, status is transmitting + */ + void startReadout(); + + /** + * Shuts down and deletes UDP Sockets + * also called in case of illegal shutdown of receiver + */ + void shutDownUDPSockets(); + + /** + * Closes file / all files(data compression involves multiple files) + */ + void closeFiles(); + + /** * Restream stop dummy packet from receiver * @return OK or FAIL */ @@ -702,8 +713,61 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter void registerCallBackRawDataModifyReady(void (*func)(char* , char*, uint32_t &,void*),void *arg); +private: + + /** + * Delete and free member parameters + */ + void DeleteMembers(); + + /** + * Initialize member parameters + */ + void InitializeMembers(); + + /** + * Sets local network parameters, but requires permissions + */ + void SetLocalNetworkParameters(); + + /** + * Set Thread Priorities + */ + void SetThreadPriorities(); + + /** + * Set up the Fifo Structure for processing buffers + * between listening and dataprocessor threads + * @return OK or FAIL + */ + int SetupFifoStructure(); + + /** + * Reset parameters for new measurement (eg. for each scan) + */ + void ResetParametersforNewMeasurement(); + + /** + * Creates UDP Sockets + * @return OK or FAIL + */ + int CreateUDPSockets(); + + /** + * Creates the first file + * also does the startAcquisitionCallBack + * @return OK or FAIL + */ + int SetupWriter(); + + /** + * Start Running + * Set running mask and post semaphore of the threads + * to start the inner loop in execution thread + */ + void StartRunning(); + - protected: /************************************************************************* * Class Members ********************************************************* @@ -739,8 +803,12 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter int flippedData[2]; /** gap pixels enable */ bool gapPixelsEnable; + /** readout flags*/ + readOutFlags readoutFlags; - //***receiver parameters*** + //*** receiver parameters *** + /** Number of Threads */ + int numThreads; /** Maximum Number of Listening Threads/ UDP Ports */ const static int MAX_NUMBER_OF_LISTENING_THREADS = 2; /** Receiver Status */ @@ -753,18 +821,22 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter frameDiscardPolicy frameDiscardMode; /** frame padding */ bool framePadding; + /** silent mode */ + bool silentMode; //***connection parameters*** + /** Number of UDP Interfaces */ + int numUDPInterfaces; /** Ethernet Interface */ - char eth[MAX_STR_LENGTH]; + char eth[MAX_NUMBER_OF_LISTENING_THREADS][MAX_STR_LENGTH]; /** Server UDP Port Number*/ uint32_t udpPortNum[MAX_NUMBER_OF_LISTENING_THREADS]; /** udp socket buffer size */ - uint32_t udpSocketBufferSize; + int64_t udpSocketBufferSize; /** actual UDP Socket Buffer Size (halved due to kernel bookkeeping) */ - uint32_t actualUDPSocketBufferSize; + int64_t actualUDPSocketBufferSize; - //***file parameters*** + //***file parameters*** /** File format */ fileFormat fileFormatType; /** File Name without frame index, file index and extension (_d0_f000000000000_8.raw)*/ @@ -775,22 +847,18 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter uint64_t fileIndex; /** Frames per file (0 means infinite) */ uint32_t framesPerFile; - /** Scan Tag */ - int scanTag; /** File Write enable */ bool fileWriteEnable; /** Overwrite enable */ bool overwriteEnable; - /** Data Compression Enable - save only hits */ - bool dataCompressionEnable; //***acquisition parameters*** /* ROI */ std::vector roi; - /** Frequency of Frames sent to GUI */ - uint32_t frameToGuiFrequency; - /** Timer of Frames sent to GUI when frequency is 0 */ - uint32_t frameToGuiTimerinMS; + /** streaming frequency */ + uint32_t streamingFrequency; + /** Streaming timer when frequency is 0 */ + uint32_t streamingTimerInMs; /** Data Stream Enable from Receiver */ bool dataStreamEnable; /** streaming port */ @@ -800,10 +868,17 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter /** additional json header */ char additionalJsonHeader[MAX_STR_LENGTH]; - //***receiver parameters*** - bool silentMode; - - + //** class objects *** + /** General Data Properties */ + GeneralData* generalData; + /** Listener Objects that listen to UDP and push into fifo */ + std::vector> listener; + /** DataProcessor Objects that pull from fifo and process data */ + std::vector> dataProcessor; + /** DataStreamer Objects that stream data via ZMQ */ + std::vector> dataStreamer; + /** Fifo Structure to store addresses of memory writes */ + std::vector> fifo; //***callback parameters*** /** @@ -820,7 +895,6 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter */ int (*startAcquisitionCallBack)(char*, char*, uint64_t, uint32_t, void*); void *pStartAcquisition; - /** * Call back for acquisition finished * callback argument is @@ -828,8 +902,6 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter */ void (*acquisitionFinishedCallBack)(uint64_t, void*); void *pAcquisitionFinished; - - /** * Call back for raw data * args to raw data ready callback are @@ -839,7 +911,6 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter */ void (*rawDataReadyCallBack)(char* , char*, uint32_t, void*); - /** * Call back for raw data (modified) * args to raw data ready callback are @@ -849,11 +920,8 @@ class UDPBaseImplementation : protected virtual slsReceiverDefs, public UDPInter */ void (*rawDataModifyReadyCallBack)(char* , char*, uint32_t &, void*); - void *pRawDataReady; - -private: - }; + diff --git a/slsReceiverSoftware/include/slsReceiverTCPIPInterface.h b/slsReceiverSoftware/include/slsReceiverTCPIPInterface.h old mode 100644 new mode 100755 index 1b28c2ed4..6e87e6c27 --- a/slsReceiverSoftware/include/slsReceiverTCPIPInterface.h +++ b/slsReceiverSoftware/include/slsReceiverTCPIPInterface.h @@ -5,10 +5,12 @@ ***********************************************/ -#include "sls_receiver_defs.h" +#include "sls_detector_defs.h" #include "receiver_defs.h" -#include "MySocketTCP.h" -#include "UDPInterface.h" + +class MySocketTCP; +class ServerInterface; +class slsReceiverImplementation; @@ -16,7 +18,9 @@ *@short interface between receiver and client */ -class slsReceiverTCPIPInterface : private virtual slsReceiverDefs { +class slsReceiverTCPIPInterface : private virtual slsDetectorDefs { + private: + enum numberMode {DEC, HEX}; public: @@ -104,30 +108,22 @@ class slsReceiverTCPIPInterface : private virtual slsReceiverDefs { */ void startTCPServer(); - /** retuns function name with function index */ - const char* getFunctionName(enum recFuncs func); - /** assigns functions to the fnum enum */ int function_table(); /** Decodes Function */ int decode_function(); - /** print socket read error */ - int printSocketReadError(); - - /** receiver object is null */ - void invalidReceiverObject(); - - /** receiver already locked */ - void receiverlocked(); - - /** receiver not idle */ - void receiverNotIdle(); - /** function not implemented for specific detector */ void functionNotImplemented(); + /** mode not implemented for specific detector */ + void modeNotImplemented(std::string modename, int mode); + + /** validate and set error */ + template + void validate(T arg, T retval, std::string modename, numberMode hex); + /** Unrecognized Function */ int M_nofunc(); @@ -175,8 +171,8 @@ class slsReceiverTCPIPInterface : private virtual slsReceiverDefs { /** set dynamic range */ int set_dynamic_range(); - /** Sets the receiver to send every nth frame to gui, or only upon gui request */ - int set_read_frequency(); + /** Sets the receiver streaming frequency */ + int set_streaming_frequency(); /** Gets receiver status */ int get_status(); @@ -187,10 +183,6 @@ class slsReceiverTCPIPInterface : private virtual slsReceiverDefs { /** Stop Receiver - stops listening to udp packets from detector*/ int stop_receiver(); - /** set status to transmitting and - * when fifo is empty later, sets status to run_finished */ - int start_readout(); - /** Set File path */ int set_file_dir(); @@ -230,8 +222,8 @@ class slsReceiverTCPIPInterface : private virtual slsReceiverDefs { /* Set the data stream enable */ int set_data_stream_enable(); - /** Sets the timer between frames streamed by receiver when frequency is set to 0 */ - int set_read_receiver_timer(); + /** Sets the steadming timer when frequency is set to 0 */ + int set_streaming_timer(); /** enable flipped data */ int set_flipped_data(); @@ -263,6 +255,9 @@ class slsReceiverTCPIPInterface : private virtual slsReceiverDefs { /** set additional json header */ int set_additional_json_header(); + /** get additional json header */ + int get_additional_json_header(); + /** set udp socket buffer size */ int set_udp_socket_buffer_size(); @@ -284,12 +279,15 @@ class slsReceiverTCPIPInterface : private virtual slsReceiverDefs { /** set deactivated receiver padding enable */ int set_deactivated_receiver_padding_enable(); + /** set readout flags */ + int set_readout_flags(); + /** detector type */ detectorType myDetectorType; /** slsReceiverBase object */ - UDPInterface *receiverBase; + slsReceiverImplementation *receiver; /** Function List */ int (slsReceiverTCPIPInterface::*flist[NUM_REC_FUNCTIONS])(); @@ -368,6 +366,10 @@ class slsReceiverTCPIPInterface : private virtual slsReceiverDefs { protected: + /** Socket */ MySocketTCP* mySock; + + /** client interface */ + ServerInterface* interface; }; diff --git a/slsReceiverSoftware/include/slsReceiverUsers.h b/slsReceiverSoftware/include/slsReceiverUsers.h old mode 100644 new mode 100755 index 8b17796d2..39456bd94 --- a/slsReceiverSoftware/include/slsReceiverUsers.h +++ b/slsReceiverSoftware/include/slsReceiverUsers.h @@ -3,8 +3,9 @@ #include #include +#include -class slsReceiver; +#include "slsReceiver.h" /** @short Class for implementing the SLS data receiver in the users application. Callbacks can be defined for processing and/or saving data @@ -23,10 +24,14 @@ public: * @param success socket creation was successfull */ slsReceiverUsers(int argc, char *argv[], int &success); - - - /** Destructor */ - ~slsReceiverUsers(); + + /** + * Constructor + * reads config file, creates socket, assigns function table + * @param tcpip_port_no TCP/IP port + * @throws + */ + slsReceiverUsers(int tcpip_port_no = 1954); /** * starts listening on the TCP port for client comminication @@ -83,6 +88,5 @@ public: char* datapointer, uint32_t &revDatasize, void*),void *arg); //receiver object - slsReceiver* receiver; + std::unique_ptr receiver; }; - diff --git a/slsReceiverSoftware/include/sls_receiver_defs.h b/slsReceiverSoftware/include/sls_receiver_defs.h deleted file mode 100755 index c23558fa8..000000000 --- a/slsReceiverSoftware/include/sls_receiver_defs.h +++ /dev/null @@ -1,323 +0,0 @@ -#pragma once - - -#ifdef __CINT__ -#define MYROOT -#define __cplusplus -#endif - -#include -#ifdef __cplusplus -#include -#include -#endif -#include "ansi.h" - - -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; - -/** default maximum string length */ -#define MAX_STR_LENGTH 1000 -#define MAX_FRAMES_PER_FILE 20000 -#define SHORT_MAX_FRAMES_PER_FILE 100000 -#define MOENCH_MAX_FRAMES_PER_FILE 1000 -#define EIGER_MAX_FRAMES_PER_FILE 10000 -#define JFRAU_MAX_FRAMES_PER_FILE 10000 -#define JFCTB_MAX_FRAMES_PER_FILE 100000 - - -#define DEFAULT_STREAMING_TIMER_IN_MS 200 - -/** default ports */ -#define DEFAULT_PORTNO 1952 -#define DEFAULT_UDP_PORTNO 50001 -#define DEFAULT_GUI_PORTNO 65001 -#define DEFAULT_ZMQ_CL_PORTNO 30001 -#define DEFAULT_ZMQ_RX_PORTNO 30001 - -#define SLS_DETECTOR_HEADER_VERSION 0x2 -#define SLS_DETECTOR_JSON_HEADER_VERSION 0x3 - -/** - \file sls_receiver_defs.h -This file contains all the basic definitions common to the slsReceiver class -and to the server programs running on the receiver - * @author Anna Bergamaschi - * @version 0.1alpha (any string) - * @see slsDetector -$Revision: 809 $ - */ - - -#ifdef __cplusplus - -/** @short class containing all the constants and enum definitions */ -class slsReceiverDefs { -public: - - slsReceiverDefs(){}; - -#endif - - /** - Type of the detector - */ - enum detectorType { - GET_DETECTOR_TYPE=-1, /**< the detector will return its type */ - GENERIC, /**< generic sls detector */ - MYTHEN, /**< mythen */ - PILATUS, /**< pilatus */ - EIGER, /**< eiger */ - GOTTHARD, /**< gotthard */ - PICASSO, /**< picasso */ - AGIPD, /**< agipd */ - MOENCH, /**< moench */ - JUNGFRAU, /**< jungfrau */ - JUNGFRAUCTB, /**< jungfrauCTBversion */ - PROPIX, /**< propix */ - MYTHEN3 /**< mythen 3 */ - }; - - - /** - return values - */ - enum { - OK, /**< function succeeded */ - FAIL, /**< function failed */ - FINISHED, /**< acquisition finished */ - FORCE_UPDATE - }; - - - /** - indexes for the acquisition timers - */ - enum timerIndex { - FRAME_NUMBER, /**< number of real time frames: total number of acquisitions is number or frames*number of cycles */ - ACQUISITION_TIME, /**< exposure time */ - FRAME_PERIOD, /**< period between exposures */ - DELAY_AFTER_TRIGGER, /**< delay between trigger and start of exposure or readout (in triggered mode) */ - GATES_NUMBER, /**< number of gates per frame (in gated mode) */ - PROBES_NUMBER, /**< number of probe types in pump-probe mode */ - CYCLES_NUMBER, /**< number of cycles: total number of acquisitions is number or frames*number of cycles */ - ACTUAL_TIME, /**< Actual time of the detector's internal timer */ - MEASUREMENT_TIME, /**< Time of the measurement from the detector (fifo) */ - - PROGRESS, /**< fraction of measurement elapsed - only get! */ - MEASUREMENTS_NUMBER, - FRAMES_FROM_START, - FRAMES_FROM_START_PG, - SAMPLES_JCTB, - SUBFRAME_ACQUISITION_TIME, /**< subframe exposure time */ - STORAGE_CELL_NUMBER, /** sls_bitset; - - typedef struct { - sls_detector_header detHeader; /**< is the detector header */ - sls_bitset packetsMask; /**< is the packets caught bit mask */ - } sls_receiver_header; - - typedef uint8_t bitset_storage[MAX_NUM_PACKETS/8]; - -#endif - /** - * frameDiscardPolicy - */ - enum frameDiscardPolicy { - GET_FRAME_DISCARD_POLICY = -1, /**< to get the missing packet mode */ - NO_DISCARD, /**< pad incomplete packets with -1, default mode */ - DISCARD_EMPTY_FRAMES, /**< discard incomplete frames, fastest mode, save space, not suitable for multiple modules */ - DISCARD_PARTIAL_FRAMES, /**< ignore missing packets, must check with packetsMask for data integrity, fast mode and suitable for multiple modules */ - NUM_DISCARD_POLICIES - }; - - - /** - format - */ - enum fileFormat { - GET_FILE_FORMAT=-1,/**< the receiver will return its file format */ - BINARY, /**< binary format */ - ASCII, /**< ascii format */ - HDF5, /**< hdf5 format */ - NUM_FILE_FORMATS - }; - - - /** - @short structure for a region of interest - xmin,xmax,ymin,ymax define the limits of the region - */ - typedef struct { - int xmin; /**< is the roi xmin (in channel number) */ - int xmax; /**< is the roi xmax (in channel number)*/ - int ymin; /**< is the roi ymin (in channel number)*/ - int ymax; /**< is the roi ymax (in channel number)*/ - } ROI ; - - - -#ifdef __cplusplus - /** returns string from enabled/disabled - \param b true or false - \returns string enabled, disabled - */ - static std::string stringEnable(bool b){\ - if(b) return std::string("enabled"); \ - else return std::string("disabled"); \ - }; - - /** returns detector type string from detector type index - \param t string can be Mythen, Pilatus, Eiger, Gotthard, Agipd, Unknown - \returns MYTHEN, PILATUS, EIGER, GOTTHARD, AGIPD, MÖNCH, GENERIC - */ - static std::string getDetectorType(detectorType t){ \ - switch (t) { \ - case MYTHEN: return std::string("Mythen"); \ - case PILATUS: return std::string("Pilatus"); \ - case EIGER: return std::string("Eiger"); \ - case GOTTHARD: return std::string("Gotthard"); \ - case AGIPD: return std::string("Agipd"); \ - case MOENCH: return std::string("Moench"); \ - case JUNGFRAU: return std::string("Jungfrau"); \ - case JUNGFRAUCTB: return std::string("JungfrauCTB"); \ - case PROPIX: return std::string("Propix"); \ - case MYTHEN3: return std::string("Mythen3"); \ - default: return std::string("Unknown"); \ - }}; - - /** returns detector type index from detector type string - \param type can be MYTHEN, PILATUS, EIGER, GOTTHARD, AGIPD, GENERIC - \returns Mythen, Pilatus, Eiger, Gotthard, Agipd, Mönch, Unknown - */ - static detectorType getDetectorType(std::string const type){\ - if (type=="Mythen") return MYTHEN; \ - if (type=="Pilatus") return PILATUS; \ - if (type=="Eiger") return EIGER; \ - if (type=="Gotthard") return GOTTHARD; \ - if (type=="Agipd") return AGIPD; \ - if (type=="Moench") return MOENCH; \ - if (type=="Jungfrau") return JUNGFRAU; \ - if (type=="JungfrauCTB") return JUNGFRAUCTB; \ - if (type=="Propix") return PROPIX; \ - if (type=="Mythen3") return MYTHEN3; \ - return GENERIC; \ - }; - - - /** returns string from run status index - \param s can be ERROR, WAITING, RUNNING, TRANSMITTING, RUN_FINISHED - \returns string error, waiting, running, data, finished - */ - static std::string runStatusType(runStatus s){\ - switch (s) { \ - case ERROR: return std::string("error"); \ - case WAITING: return std::string("waiting"); \ - case RUNNING: return std::string("running"); \ - case TRANSMITTING: return std::string("data"); \ - case RUN_FINISHED: return std::string("finished"); \ - case STOPPED: return std::string("stopped"); \ - default: return std::string("idle"); \ - }}; - - - /** returns string from file format index - \param s can be BINARY, ASCII, HDF5 - \returns string binary, ascii, hdf5 - */ - static std::string getFileFormatType(fileFormat f){\ - switch (f) { \ - case ASCII: return std::string("ascii"); \ - case HDF5: return std::string("hdf5"); \ - case BINARY: return std::string("binary"); \ - default: return std::string("unknown"); \ - }}; - - /** - * Returns string of frame discard policy index - * @param f can be NO_DISCARD, DISCARD_EMPTY_FRAMES, DISCARD_PARTIAL_FRAMES - * @returns No Discard, Discard Empty Frames, Discard Partial Frames, unknown - */ - static std::string getFrameDiscardPolicyType(frameDiscardPolicy f) { \ - switch (f) { \ - case NO_DISCARD: return std::string("No Discard"); \ - case DISCARD_EMPTY_FRAMES: return std::string("Discard Empty Frames"); \ - case DISCARD_PARTIAL_FRAMES: return std::string("Discard Partial Frames"); \ - default: return std::string("unknown"); \ - }}; \ - -#endif - -#ifdef __cplusplus -protected: -#endif - -#ifndef MYROOT -#include "sls_receiver_funcs.h" -#endif - -#ifdef __cplusplus -}; -#endif -; diff --git a/slsReceiverSoftware/include/sls_receiver_exceptions.h b/slsReceiverSoftware/include/sls_receiver_exceptions.h deleted file mode 100644 index 8ad322ff6..000000000 --- a/slsReceiverSoftware/include/sls_receiver_exceptions.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once -/************************************************ - * @file sls_receiver_exceptions.h - * @short exceptions defined - ***********************************************/ -/** - *@short exceptions defined - */ - -#include -#include - -struct SlsDetectorPackageExceptions : public std::exception { -public: - SlsDetectorPackageExceptions() {} - std::string GetMessage() const { return "SLS Detector Package Failed";}; -}; - -struct SharedMemoryException : public SlsDetectorPackageExceptions { -public: - SharedMemoryException() {} - std::string GetMessage() const { return "Shared Memory Failed";}; -}; - -struct ThreadpoolException : public SlsDetectorPackageExceptions { -public: - ThreadpoolException() {} - std::string GetMessage() const { return "Threadpool Failed";}; -}; - -struct SocketException : public SlsDetectorPackageExceptions { -public: - SocketException() {} - std::string GetMessage() const { return "Socket Failed";}; -}; - -struct SamePortSocketException : public SocketException { -public: - SamePortSocketException() {} - std::string GetMessage() const { return "Socket Failed";}; -}; - diff --git a/slsReceiverSoftware/include/sls_receiver_funcs.h b/slsReceiverSoftware/include/sls_receiver_funcs.h deleted file mode 100644 index 281088f19..000000000 --- a/slsReceiverSoftware/include/sls_receiver_funcs.h +++ /dev/null @@ -1,80 +0,0 @@ -#pragma once -/** - @internal - function indexes to call on the server - All set functions with argument -1 work as get, when possible - */ - -#define REC_FUNC_START_INDEX 128 - -enum recFuncs{ - //General functions - F_EXEC_RECEIVER_COMMAND=REC_FUNC_START_INDEX, /**< command is executed */ - F_EXIT_RECEIVER, /**< turn off receiver server */ - F_LOCK_RECEIVER, /**< Locks/Unlocks server communication to the given client */ - F_GET_LAST_RECEIVER_CLIENT_IP, /**< returns the IP of the client last connected to the receiver */ - F_SET_RECEIVER_PORT, /**< Changes communication port of the receiver */ - F_UPDATE_RECEIVER_CLIENT, /**< Returns all the important parameters to update the shared memory of the client */ - - // Identification - F_GET_RECEIVER_ID, /**< get receiver id of version */ - F_GET_RECEIVER_TYPE, /**< return receiver type */ - F_SEND_RECEIVER_DETHOSTNAME, /**< set detector hostname to receiver */ - - //network functions - F_RECEIVER_SET_ROI, /**< Sets receiver ROI */ - F_SETUP_RECEIVER_UDP, /**< sets the receiver udp connection and returns receiver mac address */ - - //Acquisition setup functions - F_SET_RECEIVER_TIMER, /**< set/get timer value */ - F_SET_RECEIVER_DYNAMIC_RANGE, /**< set/get detector dynamic range */ - F_READ_RECEIVER_FREQUENCY, /**< sets the frequency of receiver sending frames to gui */ - - // Acquisition functions - F_GET_RECEIVER_STATUS, /**< gets the status of receiver listening mode */ - F_START_RECEIVER, /**< starts the receiver listening mode */ - F_STOP_RECEIVER, /**< stops the receiver listening mode */ - F_START_RECEIVER_READOUT, /**< acquisition has stopped. start remaining readout in receiver */ - - //file functions - F_SET_RECEIVER_FILE_PATH, /**< sets receiver file directory */ - F_SET_RECEIVER_FILE_NAME, /**< sets receiver file name */ - F_SET_RECEIVER_FILE_INDEX, /**< sets receiver file index */ - F_GET_RECEIVER_FRAME_INDEX, /**< gets the receiver frame index */ - F_GET_RECEIVER_FRAMES_CAUGHT, /**< gets the number of frames caught by receiver */ - F_RESET_RECEIVER_FRAMES_CAUGHT, /**< resets the frames caught by receiver */ - F_ENABLE_RECEIVER_FILE_WRITE, /**< sets the receiver file write */ - F_ENABLE_RECEIVER_COMPRESSION, /**< enable compression in receiver */ - F_ENABLE_RECEIVER_OVERWRITE, /**< set overwrite flag in receiver */ - - F_ENABLE_RECEIVER_TEN_GIGA, /**< enable 10Gbe in receiver */ - F_SET_RECEIVER_FIFO_DEPTH, /**< set receiver fifo depth */ - - F_RECEIVER_ACTIVATE, /** < activate/deactivate readout */ - F_STREAM_DATA_FROM_RECEIVER, /**< stream data from receiver to client */ - F_READ_RECEIVER_TIMER, /** < sets the timer between each data stream in receiver */ - F_SET_FLIPPED_DATA_RECEIVER, /** < sets the enable to flip data across x/y axis (bottom/top) */ - F_SET_RECEIVER_FILE_FORMAT, /** < sets the receiver file format */ - - F_SEND_RECEIVER_DETPOSID, /** < sets the detector position id in the reveiver */ - F_SEND_RECEIVER_MULTIDETSIZE, /** < sets the multi detector size to the receiver */ - F_SET_RECEIVER_STREAMING_PORT, /** < sets the receiver streaming port */ - F_RECEIVER_STREAMING_SRC_IP, /** < sets the receiver streaming source IP */ - F_SET_RECEIVER_SILENT_MODE, /** < sets the receiver silent mode */ - F_ENABLE_GAPPIXELS_IN_RECEIVER, /** < sets gap pixels in the receiver */ - F_RESTREAM_STOP_FROM_RECEIVER, /** < restream stop from receiver */ - F_ADDITIONAL_JSON_HEADER, /** < additional json header */ - F_RECEIVER_UDP_SOCK_BUF_SIZE, /** < UDP socket buffer size */ - F_RECEIVER_REAL_UDP_SOCK_BUF_SIZE, /** < real UDP socket buffer size */ - F_SET_RECEIVER_FRAMES_PER_FILE, /** < receiver frames per file */ - F_RECEIVER_CHECK_VERSION, /** < check receiver version compatibility */ - F_RECEIVER_DISCARD_POLICY, /** < frames discard policy */ - F_RECEIVER_PADDING_ENABLE, /** < partial frames padding enable */ - F_RECEIVER_DEACTIVATED_PADDING_ENABLE, /** < deactivated receiver padding enable */ - /* Always append functions hereafter!!! */ - - - /* Always append functions before!!! */ - NUM_REC_FUNCTIONS -}; - diff --git a/slsReceiverSoftware/include/utilities.h b/slsReceiverSoftware/include/utilities.h deleted file mode 100644 index 5db78e8e1..000000000 --- a/slsReceiverSoftware/include/utilities.h +++ /dev/null @@ -1,15 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include - -#include "sls_receiver_defs.h" - -/* uncomment next line to enable debug output */ -//#define EIGER_DEBUG - - -int read_config_file(std::string fname, int *tcpip_port_no, std::map * configuration_map); - diff --git a/slsReceiverSoftware/include/versionAPI.h b/slsReceiverSoftware/include/versionAPI.h deleted file mode 120000 index a4d75aa2a..000000000 --- a/slsReceiverSoftware/include/versionAPI.h +++ /dev/null @@ -1 +0,0 @@ -../../slsDetectorSoftware/commonFiles/versionAPI.h \ No newline at end of file diff --git a/slsReceiverSoftware/include/zmq.h b/slsReceiverSoftware/include/zmq.h deleted file mode 100644 index 8970d5bd6..000000000 --- a/slsReceiverSoftware/include/zmq.h +++ /dev/null @@ -1,417 +0,0 @@ -/* - Copyright (c) 2007-2013 Contributors as noted in the AUTHORS file - - This file is part of 0MQ. - - 0MQ is free software; you can redistribute it and/or modify it under - the terms of the GNU Lesser General Public License as published by - the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - 0MQ is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License - along with this program. If not, see . - - ************************************************************************* - NOTE to contributors. This file comprises the principal public contract - for ZeroMQ API users (along with zmq_utils.h). Any change to this file - supplied in a stable release SHOULD not break existing applications. - In practice this means that the value of constants must not change, and - that old values may not be reused for new constants. - ************************************************************************* -*/ - -#ifndef __ZMQ_H_INCLUDED__ -#define __ZMQ_H_INCLUDED__ - -/* Version macros for compile-time API version detection */ -#define ZMQ_VERSION_MAJOR 4 -#define ZMQ_VERSION_MINOR 0 -#define ZMQ_VERSION_PATCH 8 - -#define ZMQ_MAKE_VERSION(major, minor, patch) \ - ((major) * 10000 + (minor) * 100 + (patch)) -#define ZMQ_VERSION \ - ZMQ_MAKE_VERSION(ZMQ_VERSION_MAJOR, ZMQ_VERSION_MINOR, ZMQ_VERSION_PATCH) - -#ifdef __cplusplus -extern "C" { -#endif - -#if !defined _WIN32_WCE -#include -#endif -#include -#include -#if defined _WIN32 -#include -#endif - -/* Handle DSO symbol visibility */ -#if defined _WIN32 -# if defined ZMQ_STATIC -# define ZMQ_EXPORT -# elif defined DLL_EXPORT -# define ZMQ_EXPORT __declspec(dllexport) -# else -# define ZMQ_EXPORT __declspec(dllimport) -# endif -#else -# if defined __SUNPRO_C || defined __SUNPRO_CC -# define ZMQ_EXPORT __global -# elif (defined __GNUC__ && __GNUC__ >= 4) || defined __INTEL_COMPILER -# define ZMQ_EXPORT __attribute__ ((visibility("default"))) -# else -# define ZMQ_EXPORT -# endif -#endif - -/* Define integer types needed for event interface */ -#if defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_OPENVMS -# include -#elif defined _MSC_VER && _MSC_VER < 1600 -# ifndef int32_t -typedef __int32 int32_t; -# endif -# ifndef uint16_t -typedef unsigned __int16 uint16_t; -# endif -# ifndef uint8_t -typedef unsigned __int8 uint8_t; -# endif -#else -# include -#endif - - -/******************************************************************************/ -/* 0MQ errors. */ -/******************************************************************************/ - -/* A number random enough not to collide with different errno ranges on */ -/* different OSes. The assumption is that error_t is at least 32-bit type. */ -#define ZMQ_HAUSNUMERO 156384712 - -/* On Windows platform some of the standard POSIX errnos are not defined. */ -#ifndef ENOTSUP -#define ENOTSUP (ZMQ_HAUSNUMERO + 1) -#endif -#ifndef EPROTONOSUPPORT -#define EPROTONOSUPPORT (ZMQ_HAUSNUMERO + 2) -#endif -#ifndef ENOBUFS -#define ENOBUFS (ZMQ_HAUSNUMERO + 3) -#endif -#ifndef ENETDOWN -#define ENETDOWN (ZMQ_HAUSNUMERO + 4) -#endif -#ifndef EADDRINUSE -#define EADDRINUSE (ZMQ_HAUSNUMERO + 5) -#endif -#ifndef EADDRNOTAVAIL -#define EADDRNOTAVAIL (ZMQ_HAUSNUMERO + 6) -#endif -#ifndef ECONNREFUSED -#define ECONNREFUSED (ZMQ_HAUSNUMERO + 7) -#endif -#ifndef EINPROGRESS -#define EINPROGRESS (ZMQ_HAUSNUMERO + 8) -#endif -#ifndef ENOTSOCK -#define ENOTSOCK (ZMQ_HAUSNUMERO + 9) -#endif -#ifndef EMSGSIZE -#define EMSGSIZE (ZMQ_HAUSNUMERO + 10) -#endif -#ifndef EAFNOSUPPORT -#define EAFNOSUPPORT (ZMQ_HAUSNUMERO + 11) -#endif -#ifndef ENETUNREACH -#define ENETUNREACH (ZMQ_HAUSNUMERO + 12) -#endif -#ifndef ECONNABORTED -#define ECONNABORTED (ZMQ_HAUSNUMERO + 13) -#endif -#ifndef ECONNRESET -#define ECONNRESET (ZMQ_HAUSNUMERO + 14) -#endif -#ifndef ENOTCONN -#define ENOTCONN (ZMQ_HAUSNUMERO + 15) -#endif -#ifndef ETIMEDOUT -#define ETIMEDOUT (ZMQ_HAUSNUMERO + 16) -#endif -#ifndef EHOSTUNREACH -#define EHOSTUNREACH (ZMQ_HAUSNUMERO + 17) -#endif -#ifndef ENETRESET -#define ENETRESET (ZMQ_HAUSNUMERO + 18) -#endif - -/* Native 0MQ error codes. */ -#define EFSM (ZMQ_HAUSNUMERO + 51) -#define ENOCOMPATPROTO (ZMQ_HAUSNUMERO + 52) -#define ETERM (ZMQ_HAUSNUMERO + 53) -#define EMTHREAD (ZMQ_HAUSNUMERO + 54) - -/* Run-time API version detection */ -ZMQ_EXPORT void zmq_version (int *major, int *minor, int *patch); - -/* This function retrieves the errno as it is known to 0MQ library. The goal */ -/* of this function is to make the code 100% portable, including where 0MQ */ -/* compiled with certain CRT library (on Windows) is linked to an */ -/* application that uses different CRT library. */ -ZMQ_EXPORT int zmq_errno (void); - -/* Resolves system errors and 0MQ errors to human-readable string. */ -ZMQ_EXPORT const char *zmq_strerror (int errnum); - -/******************************************************************************/ -/* 0MQ infrastructure (a.k.a. context) initialisation & termination. */ -/******************************************************************************/ - -/* New API */ -/* Context options */ -#define ZMQ_IO_THREADS 1 -#define ZMQ_MAX_SOCKETS 2 - -/* Default for new contexts */ -#define ZMQ_IO_THREADS_DFLT 1 -#define ZMQ_MAX_SOCKETS_DFLT 1023 - -ZMQ_EXPORT void *zmq_ctx_new (void); -ZMQ_EXPORT int zmq_ctx_term (void *context); -ZMQ_EXPORT int zmq_ctx_shutdown (void *ctx_); -ZMQ_EXPORT int zmq_ctx_set (void *context, int option, int optval); -ZMQ_EXPORT int zmq_ctx_get (void *context, int option); - -/* Old (legacy) API */ -ZMQ_EXPORT void *zmq_init (int io_threads); -ZMQ_EXPORT int zmq_term (void *context); -ZMQ_EXPORT int zmq_ctx_destroy (void *context); - - -/******************************************************************************/ -/* 0MQ message definition. */ -/******************************************************************************/ - -typedef struct zmq_msg_t {unsigned char _ [32];} zmq_msg_t; - -typedef void (zmq_free_fn) (void *data, void *hint); - -ZMQ_EXPORT int zmq_msg_init (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_init_size (zmq_msg_t *msg, size_t size); -ZMQ_EXPORT int zmq_msg_init_data (zmq_msg_t *msg, void *data, - size_t size, zmq_free_fn *ffn, void *hint); -ZMQ_EXPORT int zmq_msg_send (zmq_msg_t *msg, void *s, int flags); -ZMQ_EXPORT int zmq_msg_recv (zmq_msg_t *msg, void *s, int flags); -ZMQ_EXPORT int zmq_msg_close (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_move (zmq_msg_t *dest, zmq_msg_t *src); -ZMQ_EXPORT int zmq_msg_copy (zmq_msg_t *dest, zmq_msg_t *src); -ZMQ_EXPORT void *zmq_msg_data (zmq_msg_t *msg); -ZMQ_EXPORT size_t zmq_msg_size (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_more (zmq_msg_t *msg); -ZMQ_EXPORT int zmq_msg_get (zmq_msg_t *msg, int option); -ZMQ_EXPORT int zmq_msg_set (zmq_msg_t *msg, int option, int optval); - - -/******************************************************************************/ -/* 0MQ socket definition. */ -/******************************************************************************/ - -/* Socket types. */ -#define ZMQ_PAIR 0 -#define ZMQ_PUB 1 -#define ZMQ_SUB 2 -#define ZMQ_REQ 3 -#define ZMQ_REP 4 -#define ZMQ_DEALER 5 -#define ZMQ_ROUTER 6 -#define ZMQ_PULL 7 -#define ZMQ_PUSH 8 -#define ZMQ_XPUB 9 -#define ZMQ_XSUB 10 -#define ZMQ_STREAM 11 - -/* Deprecated aliases */ -#define ZMQ_XREQ ZMQ_DEALER -#define ZMQ_XREP ZMQ_ROUTER - -/* Socket options. */ -#define ZMQ_AFFINITY 4 -#define ZMQ_IDENTITY 5 -#define ZMQ_SUBSCRIBE 6 -#define ZMQ_UNSUBSCRIBE 7 -#define ZMQ_RATE 8 -#define ZMQ_RECOVERY_IVL 9 -#define ZMQ_SNDBUF 11 -#define ZMQ_RCVBUF 12 -#define ZMQ_RCVMORE 13 -#define ZMQ_FD 14 -#define ZMQ_EVENTS 15 -#define ZMQ_TYPE 16 -#define ZMQ_LINGER 17 -#define ZMQ_RECONNECT_IVL 18 -#define ZMQ_BACKLOG 19 -#define ZMQ_RECONNECT_IVL_MAX 21 -#define ZMQ_MAXMSGSIZE 22 -#define ZMQ_SNDHWM 23 -#define ZMQ_RCVHWM 24 -#define ZMQ_MULTICAST_HOPS 25 -#define ZMQ_RCVTIMEO 27 -#define ZMQ_SNDTIMEO 28 -#define ZMQ_LAST_ENDPOINT 32 -#define ZMQ_ROUTER_MANDATORY 33 -#define ZMQ_TCP_KEEPALIVE 34 -#define ZMQ_TCP_KEEPALIVE_CNT 35 -#define ZMQ_TCP_KEEPALIVE_IDLE 36 -#define ZMQ_TCP_KEEPALIVE_INTVL 37 -#define ZMQ_TCP_ACCEPT_FILTER 38 -#define ZMQ_IMMEDIATE 39 -#define ZMQ_XPUB_VERBOSE 40 -#define ZMQ_ROUTER_RAW 41 -#define ZMQ_IPV6 42 -#define ZMQ_MECHANISM 43 -#define ZMQ_PLAIN_SERVER 44 -#define ZMQ_PLAIN_USERNAME 45 -#define ZMQ_PLAIN_PASSWORD 46 -#define ZMQ_CURVE_SERVER 47 -#define ZMQ_CURVE_PUBLICKEY 48 -#define ZMQ_CURVE_SECRETKEY 49 -#define ZMQ_CURVE_SERVERKEY 50 -#define ZMQ_PROBE_ROUTER 51 -#define ZMQ_REQ_CORRELATE 52 -#define ZMQ_REQ_RELAXED 53 -#define ZMQ_CONFLATE 54 -#define ZMQ_ZAP_DOMAIN 55 - -/* Message options */ -#define ZMQ_MORE 1 - -/* Send/recv options. */ -#define ZMQ_DONTWAIT 1 -#define ZMQ_SNDMORE 2 - -/* Security mechanisms */ -#define ZMQ_NULL 0 -#define ZMQ_PLAIN 1 -#define ZMQ_CURVE 2 - -/* Deprecated options and aliases */ -#define ZMQ_IPV4ONLY 31 -#define ZMQ_DELAY_ATTACH_ON_CONNECT ZMQ_IMMEDIATE -#define ZMQ_NOBLOCK ZMQ_DONTWAIT -#define ZMQ_FAIL_UNROUTABLE ZMQ_ROUTER_MANDATORY -#define ZMQ_ROUTER_BEHAVIOR ZMQ_ROUTER_MANDATORY - -/******************************************************************************/ -/* 0MQ socket events and monitoring */ -/******************************************************************************/ - -/* Socket transport events (tcp and ipc only) */ -#define ZMQ_EVENT_CONNECTED 1 -#define ZMQ_EVENT_CONNECT_DELAYED 2 -#define ZMQ_EVENT_CONNECT_RETRIED 4 - -#define ZMQ_EVENT_LISTENING 8 -#define ZMQ_EVENT_BIND_FAILED 16 - -#define ZMQ_EVENT_ACCEPTED 32 -#define ZMQ_EVENT_ACCEPT_FAILED 64 - -#define ZMQ_EVENT_CLOSED 128 -#define ZMQ_EVENT_CLOSE_FAILED 256 -#define ZMQ_EVENT_DISCONNECTED 512 -#define ZMQ_EVENT_MONITOR_STOPPED 1024 - -#define ZMQ_EVENT_ALL ( ZMQ_EVENT_CONNECTED | ZMQ_EVENT_CONNECT_DELAYED | \ - ZMQ_EVENT_CONNECT_RETRIED | ZMQ_EVENT_LISTENING | \ - ZMQ_EVENT_BIND_FAILED | ZMQ_EVENT_ACCEPTED | \ - ZMQ_EVENT_ACCEPT_FAILED | ZMQ_EVENT_CLOSED | \ - ZMQ_EVENT_CLOSE_FAILED | ZMQ_EVENT_DISCONNECTED | \ - ZMQ_EVENT_MONITOR_STOPPED) - -/* Socket event data */ -typedef struct { - uint16_t event; // id of the event as bitfield - int32_t value ; // value is either error code, fd or reconnect interval -} zmq_event_t; - -ZMQ_EXPORT void *zmq_socket (void *, int type); -ZMQ_EXPORT int zmq_close (void *s); -ZMQ_EXPORT int zmq_setsockopt (void *s, int option, const void *optval, - size_t optvallen); -ZMQ_EXPORT int zmq_getsockopt (void *s, int option, void *optval, - size_t *optvallen); -ZMQ_EXPORT int zmq_bind (void *s, const char *addr); -ZMQ_EXPORT int zmq_connect (void *s, const char *addr); -ZMQ_EXPORT int zmq_unbind (void *s, const char *addr); -ZMQ_EXPORT int zmq_disconnect (void *s, const char *addr); -ZMQ_EXPORT int zmq_send (void *s, const void *buf, size_t len, int flags); -ZMQ_EXPORT int zmq_send_const (void *s, const void *buf, size_t len, int flags); -ZMQ_EXPORT int zmq_recv (void *s, void *buf, size_t len, int flags); -ZMQ_EXPORT int zmq_socket_monitor (void *s, const char *addr, int events); - -ZMQ_EXPORT int zmq_sendmsg (void *s, zmq_msg_t *msg, int flags); -ZMQ_EXPORT int zmq_recvmsg (void *s, zmq_msg_t *msg, int flags); - -/* Experimental */ -struct iovec; - -ZMQ_EXPORT int zmq_sendiov (void *s, struct iovec *iov, size_t count, int flags); -ZMQ_EXPORT int zmq_recviov (void *s, struct iovec *iov, size_t *count, int flags); - -/******************************************************************************/ -/* I/O multiplexing. */ -/******************************************************************************/ - -#define ZMQ_POLLIN 1 -#define ZMQ_POLLOUT 2 -#define ZMQ_POLLERR 4 - -typedef struct -{ - void *socket; -#if defined _WIN32 - SOCKET fd; -#else - int fd; -#endif - short events; - short revents; -} zmq_pollitem_t; - -#define ZMQ_POLLITEMS_DFLT 16 - -ZMQ_EXPORT int zmq_poll (zmq_pollitem_t *items, int nitems, long timeout); - -/* Built-in message proxy (3-way) */ - -ZMQ_EXPORT int zmq_proxy (void *frontend, void *backend, void *capture); -ZMQ_EXPORT int zmq_proxy_steerable (void *frontend, void *backend, void *capture, void *control); - -/* Encode a binary key as printable text using ZMQ RFC 32 */ -ZMQ_EXPORT char *zmq_z85_encode (char *dest, uint8_t *data, size_t size); - -/* Encode a binary key from printable text per ZMQ RFC 32 */ -ZMQ_EXPORT uint8_t *zmq_z85_decode (uint8_t *dest, char *string); - -/* Deprecated aliases */ -#define ZMQ_STREAMER 1 -#define ZMQ_FORWARDER 2 -#define ZMQ_QUEUE 3 -/* Deprecated method */ -ZMQ_EXPORT int zmq_device (int type, void *frontend, void *backend); - -#undef ZMQ_EXPORT - -#ifdef __cplusplus -} -#endif - -#endif - diff --git a/slsReceiverSoftware/slsReceiverUsers.doxy b/slsReceiverSoftware/slsReceiverUsers.doxy old mode 100644 new mode 100755 index b5d37ae18..8c91db014 --- a/slsReceiverSoftware/slsReceiverUsers.doxy +++ b/slsReceiverSoftware/slsReceiverUsers.doxy @@ -81,6 +81,6 @@ LATEX_HIDE_INDICES = YES PREDEFINED = __cplusplus -INPUT = slsReceiver/slsReceiverBase.h +INPUT = include/slsReceiverUsers.h OUTPUT_DIRECTORY = slsReceiverUsersDocs diff --git a/slsReceiverSoftware/src/.cproject b/slsReceiverSoftware/src/.cproject deleted file mode 100644 index d34dce296..000000000 --- a/slsReceiverSoftware/src/.cproject +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/slsReceiverSoftware/src/.project b/slsReceiverSoftware/src/.project deleted file mode 100644 index 3c7b96561..000000000 --- a/slsReceiverSoftware/src/.project +++ /dev/null @@ -1,28 +0,0 @@ - - - Receiver - - - newMythenSoftware - - - - org.eclipse.cdt.managedbuilder.core.genmakebuilder - clean,full,incremental, - - - - - org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder - full,incremental, - - - - - - org.eclipse.cdt.core.cnature - org.eclipse.cdt.core.ccnature - org.eclipse.cdt.managedbuilder.core.managedBuildNature - org.eclipse.cdt.managedbuilder.core.ScannerConfigNature - - diff --git a/slsReceiverSoftware/src/BinaryFile.cpp b/slsReceiverSoftware/src/BinaryFile.cpp old mode 100644 new mode 100755 index 16072fd72..12ba62a03 --- a/slsReceiverSoftware/src/BinaryFile.cpp +++ b/slsReceiverSoftware/src/BinaryFile.cpp @@ -11,14 +11,14 @@ #include -FILE* BinaryFile::masterfd = 0; +FILE* BinaryFile::masterfd = nullptr; BinaryFile::BinaryFile(int ind, uint32_t* maxf, int* nd, char* fname, char* fpath, uint64_t* findex, bool* owenable, int* dindex, int* nunits, uint64_t* nf, uint32_t* dr, uint32_t* portno, bool* smode): File(ind, maxf, nd, fname, fpath, findex, owenable, dindex, nunits, nf, dr, portno, smode), - filefd(0), + filefd(nullptr), numFramesInFile(0), numActualPacketsInFile(0) { @@ -31,13 +31,13 @@ BinaryFile::~BinaryFile() { CloseAllFiles(); } -void BinaryFile::PrintMembers() { - File::PrintMembers(); +void BinaryFile::PrintMembers(TLogLevel level) { + File::PrintMembers(level); FILE_LOG(logINFO) << "Max Frames Per File: " << *maxFramesPerFile; FILE_LOG(logINFO) << "Number of Frames in File: " << numFramesInFile; } -slsReceiverDefs::fileFormat BinaryFile::GetFileType() { +slsDetectorDefs::fileFormat BinaryFile::GetFileType() { return BINARY; } @@ -106,8 +106,7 @@ int BinaryFile::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_ // if write error if (ret != buffersize) { - cprintf(RED,"%d Error: Write to file failed for image number %lld\n", - index, (long long int)fnum); + FILE_LOG(logERROR) << index << " Error: Write to file failed for image number " << fnum; return FAIL; } return OK; diff --git a/slsReceiverSoftware/src/DataProcessor.cpp b/slsReceiverSoftware/src/DataProcessor.cpp old mode 100644 new mode 100755 index 3a71e52cd..629a7bae7 --- a/slsReceiverSoftware/src/DataProcessor.cpp +++ b/slsReceiverSoftware/src/DataProcessor.cpp @@ -14,6 +14,7 @@ #include "HDF5File.h" #endif #include "DataStreamer.h" +#include "sls_detector_exceptions.h" #include #include @@ -22,21 +23,18 @@ const std::string DataProcessor::TypeName = "DataProcessor"; -DataProcessor::DataProcessor(int ind, detectorType dtype, Fifo*& f, +DataProcessor::DataProcessor(int ind, detectorType dtype, Fifo* f, fileFormat* ftype, bool fwenable, bool* dsEnable, bool* gpEnable, uint32_t* dr, uint32_t* freq, uint32_t* timer, - bool* fp, bool* act, bool* depaden, bool* sm, - void (*dataReadycb)(char*, char*, uint32_t, void*), - void (*dataModifyReadycb)(char*, char*, uint32_t &, void*), - void *pDataReadycb) : + bool* fp, bool* act, bool* depaden, bool* sm) : ThreadObject(ind), runningFlag(0), - generalData(0), + generalData(nullptr), fifo(f), myDetectorType(dtype), - file(0), + file(nullptr), dataStreamEnable(dsEnable), fileFormatType(ftype), fileWriteEnable(fwenable), @@ -45,7 +43,7 @@ DataProcessor::DataProcessor(int ind, detectorType dtype, Fifo*& f, streamingFrequency(freq), streamingTimerInMs(timer), currentFreqCount(0), - tempBuffer(0), + tempBuffer(nullptr), activated(act), deactivatedPaddingEnable(depaden), silentMode(sm), @@ -56,13 +54,10 @@ DataProcessor::DataProcessor(int ind, detectorType dtype, Fifo*& f, firstMeasurementIndex(0), numTotalFramesCaught(0), numFramesCaught(0), - currentFrameIndex(0), - rawDataReadyCallBack(dataReadycb), - rawDataModifyReadyCallBack(dataModifyReadycb), - pRawDataReady(pDataReadycb) + currentFrameIndex(0) { if(ThreadObject::CreateThread() == FAIL) - throw std::exception(); + throw sls::RuntimeError("Could not create processing thread"); FILE_LOG(logDEBUG) << "DataProcessor " << ind << " created"; @@ -125,7 +120,7 @@ void DataProcessor::StopRunning() { runningFlag = false; } -void DataProcessor::SetFifo(Fifo*& f) { +void DataProcessor::SetFifo(Fifo* f) { fifo = f; } @@ -144,7 +139,7 @@ void DataProcessor::ResetParametersforNewMeasurement(){ if (tempBuffer) { delete [] tempBuffer; - tempBuffer = 0; + tempBuffer = nullptr; } if (*gapPixelsEnable) { tempBuffer = new char[generalData->imageSize]; @@ -166,18 +161,14 @@ void DataProcessor::RecordFirstIndices(uint64_t fnum) { firstAcquisitionIndex = fnum; } -#ifdef VERBOSE - cprintf(BLUE,"%d First Acquisition Index:%lld\tFirst Measurement Index:%lld\n", - index, (long long int)firstAcquisitionIndex, (long long int)firstMeasurementIndex); -#endif + FILE_LOG(logDEBUG1) << index << " First Acquisition Index:" << firstAcquisitionIndex << + "\tFirst Measurement Index:" << firstMeasurementIndex; } void DataProcessor::SetGeneralData(GeneralData* g) { generalData = g; -#ifdef VERY_VERBOSE generalData->Print(); -#endif if (file) { if (file->GetFileType() == HDF5) { file->SetNumberofPixels(generalData->nPixelsX, generalData->nPixelsY); @@ -200,10 +191,10 @@ void DataProcessor::SetFileFormat(const fileFormat f) { if (file && file->GetFileType() != f) { //remember the pointer values before they are destroyed int nd[MAX_DIMENSIONS];nd[0] = 0; nd[1] = 0; - uint32_t* maxf = 0; - char* fname=0; char* fpath=0; uint64_t* findex=0; - bool* owenable=0; int* dindex=0; int* nunits=0; uint64_t* nf = 0; - uint32_t* dr = 0; uint32_t* port = 0; + uint32_t* maxf = nullptr; + char* fname=nullptr; char* fpath=nullptr; uint64_t* findex=nullptr; + bool* owenable=nullptr; int* dindex=nullptr; int* nunits=nullptr; uint64_t* nf = nullptr; + uint32_t* dr = nullptr; uint32_t* port = nullptr; file->GetMemberPointerValues(nd, maxf, fname, fpath, findex, owenable, dindex, nunits, nf, dr, port); //create file writer with same pointers @@ -225,7 +216,7 @@ void DataProcessor::SetupFileWriter(bool fwe, int* nd, uint32_t* maxf, if (file) { - delete file; file = 0; + delete file; file = nullptr; } if (fileWriteEnable) { @@ -250,7 +241,7 @@ void DataProcessor::SetupFileWriter(bool fwe, int* nd, uint32_t* maxf, // only the first file int DataProcessor::CreateNewFile(bool en, uint64_t nf, uint64_t at, uint64_t st, uint64_t sp, uint64_t ap) { - if (file == NULL) + if (file == nullptr) return FAIL; file->CloseAllFiles(); if (file->CreateMasterFile(en, generalData->imageSize, @@ -276,18 +267,14 @@ void DataProcessor::EndofAcquisition(bool anyPacketsCaught, uint64_t numf) { void DataProcessor::ThreadExecution() { - char* buffer=0; + char* buffer=nullptr; fifo->PopAddress(buffer); -#ifdef FIFODEBUG - if (!index) cprintf(BLUE,"DataProcessor %d, pop 0x%p buffer:%s\n", - index,(void*)(buffer),buffer); -#endif + FILE_LOG(logDEBUG5) << "DataProcessor " << index << ", " + "pop 0x" << std::hex << (void*)(buffer) << std::dec << ":" << buffer; //check dummy uint32_t numBytes = (uint32_t)(*((uint32_t*)buffer)); -#ifdef VERBOSE - if (!index) cprintf(BLUE,"DataProcessor %d, Numbytes:%u\n", index,numBytes); -#endif + FILE_LOG(logDEBUG1) << "DataProcessor " << index << ", Numbytes:" << numBytes; if (numBytes == DUMMY_PACKET_VALUE) { StopProcessing(buffer); return; @@ -304,10 +291,8 @@ void DataProcessor::ThreadExecution() { void DataProcessor::StopProcessing(char* buf) { -#ifdef VERBOSE - if (!index) - cprintf(RED,"DataProcessing %d: Dummy\n", index); -#endif + FILE_LOG(logDEBUG1) << "DataProcessing " << index << ": Dummy"; + //stream or free if (*dataStreamEnable) fifo->PushAddressToStream(buf); @@ -317,9 +302,7 @@ void DataProcessor::StopProcessing(char* buf) { if (file) file->CloseCurrentFile(); StopRunning(); -#ifdef VERBOSE - FILE_LOG(logINFO) << index << ": Processing Completed"; -#endif + FILE_LOG(logDEBUG1) << index << ": Processing Completed"; } @@ -335,16 +318,9 @@ void DataProcessor::ProcessAnImage(char* buf) { numTotalFramesCaught++; } - -#ifdef VERBOSE - if (!index) - cprintf(BLUE,"DataProcessing %d: fnum:%lu\n", index, fnum); -#endif + FILE_LOG(logDEBUG1) << "DataProcessing " << index << ": fnum:" << fnum; if (!measurementStartedFlag) { -#ifdef VERBOSE - if (!index) cprintf(BLUE,"DataProcessing %d: fnum:%lu\n", index, fnum); -#endif RecordFirstIndices(fnum); if (*dataStreamEnable) { @@ -367,7 +343,7 @@ void DataProcessor::ProcessAnImage(char* buf) { if (*activated && *framePadding && nump < generalData->packetsPerFrame) PadMissingPackets(buf); - // deactivated and padding enabled + // deactivated and padding enabled else if (!(*activated) && *deactivatedPaddingEnable) PadMissingPackets(buf); @@ -420,11 +396,10 @@ bool DataProcessor::SendToStreamer() { bool DataProcessor::CheckTimer() { struct timespec end; clock_gettime(CLOCK_REALTIME, &end); -#ifdef VERBOSE - cprintf(BLUE,"%d Timer elapsed time:%f seconds\n", index, - ( end.tv_sec - timerBegin.tv_sec ) + ( end.tv_nsec - timerBegin.tv_nsec ) - / 1000000000.0); -#endif + + FILE_LOG(logDEBUG1) << index << " Timer elapsed time:" << + (( end.tv_sec - timerBegin.tv_sec ) + ( end.tv_nsec - timerBegin.tv_nsec ) / 1000000000.0) + << " seconds"; //still less than streaming timer, keep waiting if((( end.tv_sec - timerBegin.tv_sec ) + ( end.tv_nsec - timerBegin.tv_nsec ) / 1000000000.0) < ((double)*streamingTimerInMs/1000.00)) @@ -454,6 +429,19 @@ void DataProcessor::SetPixelDimension() { } } +void DataProcessor::registerCallBackRawDataReady(void (*func)(char* , + char*, uint32_t, void*),void *arg) { + rawDataReadyCallBack=func; + pRawDataReady=arg; +} + +void DataProcessor::registerCallBackRawDataModifyReady(void (*func)(char* , + char*, uint32_t&, void*),void *arg) { + rawDataModifyReadyCallBack=func; + pRawDataReady=arg; +} + + void DataProcessor::PadMissingPackets(char* buf) { FILE_LOG(logDEBUG) << index << ": Padding Missing Packets"; @@ -466,9 +454,8 @@ void DataProcessor::PadMissingPackets(char* buf) { uint32_t dsize = generalData->dataSize; uint32_t fifohsize = generalData->fifoBufferHeaderSize; uint32_t corrected_dsize = dsize - ((pperFrame * dsize) - generalData->imageSize); -#ifdef VERBOSE - cprintf(RED,"bitmask:%s\n", pmask.to_string().c_str()); -#endif + FILE_LOG(logDEBUG1) << "bitmask: " << pmask.to_string(); + for (unsigned int pnum = 0; pnum < pperFrame; ++pnum) { // not missing packet @@ -491,7 +478,7 @@ void DataProcessor::PadMissingPackets(char* buf) { else memset(buf + fifohsize + (pnum * dsize), 0xFF, dsize+2); break; - case JUNGFRAUCTB: + case CHIPTESTBOARD: if (pnum == (pperFrame-1)) memset(buf + fifohsize + (pnum * dsize), 0xFF, corrected_dsize); else @@ -515,8 +502,8 @@ void DataProcessor::InsertGapPixels(char* buf, uint32_t dr) { const uint32_t ny = generalData->nPixelsY; const uint32_t npx = nx * ny; - char* srcptr = 0; - char* dstptr = 0; + char* srcptr = nullptr; + char* dstptr = nullptr; const uint32_t b1px = generalData->imageSize / (npx); // not double as not dealing with 4 bit mode const uint32_t b2px = 2 * b1px; @@ -538,8 +525,8 @@ void DataProcessor::InsertGapPixels(char* buf, uint32_t dr) { // vertical filling of values { - char* srcgp1 = 0; char* srcgp2 = 0; char* srcgp3 = 0; - char* dstgp1 = 0; char* dstgp2 = 0; char* dstgp3 = 0; + char* srcgp1 = nullptr; char* srcgp2 = nullptr; char* srcgp3 = nullptr; + char* dstgp1 = nullptr; char* dstgp2 = nullptr; char* dstgp3 = nullptr; const uint32_t b3px = 3 * b1px; srcptr = tempBuffer + b1line; diff --git a/slsReceiverSoftware/src/DataStreamer.cpp b/slsReceiverSoftware/src/DataStreamer.cpp old mode 100644 new mode 100755 index 47689f48e..d76285da9 --- a/slsReceiverSoftware/src/DataStreamer.cpp +++ b/slsReceiverSoftware/src/DataStreamer.cpp @@ -8,6 +8,7 @@ #include "GeneralData.h" #include "Fifo.h" #include "ZmqSocket.h" +#include "sls_detector_exceptions.h" #include #include @@ -15,13 +16,13 @@ const std::string DataStreamer::TypeName = "DataStreamer"; -DataStreamer::DataStreamer(int ind, Fifo*& f, uint32_t* dr, std::vector* r, - uint64_t* fi, int* fd, char* ajh, bool* sm) : +DataStreamer::DataStreamer(int ind, Fifo* f, uint32_t* dr, std::vector* r, + uint64_t* fi, int* fd, char* ajh) : ThreadObject(ind), runningFlag(0), - generalData(0), + generalData(nullptr), fifo(f), - zmqSocket(0), + zmqSocket(nullptr), dynamicRange(dr), roi(r), adcConfigured(-1), @@ -32,14 +33,14 @@ DataStreamer::DataStreamer(int ind, Fifo*& f, uint32_t* dr, std::vector* r, measurementStartedFlag(false), firstAcquisitionIndex(0), firstMeasurementIndex(0), - completeBuffer(0) + completeBuffer(nullptr) { if(ThreadObject::CreateThread() == FAIL) - throw std::exception(); + throw sls::RuntimeError("Could not create streaming thread"); FILE_LOG(logDEBUG) << "DataStreamer " << ind << " created"; - memset(fileNametoStream, 0, MAX_STR_LENGTH); + // memset(fileNametoStream, 0, MAX_STR_LENGTH); } @@ -69,7 +70,7 @@ void DataStreamer::StopRunning() { runningFlag = false; } -void DataStreamer::SetFifo(Fifo*& f) { +void DataStreamer::SetFifo(Fifo* f) { fifo = f; } @@ -78,14 +79,15 @@ void DataStreamer::ResetParametersforNewAcquisition() { acquisitionStartedFlag = false; } -void DataStreamer::ResetParametersforNewMeasurement(char* fname){ +void DataStreamer::ResetParametersforNewMeasurement(const std::string& fname){ runningFlag = false; firstMeasurementIndex = 0; measurementStartedFlag = false; - strcpy(fileNametoStream, fname); - if (completeBuffer) { - delete [] completeBuffer; - completeBuffer = 0; + // strcpy(fileNametoStream, fname); + fileNametoStream = fname; + if (completeBuffer) { + delete[] completeBuffer; + completeBuffer = nullptr; } if (roi->size()) { if (generalData->myDetectorType == GOTTHARD) { @@ -107,18 +109,14 @@ void DataStreamer::RecordFirstIndices(uint64_t fnum) { firstAcquisitionIndex = fnum; } -#ifdef VERBOSE - cprintf(BLUE,"%d First Acquisition Index:%lld\tFirst Measurement Index:%lld\n", - index, (long long int)firstAcquisitionIndex, (long long int)firstMeasurementIndex); -#endif + FILE_LOG(logDEBUG1) << index << " First Acquisition Index: " << firstAcquisitionIndex << + "\tFirst Measurement Index: " << firstMeasurementIndex; } void DataStreamer::SetGeneralData(GeneralData* g) { generalData = g; -#ifdef VERY_VERBOSE generalData->Print(); -#endif } int DataStreamer::SetThreadPriority(int priority) { @@ -135,9 +133,9 @@ void DataStreamer::CreateZmqSockets(int* nunits, uint32_t port, const char* srci uint32_t portnum = port + index; try { - zmqSocket = new ZmqSocket(portnum, (strlen(srcip)?srcip:NULL)); + zmqSocket = new ZmqSocket(portnum, (strlen(srcip)?srcip:nullptr)); } catch (...) { - cprintf(RED, "Error: Could not create Zmq socket on port %d for Streamer %d\n", portnum, index); + FILE_LOG(logERROR) << "Could not create Zmq socket on port " << portnum << " for Streamer " << index; throw; } FILE_LOG(logINFO) << index << " Streamer: Zmq Server started at " << zmqSocket->GetZmqServerAddress(); @@ -147,23 +145,21 @@ void DataStreamer::CreateZmqSockets(int* nunits, uint32_t port, const char* srci void DataStreamer::CloseZmqSocket() { if (zmqSocket) { delete zmqSocket; - zmqSocket = 0; + zmqSocket = nullptr; } } void DataStreamer::ThreadExecution() { - char* buffer=0; + char* buffer=nullptr; fifo->PopAddressToStream(buffer); -#ifdef FIFODEBUG - if (!index) cprintf(BLUE,"DataStreamer %d, pop 0x%p buffer:%s\n", index,(void*)(buffer),buffer); -#endif + FILE_LOG(logDEBUG5) << "DataStreamer " << index << ", " + "pop 0x" << std::hex << (void*)(buffer) << std::dec << ":" << buffer; + //check dummy uint32_t numBytes = (uint32_t)(*((uint32_t*)buffer)); -#ifdef VERBOSE - cprintf(GREEN,"DataStreamer %d, Numbytes:%u\n", index,numBytes); -#endif + FILE_LOG(logDEBUG1) << "DataStreamer " << index << ", Numbytes:" << numBytes; if (numBytes == DUMMY_PACKET_VALUE) { StopProcessing(buffer); return; @@ -179,20 +175,17 @@ void DataStreamer::ThreadExecution() { void DataStreamer::StopProcessing(char* buf) { -#ifdef VERBOSE - if (!index) - cprintf(RED,"DataStreamer %d: Dummy\n", index); -#endif + FILE_LOG(logDEBUG1) << "DataStreamer " << index << ": Dummy"; + sls_receiver_header* header = (sls_receiver_header*) (buf); //send dummy header and data - if (!SendHeader(header, 0, 0, 0, true)) - cprintf(RED,"Error: Could not send zmq dummy header for streamer %d\n", index); + if (!SendHeader(header, 0, 0, 0, true)) { + FILE_LOG(logERROR) << "Could not send zmq dummy header for streamer " << index; + } fifo->FreeAddress(buf); StopRunning(); -#ifdef VERBOSE - FILE_LOG(logINFO) << index << ": Streaming Completed"; -#endif + FILE_LOG(logDEBUG1) << index << ": Streaming Completed"; } /** buf includes only the standard header */ @@ -200,14 +193,9 @@ void DataStreamer::ProcessAnImage(char* buf) { sls_receiver_header* header = (sls_receiver_header*) (buf + FIFO_HEADER_NUMBYTES); uint64_t fnum = header->detHeader.frameNumber; -#ifdef VERBOSE - cprintf(MAGENTA,"DataStreamer %d: fnum:%lu\n", index,fnum); -#endif + FILE_LOG(logDEBUG1) << "DataStreamer " << index << ": fnum:" << fnum; if (!measurementStartedFlag) { -#ifdef VERBOSE - if (!index) cprintf(MAGENTA,"DataStreamer %d: fnum:%lu\n", index, fnum); -#endif RecordFirstIndices(fnum); } @@ -219,17 +207,16 @@ void DataStreamer::ProcessAnImage(char* buf) { //write imagesize if (!SendHeader(header, generalData->imageSizeComplete, - generalData->nPixelsXComplete, generalData->nPixelsYComplete, false)) - cprintf(RED,"Error: Could not send zmq header for fnum %lld and streamer %d\n", - (long long int) fnum, index); - + generalData->nPixelsXComplete, generalData->nPixelsYComplete, false)) { + FILE_LOG(logERROR) << "Could not send zmq header for fnum " << fnum << " and streamer " << index; + } memcpy(completeBuffer + ((generalData->imageSize) * adcConfigured), buf + FIFO_HEADER_NUMBYTES + sizeof(sls_receiver_header), (uint32_t)(*((uint32_t*)buf)) ); - if (!zmqSocket->SendData(completeBuffer, generalData->imageSizeComplete)) - cprintf(RED,"Error: Could not send zmq data for fnum %lld and streamer %d\n", - (long long int) fnum, index); + if (!zmqSocket->SendData(completeBuffer, generalData->imageSizeComplete)) { + FILE_LOG(logERROR) << "Could not send zmq data for fnum " << fnum << " and streamer " << index; + } } @@ -237,14 +224,13 @@ void DataStreamer::ProcessAnImage(char* buf) { else { if (!SendHeader(header, (uint32_t)(*((uint32_t*)buf)), - generalData->nPixelsX, generalData->nPixelsY, false)) // new size possibly from callback - cprintf(RED,"Error: Could not send zmq header for fnum %lld and streamer %d\n", - (long long int) fnum, index); - + generalData->nPixelsX, generalData->nPixelsY, false)) {// new size possibly from callback + FILE_LOG(logERROR) << "Could not send zmq header for fnum " << fnum << " and streamer " << index; + } if (!zmqSocket->SendData(buf + FIFO_HEADER_NUMBYTES + sizeof(sls_receiver_header), - (uint32_t)(*((uint32_t*)buf)) )) // new size possibly from callback - cprintf(RED,"Error: Could not send zmq data for fnum %lld and streamer %d\n", - (long long int) fnum, index); + (uint32_t)(*((uint32_t*)buf)) )) {// new size possibly from callback + FILE_LOG(logERROR) << "Could not send zmq data for fnum " << fnum << " and streamer " << index; + } } } @@ -262,7 +248,7 @@ int DataStreamer::SendHeader(sls_receiver_header* rheader, uint32_t size, uint32 return zmqSocket->SendHeaderData(index, dummy, SLS_DETECTOR_JSON_HEADER_VERSION, *dynamicRange, *fileIndex, nx, ny, size, - acquisitionIndex, frameIndex, fileNametoStream, + acquisitionIndex, frameIndex, fileNametoStream.c_str(), header.frameNumber, header.expLength, header.packetNumber, header.bunchId, header.timestamp, header.modId, header.row, header.column, header.reserved, header.debug, header.roundRNumber, diff --git a/slsReceiverSoftware/src/Fifo.cpp b/slsReceiverSoftware/src/Fifo.cpp old mode 100644 new mode 100755 index a39be358a..74c90c7a3 --- a/slsReceiverSoftware/src/Fifo.cpp +++ b/slsReceiverSoftware/src/Fifo.cpp @@ -6,6 +6,7 @@ ***********************************************/ #include "Fifo.h" +#include "sls_detector_exceptions.h" #include #include @@ -14,29 +15,28 @@ Fifo::Fifo(int ind, uint32_t fifoItemSize, uint32_t depth): index(ind), - memory(0), - fifoBound(0), - fifoFree(0), - fifoStream(0), + memory(nullptr), + fifoBound(nullptr), + fifoFree(nullptr), + fifoStream(nullptr), fifoDepth(depth), status_fifoBound(0), status_fifoFree(depth){ - FILE_LOG(logDEBUG) << __AT__ << " called"; + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; if(CreateFifos(fifoItemSize) == FAIL) - throw std::exception(); + throw sls::RuntimeError("Could not create FIFO"); } Fifo::~Fifo() { - FILE_LOG(logDEBUG) << __AT__ << " called"; - //cprintf(BLUE,"Fifo Object %d: Goodbye\n", index); + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; DestroyFifos(); } int Fifo::CreateFifos(uint32_t fifoItemSize) { - FILE_LOG(logDEBUG) << __AT__ << " called"; + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; //destroy if not already DestroyFifos(); @@ -48,7 +48,7 @@ int Fifo::CreateFifos(uint32_t fifoItemSize) { //allocate memory size_t mem_len = fifoItemSize * fifoDepth * sizeof(char); memory = (char*) malloc (mem_len); - if (memory == NULL){ + if (memory == nullptr){ FILE_LOG(logERROR) << "Could not allocate memory for fifos"; return FAIL; } @@ -69,23 +69,23 @@ int Fifo::CreateFifos(uint32_t fifoItemSize) { void Fifo::DestroyFifos(){ - FILE_LOG(logDEBUG) << __AT__ << " called"; + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; if(memory) { free(memory); - memory = 0; + memory = nullptr; } if (fifoBound) { delete fifoBound; - fifoBound = 0; + fifoBound = nullptr; } if (fifoFree) { delete fifoFree; - fifoFree = 0; + fifoFree = nullptr; } if (fifoStream) { delete fifoStream; - fifoStream = 0; + fifoStream = nullptr; } } diff --git a/slsReceiverSoftware/src/File.cpp b/slsReceiverSoftware/src/File.cpp old mode 100644 new mode 100755 index d7748cb26..b72324e39 --- a/slsReceiverSoftware/src/File.cpp +++ b/slsReceiverSoftware/src/File.cpp @@ -38,8 +38,8 @@ std::string File::GetCurrentFileName() { return currentFileName; } -void File::PrintMembers() { - FILE_LOG(logINFO) << "\nGeneral Writer Variables:" << std::endl +void File::PrintMembers(TLogLevel level) { + FILE_LOG(level) << "\nGeneral Writer Variables:" << std::endl << "Index: " << index << std::endl << "Max Frames Per File: " << *maxFramesPerFile << std::endl << "Number of Detectors in x dir: " << numDetX << std::endl diff --git a/slsReceiverSoftware/src/HDF5File.cpp b/slsReceiverSoftware/src/HDF5File.cpp old mode 100644 new mode 100755 index 597c1bd6e..f494f48ea --- a/slsReceiverSoftware/src/HDF5File.cpp +++ b/slsReceiverSoftware/src/HDF5File.cpp @@ -38,9 +38,7 @@ HDF5File::HDF5File(int ind, uint32_t* maxf, dataspace_para(0), extNumImages(0) { -#ifdef VERBOSE PrintMembers(); -#endif dataset_para.clear(); parameterNames.clear(); parameterDataTypes.clear(); @@ -95,15 +93,15 @@ HDF5File::~HDF5File() { CloseAllFiles(); } -void HDF5File::PrintMembers() { +void HDF5File::PrintMembers(TLogLevel level) { File::PrintMembers(); UpdateDataType(); if (datatype == PredType::STD_U8LE) { - FILE_LOG(logINFO) << "Data Type: 4 or 8"; + FILE_LOG(level) << "Data Type: 4 or 8"; } else if (datatype == PredType::STD_U16LE) { - FILE_LOG(logINFO) << "Data Type: 16"; + FILE_LOG(level) << "Data Type: 16"; } else if (datatype == PredType::STD_U32LE) { - FILE_LOG(logINFO) << "Data Type: 32"; + FILE_LOG(level) << "Data Type: 32"; } else { FILE_LOG(logERROR) << "unknown data type"; } @@ -116,7 +114,7 @@ void HDF5File::SetNumberofPixels(uint32_t nx, uint32_t ny) { } -slsReceiverDefs::fileFormat HDF5File::GetFileType() { +slsDetectorDefs::fileFormat HDF5File::GetFileType() { return HDF5; } @@ -154,8 +152,6 @@ int HDF5File::CreateFile(uint64_t fnum) { return FAIL; } pthread_mutex_unlock(&Mutex); - if (dataspace == NULL) - cprintf(RED,"Got nothing!\n"); if(!(*silentMode)) { FILE_LOG(logINFO) << *udpPortNumber << ": HDF5 File created: " << currentFileName; @@ -214,9 +210,8 @@ int HDF5File::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t if (HDF5FileStatic::ExtendDataset(index, dataspace, dataset, dataspace_para, dataset_para, *numImages) == OK) { if (!(*silentMode)) { - cprintf(BLUE,"%d Extending HDF5 dataset by %llu, Total x Dimension: %llu\n", - index, (long long unsigned int)extNumImages, - (long long unsigned int)(extNumImages + *numImages)); + FILE_LOG(logINFO) << index << " Extending HDF5 dataset by " << + extNumImages << ", Total x Dimension: " << (extNumImages + *numImages); } extNumImages += *numImages; } @@ -238,7 +233,7 @@ int HDF5File::WriteToFile(char* buffer, int buffersize, uint64_t fnum, uint32_t } } pthread_mutex_unlock(&Mutex); - cprintf(RED,"%d Error: Write to file failed\n", index); + FILE_LOG(logERROR) << index << "Write to file failed"; return FAIL; } diff --git a/slsReceiverSoftware/src/Listener.cpp b/slsReceiverSoftware/src/Listener.cpp old mode 100644 new mode 100755 index 22805f7b8..aaa265133 --- a/slsReceiverSoftware/src/Listener.cpp +++ b/slsReceiverSoftware/src/Listener.cpp @@ -10,6 +10,8 @@ #include "GeneralData.h" #include "Fifo.h" #include "genericSocket.h" +#include "container_utils.h" // For sls::make_unique<> +#include "sls_detector_exceptions.h" #include #include @@ -18,17 +20,17 @@ const std::string Listener::TypeName = "Listener"; -Listener::Listener(int ind, detectorType dtype, Fifo*& f, runStatus* s, +Listener::Listener(int ind, detectorType dtype, Fifo* f, runStatus* s, uint32_t* portno, char* e, uint64_t* nf, uint32_t* dr, - uint32_t* us, uint32_t* as, uint32_t* fpf, + int64_t* us, int64_t* as, uint32_t* fpf, frameDiscardPolicy* fdp, bool* act, bool* depaden, bool* sm) : ThreadObject(ind), runningFlag(0), - generalData(0), + generalData(nullptr), fifo(f), myDetectorType(dtype), status(s), - udpSocket(0), + udpSocket(nullptr), udpPortNumber(portno), eth(e), numImages(nf), @@ -50,15 +52,13 @@ Listener::Listener(int ind, detectorType dtype, Fifo*& f, runStatus* s, lastCaughtFrameIndex(0), currentFrameIndex(0), carryOverFlag(0), - carryOverPacket(0), - listeningPacket(0), udpSocketAlive(0), numPacketsStatistic(0), numFramesStatistic(0), oddStartingPacket(true) { if(ThreadObject::CreateThread() == FAIL) - throw std::exception(); + throw sls::RuntimeError("Could not create listener thread"); FILE_LOG(logDEBUG) << "Listener " << ind << " created"; } @@ -66,12 +66,10 @@ Listener::Listener(int ind, detectorType dtype, Fifo*& f, runStatus* s, Listener::~Listener() { if (udpSocket){ - delete udpSocket; sem_post(&semaphore_socket); sem_destroy(&semaphore_socket); } - if (carryOverPacket) delete [] carryOverPacket; - if (listeningPacket) delete [] listeningPacket; + ThreadObject::DestroyThread(); } @@ -111,7 +109,7 @@ void Listener::StopRunning() { } -void Listener::SetFifo(Fifo*& f) { +void Listener::SetFifo(Fifo* f) { fifo = f; } @@ -130,14 +128,10 @@ void Listener::ResetParametersforNewMeasurement() { numPacketsCaught = 0; firstMeasurementIndex = 0; carryOverFlag = false; - if (carryOverPacket) - delete [] carryOverPacket; - carryOverPacket = new char[generalData->packetSize]; - memset(carryOverPacket,0,generalData->packetSize); - if (listeningPacket) - delete [] listeningPacket; - listeningPacket = new char[generalData->packetSize]; - memset(listeningPacket,0,generalData->packetSize); + carryOverPacket = sls::make_unique(generalData->packetSize); + memset(carryOverPacket.get(),0,generalData->packetSize); + listeningPacket = sls::make_unique(generalData->packetSize); + memset(carryOverPacket.get(),0,generalData->packetSize); numPacketsStatistic = 0; numFramesStatistic = 0; @@ -162,19 +156,18 @@ void Listener::RecordFirstIndices(uint64_t fnum) { } if(!(*silentMode)) { - if (!index) cprintf(BLUE,"%d First Acquisition Index:%lu\n" - "%d First Measurement Index:%lu\n", - index, firstAcquisitionIndex, - index, firstMeasurementIndex); + if (!index) { + FILE_LOG(logINFOBLUE) << index << + " First Acquisition Index: " << firstAcquisitionIndex; + FILE_LOG(logDEBUG1) << index << " First Measurement Index: " << firstMeasurementIndex; + } } } -void Listener::SetGeneralData(GeneralData*& g) { +void Listener::SetGeneralData(GeneralData* g) { generalData = g; -#ifdef VERY_VERBOSE generalData->Print(); -#endif } @@ -194,7 +187,7 @@ int Listener::CreateUDPSockets() { } //if eth is mistaken with ip address - if (strchr(eth,'.') != NULL){ + if (strchr(eth,'.') != nullptr){ memset(eth, 0, MAX_STR_LENGTH); } if(!strlen(eth)){ @@ -204,10 +197,9 @@ int Listener::CreateUDPSockets() { ShutDownUDPSocket(); try{ - genericSocket* g = new genericSocket(*udpPortNumber, genericSocket::UDP, - generalData->packetSize, (strlen(eth)?eth:NULL), generalData->headerPacketSize, + udpSocket = sls::make_unique(*udpPortNumber, genericSocket::UDP, + generalData->packetSize, (strlen(eth)?eth:nullptr), generalData->headerPacketSize, *udpSocketBufferSize); - udpSocket = g; FILE_LOG(logINFO) << index << ": UDP port opened at port " << *udpPortNumber; } catch (...) { FILE_LOG(logERROR) << "Could not create UDP socket on port " << *udpPortNumber; @@ -234,15 +226,13 @@ void Listener::ShutDownUDPSocket() { // wait only if the threads have started as it is the threads that //give a post to semaphore(at stopListening) if (runningFlag) - sem_wait(&semaphore_socket); - delete udpSocket; - udpSocket = 0; + sem_wait(&semaphore_socket); sem_destroy(&semaphore_socket); } } -int Listener::CreateDummySocketForUDPSocketBufferSize(uint32_t s) { +int Listener::CreateDummySocketForUDPSocketBufferSize(int64_t s) { FILE_LOG(logINFO) << "Testing UDP Socket Buffer size with test port " << *udpPortNumber; if (!(*activated)) { @@ -250,47 +240,32 @@ int Listener::CreateDummySocketForUDPSocketBufferSize(uint32_t s) { return OK; } - uint32_t temp = *udpSocketBufferSize; + int64_t temp = *udpSocketBufferSize; *udpSocketBufferSize = s; //if eth is mistaken with ip address - if (strchr(eth,'.') != NULL){ + if (strchr(eth,'.') != nullptr){ memset(eth, 0, MAX_STR_LENGTH); } - // shutdown if any open - if(udpSocket){ - udpSocket->ShutDownSocket(); - delete udpSocket; - udpSocket = 0; - } - //create dummy socket try { - udpSocket = new genericSocket(*udpPortNumber, genericSocket::UDP, - generalData->packetSize, (strlen(eth)?eth:NULL), generalData->headerPacketSize, + genericSocket g(*udpPortNumber, genericSocket::UDP, + generalData->packetSize, (strlen(eth)?eth:nullptr), generalData->headerPacketSize, *udpSocketBufferSize); + + // doubled due to kernel bookkeeping (could also be less due to permissions) + *actualUDPSocketBufferSize = g.getActualUDPSocketBufferSize(); + if (*actualUDPSocketBufferSize != (s*2)) { + *udpSocketBufferSize = temp; + } + } catch (...) { FILE_LOG(logERROR) << "Could not create a test UDP socket on port " << *udpPortNumber; return FAIL; } - // doubled due to kernel bookkeeping (could also be less due to permissions) - *actualUDPSocketBufferSize = udpSocket->getActualUDPSocketBufferSize(); - if (*actualUDPSocketBufferSize != (s*2)) { - *udpSocketBufferSize = temp; - } - - - // shutdown socket - if(udpSocket){ - udpSocketAlive = false; - udpSocket->ShutDownSocket(); - delete udpSocket; - udpSocket = 0; - } - return OK; } @@ -304,9 +279,8 @@ void Listener::ThreadExecution() { int rc = 0; fifo->GetNewAddress(buffer); -#ifdef FIFODEBUG - cprintf(GREEN,"Listener %d, pop 0x%p buffer:%s\n", index,(void*)(buffer),buffer); -#endif + FILE_LOG(logDEBUG5) << "Listener " << index << ", " + "pop 0x" << std::hex << (void*)(buffer) << std::dec << ":" << buffer; //udpsocket doesnt exist if (*activated && !udpSocketAlive && !carryOverFlag) { @@ -324,7 +298,6 @@ void Listener::ThreadExecution() { //error check, (should not be here) if not transmitting yet (previous if) rc should be > 0 if (rc == 0) { - //cprintf(RED,"%d Socket shut down while waiting for future packet. udpsocketalive:%d\n",index, udpSocketAlive ); if (!udpSocketAlive) { (*((uint32_t*)buffer)) = 0; StopListening(buffer); @@ -366,10 +339,8 @@ void Listener::StopListening(char* buf) { StopRunning(); sem_post(&semaphore_socket); -#ifdef VERBOSE - cprintf(GREEN,"%d: Listening Packets (%u) : %llu\n", index, *udpPortNumber, numPacketsCaught); - cprintf(GREEN,"%d: Listening Completed\n", index); -#endif + FILE_LOG(logDEBUG1) << index << ": Listening Packets (" << *udpPortNumber << ") : " << numPacketsCaught; + FILE_LOG(logDEBUG1) << index << ": Listening Completed"; } @@ -386,8 +357,8 @@ uint32_t Listener::ListenToAnImage(char* buf) { uint32_t fifohsize = generalData->fifoBufferHeaderSize; uint32_t pperFrame = generalData->packetsPerFrame; bool isHeaderEmpty = true; - sls_detector_header* old_header = 0; - sls_receiver_header* new_header = 0; + sls_detector_header* old_header = nullptr; + sls_receiver_header* new_header = nullptr; bool standardheader = generalData->standardheader; uint32_t corrected_dsize = dsize - ((pperFrame * dsize) - generalData->imageSize); @@ -422,23 +393,24 @@ uint32_t Listener::ListenToAnImage(char* buf) { //look for carry over if (carryOverFlag) { - //cprintf(RED,"%d carry flag\n",index); + FILE_LOG(logDEBUG3) << index << "carry flag"; //check if its the current image packet // -------------------------- new header ---------------------------------------------------------------------- if (standardheader) { - old_header = (sls_detector_header*) (carryOverPacket + esize); + old_header = (sls_detector_header*) (&carryOverPacket[esize]); fnum = old_header->frameNumber; pnum = old_header->packetNumber; } // -------------------old header ----------------------------------------------------------------------------- else { - generalData->GetHeaderInfo(index, carryOverPacket + esize, + generalData->GetHeaderInfo(index, &carryOverPacket[esize], *dynamicRange, oddStartingPacket, fnum, pnum, snum, bid); } //------------------------------------------------------------------------------------------------------------ if (fnum != currentFrameIndex) { if (fnum < currentFrameIndex) { - cprintf(RED,"Error:(Weird), With carry flag: Frame number %lu less than current frame number %lu\n", fnum, currentFrameIndex); + FILE_LOG(logERROR) << "(Weird), With carry flag: Frame number " << + fnum << " less than current frame number " << currentFrameIndex; return 0; } switch(*frameDiscardMode) { @@ -465,24 +437,25 @@ uint32_t Listener::ListenToAnImage(char* buf) { // 2nd packet: 4 bytes fnum, previous 1*2 bytes data + 640*2 bytes data !! case GOTTHARD: if(!pnum) - memcpy(buf + fifohsize , carryOverPacket + hsize+4, dsize-2); + memcpy(buf + fifohsize , &carryOverPacket[hsize+4], dsize-2); else - memcpy(buf + fifohsize + dsize - 2, carryOverPacket + hsize, dsize+2); + memcpy(buf + fifohsize + dsize - 2, &carryOverPacket[hsize], dsize+2); break; - case JUNGFRAUCTB: + case CHIPTESTBOARD: + case MOENCH: if (pnum == (pperFrame-1)) - memcpy(buf + fifohsize + (pnum * dsize), carryOverPacket + hsize, corrected_dsize); + memcpy(buf + fifohsize + (pnum * dsize), &carryOverPacket[hsize], corrected_dsize); else - memcpy(buf + fifohsize + (pnum * dsize), carryOverPacket + hsize, dsize); + memcpy(buf + fifohsize + (pnum * dsize), &carryOverPacket[hsize], dsize); break; default: - memcpy(buf + fifohsize + (pnum * dsize), carryOverPacket + hsize, dsize); + memcpy(buf + fifohsize + (pnum * dsize), &carryOverPacket[hsize], dsize); break; } carryOverFlag = false; ++numpackets; //number of packets in this image (each time its copied to buf) - new_header->packetsMask[pnum] = 1; + new_header->packetsMask[((pnum < MAX_NUM_PACKETS) ? pnum : MAX_NUM_PACKETS)] = 1; //writer header if(isHeaderEmpty) { @@ -512,7 +485,7 @@ uint32_t Listener::ListenToAnImage(char* buf) { //listen to new packet rc = 0; if (udpSocketAlive){ - rc = udpSocket->ReceiveDataOnly(listeningPacket); + rc = udpSocket->ReceiveDataOnly(&listeningPacket[0]); } // end of acquisition if(rc <= 0) { @@ -542,51 +515,49 @@ uint32_t Listener::ListenToAnImage(char* buf) { // -------------------------- new header ---------------------------------------------------------------------- if (standardheader) { - old_header = (sls_detector_header*) (listeningPacket + esize); + old_header = (sls_detector_header*) (&listeningPacket[esize]); fnum = old_header->frameNumber; pnum = old_header->packetNumber; } // -------------------old header ----------------------------------------------------------------------------- else { - // set first packet to be odd or even (check required when switching from roi to no roi) - if (myDetectorType == GOTTHARD && !measurementStartedFlag) { - oddStartingPacket = generalData->SetOddStartingPacket(index, listeningPacket + esize); - } + // set first packet to be odd or even (check required when switching from roi to no roi) + if (myDetectorType == GOTTHARD && !measurementStartedFlag) { + oddStartingPacket = generalData->SetOddStartingPacket(index, &listeningPacket[esize]); + } - generalData->GetHeaderInfo(index, listeningPacket + esize, + generalData->GetHeaderInfo(index, &listeningPacket[esize], *dynamicRange, oddStartingPacket, fnum, pnum, snum, bid); } //------------------------------------------------------------------------------------------------------------ // Eiger Firmware in a weird state if (myDetectorType == EIGER && fnum == 0) { - cprintf(RED,"[%u]: Got Frame Number Zero from Firmware. Discarding Packet\n", *udpPortNumber); + FILE_LOG(logERROR) << "[" << *udpPortNumber << "]: Got Frame Number " + "Zero from Firmware. Discarding Packet"; numPacketsCaught--; return 0; } lastCaughtFrameIndex = fnum; + FILE_LOG(logDEBUG5) << "Listening " << index << ": currentfindex:" << currentFrameIndex << + ", fnum:" << fnum << ", pnum:" << pnum << ", numpackets:" << numpackets; - //#ifdef VERBOSE - //if (!index) - cprintf(GREEN,"Listening %d: currentfindex:%lu, fnum:%lu, pnum:%u numpackets:%u\n", - index,currentFrameIndex, fnum, pnum, numpackets); - //#endif if (!measurementStartedFlag) RecordFirstIndices(fnum); - if (pnum >= pperFrame ) { - cprintf(RED,"bad packet, throwing away. packets caught so far: %d\n", numpackets); - - return 0; // bad packet - } + if (pnum >= pperFrame ) { + FILE_LOG(logERROR) << "Bad packet " << pnum << + "(fnum: " << fnum << "), throwing away. " + "Packets caught so far: " << numpackets; + return 0; // bad packet + } //future packet by looking at image number (all other detectors) if (fnum != currentFrameIndex) { - //cprintf(RED,"setting carry over flag to true num:%llu nump:%u\n",fnum, numpackets ); carryOverFlag = true; - memcpy(carryOverPacket,listeningPacket, generalData->packetSize); + memcpy(carryOverPacket.get(), &listeningPacket[0], generalData->packetSize); switch(*frameDiscardMode) { case DISCARD_EMPTY_FRAMES: @@ -612,23 +583,23 @@ uint32_t Listener::ListenToAnImage(char* buf) { // 2nd packet: 4 bytes fnum, previous 1*2 bytes data + 640*2 bytes data !! case GOTTHARD: if(!pnum) - memcpy(buf + fifohsize + (pnum * dsize), listeningPacket + hsize+4, dsize-2); + memcpy(buf + fifohsize + (pnum * dsize), &listeningPacket[hsize+4], dsize-2); else - memcpy(buf + fifohsize + (pnum * dsize) - 2, listeningPacket + hsize, dsize+2); + memcpy(buf + fifohsize + (pnum * dsize) - 2, &listeningPacket[hsize], dsize+2); break; - case JUNGFRAUCTB: - + case CHIPTESTBOARD: + case MOENCH: if (pnum == (pperFrame-1)) - memcpy(buf + fifohsize + (pnum * dsize), listeningPacket + hsize, corrected_dsize); + memcpy(buf + fifohsize + (pnum * dsize), &listeningPacket[hsize], corrected_dsize); else - memcpy(buf + fifohsize + (pnum * dsize), listeningPacket + hsize, dsize); + memcpy(buf + fifohsize + (pnum * dsize), &listeningPacket[hsize], dsize); break; default: - memcpy(buf + fifohsize + (pnum * dsize), listeningPacket + hsize, dsize); + memcpy(buf + fifohsize + (pnum * dsize), &listeningPacket[hsize], dsize); break; } ++numpackets; //number of packets in this image (each time its copied to buf) - new_header->packetsMask[pnum] = 1; + new_header->packetsMask[((pnum < MAX_NUM_PACKETS) ? pnum : MAX_NUM_PACKETS)] = 1; if(isHeaderEmpty) { // -------------------------- new header ---------------------------------------------------------------------- @@ -657,19 +628,18 @@ uint32_t Listener::ListenToAnImage(char* buf) { void Listener::PrintFifoStatistics() { -#ifdef VERBOSE - cout << "numFramesStatistic:" << numFramesStatistic << " numPacketsStatistic:" << numPacketsStatistic << endl; -#endif + FILE_LOG(logDEBUG1) << "numFramesStatistic:" << numFramesStatistic << " numPacketsStatistic:" << numPacketsStatistic; + //calculate packet loss - int64_t loss = -1; - loss = (numFramesStatistic*(generalData->packetsPerFrame)) - numPacketsStatistic; + int64_t loss = (numFramesStatistic*(generalData->packetsPerFrame)) - numPacketsStatistic; numPacketsStatistic = 0; numFramesStatistic = 0; - if (loss) - cprintf(RED,"[%u]: Packet_Loss:%lu Used_Fifo_Max_Level:%d \tFree_Slots_Min_Level:%d \tCurrent_Frame#:%lu\n", - *udpPortNumber,loss, fifo->GetMaxLevelForFifoBound() , fifo->GetMinLevelForFifoFree(), currentFrameIndex); - else - cprintf(GREEN,"[%u]: Packet_Loss:%lu Used_Fifo_Max_Level:%d \tFree_Slots_Min_Level:%d \tCurrent_Frame#:%lu\n", - *udpPortNumber,loss, fifo->GetMaxLevelForFifoBound(), fifo->GetMinLevelForFifoFree(), currentFrameIndex); + const auto color = loss ? logINFORED : logINFOGREEN; + FILE_LOG(color) << "[" << *udpPortNumber << "]: " + "Packet_Loss:" << loss << + " Used_Fifo_Max_Level:" << fifo->GetMaxLevelForFifoBound() << + " \tFree_Slots_Min_Level:" << fifo->GetMinLevelForFifoFree() << + " \tCurrent_Frame#:" << currentFrameIndex; + } diff --git a/slsReceiverSoftware/src/MySocketTCP.cpp b/slsReceiverSoftware/src/MySocketTCP.cpp deleted file mode 100644 index b34231352..000000000 --- a/slsReceiverSoftware/src/MySocketTCP.cpp +++ /dev/null @@ -1,46 +0,0 @@ - -//version 1.0, base development, Ian 19/01/09 - - -#include "MySocketTCP.h" -#include -#include -#include - - - - -int MySocketTCP::SendData(void* buf,int length){//length in characters - int ndata = SendDataAndKeepConnection(buf,length); - Disconnect(); - return ndata; -} - -int MySocketTCP::SendDataAndKeepConnection(void* buf,int length){//length in characters - if(last_keep_connection_open_action_was_a_send) Disconnect(); //to keep a structured data flow; - - Connect(); - int total_sent=SendDataOnly(buf,length); - last_keep_connection_open_action_was_a_send=1; - return total_sent; -} - - - - -int MySocketTCP::ReceiveData(void* buf,int length){//length in characters - int ndata = ReceiveDataAndKeepConnection(buf,length); - Disconnect(); - return ndata; -} - -int MySocketTCP::ReceiveDataAndKeepConnection(void* buf,int length){//length in characters - if(!last_keep_connection_open_action_was_a_send) Disconnect(); //to a keep structured data flow; - - Connect(); - // should preform two reads one to receive incomming char count - int total_received=ReceiveDataOnly(buf,length); - last_keep_connection_open_action_was_a_send=0; - return total_received; -} - diff --git a/slsReceiverSoftware/src/ThreadObject.cpp b/slsReceiverSoftware/src/ThreadObject.cpp old mode 100644 new mode 100755 index cd381cc21..47186fcd1 --- a/slsReceiverSoftware/src/ThreadObject.cpp +++ b/slsReceiverSoftware/src/ThreadObject.cpp @@ -39,7 +39,7 @@ void ThreadObject::DestroyThread() { if(alive){ killThread = true; sem_post(&semaphore); - pthread_join(thread,NULL); + pthread_join(thread,nullptr); sem_destroy(&semaphore); killThread = false; alive = false; @@ -56,7 +56,7 @@ int ThreadObject::CreateThread() { sem_init(&semaphore,1,0); killThread = false; - if(pthread_create(&thread, NULL,StartThread, (void*) this)){ + if(pthread_create(&thread, nullptr,StartThread, (void*) this)){ FILE_LOG(logERROR) << "Could not create " << GetType() << " thread with index " << index; return FAIL; } @@ -74,7 +74,8 @@ void* ThreadObject::StartThread(void* thisPointer) { void ThreadObject::RunningThread() { - cprintf(BLUE,"Created [ %s Thread %d, Tid: %ld ]\n", GetType().c_str(),index, (long)syscall(SYS_gettid)); + FILE_LOG(logINFOBLUE) << "Created [ " << GetType() << "Thread " << index << ", " + "Tid: " << syscall(SYS_gettid) << "]"; while(true) { while(IsRunning()) { @@ -88,8 +89,9 @@ void ThreadObject::RunningThread() { sem_wait(&semaphore); if(killThread) { - cprintf(BLUE,"Exiting [ %s Thread %d, Tid: %ld ]\n", GetType().c_str(),index, (long)syscall(SYS_gettid)); - pthread_exit(NULL); + FILE_LOG(logINFOBLUE) << "Exiting [ " << GetType() << + " Thread " << index << ", Tid: " << syscall(SYS_gettid) << "]"; + pthread_exit(nullptr); } }//end of outer loop diff --git a/slsReceiverSoftware/src/UDPBaseImplementation.cpp b/slsReceiverSoftware/src/UDPBaseImplementation.cpp deleted file mode 100644 index f8e28cb71..000000000 --- a/slsReceiverSoftware/src/UDPBaseImplementation.cpp +++ /dev/null @@ -1,825 +0,0 @@ -//#ifdef SLS_RECEIVER_UDP_FUNCTIONS -/********************************************//** - * @file UDPBaseImplementation.cpp - * @short does all the functions for a receiver, set/get parameters, start/stop etc. - ***********************************************/ - -#include "UDPBaseImplementation.h" - -#include // stat -#include -#include - - - -/************************************************************************* - * Constructor & Destructor ********************************************** - * They access local cache of configuration or detector parameters ******* - *************************************************************************/ -UDPBaseImplementation::UDPBaseImplementation(){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - initializeMembers(); - - //***callback parameters*** - startAcquisitionCallBack = NULL; - pStartAcquisition = NULL; - acquisitionFinishedCallBack = NULL; - pAcquisitionFinished = NULL; - rawDataReadyCallBack = NULL; - rawDataModifyReadyCallBack = NULL; - pRawDataReady = NULL; -} - -void UDPBaseImplementation::initializeMembers(){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - FILE_LOG(logDEBUG) << "Info: Initializing base members"; - //**detector parameters*** - for (int i = 0; i < MAX_DIMENSIONS; ++i) - numDet[i] = 0; - detID = 0; - myDetectorType = GENERIC; - strcpy(detHostname,""); - acquisitionPeriod = 0; - acquisitionTime = 0; - subExpTime = 0; - subPeriod = 0; - numberOfFrames = 0; - numberOfSamples = 0; - dynamicRange = 16; - tengigaEnable = false; - fifoDepth = 0; - flippedData[0] = 0; - flippedData[1] = 0; - gapPixelsEnable = false; - - //***receiver parameters*** - status = IDLE; - activated = true; - deactivatedPaddingEnable = true; - frameDiscardMode = NO_DISCARD; - framePadding = false; - - //***connection parameters*** - strcpy(eth,""); - for(int i=0;i 1) return -1; - return flippedData[axis]; -} - -bool UDPBaseImplementation::getGapPixelsEnable() const { - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return gapPixelsEnable; -} - -/***file parameters***/ -slsReceiverDefs::fileFormat UDPBaseImplementation::getFileFormat() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return fileFormatType; -} - - -char *UDPBaseImplementation::getFileName() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - //not initialized - if(!strlen(fileName)) - return NULL; - - char* output = new char[MAX_STR_LENGTH](); - strcpy(output,fileName); - //freed by calling function - return output; -} - -char *UDPBaseImplementation::getFilePath() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - //not initialized - if(!strlen(filePath)) - return NULL; - - char* output = new char[MAX_STR_LENGTH](); - strcpy(output,filePath); - //freed by calling function - return output; -} - -uint64_t UDPBaseImplementation::getFileIndex() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return fileIndex; -} - -uint32_t UDPBaseImplementation::getFramesPerFile() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return framesPerFile; -} - -slsReceiverDefs::frameDiscardPolicy UDPBaseImplementation::getFrameDiscardPolicy() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return frameDiscardMode; -} - -bool UDPBaseImplementation::getFramePaddingEnable() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return framePadding; -} - -int UDPBaseImplementation::getScanTag() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return scanTag; -} - -bool UDPBaseImplementation::getFileWriteEnable() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return fileWriteEnable; -} - -bool UDPBaseImplementation::getOverwriteEnable() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return overwriteEnable; -} - -bool UDPBaseImplementation::getDataCompressionEnable() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return dataCompressionEnable; -} - -/***acquisition count parameters***/ -uint64_t UDPBaseImplementation::getTotalFramesCaught() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return 0; -} - -uint64_t UDPBaseImplementation::getFramesCaught() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return 0; -} - -int64_t UDPBaseImplementation::getAcquisitionIndex() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return -1; -} - - -/***connection parameters***/ -uint32_t UDPBaseImplementation::getUDPPortNumber() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return udpPortNum[0]; -} - -uint32_t UDPBaseImplementation::getUDPPortNumber2() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return udpPortNum[1]; -} - -char *UDPBaseImplementation::getEthernetInterface() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - char* output = new char[MAX_STR_LENGTH](); - strcpy(output,eth); - //freed by calling function - return output; -} - - -/***acquisition parameters***/ -std::vector UDPBaseImplementation::getROI() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return roi; -} - -uint32_t UDPBaseImplementation::getFrameToGuiFrequency() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return frameToGuiFrequency; -} - -uint32_t UDPBaseImplementation::getFrameToGuiTimer() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return frameToGuiTimerinMS; -} - -bool UDPBaseImplementation::getDataStreamEnable() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return dataStreamEnable; -} - -uint64_t UDPBaseImplementation::getAcquisitionPeriod() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return acquisitionPeriod; -} - -uint64_t UDPBaseImplementation::getAcquisitionTime() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return acquisitionTime; -} - -uint64_t UDPBaseImplementation::getSubExpTime() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return subExpTime; -} - -uint64_t UDPBaseImplementation::getSubPeriod() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return subPeriod; -} - -uint64_t UDPBaseImplementation::getNumberOfFrames() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return numberOfFrames; -} - -uint64_t UDPBaseImplementation::getNumberofSamples() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return numberOfSamples; -} - -uint32_t UDPBaseImplementation::getDynamicRange() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return dynamicRange;} - -bool UDPBaseImplementation::getTenGigaEnable() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return tengigaEnable; -} - -uint32_t UDPBaseImplementation::getFifoDepth() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return fifoDepth; -} - -/***receiver status***/ -slsReceiverDefs::runStatus UDPBaseImplementation::getStatus() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return status;} - -bool UDPBaseImplementation::getSilentMode() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return silentMode;} - -bool UDPBaseImplementation::getActivate() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return activated; -} - -bool UDPBaseImplementation::getDeactivatedPadding() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return deactivatedPaddingEnable; -} - -uint32_t UDPBaseImplementation::getStreamingPort() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return streamingPort; -} - -char *UDPBaseImplementation::getStreamingSourceIP() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - char* output = new char[MAX_STR_LENGTH](); - strcpy(output,streamingSrcIP); - //freed by calling function - return output; -} - -char *UDPBaseImplementation::getAdditionalJsonHeader() const{ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - char* output = new char[MAX_STR_LENGTH](); - memset(output, 0, MAX_STR_LENGTH); - strcpy(output,additionalJsonHeader); - //freed by calling function - return output; -} - -uint32_t UDPBaseImplementation::getUDPSocketBufferSize() const { - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return udpSocketBufferSize; -} - -uint32_t UDPBaseImplementation::getActualUDPSocketBufferSize() const { - FILE_LOG(logDEBUG) << __AT__ << " starting"; - return actualUDPSocketBufferSize; -} - -/************************************************************************* - * Setters *************************************************************** - * They modify the local cache of configuration or detector parameters *** - *************************************************************************/ - -/**initial parameters***/ -void UDPBaseImplementation::configure(std::map config_map){ - FILE_LOG(logERROR) << __AT__ << " doing nothing..."; - FILE_LOG(logERROR) << __AT__ << " must be overridden by child classes"; -} - -void UDPBaseImplementation::setMultiDetectorSize(const int* size) { - FILE_LOG(logDEBUG) << __AT__ << " starting"; - char message[100]; - strcpy(message, "Detector Size: ("); - for (int i = 0; i < MAX_DIMENSIONS; ++i) { - if (myDetectorType == EIGER && (!i)) - numDet[i] = size[i]*2; - else - numDet[i] = size[i]; - sprintf(message,"%s%d",message,numDet[i]); - if (i < MAX_DIMENSIONS-1 ) - strcat(message,","); - } - strcat(message,")"); - FILE_LOG(logINFO) << message; -} - -void UDPBaseImplementation::setFlippedData(int axis, int enable){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - if(axis<0 || axis>1) return; - flippedData[axis] = enable==0?0:1; - FILE_LOG(logINFO) << "Flipped Data: " << flippedData[0] << " , " << flippedData[1]; -} - -int UDPBaseImplementation::setGapPixelsEnable(const bool b) { - FILE_LOG(logDEBUG) << __AT__ << " starting"; - gapPixelsEnable = b; - FILE_LOG(logINFO) << "Gap Pixels Enable: " << gapPixelsEnable; - - // overridden - return OK; -} - -/***file parameters***/ -void UDPBaseImplementation::setFileFormat(const fileFormat f){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - switch(f){ -#ifdef HDF5C - case HDF5: - fileFormatType = HDF5; - break; -#endif - default: - fileFormatType = BINARY; - break; - } - - FILE_LOG(logINFO) << "File Format: " << getFileFormatType(fileFormatType); -} - - -void UDPBaseImplementation::setFileName(const char c[]){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - if(strlen(c)) - strcpy(fileName, c); - FILE_LOG(logINFO) << "File name: " << fileName; -} - -void UDPBaseImplementation::setFilePath(const char c[]){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - - if(strlen(c)){ - //check if filepath exists - struct stat st; - if(stat(c,&st) == 0) - strcpy(filePath,c); - else - FILE_LOG(logERROR) << "FilePath does not exist: " << filePath; - } - FILE_LOG(logINFO) << "File path: " << filePath; -} - -void UDPBaseImplementation::setFileIndex(const uint64_t i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - fileIndex = i; - FILE_LOG(logINFO) << "File Index: " << fileIndex; -} - -void UDPBaseImplementation::setFramesPerFile(const uint32_t i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - framesPerFile = i; - FILE_LOG(logINFO) << "Frames per file: " << framesPerFile; -} - -void UDPBaseImplementation::setFrameDiscardPolicy(const frameDiscardPolicy i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - if (i >= 0 && i < NUM_DISCARD_POLICIES) - frameDiscardMode = i; - - FILE_LOG(logINFO) << "Frame Discard Policy: " << getFrameDiscardPolicyType(frameDiscardMode); -} - -void UDPBaseImplementation::setFramePaddingEnable(const bool i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - framePadding = i; - FILE_LOG(logINFO) << "Frame Padding: " << framePadding; -} - -//FIXME: needed? -void UDPBaseImplementation::setScanTag(const int i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - scanTag = i; - FILE_LOG(logINFO) << "Scan Tag: " << scanTag; - -} - -void UDPBaseImplementation::setFileWriteEnable(const bool b){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - fileWriteEnable = b; - FILE_LOG(logINFO) << "File Write Enable: " << stringEnable(fileWriteEnable); -} - -void UDPBaseImplementation::setOverwriteEnable(const bool b){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - overwriteEnable = b; - FILE_LOG(logINFO) << "Overwrite Enable: " << stringEnable(overwriteEnable); -} - -int UDPBaseImplementation::setDataCompressionEnable(const bool b){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - dataCompressionEnable = b; - FILE_LOG(logINFO) << "Data Compression : " << stringEnable(dataCompressionEnable); - - //overridden methods might return FAIL - return OK; -} - - -/***connection parameters***/ -void UDPBaseImplementation::setUDPPortNumber(const uint32_t i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - udpPortNum[0] = i; - FILE_LOG(logINFO) << "UDP Port Number[0]: " << udpPortNum[0]; -} - -void UDPBaseImplementation::setUDPPortNumber2(const uint32_t i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - udpPortNum[1] = i; - FILE_LOG(logINFO) << "UDP Port Number[1]: " << udpPortNum[1]; -} - -void UDPBaseImplementation::setEthernetInterface(const char* c){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - strcpy(eth, c); - FILE_LOG(logINFO) << "Ethernet Interface: " << eth; -} - - -/***acquisition parameters***/ -int UDPBaseImplementation::setROI(const std::vector i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - roi = i; - - std::stringstream sstm; - sstm << "ROI: "; - if (!roi.size()) - sstm << "0"; - else { - for (unsigned int i = 0; i < roi.size(); ++i) { - sstm << "( " << - roi[i].xmin << ", " << - roi[i].xmax << ", " << - roi[i].ymin << ", " << - roi[i].ymax << " )"; - } - } - std::string message = sstm.str(); - FILE_LOG(logINFO) << message; - - //overrridden child classes might return FAIL - return OK; -} - -int UDPBaseImplementation::setFrameToGuiFrequency(const uint32_t freq){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - frameToGuiFrequency = freq; - FILE_LOG(logINFO) << "Frame To Gui Frequency: " << frameToGuiFrequency; - - //overrridden child classes might return FAIL - return OK; -} - -void UDPBaseImplementation::setFrameToGuiTimer(const uint32_t time_in_ms){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - frameToGuiTimerinMS = time_in_ms; - FILE_LOG(logINFO) << "Frame To Gui Timer: " << frameToGuiTimerinMS; -} - - -int UDPBaseImplementation::setDataStreamEnable(const bool enable){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - dataStreamEnable = enable; - FILE_LOG(logINFO) << "Streaming Data from Receiver: " << dataStreamEnable; - - //overrridden child classes might return FAIL - return OK; -} - - -int UDPBaseImplementation::setAcquisitionPeriod(const uint64_t i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - acquisitionPeriod = i; - FILE_LOG(logINFO) << "Acquisition Period: " << (double)acquisitionPeriod/(1E9) << "s"; - - //overrridden child classes might return FAIL - return OK; -} - -int UDPBaseImplementation::setAcquisitionTime(const uint64_t i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - acquisitionTime = i; - FILE_LOG(logINFO) << "Acquisition Time: " << (double)acquisitionTime/(1E9) << "s"; - - //overrridden child classes might return FAIL - return OK; -} - -void UDPBaseImplementation::setSubExpTime(const uint64_t i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - subExpTime = i; - FILE_LOG(logINFO) << "Sub Exposure Time: " << (double)subExpTime/(1E9) << "s"; -} - -void UDPBaseImplementation::setSubPeriod(const uint64_t i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - subPeriod = i; - FILE_LOG(logINFO) << "Sub Exposure Time: " << (double)subPeriod/(1E9) << "s"; -} - -int UDPBaseImplementation::setNumberOfFrames(const uint64_t i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - numberOfFrames = i; - FILE_LOG(logINFO) << "Number of Frames: " << numberOfFrames; - - //overrridden child classes might return FAIL - return OK; -} - -int UDPBaseImplementation::setNumberofSamples(const uint64_t i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - numberOfSamples = i; - FILE_LOG(logINFO) << "Number of Samples: " << numberOfSamples; - - //overrridden child classes might return FAIL - return OK; -} - -int UDPBaseImplementation::setDynamicRange(const uint32_t i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - dynamicRange = i; - FILE_LOG(logINFO) << "Dynamic Range: " << dynamicRange; - - //overrridden child classes might return FAIL - return OK; -} - -int UDPBaseImplementation::setTenGigaEnable(const bool b){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - tengigaEnable = b; - FILE_LOG(logINFO) << "Ten Giga Enable: " << stringEnable(tengigaEnable); - - //overridden functions might return FAIL - return OK; -} - -int UDPBaseImplementation::setFifoDepth(const uint32_t i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - fifoDepth = i; - FILE_LOG(logINFO) << "Fifo Depth: " << i; - - //overridden functions might return FAIL - return OK; -} - -/***receiver parameters***/ -void UDPBaseImplementation::setSilentMode(const bool i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - silentMode = i; - FILE_LOG(logINFO) << "Silent Mode: " << i; -} - -/************************************************************************* - * Behavioral functions*************************************************** - * They may modify the status of the receiver **************************** - *************************************************************************/ - - -/***initial functions***/ -int UDPBaseImplementation::setDetectorType(const detectorType d){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - myDetectorType = d; - //if eiger, set numberofListeningThreads = 2; - FILE_LOG(logINFO) << "Detector Type: " << getDetectorType(d); - return OK; -} - -void UDPBaseImplementation::setDetectorPositionId(const int i){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - detID = i; - FILE_LOG(logINFO) << "Detector Position Id: " << detID; -} - -void UDPBaseImplementation::initialize(const char *c){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - if(strlen(c)) - strcpy(detHostname, c); - FILE_LOG(logINFO) << "Detector Hostname: " << detHostname; -} - - -/***acquisition functions***/ -void UDPBaseImplementation::resetAcquisitionCount(){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - //overriden by resetting of new acquisition parameters -} - -int UDPBaseImplementation::startReceiver(char *c){ - FILE_LOG(logERROR) << __AT__ << " doing nothing..."; - FILE_LOG(logERROR) << __AT__ << " must be overridden by child classes"; - return OK; -} - -void UDPBaseImplementation::stopReceiver(){ - FILE_LOG(logERROR) << __AT__ << " doing nothing..."; - FILE_LOG(logERROR) << __AT__ << " must be overridden by child classes"; -} - -void UDPBaseImplementation::startReadout(){ - FILE_LOG(logERROR) << __AT__ << " doing nothing..."; - FILE_LOG(logERROR) << __AT__ << " must be overridden by child classes"; -} - -void UDPBaseImplementation::shutDownUDPSockets(){ - FILE_LOG(logERROR) << __AT__ << " doing nothing..."; - FILE_LOG(logERROR) << __AT__ << " must be overridden by child classes"; -} - - -//FIXME: needed, isnt stopReceiver enough? -void UDPBaseImplementation::abort(){ - FILE_LOG(logERROR) << __AT__ << " doing nothing..."; - FILE_LOG(logERROR) << __AT__ << " must be overridden by child classes"; -} - - -bool UDPBaseImplementation::setActivate(bool enable){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - activated = enable; - FILE_LOG(logINFO) << "Activation: " << stringEnable(activated); - return activated; -} - -bool UDPBaseImplementation::setDeactivatedPadding(bool enable){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - deactivatedPaddingEnable = enable; - FILE_LOG(logINFO) << "Deactivated Padding Enable: " << stringEnable(deactivatedPaddingEnable); - return deactivatedPaddingEnable; -} - -void UDPBaseImplementation::setStreamingPort(const uint32_t i) { - streamingPort = i; - - FILE_LOG(logINFO) << "Streaming Port: " << streamingPort; -} - -void UDPBaseImplementation::setStreamingSourceIP(const char c[]){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - strcpy(streamingSrcIP, c); - FILE_LOG(logINFO) << "Streaming Source IP: " << streamingSrcIP; -} - -void UDPBaseImplementation::setAdditionalJsonHeader(const char c[]){ - FILE_LOG(logDEBUG) << __AT__ << " starting"; - strcpy(additionalJsonHeader, c); - FILE_LOG(logINFO) << "Additional JSON Header: " << additionalJsonHeader; -} - -int UDPBaseImplementation::setUDPSocketBufferSize(const uint32_t s) { - FILE_LOG(logDEBUG) << __AT__ << " starting"; - - udpSocketBufferSize = s; - return OK; -} - - -int UDPBaseImplementation::restreamStop() { - FILE_LOG(logERROR) << __AT__ << " doing nothing..."; - FILE_LOG(logERROR) << __AT__ << " must be overridden by child classes"; - return OK; -} - -/***callback functions***/ -void UDPBaseImplementation::registerCallBackStartAcquisition(int (*func)(char*, char*, uint64_t, uint32_t, void*),void *arg){ - startAcquisitionCallBack=func; - pStartAcquisition=arg; -} - -void UDPBaseImplementation::registerCallBackAcquisitionFinished(void (*func)(uint64_t, void*),void *arg){ - acquisitionFinishedCallBack=func; - pAcquisitionFinished=arg; -} - -void UDPBaseImplementation::registerCallBackRawDataReady(void (*func)(char* , - char*, uint32_t, void*),void *arg){ - rawDataReadyCallBack=func; - pRawDataReady=arg; -} - -void UDPBaseImplementation::registerCallBackRawDataModifyReady(void (*func)(char* , - char*, uint32_t&, void*),void *arg){ - rawDataModifyReadyCallBack=func; - pRawDataReady=arg; -} -//#endif diff --git a/slsReceiverSoftware/src/UDPInterface.cpp b/slsReceiverSoftware/src/UDPInterface.cpp deleted file mode 100644 index 73d5835af..000000000 --- a/slsReceiverSoftware/src/UDPInterface.cpp +++ /dev/null @@ -1,30 +0,0 @@ -//#ifdef SLS_RECEIVER_UDP_FUNCTIONS -/********************************************//** - * @file slsReceiverUDPFunctions.cpp - * @short does all the functions for a receiver, set/get parameters, start/stop etc. - ***********************************************/ - - -#include -#include - - -#include "UDPInterface.h" -#include "UDPBaseImplementation.h" -#include "UDPStandardImplementation.h" - - -UDPInterface * UDPInterface::create(std::string receiver_type){ - - if (receiver_type == "standard"){ - FILE_LOG(logINFO) << "Starting " << receiver_type; - return new UDPStandardImplementation(); - } - else{ - FILE_LOG(logERROR) << "UDP interface not supported, using base implementation"; - return new UDPBaseImplementation(); - } -} - - -//#endif diff --git a/slsReceiverSoftware/src/UDPStandardImplementation.cpp b/slsReceiverSoftware/src/UDPStandardImplementation.cpp deleted file mode 100644 index 75d611006..000000000 --- a/slsReceiverSoftware/src/UDPStandardImplementation.cpp +++ /dev/null @@ -1,822 +0,0 @@ -/********************************************//** - * @file UDPStandardImplementation.cpp - * @short does all the functions for a receiver, set/get parameters, start/stop etc. - ***********************************************/ - - -#include "UDPStandardImplementation.h" -#include "GeneralData.h" -#include "Listener.h" -#include "DataProcessor.h" -#include "DataStreamer.h" -#include "Fifo.h" -#include "ZmqSocket.h" //just for the zmq port define - -#include //system -#include //strcpy -#include //eperm -#include - - -/** cosntructor & destructor */ - -UDPStandardImplementation::UDPStandardImplementation() { - InitializeMembers(); -} - - -UDPStandardImplementation::~UDPStandardImplementation() { - DeleteMembers(); -} - - -void UDPStandardImplementation::DeleteMembers() { - if (generalData) { delete generalData; generalData=0;} - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - delete(*it); - listener.clear(); - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - delete(*it); - dataProcessor.clear(); - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - delete(*it); - dataStreamer.clear(); - for (std::vector::const_iterator it = fifo.begin(); it != fifo.end(); ++it) - delete(*it); - fifo.clear(); -} - - -void UDPStandardImplementation::InitializeMembers() { - UDPBaseImplementation::initializeMembers(); - acquisitionPeriod = SAMPLE_TIME_IN_NS; - - //*** receiver parameters *** - numThreads = 1; - numberofJobs = 1; - nroichannels = 0; - - //** class objects *** - generalData = 0; -} - - - -/*** Overloaded Functions called by TCP Interface ***/ - -uint64_t UDPStandardImplementation::getTotalFramesCaught() const { - uint64_t sum = 0; - uint32_t flagsum = 0; - - std::vector::const_iterator it; - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) { - flagsum += ((*it)->GetMeasurementStartedFlag() ? 1 : 0); - sum += (*it)->GetNumTotalFramesCaught(); - } - - //no data processed - if (flagsum != dataProcessor.size()) return 0; - - return (sum/dataProcessor.size()); -} - -uint64_t UDPStandardImplementation::getFramesCaught() const { - uint64_t sum = 0; - uint32_t flagsum = 0; - - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) { - flagsum += ((*it)->GetAcquisitionStartedFlag() ? 1 : 0); - sum += (*it)->GetNumFramesCaught(); - } - - //no data processed - if (flagsum != dataProcessor.size()) return 0; - - return (sum/dataProcessor.size()); -} - -int64_t UDPStandardImplementation::getAcquisitionIndex() const { - uint64_t sum = 0; - uint32_t flagsum = 0; - - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it){ - flagsum += ((*it)->GetAcquisitionStartedFlag() ? 1 : 0); - sum += (*it)->GetActualProcessedAcquisitionIndex(); - } - - //no data processed - if (flagsum != dataProcessor.size()) return -1; - - return (sum/dataProcessor.size()); -} - - - -int UDPStandardImplementation::setGapPixelsEnable(const bool b) { - if (gapPixelsEnable != b) { - gapPixelsEnable = b; - - // side effects - generalData->SetGapPixelsEnable(b, dynamicRange); - // to update npixelsx, npixelsy in file writer - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - (*it)->SetPixelDimension(); - - numberofJobs = -1; //changes to imagesize has to be noted to recreate fifo structure - if (SetupFifoStructure() == FAIL) - return FAIL; - } - FILE_LOG(logINFO) << "Gap Pixels Enable: " << gapPixelsEnable; - return OK; -} - - -void UDPStandardImplementation::setFileFormat(const fileFormat f){ - switch(f){ -#ifdef HDF5C - case HDF5: - fileFormatType = HDF5; - break; -#endif - default: - fileFormatType = BINARY; - break; - } - //destroy file writer, set file format and create file writer - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - (*it)->SetFileFormat(f); - - FILE_LOG(logINFO) << "File Format:" << getFileFormatType(fileFormatType); -} - - -void UDPStandardImplementation::setFileWriteEnable(const bool b){ - if (fileWriteEnable != b){ - fileWriteEnable = b; - for (unsigned int i = 0; i < dataProcessor.size(); ++i) { - dataProcessor[i]->SetupFileWriter(fileWriteEnable, (int*)numDet, - &framesPerFile, fileName, filePath, &fileIndex, &overwriteEnable, - &detID, &numThreads, &numberOfFrames, &dynamicRange, &udpPortNum[i], - generalData); - } - } - - FILE_LOG(logINFO) << "File Write Enable: " << stringEnable(fileWriteEnable); -} - - - - -int UDPStandardImplementation::setROI(const std::vector i) { - if (myDetectorType != GOTTHARD) { - cprintf(RED, "Error: Can not set ROI for this detector\n"); - return FAIL; - } - - - bool change = false; - if (roi.size() != i.size()) - change = true; - else { - for (unsigned int iloop = 0; iloop < i.size(); ++iloop) { - if ( - (roi[iloop].xmin != i[iloop].xmin) || - (roi[iloop].xmax != i[iloop].xmax) || - (roi[iloop].ymin != i[iloop].ymin) || - (roi[iloop].xmax != i[iloop].xmax)) { - change = true; - break; - } - } - } - - if (change) { - - roi = i; - - generalData->SetROI(i); - framesPerFile = generalData->maxFramesPerFile; - - numberofJobs = -1; //changes to imagesize has to be noted to recreate fifo structure - if (SetupFifoStructure() == FAIL) - return FAIL; - - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - (*it)->SetGeneralData(generalData); - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - (*it)->SetGeneralData(generalData); - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - (*it)->SetGeneralData(generalData); - } - - - std::stringstream sstm; - sstm << "ROI: "; - if (!roi.size()) - sstm << "0"; - else { - for (unsigned int i = 0; i < roi.size(); ++i) { - sstm << "( " << - roi[i].xmin << ", " << - roi[i].xmax << ", " << - roi[i].ymin << ", " << - roi[i].ymax << " )"; - } - } - std::string message = sstm.str(); - FILE_LOG(logINFO) << message; - return OK; -} - - -int UDPStandardImplementation::setFrameToGuiFrequency(const uint32_t freq) { - if (frameToGuiFrequency != freq) { - frameToGuiFrequency = freq; - } - FILE_LOG(logINFO) << "Frame to Gui Frequency: " << frameToGuiFrequency; - return OK; -} - - -int UDPStandardImplementation::setDataStreamEnable(const bool enable) { - - if (dataStreamEnable != enable) { - dataStreamEnable = enable; - - //data sockets have to be created again as the client ones are - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - delete(*it); - dataStreamer.clear(); - - if (enable) { - for ( int i = 0; i < numThreads; ++i ) { - try { - DataStreamer* s = new DataStreamer(i, fifo[i], &dynamicRange, - &roi, &fileIndex, flippedData, additionalJsonHeader, &silentMode); - dataStreamer.push_back(s); - dataStreamer[i]->SetGeneralData(generalData); - dataStreamer[i]->CreateZmqSockets(&numThreads, streamingPort, streamingSrcIP); - } - catch(...) { - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - delete(*it); - dataStreamer.clear(); - dataStreamEnable = false; - return FAIL; - } - } - SetThreadPriorities(); - } - } - FILE_LOG(logINFO) << "Data Send to Gui: " << dataStreamEnable; - return OK; -} - - - -int UDPStandardImplementation::setNumberofSamples(const uint64_t i) { - if (numberOfSamples != i) { - numberOfSamples = i; - - generalData->setNumberofSamples(i, nroichannels); - numberofJobs = -1; //changes to imagesize has to be noted to recreate fifo structure - if (SetupFifoStructure() == FAIL) - return FAIL; - } - FILE_LOG (logINFO) << "Number of Samples: " << numberOfSamples; - FILE_LOG (logINFO) << "Packets per Frame: " << (generalData->packetsPerFrame); - return OK; -} - - -int UDPStandardImplementation::setDynamicRange(const uint32_t i) { - if (dynamicRange != i) { - dynamicRange = i; - - //side effects - generalData->SetDynamicRange(i,tengigaEnable); - generalData->SetGapPixelsEnable(gapPixelsEnable, dynamicRange); - // to update npixelsx, npixelsy in file writer - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - (*it)->SetPixelDimension(); - - numberofJobs = -1; //changes to imagesize has to be noted to recreate fifo structure - if (SetupFifoStructure() == FAIL) - return FAIL; - } - FILE_LOG(logINFO) << "Dynamic Range: " << dynamicRange; - return OK; -} - - -int UDPStandardImplementation::setTenGigaEnable(const bool b) { - if (tengigaEnable != b) { - tengigaEnable = b; - //side effects - generalData->SetTenGigaEnable(b,dynamicRange); - - numberofJobs = -1; //changes to imagesize has to be noted to recreate fifo structure - if (SetupFifoStructure() == FAIL) - return FAIL; - } - FILE_LOG(logINFO) << "Ten Giga: " << stringEnable(tengigaEnable); - return OK; -} - - -int UDPStandardImplementation::setFifoDepth(const uint32_t i) { - if (fifoDepth != i) { - fifoDepth = i; - - numberofJobs = -1; //changes to imagesize has to be noted to recreate fifo structure - if (SetupFifoStructure() == FAIL) - return FAIL; - } - FILE_LOG(logINFO) << "Fifo Depth: " << i; - return OK; -} - - - -int UDPStandardImplementation::setDetectorType(const detectorType d) { - FILE_LOG(logDEBUG) << "Setting receiver type"; - DeleteMembers(); - InitializeMembers(); - myDetectorType = d; - switch(myDetectorType) { - case GOTTHARD: - case PROPIX: - case MOENCH: - case EIGER: - case JUNGFRAUCTB: - case JUNGFRAU: - FILE_LOG(logINFO) << " ***** " << getDetectorType(d) << " Receiver *****"; - break; - default: - FILE_LOG(logERROR) << "This is an unknown receiver type " << (int)d; - return FAIL; - } - - - //set detector specific variables - switch(myDetectorType) { - case GOTTHARD: generalData = new GotthardData(); break; - case PROPIX: generalData = new PropixData(); break; - case MOENCH: generalData = new Moench02Data(); break; - case EIGER: generalData = new EigerData(); break; - case JUNGFRAUCTB: generalData = new JCTBData(); break; - case JUNGFRAU: generalData = new JungfrauData(); break; - default: break; - } - numThreads = generalData->threadsPerReceiver; - fifoDepth = generalData->defaultFifoDepth; - udpSocketBufferSize = generalData->defaultUdpSocketBufferSize; - framesPerFile = generalData->maxFramesPerFile; - - //local network parameters - SetLocalNetworkParameters(); - - //create fifo structure - numberofJobs = -1; - if (SetupFifoStructure() == FAIL) { - FILE_LOG(logERROR) << "Could not allocate memory for fifo structure"; - return FAIL; - } - - //create threads - for ( int i = 0; i < numThreads; ++i ) { - - try { - Listener* l = new Listener(i, myDetectorType, fifo[i], &status, - &udpPortNum[i], eth, &numberOfFrames, &dynamicRange, - &udpSocketBufferSize, &actualUDPSocketBufferSize, &framesPerFile, - &frameDiscardMode, &activated, &deactivatedPaddingEnable, &silentMode); - listener.push_back(l); - - DataProcessor* p = new DataProcessor(i, myDetectorType, fifo[i], &fileFormatType, - fileWriteEnable, &dataStreamEnable, &gapPixelsEnable, - &dynamicRange, &frameToGuiFrequency, &frameToGuiTimerinMS, - &framePadding, &activated, &deactivatedPaddingEnable, &silentMode, - rawDataReadyCallBack, rawDataModifyReadyCallBack, pRawDataReady); - dataProcessor.push_back(p); - } - catch (...) { - FILE_LOG(logERROR) << "Could not create listener/dataprocessor threads (index:" << i << ")"; - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - delete(*it); - listener.clear(); - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - delete(*it); - dataProcessor.clear(); - return FAIL; - } - } - - //set up writer and callbacks - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - (*it)->SetGeneralData(generalData); - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - (*it)->SetGeneralData(generalData); - - SetThreadPriorities(); - - // check udp socket buffer size - setUDPSocketBufferSize(udpSocketBufferSize); - - FILE_LOG(logDEBUG) << " Detector type set to " << getDetectorType(d); - return OK; -} - - - - -void UDPStandardImplementation::setDetectorPositionId(const int i){ - detID = i; - FILE_LOG(logINFO) << "Detector Position Id:" << detID; - for (unsigned int i = 0; i < dataProcessor.size(); ++i) { - dataProcessor[i]->SetupFileWriter(fileWriteEnable, (int*)numDet, - &framesPerFile, fileName, filePath, &fileIndex, &overwriteEnable, - &detID, &numThreads, &numberOfFrames, &dynamicRange, &udpPortNum[i], - generalData); - } - - for (unsigned int i = 0; i < listener.size(); ++i) { - uint16_t row = 0, col = 0; - row = detID % numDet[1]; // row - col = (detID / numDet[1]) * ((myDetectorType == EIGER) ? 2 : 1) + i; // col for horiz. udp ports - listener[i]->SetHardCodedPosition(row, col); - } -} - - -void UDPStandardImplementation::resetAcquisitionCount() { - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - (*it)->ResetParametersforNewAcquisition(); - - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - (*it)->ResetParametersforNewAcquisition(); - - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - (*it)->ResetParametersforNewAcquisition(); - - FILE_LOG(logINFO) << "Acquisition Count has been reset"; -} - - - -int UDPStandardImplementation::startReceiver(char *c) { - cprintf(RESET,"\n"); - FILE_LOG(logINFO) << "Starting Receiver"; - ResetParametersforNewMeasurement(); - - //listener - if (CreateUDPSockets() == FAIL) { - strcpy(c,"Could not create UDP Socket(s)."); - FILE_LOG(logERROR) << c; - return FAIL; - } - - //callbacks - if (startAcquisitionCallBack) { - startAcquisitionCallBack(filePath, fileName, fileIndex, - (generalData->imageSize) * numberofJobs + (generalData->fifoBufferHeaderSize), pStartAcquisition); - if (rawDataReadyCallBack != NULL) { - FILE_LOG(logINFO) << "Data Write has been defined externally"; - } - } - - //processor->writer - if (fileWriteEnable) { - if (SetupWriter() == FAIL) { - strcpy(c,"Could not create file."); - FILE_LOG(logERROR) << c; - return FAIL; - } - } else - FILE_LOG(logINFO) << "File Write Disabled"; - - FILE_LOG(logINFO) << "Ready ..."; - - //status - status = RUNNING; - - //Let Threads continue to be ready for acquisition - StartRunning(); - - FILE_LOG(logINFO) << "Receiver Started"; - FILE_LOG(logINFO) << "Status: " << runStatusType(status); - return OK; -} - - - -void UDPStandardImplementation::stopReceiver(){ - FILE_LOG(logINFO) << "Stopping Receiver"; - - //set status to transmitting - startReadout(); - - //wait for the processes (Listener and DataProcessor) to be done - bool running = true; - while(running) { - running = false; - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - if ((*it)->IsRunning()) - running = true; - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - if ((*it)->IsRunning()) - running = true; - usleep(5000); - } - - - //create virtual file - if (fileWriteEnable && fileFormatType == HDF5) { - uint64_t maxIndexCaught = 0; - bool anycaught = false; - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) { - maxIndexCaught = std::max(maxIndexCaught, (*it)->GetProcessedMeasurementIndex()); - if((*it)->GetMeasurementStartedFlag()) - anycaught = true; - } - //to create virtual file & set files/acquisition to 0 (only hdf5 at the moment) - dataProcessor[0]->EndofAcquisition(anycaught, maxIndexCaught); - } - - //wait for the processes (DataStreamer) to be done - running = true; - while(running) { - running = false; - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - if ((*it)->IsRunning()) - running = true; - usleep(5000); - } - - status = RUN_FINISHED; - FILE_LOG(logINFO) << "Status: " << runStatusType(status); - - - { //statistics - uint64_t tot = 0; - for (int i = 0; i < numThreads; i++) { - tot += dataProcessor[i]->GetNumFramesCaught(); - - uint64_t missingpackets = numberOfFrames*generalData->packetsPerFrame-listener[i]->GetPacketsCaught(); - if ((int)missingpackets > 0) { - cprintf(RED, "\n[Port %d]\n",udpPortNum[i]); - cprintf(RED, "Missing Packets\t\t: %lld\n",(long long int)missingpackets); - cprintf(RED, "Complete Frames\t\t: %lld\n",(long long int)dataProcessor[i]->GetNumFramesCaught()); - cprintf(RED, "Last Frame Caught\t: %lld\n",(long long int)listener[i]->GetLastFrameIndexCaught()); - }else{ - cprintf(GREEN, "\n[Port %d]\n",udpPortNum[i]); - cprintf(GREEN, "Missing Packets\t\t: %lld\n",(long long int)missingpackets); - cprintf(GREEN, "Complete Frames\t\t: %lld\n",(long long int)dataProcessor[i]->GetNumFramesCaught()); - cprintf(GREEN, "Last Frame Caught\t: %lld\n",(long long int)listener[i]->GetLastFrameIndexCaught()); - } - } - if(!activated) - cprintf(RED,"Note: Deactivated Receiver\n"); - //callback - if (acquisitionFinishedCallBack) - acquisitionFinishedCallBack((tot/numThreads), pAcquisitionFinished); - } - - //change status - status = IDLE; - - FILE_LOG(logINFO) << "Receiver Stopped"; - FILE_LOG(logINFO) << "Status: " << runStatusType(status); -} - - - -void UDPStandardImplementation::startReadout(){ - if(status == RUNNING){ - - // wait for incoming delayed packets - //current packets caught - volatile int totalP = 0,prev=-1; - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - totalP += (*it)->GetPacketsCaught(); - - //wait for all packets - if((unsigned long long int)totalP!=numberOfFrames*generalData->packetsPerFrame*listener.size()){ - - //wait as long as there is change from prev totalP, - while(prev != totalP){ -#ifdef VERY_VERBOSE - cprintf(MAGENTA,"waiting for all packets prevP:%d totalP:%d\n", - prev,totalP); - -#endif - //usleep(1*1000*1000);usleep(1*1000*1000);usleep(1*1000*1000);usleep(1*1000*1000); - usleep(5*1000);/* Need to find optimal time **/ - - prev = totalP; - totalP = 0; - - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - totalP += (*it)->GetPacketsCaught(); -#ifdef VERY_VERBOSE - cprintf(MAGENTA,"\tupdated: totalP:%d\n",totalP); -#endif - } - } - - - //set status - status = TRANSMITTING; - FILE_LOG(logINFO) << "Status: Transmitting"; - } - //shut down udp sockets so as to make listeners push dummy (end) packets for processors - shutDownUDPSockets(); -} - - -void UDPStandardImplementation::shutDownUDPSockets() { - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - (*it)->ShutDownUDPSocket(); -} - - - -void UDPStandardImplementation::closeFiles() { - uint64_t maxIndexCaught = 0; - bool anycaught = false; - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) { - (*it)->CloseFiles(); - maxIndexCaught = std::max(maxIndexCaught, (*it)->GetProcessedMeasurementIndex()); - if((*it)->GetMeasurementStartedFlag()) - anycaught = true; - } - //to create virtual file & set files/acquisition to 0 (only hdf5 at the moment) - dataProcessor[0]->EndofAcquisition(anycaught, maxIndexCaught); -} - -int UDPStandardImplementation::setUDPSocketBufferSize(const uint32_t s) { - if (listener.size()) - return listener[0]->CreateDummySocketForUDPSocketBufferSize(s); - return FAIL; -} - -int UDPStandardImplementation::restreamStop() { - bool ret = OK; - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) { - if ((*it)->RestreamStop() == FAIL) - ret = FAIL; - } - - // if fail, prints in datastreamer - if (ret == OK) { - FILE_LOG(logINFO) << "Restreaming Dummy Header via ZMQ successful"; - } - - return ret; -} - - -void UDPStandardImplementation::SetLocalNetworkParameters() { - - // to increase Max length of input packet queue - int max_back_log; - const char *proc_file_name = "/proc/sys/net/core/netdev_max_backlog"; - { - std::ifstream proc_file(proc_file_name); - proc_file >> max_back_log; - } - - if (max_back_log < MAX_SOCKET_INPUT_PACKET_QUEUE) { - std::ofstream proc_file(proc_file_name); - if (proc_file.good()) { - proc_file << MAX_SOCKET_INPUT_PACKET_QUEUE << std::endl; - cprintf(GREEN, "Max length of input packet queue " - "[/proc/sys/net/core/netdev_max_backlog] modified to %d\n", - MAX_SOCKET_INPUT_PACKET_QUEUE); - } else { - const char *msg = "Could not change max length of " - "input packet queue [net.core.netdev_max_backlog]. (No Root Privileges?)"; - FILE_LOG(logWARNING) << msg; - } - } -} - - - -void UDPStandardImplementation::SetThreadPriorities() { - - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it){ - if ((*it)->SetThreadPriority(LISTENER_PRIORITY) == FAIL) { - FILE_LOG(logWARNING) << "Could not prioritize listener threads. (No Root Privileges?)"; - return; - } - } - std::ostringstream osfn; - osfn << "Priorities set - " - "Listener:" << LISTENER_PRIORITY; - - FILE_LOG(logINFO) << osfn.str(); -} - - -int UDPStandardImplementation::SetupFifoStructure() { - numberofJobs = 1; - - - for (std::vector::const_iterator it = fifo.begin(); it != fifo.end(); ++it) - delete(*it); - fifo.clear(); - for ( int i = 0; i < numThreads; ++i ) { - - //create fifo structure - try { - Fifo* f = new Fifo (i, - (generalData->imageSize) * numberofJobs + (generalData->fifoBufferHeaderSize), - fifoDepth); - fifo.push_back(f); - } catch (...) { - cprintf(RED,"Error: Could not allocate memory for fifo structure of index %d\n", i); - for (std::vector::const_iterator it = fifo.begin(); it != fifo.end(); ++it) - delete(*it); - fifo.clear(); - return FAIL; - } - //set the listener & dataprocessor threads to point to the right fifo - if(listener.size())listener[i]->SetFifo(fifo[i]); - if(dataProcessor.size())dataProcessor[i]->SetFifo(fifo[i]); - if(dataStreamer.size())dataStreamer[i]->SetFifo(fifo[i]); - } - - FILE_LOG(logINFO) << "Memory Allocated Per Fifo: " << ( ((generalData->imageSize) * numberofJobs + (generalData->fifoBufferHeaderSize)) * fifoDepth) << " bytes" ; - FILE_LOG(logINFO) << numThreads << " Fifo structure(s) reconstructed"; - return OK; -} - - - -void UDPStandardImplementation::ResetParametersforNewMeasurement() { - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) - (*it)->ResetParametersforNewMeasurement(); - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it) - (*it)->ResetParametersforNewMeasurement(); - - if (dataStreamEnable) { - char fnametostream[MAX_STR_LENGTH]; - snprintf(fnametostream, MAX_STR_LENGTH, "%s/%s", filePath, fileName); - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it) - (*it)->ResetParametersforNewMeasurement(fnametostream); - } -} - - - -int UDPStandardImplementation::CreateUDPSockets() { - bool error = false; - for (unsigned int i = 0; i < listener.size(); ++i) - if (listener[i]->CreateUDPSockets() == FAIL) { - error = true; - break; - } - if (error) { - shutDownUDPSockets(); - return FAIL; - } - - FILE_LOG(logDEBUG) << "UDP socket(s) created successfully."; - return OK; -} - - -int UDPStandardImplementation::SetupWriter() { - bool error = false; - for (unsigned int i = 0; i < dataProcessor.size(); ++i) - if (dataProcessor[i]->CreateNewFile(tengigaEnable, - numberOfFrames, acquisitionTime, subExpTime, subPeriod, acquisitionPeriod) == FAIL) { - error = true; - break; - } - if (error) { - shutDownUDPSockets(); - closeFiles(); - return FAIL; - } - - return OK; -} - - -void UDPStandardImplementation::StartRunning() { - //set running mask and post semaphore to start the inner loop in execution thread - for (std::vector::const_iterator it = listener.begin(); it != listener.end(); ++it) { - (*it)->StartRunning(); - (*it)->Continue(); - } - for (std::vector::const_iterator it = dataProcessor.begin(); it != dataProcessor.end(); ++it){ - (*it)->StartRunning(); - (*it)->Continue(); - } - for (std::vector::const_iterator it = dataStreamer.begin(); it != dataStreamer.end(); ++it){ - (*it)->StartRunning(); - (*it)->Continue(); - } -} diff --git a/slsReceiverSoftware/src/main.cpp b/slsReceiverSoftware/src/main.cpp old mode 100644 new mode 100755 index 2b2166d83..635298562 --- a/slsReceiverSoftware/src/main.cpp +++ b/slsReceiverSoftware/src/main.cpp @@ -1,17 +1,14 @@ /* A simple server in the internet domain using TCP The port number is passed as an argument */ -#include "sls_receiver_defs.h" +#include "sls_detector_defs.h" #include "slsReceiverUsers.h" +#include "logger.h" #include #include #include //SIGINT #include //system - -#include "utilities.h" -#include "logger.h" - #include //wait #include //wait #include //usleep @@ -24,37 +21,40 @@ void sigInterruptHandler(int p){ keeprunning = false; } +/** Define Colors to print data call back in different colors for different recievers */ /* -int StartAcq(char* filepath, char* filename, uint64_t fileindex, uint32_t datasize, void*p){ - printf("#### StartAcq: filepath:%s filename:%s fileindex:%llu datasize:%u ####\n", - filepath, filename, fileindex, datasize); +#define PRINT_IN_COLOR(c,f, ...) printf ("\033[%dm" f RESET, 30 + c+1, ##__VA_ARGS__) - cprintf(BLUE, "--StartAcq: returning 0\n"); +int StartAcq(char* filepath, char* filename, uint64_t fileindex, uint32_t datasize, void*p){ + FILE_LOG(logINFO) << "#### StartAcq: " + "filepath: " << filepath << "filename: " << filename << + "fileindex: " << fileindex << "datasize: " << datasize << " ####"; + FILE_LOG(logINFO) << "--StartAcq: returning 0"; return 0; } void AcquisitionFinished(uint64_t frames, void*p){ - cprintf(BLUE, "#### AcquisitionFinished: frames:%llu ####\n",frames); + FILE_LOG(logINFO) << "#### AcquisitionFinished: frames:" << frames << " ####"; } void GetData(char* metadata, char* datapointer, uint32_t datasize, void* p){ - slsReceiverDefs::sls_receiver_header* header = (slsReceiverDefs::sls_receiver_header*)metadata; - slsReceiverDefs::sls_detector_header detectorHeader = header->detHeader; + slsDetectorDefs::sls_receiver_header* header = (slsDetectorDefs::sls_receiver_header*)metadata; + slsDetectorDefs::sls_detector_header detectorHeader = header->detHeader; PRINT_IN_COLOR (detectorHeader.modId?detectorHeader.modId:detectorHeader.row, "#### %d GetData: ####\n" - "frameNumber: %llu\t\texpLength: %u\t\tpacketNumber: %u\t\tbunchId: %llu" - "\t\ttimestamp: %llu\t\tmodId: %u\t\t" - "xCrow%u\t\tcolumn: %u\t\tcolumn: %u\t\tdebug: %u" + "frameNumber: %lu\t\texpLength: %u\t\tpacketNumber: %u\t\tbunchId: %lu" + "\t\ttimestamp: %lu\t\tmodId: %u\t\t" + "row: %u\t\tcolumn: %u\t\treserved: %u\t\tdebug: %u" "\t\troundRNumber: %u\t\tdetType: %u\t\tversion: %u" //"\t\tpacketsMask:%s" "\t\tfirstbytedata: 0x%x\t\tdatsize: %u\n\n", - detectorHeader.row, detectorHeader.frameNumber, - detectorHeader.expLength, detectorHeader.packetNumber, detectorHeader.bunchId, - detectorHeader.timestamp, detectorHeader.modId, - detectorHeader.row, detectorHeader.column, detectorHeader.column, + detectorHeader.row, (long unsigned int)detectorHeader.frameNumber, + detectorHeader.expLength, detectorHeader.packetNumber, (long unsigned int)detectorHeader.bunchId, + (long unsigned int)detectorHeader.timestamp, detectorHeader.modId, + detectorHeader.row, detectorHeader.column, detectorHeader.reserved, detectorHeader.debug, detectorHeader.roundRNumber, detectorHeader.detType, detectorHeader.version, //header->packetsMask.to_string().c_str(), @@ -66,15 +66,15 @@ void GetData(char* metadata, char* datapointer, uint32_t datasize, void* p){ int main(int argc, char *argv[]) { keeprunning = true; - cprintf(BLUE,"Created [ Tid: %ld ]\n", (long)syscall(SYS_gettid)); + FILE_LOG(logINFOBLUE) << "Created [ Tid: " << syscall(SYS_gettid) << " ]"; // Catch signal SIGINT to close files and call destructors properly struct sigaction sa; sa.sa_flags=0; // no flags sa.sa_handler=sigInterruptHandler; // handler function sigemptyset(&sa.sa_mask); // dont block additional signals during invocation of handler - if (sigaction(SIGINT, &sa, NULL) == -1) { - cprintf(RED, "Could not set handler function for SIGINT\n"); + if (sigaction(SIGINT, &sa, nullptr) == -1) { + FILE_LOG(logERROR) << "Could not set handler function for SIGINT"; } @@ -84,16 +84,16 @@ int main(int argc, char *argv[]) { asa.sa_flags=0; // no flags asa.sa_handler=SIG_IGN; // handler function sigemptyset(&asa.sa_mask); // dont block additional signals during invocation of handler - if (sigaction(SIGPIPE, &asa, NULL) == -1) { - cprintf(RED, "Could not set handler function for SIGPIPE\n"); + if (sigaction(SIGPIPE, &asa, nullptr) == -1) { + FILE_LOG(logERROR) << "Could not set handler function for SIGPIPE"; } - int ret = slsReceiverDefs::OK; + int ret = slsDetectorDefs::OK; slsReceiverUsers *receiver = new slsReceiverUsers(argc, argv, ret); - if(ret==slsReceiverDefs::FAIL){ + if(ret==slsDetectorDefs::FAIL){ delete receiver; - cprintf(BLUE,"Exiting [ Tid: %ld ]\n", (long)syscall(SYS_gettid)); + FILE_LOG(logINFOBLUE) << "Exiting [ Tid: " << syscall(SYS_gettid) << " ]"; exit(EXIT_FAILURE); } @@ -140,20 +140,20 @@ int main(int argc, char *argv[]) { //start tcp server thread - if (receiver->start() == slsReceiverDefs::FAIL){ + if (receiver->start() == slsDetectorDefs::FAIL){ delete receiver; - cprintf(BLUE,"Exiting [ Tid: %ld ]\n", (long)syscall(SYS_gettid)); + FILE_LOG(logINFOBLUE) << "Exiting [ Tid: " << syscall(SYS_gettid) << " ]"; exit(EXIT_FAILURE); } FILE_LOG(logINFO) << "Ready ... "; - cprintf(RESET, "\n[ Press \'Ctrl+c\' to exit ]\n"); + FILE_LOG(logINFO) << "[ Press \'Ctrl+c\' to exit ]"; while(keeprunning) pause(); delete receiver; - cprintf(BLUE,"Exiting [ Tid: %ld ]\n", (long)syscall(SYS_gettid)); - FILE_LOG(logINFO) << "Goodbye!"; + FILE_LOG(logINFOBLUE) << "Exiting [ Tid: " << syscall(SYS_gettid) << " ]"; + FILE_LOG(logINFO) << "Exiting Receiver"; return 0; } diff --git a/slsReceiverSoftware/src/slsReceiver.cpp b/slsReceiverSoftware/src/slsReceiver.cpp old mode 100644 new mode 100755 index 06c81d01f..ea400b5c2 --- a/slsReceiverSoftware/src/slsReceiver.cpp +++ b/slsReceiverSoftware/src/slsReceiver.cpp @@ -11,31 +11,30 @@ #include #include +#include "container_utils.h" // For sls::make_unique<> + #include "slsReceiver.h" -#include "gitInfoReceiver.h" - - - +#include "slsReceiverTCPIPInterface.h" +#include "sls_detector_exceptions.h" +#include "versionAPI.h" +#include "logger.h" slsReceiver::slsReceiver(int argc, char *argv[]): - tcpipInterface (0) { + tcpipInterface (nullptr) { // options std::map configuration_map; int tcpip_port_no = 1954; - std::string fname = ""; - int64_t tempval = 0; //parse command line for config static struct option long_options[] = { // These options set a flag. //{"verbose", no_argument, &verbose_flag, 1}, // These options don’t set a flag. We distinguish them by their indices. - {"config", required_argument, 0, 'f'}, - {"rx_tcpport", required_argument, 0, 't'}, - {"version", no_argument, 0, 'v'}, - {"help", no_argument, 0, 'h'}, - {0, 0, 0, 0} + {"rx_tcpport", required_argument, nullptr, 't'}, + {"version", no_argument, nullptr, 'v'}, + {"help", no_argument, nullptr, 'h'}, + {nullptr, 0, nullptr, 0} }; //initialize global optind variable (required when instantiating multiple receivers in the same process) @@ -53,22 +52,13 @@ slsReceiver::slsReceiver(int argc, char *argv[]): switch(c){ - case 'f': - fname = optarg; -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG) << long_options[option_index].name << " " << optarg << endl; -#endif - break; - case 't': sscanf(optarg, "%d", &tcpip_port_no); break; case 'v': - tempval = GITREV; - tempval = (tempval <<32) | GITDATE; - std::cout << "SLS Receiver " << GITBRANCH << " (0x" << std::hex << tempval << ")" << std::endl; - throw std::exception(); + std::cout << "SLS Receiver " << GITBRANCH << " (0x" << std::hex << APIRECEIVER << ")" << std::endl; + throw sls::RuntimeError(); case 'h': default: @@ -76,30 +66,25 @@ slsReceiver::slsReceiver(int argc, char *argv[]): + std::string(argv[0]) + "\n" + "Usage: " + std::string(argv[0]) + " [arguments]\n" + "Possible arguments are:\n" - + "\t-f, --config : Loads config from file\n" + "\t-t, --rx_tcpport : TCP Communication Port with client. \n" + "\t Default: 1954. Required for multiple \n" + "\t receivers\n\n"; FILE_LOG(logINFO) << help_message << std::endl; - throw std::exception(); + throw sls::RuntimeError(); } } - if( !fname.empty() && read_config_file(fname, &tcpip_port_no, &configuration_map) == FAIL) { - throw std::exception(); - } - // might throw an exception - tcpipInterface = new slsReceiverTCPIPInterface(tcpip_port_no); - + tcpipInterface = sls::make_unique(tcpip_port_no); } -slsReceiver::~slsReceiver() { - if(tcpipInterface) - delete tcpipInterface; +slsReceiver::slsReceiver(int tcpip_port_no) +{ + // might throw an exception + tcpipInterface = sls::make_unique(tcpip_port_no); } diff --git a/slsReceiverSoftware/src/slsReceiverImplementation.cpp b/slsReceiverSoftware/src/slsReceiverImplementation.cpp new file mode 100755 index 000000000..2cf3801da --- /dev/null +++ b/slsReceiverSoftware/src/slsReceiverImplementation.cpp @@ -0,0 +1,1499 @@ +/********************************************//** + * @file slsReceiverImplementation.cpp + * @short does all the functions for a receiver, set/get parameters, start/stop etc. + ***********************************************/ + + +#include "slsReceiverImplementation.h" +#include "GeneralData.h" +#include "Listener.h" +#include "DataProcessor.h" +#include "DataStreamer.h" +#include "Fifo.h" +#include "ZmqSocket.h" //just for the zmq port define + +#include // stat +#include +#include +#include //system +#include //strcpy +#include //eperm +#include + + +/** cosntructor & destructor */ + +slsReceiverImplementation::slsReceiverImplementation() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + InitializeMembers(); +} + + +slsReceiverImplementation::~slsReceiverImplementation() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + DeleteMembers(); +} + + +void slsReceiverImplementation::DeleteMembers() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + if (generalData) { + delete generalData; + generalData=nullptr; + } + + listener.clear(); + dataProcessor.clear(); + dataStreamer.clear(); + fifo.clear(); +} + + +void slsReceiverImplementation::InitializeMembers() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + //**detector parameters*** + myDetectorType = GENERIC; + for (int i = 0; i < MAX_DIMENSIONS; ++i) + numDet[i] = 0; + detID = 0; + strcpy(detHostname,""); + acquisitionPeriod = SAMPLE_TIME_IN_NS; + acquisitionTime = 0; + subExpTime = 0; + subPeriod = 0; + numberOfFrames = 0; + numberOfSamples = 0; + dynamicRange = 16; + tengigaEnable = false; + fifoDepth = 0; + flippedData[0] = 0; + flippedData[1] = 0; + gapPixelsEnable = false; + readoutFlags = GET_READOUT_FLAGS; + + //*** receiver parameters *** + numThreads = 1; + status = IDLE; + activated = true; + deactivatedPaddingEnable = true; + frameDiscardMode = NO_DISCARD; + framePadding = false; + silentMode = false; + + //***connection parameters*** + numUDPInterfaces = 1; + for(int i=0;i 1) return -1; + return flippedData[axis]; +} + +bool slsReceiverImplementation::getGapPixelsEnable() const { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return gapPixelsEnable; +} + +slsDetectorDefs::readOutFlags slsReceiverImplementation::getReadOutFlags() const { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return readoutFlags; +} + + +/***file parameters***/ +slsDetectorDefs::fileFormat slsReceiverImplementation::getFileFormat() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return fileFormatType; +} + + +std::string slsReceiverImplementation::getFileName() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return std::string(fileName); +} + +std::string slsReceiverImplementation::getFilePath() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return std::string(filePath); +} + +uint64_t slsReceiverImplementation::getFileIndex() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return fileIndex; +} + +uint32_t slsReceiverImplementation::getFramesPerFile() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return framesPerFile; +} + +slsDetectorDefs::frameDiscardPolicy slsReceiverImplementation::getFrameDiscardPolicy() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return frameDiscardMode; +} + +bool slsReceiverImplementation::getFramePaddingEnable() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return framePadding; +} + + +bool slsReceiverImplementation::getFileWriteEnable() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return fileWriteEnable; +} + +bool slsReceiverImplementation::getOverwriteEnable() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return overwriteEnable; +} + + +/***acquisition count parameters***/ +uint64_t slsReceiverImplementation::getTotalFramesCaught() const { + uint64_t sum = 0; + uint32_t flagsum = 0; + + for (const auto& it : dataProcessor) { + flagsum += it->GetMeasurementStartedFlag(); + sum += it->GetNumTotalFramesCaught(); + } + //no data processed + if (flagsum != dataProcessor.size()) + return 0; + + return (sum/dataProcessor.size()); +} + +uint64_t slsReceiverImplementation::getFramesCaught() const { + uint64_t sum = 0; + uint32_t flagsum = 0; + + for (const auto& it : dataProcessor) { + flagsum += it->GetMeasurementStartedFlag(); + sum += it->GetNumFramesCaught(); + } + //no data processed + if (flagsum != dataProcessor.size()) + return 0; + + return (sum/dataProcessor.size()); +} + +int64_t slsReceiverImplementation::getAcquisitionIndex() const { + uint64_t sum = 0; + uint32_t flagsum = 0; + + for (const auto& it : dataProcessor) { + flagsum += it->GetMeasurementStartedFlag(); + sum += it->GetActualProcessedAcquisitionIndex(); + } + //no data processed + if (flagsum != dataProcessor.size()) + return -1; + + return (sum/dataProcessor.size()); +} + + + + +/***connection parameters***/ +uint32_t slsReceiverImplementation::getUDPPortNumber() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return udpPortNum[0]; +} + +uint32_t slsReceiverImplementation::getUDPPortNumber2() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return udpPortNum[1]; +} + +std::string slsReceiverImplementation::getEthernetInterface() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return std::string(eth[0]); +} + +std::string slsReceiverImplementation::getEthernetInterface2() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return std::string(eth[1]); +} + +int slsReceiverImplementation::getNumberofUDPInterfaces() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return numUDPInterfaces; +} + + +/***acquisition parameters***/ +std::vector slsReceiverImplementation::getROI() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return roi; +} + +uint32_t slsReceiverImplementation::getStreamingFrequency() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return streamingFrequency; +} + +uint32_t slsReceiverImplementation::getStreamingTimer() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return streamingTimerInMs; +} + +bool slsReceiverImplementation::getDataStreamEnable() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return dataStreamEnable; +} + +uint64_t slsReceiverImplementation::getAcquisitionPeriod() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return acquisitionPeriod; +} + +uint64_t slsReceiverImplementation::getAcquisitionTime() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return acquisitionTime; +} + +uint64_t slsReceiverImplementation::getSubExpTime() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return subExpTime; +} + +uint64_t slsReceiverImplementation::getSubPeriod() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return subPeriod; +} + +uint64_t slsReceiverImplementation::getNumberOfFrames() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return numberOfFrames; +} + +uint64_t slsReceiverImplementation::getNumberofSamples() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return numberOfSamples; +} + +uint32_t slsReceiverImplementation::getDynamicRange() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return dynamicRange;} + +bool slsReceiverImplementation::getTenGigaEnable() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return tengigaEnable; +} + +uint32_t slsReceiverImplementation::getFifoDepth() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return fifoDepth; +} + +/***receiver status***/ +slsDetectorDefs::runStatus slsReceiverImplementation::getStatus() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return status; +} + +bool slsReceiverImplementation::getSilentMode() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return silentMode; +} + +bool slsReceiverImplementation::getActivate() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return activated; +} + +bool slsReceiverImplementation::getDeactivatedPadding() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return deactivatedPaddingEnable; +} + +uint32_t slsReceiverImplementation::getStreamingPort() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return streamingPort; +} + +std::string slsReceiverImplementation::getStreamingSourceIP() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return std::string(streamingSrcIP); +} + +std::string slsReceiverImplementation::getAdditionalJsonHeader() const{ + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return std::string(additionalJsonHeader); +} + +int64_t slsReceiverImplementation::getUDPSocketBufferSize() const { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return udpSocketBufferSize; +} + +int64_t slsReceiverImplementation::getActualUDPSocketBufferSize() const { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + return actualUDPSocketBufferSize; +} + + +/************************************************************************* + * Setters *************************************************************** + * They modify the local cache of configuration or detector parameters *** + *************************************************************************/ + +/**initial parameters***/ + +void slsReceiverImplementation::setDetectorHostname(const char *c) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + if(strlen(c)) + strcpy(detHostname, c); + FILE_LOG(logINFO) << "Detector Hostname: " << detHostname; +} + + +void slsReceiverImplementation::setMultiDetectorSize(const int* size) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + std::string log_message = "Detector Size (ports): ("; + for (int i = 0; i < MAX_DIMENSIONS; ++i) { + // x dir (colums) each udp port + if (myDetectorType == EIGER && i == X) + numDet[i] = size[i] * 2; + // y dir (rows) each udp port + else if (numUDPInterfaces == 2 && i == Y) + numDet[i] = size[i] * 2; + else + numDet[i] = size[i]; + log_message += std::to_string(numDet[i]); + if (i < MAX_DIMENSIONS-1 ) + log_message += ", "; + } + log_message += ")"; + FILE_LOG(logINFO) << log_message; +} + + +void slsReceiverImplementation::setFlippedData(int axis, int enable) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + if(axis<0 || axis>1) + return; + flippedData[axis] = enable==0?0:1; + FILE_LOG(logINFO) << "Flipped Data: " << flippedData[0] << " , " << flippedData[1]; +} + + +int slsReceiverImplementation::setGapPixelsEnable(const bool b) { + if (gapPixelsEnable != b) { + gapPixelsEnable = b; + + // side effects + generalData->SetGapPixelsEnable(b, dynamicRange); + for (const auto& it : dataProcessor) + it->SetPixelDimension(); + if (SetupFifoStructure() == FAIL) + return FAIL; + } + FILE_LOG(logINFO) << "Gap Pixels Enable: " << gapPixelsEnable; + return OK; +} + + +int slsReceiverImplementation::setReadOutFlags(const readOutFlags f) { + if (readoutFlags != f) { + readoutFlags = f; + + // side effects + if (myDetectorType == CHIPTESTBOARD) { + generalData->setImageSize(roi, numberOfSamples, tengigaEnable, readoutFlags); + for (const auto& it : dataProcessor) + it->SetPixelDimension(); + if (SetupFifoStructure() == FAIL) + return FAIL; + } + } + std::string flag; + if (f == NORMAL_READOUT) + flag = "normal(analog, no digital)"; + else if (f & STORE_IN_RAM) + flag.append("storeinram "); + if (f & TOT_MODE) + flag.append("tot "); + if (f & CONTINOUS_RO) + flag.append("continous "); + if (f & PARALLEL) + flag.append("parallel "); + if (f & NONPARALLEL) + flag.append("nonparallel "); + if (f & SAFE) + flag.append("safe "); + if (f & DIGITAL_ONLY) + flag.append("digital "); + if (f & ANALOG_AND_DIGITAL) + flag.append("analog_digital "); + if (f & SHOW_OVERFLOW) + flag.append("overflow "); + if (f & NOOVERFLOW) + flag.append("nooverflow "); + + FILE_LOG(logINFO) << "ReadoutFlags: " << flag; + if (myDetectorType == CHIPTESTBOARD) { + FILE_LOG (logINFO) << "Packets per Frame: " << (generalData->packetsPerFrame); + } + return OK; +} + + +void slsReceiverImplementation::setFileFormat(const fileFormat f) { + switch(f) { +#ifdef HDF5C + case HDF5: + fileFormatType = HDF5; + break; +#endif + default: + fileFormatType = BINARY; + break; + } + + for(const auto& it : dataProcessor) + it->SetFileFormat(f); + + FILE_LOG(logINFO) << "File Format: " << getFileFormatType(fileFormatType); +} + + +void slsReceiverImplementation::setFileName(const char c[]) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + if(strlen(c)) + strcpy(fileName, c); + FILE_LOG(logINFO) << "File name: " << fileName; +} + + +void slsReceiverImplementation::setFilePath(const char c[]) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + + if(strlen(c)) { + //check if filepath exists + struct stat st; + if(stat(c,&st) == 0) + strcpy(filePath,c); + else + FILE_LOG(logERROR) << "FilePath does not exist: " << filePath; + } + FILE_LOG(logINFO) << "File path: " << filePath; +} + + +void slsReceiverImplementation::setFileIndex(const uint64_t i) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + fileIndex = i; + FILE_LOG(logINFO) << "File Index: " << fileIndex; +} + + +void slsReceiverImplementation::setFramesPerFile(const uint32_t i) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + framesPerFile = i; + FILE_LOG(logINFO) << "Frames per file: " << framesPerFile; +} + + +void slsReceiverImplementation::setFrameDiscardPolicy(const frameDiscardPolicy i) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + if (i >= 0 && i < NUM_DISCARD_POLICIES) + frameDiscardMode = i; + + FILE_LOG(logINFO) << "Frame Discard Policy: " << getFrameDiscardPolicyType(frameDiscardMode); +} + + +void slsReceiverImplementation::setFramePaddingEnable(const bool i) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + framePadding = i; + FILE_LOG(logINFO) << "Frame Padding: " << framePadding; +} + + +void slsReceiverImplementation::setFileWriteEnable(const bool b) { + if (fileWriteEnable != b) { + fileWriteEnable = b; + for (unsigned int i = 0; i < dataProcessor.size(); ++i) { + dataProcessor[i]->SetupFileWriter(fileWriteEnable, (int*)numDet, + &framesPerFile, fileName, filePath, &fileIndex, &overwriteEnable, + &detID, &numThreads, &numberOfFrames, &dynamicRange, &udpPortNum[i], + generalData); + } + } + + FILE_LOG(logINFO) << "File Write Enable: " << stringEnable(fileWriteEnable); +} + + +void slsReceiverImplementation::setOverwriteEnable(const bool b) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + overwriteEnable = b; + FILE_LOG(logINFO) << "Overwrite Enable: " << stringEnable(overwriteEnable); +} + + +/***connection parameters***/ +void slsReceiverImplementation::setUDPPortNumber(const uint32_t i) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + udpPortNum[0] = i; + FILE_LOG(logINFO) << "UDP Port Number[0]: " << udpPortNum[0]; +} + +void slsReceiverImplementation::setUDPPortNumber2(const uint32_t i) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + udpPortNum[1] = i; + FILE_LOG(logINFO) << "UDP Port Number[1]: " << udpPortNum[1]; +} + +void slsReceiverImplementation::setEthernetInterface(const char* c) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + strcpy(eth[0], c); + FILE_LOG(logINFO) << "Ethernet Interface: " << eth[0]; +} + +void slsReceiverImplementation::setEthernetInterface2(const char* c) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + strcpy(eth[1], c); + FILE_LOG(logINFO) << "Ethernet Interface 2: " << eth[1]; +} + +int slsReceiverImplementation::setNumberofUDPInterfaces(const int n) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + if (numUDPInterfaces != n) { + + // reduce number of detectors in y dir (rows) if it had 2 interfaces before + if (numUDPInterfaces == 2) + numDet[Y] /= 2; + + numUDPInterfaces = n; + + // clear all threads and fifos + listener.clear(); + dataProcessor.clear(); + dataStreamer.clear(); + fifo.clear(); + + // set local variables + generalData->SetNumberofInterfaces(n); + numThreads = generalData->threadsPerReceiver; + udpSocketBufferSize = generalData->defaultUdpSocketBufferSize; + + // fifo + if (SetupFifoStructure() == FAIL) + return FAIL; + + //create threads + for ( int i = 0; i < numThreads; ++i ) { + // listener and dataprocessor threads + try { + auto fifo_ptr = fifo[i].get(); + listener.push_back(sls::make_unique(i, myDetectorType, fifo_ptr, &status, + &udpPortNum[i], eth[i], &numberOfFrames, &dynamicRange, + &udpSocketBufferSize, &actualUDPSocketBufferSize, &framesPerFile, + &frameDiscardMode, &activated, &deactivatedPaddingEnable, &silentMode)); + listener[i]->SetGeneralData(generalData); + + dataProcessor.push_back(sls::make_unique(i, myDetectorType, fifo_ptr, &fileFormatType, + fileWriteEnable, &dataStreamEnable, &gapPixelsEnable, + &dynamicRange, &streamingFrequency, &streamingTimerInMs, + &framePadding, &activated, &deactivatedPaddingEnable, &silentMode)); + dataProcessor[i]->SetGeneralData(generalData); + } + catch (...) { + FILE_LOG(logERROR) << "Could not create listener/dataprocessor threads (index:" << i << ")"; + listener.clear(); + dataProcessor.clear(); + return FAIL; + } + // streamer threads + if (dataStreamEnable) { + try { + + dataStreamer.push_back(sls::make_unique(i, fifo[i].get(), &dynamicRange, + &roi, &fileIndex, flippedData, additionalJsonHeader)); + dataStreamer[i]->SetGeneralData(generalData); + dataStreamer[i]->CreateZmqSockets(&numThreads, streamingPort, streamingSrcIP); + + } catch(...) { + FILE_LOG(logERROR) << "Could not create datastreamer threads (index:" << i << ")"; + if (dataStreamEnable) { + dataStreamer.clear(); + dataStreamEnable = false; + } + return FAIL; + } + } + } + + SetThreadPriorities(); + + // update (from 1 to 2 interface) & also for printout + setMultiDetectorSize(numDet); + // update row and column in dataprocessor + setDetectorPositionId(detID); + + // test socket buffer size with current set up + if (setUDPSocketBufferSize(0) == FAIL) { + return FAIL; + } + } + + FILE_LOG(logINFO) << "Number of Interfaces: " << numUDPInterfaces; + return OK; +} + +int slsReceiverImplementation::setUDPSocketBufferSize(const int64_t s) { + int64_t size = (s == 0) ? udpSocketBufferSize : s; + size_t listSize = listener.size(); + + if (myDetectorType == JUNGFRAU && (int)listSize != numUDPInterfaces) { + FILE_LOG(logERROR) << "Number of Interfaces " << numUDPInterfaces << " do not match listener size " << listSize; + return FAIL; + } + + for (unsigned int i = 0; i < listSize; ++i) { + if (listener[i]->CreateDummySocketForUDPSocketBufferSize(size) == FAIL) + return FAIL; + } + + return OK; +} + + +/***acquisition parameters***/ +int slsReceiverImplementation::setROI(const std::vector new_roi) { + bool change = false; + if (roi.size() != new_roi.size()) + change = true; + else { + for (size_t i = 0; i != new_roi.size(); ++i) { + if ((roi[i].xmin != new_roi[i].xmin) || + (roi[i].xmax != new_roi[i].xmax) || + (roi[i].ymin != new_roi[i].ymin) || + (roi[i].xmax != new_roi[i].xmax)) { + change = true; + break; + } + } + } + + if (change) { + roi = new_roi; + switch (myDetectorType) { + case GOTTHARD: + generalData->SetROI(new_roi); + framesPerFile = generalData->maxFramesPerFile; + break; + case MOENCH: + generalData->setImageSize(roi, numberOfSamples, tengigaEnable); + break; + case CHIPTESTBOARD: + generalData->setImageSize(roi, numberOfSamples, tengigaEnable, + readoutFlags); + break; + default: + break; + } + for (const auto& it : dataProcessor) + it->SetPixelDimension(); + if (SetupFifoStructure() == FAIL) + return FAIL; + } + + + std::stringstream sstm; + sstm << "ROI: "; + if (!roi.size()) + sstm << "0"; + else { + for (size_t i = 0; i < roi.size(); ++i) { + sstm << "( " << + roi[i].xmin << ", " << + roi[i].xmax << ", " << + roi[i].ymin << ", " << + roi[i].ymax << " )"; + } + } + std::string message = sstm.str(); + FILE_LOG(logINFO) << message; + FILE_LOG (logINFO) << "Packets per Frame: " << (generalData->packetsPerFrame); + return OK; +} + + +int slsReceiverImplementation::setStreamingFrequency(const uint32_t freq) { + if (streamingFrequency != freq) { + streamingFrequency = freq; + } + FILE_LOG(logINFO) << "Streaming Frequency: " << streamingFrequency; + return OK; +} + +void slsReceiverImplementation::setStreamingTimer(const uint32_t time_in_ms) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + streamingTimerInMs = time_in_ms; + FILE_LOG(logINFO) << "Streamer Timer: " << streamingTimerInMs; +} + + +int slsReceiverImplementation::setDataStreamEnable(const bool enable) { + + if (dataStreamEnable != enable) { + dataStreamEnable = enable; + + //data sockets have to be created again as the client ones are + dataStreamer.clear(); + + if (enable) { + for ( int i = 0; i < numThreads; ++i ) { + try { + dataStreamer.push_back(sls::make_unique(i, fifo[i].get(), &dynamicRange, + &roi, &fileIndex, flippedData, additionalJsonHeader)); + dataStreamer[i]->SetGeneralData(generalData); + dataStreamer[i]->CreateZmqSockets(&numThreads, streamingPort, streamingSrcIP); + } + catch(...) { + dataStreamer.clear(); + dataStreamEnable = false; + return FAIL; + } + } + SetThreadPriorities(); + } + } + FILE_LOG(logINFO) << "Data Send to Gui: " << dataStreamEnable; + return OK; +} + + +void slsReceiverImplementation::setStreamingPort(const uint32_t i) { + streamingPort = i; + + FILE_LOG(logINFO) << "Streaming Port: " << streamingPort; +} + + +void slsReceiverImplementation::setStreamingSourceIP(const char c[]) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + strcpy(streamingSrcIP, c); + FILE_LOG(logINFO) << "Streaming Source IP: " << streamingSrcIP; +} + + +void slsReceiverImplementation::setAdditionalJsonHeader(const char c[]) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + strcpy(additionalJsonHeader, c); + FILE_LOG(logINFO) << "Additional JSON Header: " << additionalJsonHeader; +} + + +int slsReceiverImplementation::setAcquisitionPeriod(const uint64_t i) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + acquisitionPeriod = i; + FILE_LOG(logINFO) << "Acquisition Period: " << (double)acquisitionPeriod/(1E9) << "s"; + + return OK; +} + +int slsReceiverImplementation::setAcquisitionTime(const uint64_t i) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + acquisitionTime = i; + FILE_LOG(logINFO) << "Acquisition Time: " << (double)acquisitionTime/(1E9) << "s"; + + return OK; +} + +void slsReceiverImplementation::setSubExpTime(const uint64_t i) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + subExpTime = i; + FILE_LOG(logINFO) << "Sub Exposure Time: " << (double)subExpTime/(1E9) << "s"; +} + +void slsReceiverImplementation::setSubPeriod(const uint64_t i) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + subPeriod = i; + FILE_LOG(logINFO) << "Sub Exposure Period: " << (double)subPeriod/(1E9) << "s"; +} + +int slsReceiverImplementation::setNumberOfFrames(const uint64_t i) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + numberOfFrames = i; + FILE_LOG(logINFO) << "Number of Frames: " << numberOfFrames; + + return OK; +} + + +int slsReceiverImplementation::setNumberofSamples(const uint64_t i) { + if (numberOfSamples != i) { + numberOfSamples = i; + + if(myDetectorType == MOENCH) { + generalData->setImageSize(roi, numberOfSamples, tengigaEnable); + } else if(myDetectorType == CHIPTESTBOARD) { + generalData->setImageSize(roi, numberOfSamples, tengigaEnable, readoutFlags); + } + for (const auto& it : dataProcessor) + it->SetPixelDimension(); + if (SetupFifoStructure() == FAIL) + return FAIL; + } + FILE_LOG (logINFO) << "Number of Samples: " << numberOfSamples; + FILE_LOG (logINFO) << "Packets per Frame: " << (generalData->packetsPerFrame); + return OK; +} + + +int slsReceiverImplementation::setDynamicRange(const uint32_t i) { + // only eiger + if (dynamicRange != i) { + dynamicRange = i; + generalData->SetDynamicRange(i,tengigaEnable); + generalData->SetGapPixelsEnable(gapPixelsEnable, dynamicRange); + // to update npixelsx, npixelsy in file writer + for (const auto& it : dataProcessor) + it->SetPixelDimension(); + if (SetupFifoStructure() == FAIL) + return FAIL; + } + FILE_LOG(logINFO) << "Dynamic Range: " << dynamicRange; + return OK; +} + + +int slsReceiverImplementation::setTenGigaEnable(const bool b) { + if (tengigaEnable != b) { + tengigaEnable = b; + //side effects + switch(myDetectorType) { + case EIGER: + generalData->SetTenGigaEnable(b,dynamicRange); + break; + case MOENCH: + generalData->setImageSize(roi, numberOfSamples, tengigaEnable); + break; + case CHIPTESTBOARD: + generalData->setImageSize(roi, numberOfSamples, tengigaEnable, readoutFlags); + break; + default: + break; + } + + if (SetupFifoStructure() == FAIL) + return FAIL; + } + FILE_LOG(logINFO) << "Ten Giga: " << stringEnable(tengigaEnable); + FILE_LOG (logINFO) << "Packets per Frame: " << (generalData->packetsPerFrame); + return OK; +} + + +int slsReceiverImplementation::setFifoDepth(const uint32_t i) { + if (fifoDepth != i) { + fifoDepth = i; + if (SetupFifoStructure() == FAIL) + return FAIL; + } + FILE_LOG(logINFO) << "Fifo Depth: " << i; + return OK; +} + + +/***receiver parameters***/ +bool slsReceiverImplementation::setActivate(bool enable) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + activated = enable; + FILE_LOG(logINFO) << "Activation: " << stringEnable(activated); + return activated; +} + + +bool slsReceiverImplementation::setDeactivatedPadding(bool enable) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + deactivatedPaddingEnable = enable; + FILE_LOG(logINFO) << "Deactivated Padding Enable: " << stringEnable(deactivatedPaddingEnable); + return deactivatedPaddingEnable; +} + +void slsReceiverImplementation::setSilentMode(const bool i) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + silentMode = i; + FILE_LOG(logINFO) << "Silent Mode: " << i; +} + + +/************************************************************************* + * Behavioral functions*************************************************** + * They may modify the status of the receiver **************************** + *************************************************************************/ + + +/***initial functions***/ +int slsReceiverImplementation::setDetectorType(const detectorType d) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + DeleteMembers(); + InitializeMembers(); + myDetectorType = d; + switch(myDetectorType) { + case GOTTHARD: + case EIGER: + case JUNGFRAU: + case CHIPTESTBOARD: + case MOENCH: + FILE_LOG(logINFO) << " ***** " << detectorTypeToString(d) << " Receiver *****"; + break; + default: + FILE_LOG(logERROR) << "This is an unknown receiver type " << (int)d; + return FAIL; + } + + + //set detector specific variables + switch(myDetectorType) { + case GOTTHARD: generalData = new GotthardData(); break; + case EIGER: generalData = new EigerData(); break; + case JUNGFRAU: generalData = new JungfrauData(); break; + case CHIPTESTBOARD: generalData = new ChipTestBoardData(); break; + case MOENCH: generalData = new MoenchData(); break; + default: break; + } + numThreads = generalData->threadsPerReceiver; + fifoDepth = generalData->defaultFifoDepth; + udpSocketBufferSize = generalData->defaultUdpSocketBufferSize; + framesPerFile = generalData->maxFramesPerFile; + + SetLocalNetworkParameters(); + if (SetupFifoStructure() == FAIL) { + FILE_LOG(logERROR) << "Could not allocate memory for fifo structure"; + return FAIL; + } + + //create threads + for ( int i = 0; i < numThreads; ++i ) { + + try { + auto fifo_ptr = fifo[i].get(); + listener.push_back(sls::make_unique(i, myDetectorType, fifo_ptr, &status, + &udpPortNum[i], eth[i], &numberOfFrames, &dynamicRange, + &udpSocketBufferSize, &actualUDPSocketBufferSize, &framesPerFile, + &frameDiscardMode, &activated, &deactivatedPaddingEnable, &silentMode)); + dataProcessor.push_back(sls::make_unique(i, myDetectorType, fifo_ptr, &fileFormatType, + fileWriteEnable, &dataStreamEnable, &gapPixelsEnable, + &dynamicRange, &streamingFrequency, &streamingTimerInMs, + &framePadding, &activated, &deactivatedPaddingEnable, &silentMode)); + } + catch (...) { + FILE_LOG(logERROR) << "Could not create listener/dataprocessor threads (index:" << i << ")"; + listener.clear(); + dataProcessor.clear(); + return FAIL; + } + } + + //set up writer and callbacks + + for (const auto& it : listener) + it->SetGeneralData(generalData); + for (const auto& it : dataProcessor) + it->SetGeneralData(generalData); + SetThreadPriorities(); + + FILE_LOG(logDEBUG) << " Detector type set to " << detectorTypeToString(d); + return OK; +} + + + + +void slsReceiverImplementation::setDetectorPositionId(const int id) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + detID = id; + FILE_LOG(logINFO) << "Detector Position Id:" << detID; + for (unsigned int i = 0; i < dataProcessor.size(); ++i) { + dataProcessor[i]->SetupFileWriter(fileWriteEnable, (int*)numDet, + &framesPerFile, fileName, filePath, &fileIndex, &overwriteEnable, + &detID, &numThreads, &numberOfFrames, &dynamicRange, &udpPortNum[i], + generalData); + } + + for (unsigned int i = 0; i < listener.size(); ++i) { + uint16_t row = 0, col = 0; + row = (detID % numDet[1]) * ((numUDPInterfaces == 2) ? 2 : 1); // row + col = (detID / numDet[1]) * ((myDetectorType == EIGER) ? 2 : 1) + i; // col for horiz. udp ports + listener[i]->SetHardCodedPosition(row, col); + } +} + + +/***acquisition functions***/ +void slsReceiverImplementation::resetAcquisitionCount() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + for (const auto& it : listener) + it->ResetParametersforNewAcquisition(); + for (const auto& it : dataProcessor) + it->ResetParametersforNewAcquisition(); + for (const auto& it: dataStreamer) + it->ResetParametersforNewAcquisition(); + + FILE_LOG(logINFO) << "Acquisition Count has been reset"; +} + + + +int slsReceiverImplementation::startReceiver(char *c) { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + FILE_LOG(logINFO) << "Starting Receiver"; + ResetParametersforNewMeasurement(); + + //listener + if (CreateUDPSockets() == FAIL) { + strcpy(c,"Could not create UDP Socket(s)."); + FILE_LOG(logERROR) << c; + return FAIL; + } + + //callbacks + if (startAcquisitionCallBack) { + startAcquisitionCallBack(filePath, fileName, fileIndex, + (generalData->imageSize) + (generalData->fifoBufferHeaderSize), pStartAcquisition); + if (rawDataReadyCallBack != nullptr) { + FILE_LOG(logINFO) << "Data Write has been defined externally"; + } + } + + //processor->writer + if (fileWriteEnable) { + if (SetupWriter() == FAIL) { + strcpy(c,"Could not create file.\n"); + FILE_LOG(logERROR) << c; + return FAIL; + } + } else + FILE_LOG(logINFO) << "File Write Disabled"; + + FILE_LOG(logINFO) << "Ready ..."; + + //status + status = RUNNING; + + //Let Threads continue to be ready for acquisition + StartRunning(); + + FILE_LOG(logINFO) << "Receiver Started"; + FILE_LOG(logINFO) << "Status: " << runStatusType(status); + return OK; +} + + + +void slsReceiverImplementation::stopReceiver() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + FILE_LOG(logINFO) << "Stopping Receiver"; + + //set status to transmitting + startReadout(); + + //wait for the processes (Listener and DataProcessor) to be done + bool running = true; + while(running) { + running = false; + for (const auto& it : listener) + if (it->IsRunning()) + running = true; + + for (const auto& it : dataProcessor) + if (it->IsRunning()) + running = true; + usleep(5000); + } + + + //create virtual file + if (fileWriteEnable && fileFormatType == HDF5) { + uint64_t maxIndexCaught = 0; + bool anycaught = false; + for (const auto& it : dataProcessor) { + maxIndexCaught = std::max(maxIndexCaught, it->GetProcessedMeasurementIndex()); + if(it->GetMeasurementStartedFlag()) + anycaught = true; + } + //to create virtual file & set files/acquisition to 0 (only hdf5 at the moment) + dataProcessor[0]->EndofAcquisition(anycaught, maxIndexCaught); + } + + //wait for the processes (DataStreamer) to be done + running = true; + while(running) { + running = false; + for (const auto& it : dataStreamer) + if (it->IsRunning()) + running = true; + usleep(5000); + } + + status = RUN_FINISHED; + FILE_LOG(logINFO) << "Status: " << runStatusType(status); + + + { //statistics + uint64_t tot = 0; + for (int i = 0; i < numThreads; i++) { + tot += dataProcessor[i]->GetNumFramesCaught(); + + int64_t missingpackets = numberOfFrames*generalData->packetsPerFrame-listener[i]->GetPacketsCaught(); + TLogLevel lev = (((int64_t)missingpackets) > 0) ? logINFORED : logINFOGREEN; + FILE_LOG(lev) << + // udp port number could be the second if selected interface is 2 for jungfrau + "Summary of Port " << udpPortNum[i] << + "\n\tMissing Packets\t\t: " << missingpackets << + "\n\tComplete Frames\t\t: " << dataProcessor[i]->GetNumFramesCaught() << + "\n\tLast Frame Caught\t: " << listener[i]->GetLastFrameIndexCaught(); + } + if(!activated) { + FILE_LOG(logINFORED) << "Deactivated Receiver"; + } + //callback + if (acquisitionFinishedCallBack) + acquisitionFinishedCallBack((tot/numThreads), pAcquisitionFinished); + } + + //change status + status = IDLE; + + FILE_LOG(logINFO) << "Receiver Stopped"; + FILE_LOG(logINFO) << "Status: " << runStatusType(status); +} + + + +void slsReceiverImplementation::startReadout() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + if(status == RUNNING) { + // wait for incoming delayed packets + int totalPacketsReceived = 0; + int previousValue=-1; + for(const auto& it : listener) + totalPacketsReceived += it->GetPacketsCaught(); + + //wait for all packets + const int numPacketsToReceive = numberOfFrames * generalData->packetsPerFrame * listener.size(); + if(totalPacketsReceived != numPacketsToReceive) { + while(totalPacketsReceived != previousValue) { + FILE_LOG(logDEBUG3) << "waiting for all packets, previousValue:" << previousValue << + " totalPacketsReceived: " << totalPacketsReceived; + usleep(5*1000);/* TODO! Need to find optimal time **/ + previousValue = totalPacketsReceived; + totalPacketsReceived = 0; + for(const auto& it : listener) + totalPacketsReceived += it->GetPacketsCaught(); + + FILE_LOG(logDEBUG3) << "\tupdated: totalPacketsReceived:" << totalPacketsReceived; + } + } + status = TRANSMITTING; + FILE_LOG(logINFO) << "Status: Transmitting"; + } + //shut down udp sockets to make listeners push dummy (end) packets for processors + shutDownUDPSockets(); +} + + +void slsReceiverImplementation::shutDownUDPSockets() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + for (const auto& it : listener) + it->ShutDownUDPSocket(); +} + + + +void slsReceiverImplementation::closeFiles() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + uint64_t maxIndexCaught = 0; + bool anycaught = false; + for (const auto& it : dataProcessor) { + it->CloseFiles(); + maxIndexCaught = std::max(maxIndexCaught, it->GetProcessedMeasurementIndex()); + if(it->GetMeasurementStartedFlag()) + anycaught = true; + } + //to create virtual file & set files/acquisition to 0 (only hdf5 at the moment) + dataProcessor[0]->EndofAcquisition(anycaught, maxIndexCaught); +} + + +int slsReceiverImplementation::restreamStop() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + bool ret = OK; + for (const auto& it : dataStreamer) { + if (it->RestreamStop() == FAIL) + ret = FAIL; + } + // if fail, prints in datastreamer + if (ret == OK) { + FILE_LOG(logINFO) << "Restreaming Dummy Header via ZMQ successful"; + } + + return ret; +} + + + +/***callback functions***/ +void slsReceiverImplementation::registerCallBackStartAcquisition(int (*func)(char*, char*, uint64_t, uint32_t, void*),void *arg) { + startAcquisitionCallBack=func; + pStartAcquisition=arg; +} + +void slsReceiverImplementation::registerCallBackAcquisitionFinished(void (*func)(uint64_t, void*),void *arg) { + acquisitionFinishedCallBack=func; + pAcquisitionFinished=arg; +} + +void slsReceiverImplementation::registerCallBackRawDataReady(void (*func)(char* , + char*, uint32_t, void*),void *arg) { + rawDataReadyCallBack=func; + pRawDataReady=arg; + for (const auto& it : dataProcessor) + it->registerCallBackRawDataReady(rawDataReadyCallBack,pRawDataReady); +} + +void slsReceiverImplementation::registerCallBackRawDataModifyReady(void (*func)(char* , + char*, uint32_t&, void*),void *arg) { + rawDataModifyReadyCallBack=func; + pRawDataReady=arg; + for (const auto& it : dataProcessor) + it->registerCallBackRawDataModifyReady(rawDataModifyReadyCallBack,pRawDataReady); +} + + +void slsReceiverImplementation::SetLocalNetworkParameters() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + // to increase Max length of input packet queue + int max_back_log; + const char *proc_file_name = "/proc/sys/net/core/netdev_max_backlog"; + { + std::ifstream proc_file(proc_file_name); + proc_file >> max_back_log; + } + + if (max_back_log < MAX_SOCKET_INPUT_PACKET_QUEUE) { + std::ofstream proc_file(proc_file_name); + if (proc_file.good()) { + proc_file << MAX_SOCKET_INPUT_PACKET_QUEUE << std::endl; + FILE_LOG(logINFOBLUE) << "Max length of input packet queue " + "[/proc/sys/net/core/netdev_max_backlog] modified to " << + MAX_SOCKET_INPUT_PACKET_QUEUE; + } else { + FILE_LOG(logWARNING) << "Could not change max length of " + "input packet queue [net.core.netdev_max_backlog]. (No Root Privileges?)"; + } + } +} + + + +void slsReceiverImplementation::SetThreadPriorities() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + for (const auto& it : listener) { + if (it->SetThreadPriority(LISTENER_PRIORITY) == FAIL) { + FILE_LOG(logWARNING) << "Could not prioritize listener threads. (No Root Privileges?)"; + return; + } + } + std::ostringstream osfn; + osfn << "Priorities set - " + "Listener:" << LISTENER_PRIORITY; + + FILE_LOG(logINFO) << osfn.str(); +} + + +int slsReceiverImplementation::SetupFifoStructure() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + fifo.clear(); + for ( int i = 0; i < numThreads; ++i ) { + + //create fifo structure + try { + fifo.push_back(sls::make_unique(i, + (generalData->imageSize) + (generalData->fifoBufferHeaderSize), + fifoDepth)); + } catch (...) { + FILE_LOG(logERROR) << "Could not allocate memory for fifo structure of index " << i; + fifo.clear(); + return FAIL; + } + //set the listener & dataprocessor threads to point to the right fifo + if(listener.size())listener[i]->SetFifo(fifo[i].get()); + if(dataProcessor.size())dataProcessor[i]->SetFifo(fifo[i].get()); + if(dataStreamer.size())dataStreamer[i]->SetFifo(fifo[i].get()); + } + + FILE_LOG(logINFO) << "Memory Allocated Per Fifo: " << ( ((generalData->imageSize) + (generalData->fifoBufferHeaderSize)) * fifoDepth) << " bytes" ; + FILE_LOG(logINFO) << numThreads << " Fifo structure(s) reconstructed"; + return OK; +} + + + +void slsReceiverImplementation::ResetParametersforNewMeasurement() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + + for (const auto& it : listener) + it->ResetParametersforNewMeasurement(); + for (const auto& it : dataProcessor) + it->ResetParametersforNewMeasurement(); + + if (dataStreamEnable) { + char fnametostream[MAX_STR_LENGTH*2]; + snprintf(fnametostream, MAX_STR_LENGTH*2, "%s/%s", filePath, fileName); + for (const auto& it : dataStreamer) + it->ResetParametersforNewMeasurement(fnametostream); + } +} + + + +int slsReceiverImplementation::CreateUDPSockets() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + bool error = false; + + for (unsigned int i = 0; i < listener.size(); ++i) { + if (listener[i]->CreateUDPSockets() == FAIL) { + error = true; + break; + } + } + + + if (error) { + shutDownUDPSockets(); + return FAIL; + } + + FILE_LOG(logDEBUG) << "UDP socket(s) created successfully."; + return OK; +} + + +int slsReceiverImplementation::SetupWriter() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + bool error = false; + for (unsigned int i = 0; i < dataProcessor.size(); ++i) + if (dataProcessor[i]->CreateNewFile(tengigaEnable, + numberOfFrames, acquisitionTime, subExpTime, subPeriod, acquisitionPeriod) == FAIL) { + error = true; + break; + } + if (error) { + shutDownUDPSockets(); + closeFiles(); + return FAIL; + } + + return OK; +} + + +void slsReceiverImplementation::StartRunning() { + FILE_LOG(logDEBUG3) << __SHORT_AT__ << " called"; + //set running mask and post semaphore to start the inner loop in execution thread + for (const auto& it : listener) { + it->StartRunning(); + it->Continue(); + } + for (const auto& it : dataProcessor) { + it->StartRunning(); + it->Continue(); + } + for (const auto& it : dataStreamer) { + it->StartRunning(); + it->Continue(); + } +} diff --git a/slsReceiverSoftware/src/slsReceiverTCPIPInterface.cpp b/slsReceiverSoftware/src/slsReceiverTCPIPInterface.cpp old mode 100644 new mode 100755 index fb1b82905..a64bc9d3b --- a/slsReceiverSoftware/src/slsReceiverTCPIPInterface.cpp +++ b/slsReceiverSoftware/src/slsReceiverTCPIPInterface.cpp @@ -4,8 +4,9 @@ ***********************************************/ #include "slsReceiverTCPIPInterface.h" -#include "UDPInterface.h" -#include "gitInfoReceiver.h" +#include "slsReceiverImplementation.h" +#include "MySocketTCP.h" +#include "ServerInterface.h" #include "slsReceiverUsers.h" #include "slsReceiver.h" #include "versionAPI.h" @@ -18,43 +19,47 @@ #include #include #include - - +#include +#include //unique_ptr slsReceiverTCPIPInterface::~slsReceiverTCPIPInterface() { stop(); if(mySock) { delete mySock; - mySock=NULL; + mySock=nullptr; } - if(receiverBase) - delete receiverBase; + if (interface) + delete interface; + if(receiver) + delete receiver; } slsReceiverTCPIPInterface::slsReceiverTCPIPInterface(int pn): myDetectorType(GOTTHARD), - receiverBase(0), + receiver(nullptr), ret(OK), fnum(-1), lockStatus(0), killTCPServerThread(0), tcpThreadCreated(false), portNumber(DEFAULT_PORTNO+2), - mySock(0) + mySock(nullptr), + interface(nullptr) { //***callback parameters*** - startAcquisitionCallBack = NULL; - pStartAcquisition = NULL; - acquisitionFinishedCallBack = NULL; - pAcquisitionFinished = NULL; - rawDataReadyCallBack = NULL; - rawDataModifyReadyCallBack = NULL; - pRawDataReady = NULL; + startAcquisitionCallBack = nullptr; + pStartAcquisition = nullptr; + acquisitionFinishedCallBack = nullptr; + pAcquisitionFinished = nullptr; + rawDataReadyCallBack = nullptr; + rawDataModifyReadyCallBack = nullptr; + pRawDataReady = nullptr; // create socket portNumber = (pn > 0 ? pn : DEFAULT_PORTNO + 2); MySocketTCP* m = new MySocketTCP(portNumber); mySock = m; + interface = new ServerInterface(mySock, -1, "Receiver"); //initialize variables strcpy(mySock->lastClientIP,"none"); @@ -63,17 +68,13 @@ slsReceiverTCPIPInterface::slsReceiverTCPIPInterface(int pn): strcpy(mess,"dummy message"); function_table(); -#ifdef VERYVERBOSE - FILE_LOG(logINFO) << "Function table assigned."; -#endif - } int slsReceiverTCPIPInterface::start(){ FILE_LOG(logDEBUG) << "Creating TCP Server Thread"; killTCPServerThread = 0; - if(pthread_create(&TCPServer_thread, NULL,startTCPServerThread, (void*) this)){ + if(pthread_create(&TCPServer_thread, nullptr,startTCPServerThread, (void*) this)){ FILE_LOG(logERROR) << "Could not create TCP Server thread"; return FAIL; } @@ -91,7 +92,7 @@ void slsReceiverTCPIPInterface::stop(){ killTCPServerThread = 1; if(mySock) mySock->ShutDownSocket(); FILE_LOG(logDEBUG) << "TCP Socket closed on port " << portNumber; - pthread_join(TCPServer_thread, NULL); + pthread_join(TCPServer_thread, nullptr); tcpThreadCreated = false; killTCPServerThread = 0; FILE_LOG(logDEBUG) << "Exiting TCP Server Thread on port " << portNumber; @@ -101,8 +102,7 @@ void slsReceiverTCPIPInterface::stop(){ int64_t slsReceiverTCPIPInterface::getReceiverVersion(){ - int64_t retval = GITDATE & 0xFFFFFF; - return retval; + return APIRECEIVER; } @@ -139,119 +139,42 @@ void* slsReceiverTCPIPInterface::startTCPServerThread(void *this_pointer){ void slsReceiverTCPIPInterface::startTCPServer(){ - cprintf(BLUE,"Created [ TCP server Tid: %ld ]\n", (long)syscall(SYS_gettid)); + FILE_LOG(logINFOBLUE) << "Created [ TCP server Tid: " << syscall(SYS_gettid) << "]";; FILE_LOG(logINFO) << "SLS Receiver starting TCP Server on port " << portNumber << std::endl; + int ret = OK; -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG5) << "Starting Receiver TCP Server"; -#endif - int v=OK; - - while(1) { -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG5); -#endif -#ifdef VERY_VERBOSE - FILE_LOG(logDEBUG5) << "Waiting for client call"; -#endif + while(true) { if(mySock->Connect() >= 0){ -#ifdef VERY_VERBOSE - FILE_LOG(logDEBUG5) << "Conenction accepted"; -#endif - // std::cout << "connected" << std::endl; - v = decode_function(); -#ifdef VERY_VERBOSE - FILE_LOG(logDEBUG5) << "function executed"; -#endif + ret = decode_function(); mySock->Disconnect(); -#ifdef VERY_VERBOSE - FILE_LOG(logDEBUG5) << "connection closed"; -#endif } //if tcp command was to exit server - if(v==GOODBYE){ + if(ret == GOODBYE){ FILE_LOG(logINFO) << "Shutting down UDP Socket"; - if(receiverBase){ - receiverBase->shutDownUDPSockets(); + if(receiver){ + receiver->shutDownUDPSockets(); } mySock->exitServer(); - cprintf(BLUE,"Exiting [ TCP server Tid: %ld ]\n", (long)syscall(SYS_gettid)); - pthread_exit(NULL); + FILE_LOG(logINFOBLUE) << "Exiting [ TCP server Tid: " << syscall(SYS_gettid) <<"]"; + pthread_exit(nullptr); } //if user entered exit if(killTCPServerThread) { - if (v != GOODBYE) { - if(receiverBase){ - receiverBase->shutDownUDPSockets(); + if (ret != GOODBYE) { + if(receiver){ + receiver->shutDownUDPSockets(); } } - cprintf(BLUE,"Exiting [ TCP server Tid: %ld ]\n", (long)syscall(SYS_gettid)); - pthread_exit(NULL); + FILE_LOG(logINFOBLUE) << "Exiting [ TCP server Tid: " << syscall(SYS_gettid) <<"]"; + pthread_exit(nullptr); } - } } -const char* slsReceiverTCPIPInterface::getFunctionName(enum recFuncs func) { - switch (func) { - case F_EXEC_RECEIVER_COMMAND: return "F_EXEC_RECEIVER_COMMAND"; - case F_EXIT_RECEIVER: return "F_EXIT_RECEIVER"; - case F_LOCK_RECEIVER: return "F_LOCK_RECEIVER"; - case F_GET_LAST_RECEIVER_CLIENT_IP: return "F_GET_LAST_RECEIVER_CLIENT_IP"; - case F_SET_RECEIVER_PORT: return "F_SET_RECEIVER_PORT"; - case F_UPDATE_RECEIVER_CLIENT: return "F_UPDATE_RECEIVER_CLIENT"; - case F_GET_RECEIVER_ID: return "F_GET_RECEIVER_ID"; - case F_GET_RECEIVER_TYPE: return "F_GET_RECEIVER_TYPE"; - case F_SEND_RECEIVER_DETHOSTNAME: return "F_SEND_RECEIVER_DETHOSTNAME"; - case F_RECEIVER_SET_ROI: return "F_RECEIVER_SET_ROI"; - case F_SETUP_RECEIVER_UDP: return "F_SETUP_RECEIVER_UDP"; - case F_SET_RECEIVER_TIMER: return "F_SET_RECEIVER_TIMER"; - case F_SET_RECEIVER_DYNAMIC_RANGE: return "F_SET_RECEIVER_DYNAMIC_RANGE"; - case F_READ_RECEIVER_FREQUENCY: return "F_READ_RECEIVER_FREQUENCY"; - case F_GET_RECEIVER_STATUS: return "F_GET_RECEIVER_STATUS"; - case F_START_RECEIVER: return "F_START_RECEIVER"; - case F_STOP_RECEIVER: return "F_STOP_RECEIVER"; - case F_START_RECEIVER_READOUT: return "F_START_RECEIVER_READOUT"; - case F_SET_RECEIVER_FILE_PATH: return "F_SET_RECEIVER_FILE_PATH"; - case F_SET_RECEIVER_FILE_NAME: return "F_SET_RECEIVER_FILE_NAME"; - case F_SET_RECEIVER_FILE_INDEX: return "F_SET_RECEIVER_FILE_INDEX"; - case F_GET_RECEIVER_FRAME_INDEX: return "F_GET_RECEIVER_FRAME_INDEX"; - case F_GET_RECEIVER_FRAMES_CAUGHT: return "F_GET_RECEIVER_FRAMES_CAUGHT"; - case F_RESET_RECEIVER_FRAMES_CAUGHT:return "F_RESET_RECEIVER_FRAMES_CAUGHT"; - case F_ENABLE_RECEIVER_FILE_WRITE: return "F_ENABLE_RECEIVER_FILE_WRITE"; - case F_ENABLE_RECEIVER_COMPRESSION: return "F_ENABLE_RECEIVER_COMPRESSION"; - case F_ENABLE_RECEIVER_OVERWRITE: return "F_ENABLE_RECEIVER_OVERWRITE"; - case F_ENABLE_RECEIVER_TEN_GIGA: return "F_ENABLE_RECEIVER_TEN_GIGA"; - case F_SET_RECEIVER_FIFO_DEPTH: return "F_SET_RECEIVER_FIFO_DEPTH"; - case F_RECEIVER_ACTIVATE: return "F_RECEIVER_ACTIVATE"; - case F_STREAM_DATA_FROM_RECEIVER: return "F_STREAM_DATA_FROM_RECEIVER"; - case F_READ_RECEIVER_TIMER: return "F_READ_RECEIVER_TIMER"; - case F_SET_FLIPPED_DATA_RECEIVER: return "F_SET_FLIPPED_DATA_RECEIVER"; - case F_SET_RECEIVER_FILE_FORMAT: return "F_SET_RECEIVER_FILE_FORMAT"; - case F_SEND_RECEIVER_DETPOSID: return "F_SEND_RECEIVER_DETPOSID"; - case F_SEND_RECEIVER_MULTIDETSIZE: return "F_SEND_RECEIVER_MULTIDETSIZE"; - case F_SET_RECEIVER_STREAMING_PORT: return "F_SET_RECEIVER_STREAMING_PORT"; - case F_SET_RECEIVER_SILENT_MODE: return "F_SET_RECEIVER_SILENT_MODE"; - case F_RECEIVER_STREAMING_SRC_IP: return "F_RECEIVER_STREAMING_SRC_IP"; - case F_ENABLE_GAPPIXELS_IN_RECEIVER:return "F_ENABLE_GAPPIXELS_IN_RECEIVER"; - case F_RESTREAM_STOP_FROM_RECEIVER: return "F_RESTREAM_STOP_FROM_RECEIVER"; - case F_ADDITIONAL_JSON_HEADER: return "F_ADDITIONAL_JSON_HEADER"; - case F_RECEIVER_UDP_SOCK_BUF_SIZE: return "F_RECEIVER_UDP_SOCK_BUF_SIZE"; - case F_RECEIVER_REAL_UDP_SOCK_BUF_SIZE: return "F_RECEIVER_REAL_UDP_SOCK_BUF_SIZE"; - case F_SET_RECEIVER_FRAMES_PER_FILE:return "F_SET_RECEIVER_FRAMES_PER_FILE"; - case F_RECEIVER_CHECK_VERSION: return "F_RECEIVER_CHECK_VERSION"; - case F_RECEIVER_DISCARD_POLICY: return "F_RECEIVER_DISCARD_POLICY"; - case F_RECEIVER_PADDING_ENABLE: return "F_RECEIVER_PADDING_ENABLE"; - case F_RECEIVER_DEACTIVATED_PADDING_ENABLE: return "F_RECEIVER_DEACTIVATED_PADDING_ENABLE"; - - default: return "Unknown Function"; - } -} - int slsReceiverTCPIPInterface::function_table(){ @@ -268,11 +191,10 @@ int slsReceiverTCPIPInterface::function_table(){ flist[F_SETUP_RECEIVER_UDP] = &slsReceiverTCPIPInterface::setup_udp; flist[F_SET_RECEIVER_TIMER] = &slsReceiverTCPIPInterface::set_timer; flist[F_SET_RECEIVER_DYNAMIC_RANGE] = &slsReceiverTCPIPInterface::set_dynamic_range; - flist[F_READ_RECEIVER_FREQUENCY] = &slsReceiverTCPIPInterface::set_read_frequency; + flist[F_RECEIVER_STREAMING_FREQUENCY] = &slsReceiverTCPIPInterface::set_streaming_frequency; flist[F_GET_RECEIVER_STATUS] = &slsReceiverTCPIPInterface::get_status; flist[F_START_RECEIVER] = &slsReceiverTCPIPInterface::start_receiver; flist[F_STOP_RECEIVER] = &slsReceiverTCPIPInterface::stop_receiver; - flist[F_START_RECEIVER_READOUT] = &slsReceiverTCPIPInterface::start_readout; flist[F_SET_RECEIVER_FILE_PATH] = &slsReceiverTCPIPInterface::set_file_dir; flist[F_SET_RECEIVER_FILE_NAME] = &slsReceiverTCPIPInterface::set_file_name; flist[F_SET_RECEIVER_FILE_INDEX] = &slsReceiverTCPIPInterface::set_file_index; @@ -280,23 +202,23 @@ int slsReceiverTCPIPInterface::function_table(){ flist[F_GET_RECEIVER_FRAMES_CAUGHT] = &slsReceiverTCPIPInterface::get_frames_caught; flist[F_RESET_RECEIVER_FRAMES_CAUGHT] = &slsReceiverTCPIPInterface::reset_frames_caught; flist[F_ENABLE_RECEIVER_FILE_WRITE] = &slsReceiverTCPIPInterface::enable_file_write; - flist[F_ENABLE_RECEIVER_COMPRESSION] = &slsReceiverTCPIPInterface::enable_compression; flist[F_ENABLE_RECEIVER_OVERWRITE] = &slsReceiverTCPIPInterface::enable_overwrite; flist[F_ENABLE_RECEIVER_TEN_GIGA] = &slsReceiverTCPIPInterface::enable_tengiga; flist[F_SET_RECEIVER_FIFO_DEPTH] = &slsReceiverTCPIPInterface::set_fifo_depth; flist[F_RECEIVER_ACTIVATE] = &slsReceiverTCPIPInterface::set_activate; flist[F_STREAM_DATA_FROM_RECEIVER] = &slsReceiverTCPIPInterface::set_data_stream_enable; - flist[F_READ_RECEIVER_TIMER] = &slsReceiverTCPIPInterface::set_read_receiver_timer; + flist[F_RECEIVER_STREAMING_TIMER] = &slsReceiverTCPIPInterface::set_streaming_timer; flist[F_SET_FLIPPED_DATA_RECEIVER] = &slsReceiverTCPIPInterface::set_flipped_data; flist[F_SET_RECEIVER_FILE_FORMAT] = &slsReceiverTCPIPInterface::set_file_format; flist[F_SEND_RECEIVER_DETPOSID] = &slsReceiverTCPIPInterface::set_detector_posid; flist[F_SEND_RECEIVER_MULTIDETSIZE] = &slsReceiverTCPIPInterface::set_multi_detector_size; flist[F_SET_RECEIVER_STREAMING_PORT] = &slsReceiverTCPIPInterface::set_streaming_port; - flist[F_SET_RECEIVER_SILENT_MODE] = &slsReceiverTCPIPInterface::set_silent_mode; flist[F_RECEIVER_STREAMING_SRC_IP] = &slsReceiverTCPIPInterface::set_streaming_source_ip; + flist[F_SET_RECEIVER_SILENT_MODE] = &slsReceiverTCPIPInterface::set_silent_mode; flist[F_ENABLE_GAPPIXELS_IN_RECEIVER] = &slsReceiverTCPIPInterface::enable_gap_pixels; flist[F_RESTREAM_STOP_FROM_RECEIVER] = &slsReceiverTCPIPInterface::restream_stop; flist[F_ADDITIONAL_JSON_HEADER] = &slsReceiverTCPIPInterface::set_additional_json_header; + flist[F_GET_ADDITIONAL_JSON_HEADER] = &slsReceiverTCPIPInterface::get_additional_json_header; flist[F_RECEIVER_UDP_SOCK_BUF_SIZE] = &slsReceiverTCPIPInterface::set_udp_socket_buffer_size; flist[F_RECEIVER_REAL_UDP_SOCK_BUF_SIZE]= &slsReceiverTCPIPInterface::get_real_udp_socket_buffer_size; flist[F_SET_RECEIVER_FRAMES_PER_FILE] = &slsReceiverTCPIPInterface::set_frames_per_file; @@ -304,15 +226,14 @@ int slsReceiverTCPIPInterface::function_table(){ flist[F_RECEIVER_DISCARD_POLICY] = &slsReceiverTCPIPInterface::set_discard_policy; flist[F_RECEIVER_PADDING_ENABLE] = &slsReceiverTCPIPInterface::set_padding_enable; flist[F_RECEIVER_DEACTIVATED_PADDING_ENABLE] = &slsReceiverTCPIPInterface::set_deactivated_receiver_padding_enable; + flist[F_RECEIVER_SET_READOUT_FLAGS] = &slsReceiverTCPIPInterface::set_readout_flags; - -#ifdef VERYVERBOSE - for (int i = 0; i < NUM_REC_FUNCTIONS ; i++) { - FILE_LOG(logINFO) << "function fnum: " << i << " (" << getFunctionName((enum recFuncs)i) << ") located at " << (unsigned int)flist[i]; + for (int i = NUM_DET_FUNCTIONS + 1; i < NUM_REC_FUNCTIONS ; i++) { + FILE_LOG(logDEBUG1) << "function fnum: " << i << " (" << + getFunctionNameFromEnum((enum detFuncs)i) << ") located at " << flist[i]; } -#endif - return OK; + return OK; } @@ -320,90 +241,75 @@ int slsReceiverTCPIPInterface::function_table(){ int slsReceiverTCPIPInterface::decode_function(){ ret = FAIL; -#ifdef VERYVERBOSE - cprintf(RESET,"\n"); -#endif - FILE_LOG(logDEBUG1) << "waiting to receive data"; int n = mySock->ReceiveDataOnly(&fnum,sizeof(fnum)); if (n <= 0) { - FILE_LOG(logDEBUG1) << "ERROR reading from socket. " + FILE_LOG(logDEBUG3) << "Could not read socket. " "Received " << n << " bytes," << - "fnum:" << fnum << " " - "(" << getFunctionName((enum recFuncs)fnum) << ")"; + "fnum:" << fnum << " " + "(" << getFunctionNameFromEnum((enum detFuncs)fnum) << ")"; return FAIL; } else - FILE_LOG(logDEBUG1) << "Received " << n << " bytes"; + FILE_LOG(logDEBUG3) << "Received " << n << " bytes"; - FILE_LOG(logDEBUG1) << "calling function fnum: "<< fnum << " " - "(" << getFunctionName((enum recFuncs)fnum) << ") " - "located at " << flist[fnum]; - - if (fnum < REC_FUNC_START_INDEX || fnum >= NUM_REC_FUNCTIONS) { + if (fnum <= NUM_DET_FUNCTIONS || fnum >= NUM_REC_FUNCTIONS) { FILE_LOG(logERROR) << "Unknown function enum " << fnum; - ret=(this->M_nofunc)(); + ret = (this->M_nofunc)(); } else{ - ret=(this->*flist[fnum])(); - } - if (ret == FAIL) { - FILE_LOG(logERROR) << "Failed to execute function = " << fnum << " (" << getFunctionName((enum recFuncs)fnum) << ")"; + FILE_LOG(logDEBUG1) << "calling function fnum: "<< fnum << " " + "(" << getFunctionNameFromEnum((enum detFuncs)fnum) << ") " + "located at " << flist[fnum]; + ret = (this->*flist[fnum])(); + + if (ret == FAIL) { + FILE_LOG(logDEBUG1) << "Failed to execute function = " << fnum << " (" + << getFunctionNameFromEnum((enum detFuncs)fnum) << ")"; + } else FILE_LOG(logDEBUG1) << "Function " << + getFunctionNameFromEnum((enum detFuncs)fnum) << " executed OK"; } return ret; } - -int slsReceiverTCPIPInterface::printSocketReadError() { - FILE_LOG(logERROR) << "Reading from socket failed. Possible socket crash"; - return FAIL; -} - - -void slsReceiverTCPIPInterface::invalidReceiverObject() { - ret=FAIL; - strcpy(mess,"Receiver not set up. Please use rx_hostname first.\n"); - FILE_LOG(logERROR) << mess; -} - - -void slsReceiverTCPIPInterface::receiverlocked() { - ret = FAIL; - sprintf(mess,"Receiver locked by %s\n",mySock->lastClientIP); - FILE_LOG(logERROR) << mess; -} - - -void slsReceiverTCPIPInterface::receiverNotIdle() { - ret = FAIL; - sprintf(mess,"Can not execute %s when receiver is not idle\n", getFunctionName((enum recFuncs)fnum)); - FILE_LOG(logERROR) << mess; -} - void slsReceiverTCPIPInterface::functionNotImplemented() { ret = FAIL; - sprintf(mess, "Function (%s) is not implemented for this detector\n",getFunctionName((enum recFuncs)fnum)); + sprintf(mess, "Function (%s) is not implemented for this detector\n", + getFunctionNameFromEnum((enum detFuncs)fnum)); FILE_LOG(logERROR) << mess; } +void slsReceiverTCPIPInterface::modeNotImplemented(std::string modename, int mode) { + ret = FAIL; + sprintf(mess, "%s (%d) is not implemented for this detector\n", modename.c_str(), mode); + FILE_LOG(logERROR) << mess; +} -int slsReceiverTCPIPInterface::M_nofunc(){printf("111 \n"); +template +void slsReceiverTCPIPInterface::validate(T arg, T retval, std::string modename, numberMode hex) { + if (ret == OK && arg != -1 && retval != arg) { + ret = FAIL; + if (hex) + sprintf(mess, "Could not %s. Set 0x%x, but read 0x%x\n", + modename.c_str(), (unsigned int) arg, (unsigned int) retval); + else + sprintf(mess, "Could not %s. Set %d, but read %d\n", + modename.c_str(), (unsigned int) arg, (unsigned int) retval); + FILE_LOG(logERROR) << mess; + } +} + +int slsReceiverTCPIPInterface::M_nofunc(){ ret = FAIL; memset(mess, 0, sizeof(mess)); - int n = 0; // to receive any arguments + int n = 1; while (n > 0) - n = mySock->ReceiveDataOnly(mess,MAX_STR_LENGTH); + n = mySock->ReceiveDataOnly(mess, MAX_STR_LENGTH); - strcpy(mess,"Unrecognized Function. Please do not proceed.\n"); + sprintf(mess,"Unrecognized Function enum %d. Please do not proceed.\n", fnum); FILE_LOG(logERROR) << mess; - - // send ok / fail - mySock->SendDataOnly(&ret,sizeof(ret)); - // send return argument - mySock->SendDataOnly(mess,sizeof(mess)); - // return ok / fail - return ret; + return interface->Server_SendResult(false, ret, nullptr, 0, mess); } @@ -412,49 +318,46 @@ int slsReceiverTCPIPInterface::M_nofunc(){printf("111 \n"); int slsReceiverTCPIPInterface::exec_command() { ret = OK; memset(mess, 0, sizeof(mess)); - char cmd[MAX_STR_LENGTH]; - memset(cmd,0,sizeof(cmd)); - int sysret = 0; + char cmd[MAX_STR_LENGTH] = {0}; + char retval[MAX_STR_LENGTH] = {0}; - // receive arguments - if (mySock->ReceiveDataOnly(cmd,MAX_STR_LENGTH) < 0) - return printSocketReadError(); + // get args, return if socket crashed + if (interface->Server_ReceiveArg(ret, mess, cmd, MAX_STR_LENGTH) == FAIL) + return FAIL; + FILE_LOG(logINFO) << "Executing command (" << cmd << ")"; - // execute action -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG5) << "executing command " << cmd; -#endif - if (mySock->differentClients && lockStatus) - receiverlocked(); - else { - sysret=system(cmd); - //should be replaced by popen - if (sysret == 0) { - sprintf(mess,"Succeeded\n"); - } else { + // verify if receiver is unlocked + if (interface->Server_VerifyLock(ret, mess, lockStatus) == OK) { + + const size_t tempsize = 256; + std::array temp; + std::string sresult; + std::shared_ptr pipe(popen(cmd, "r"), pclose); + if (!pipe) { ret = FAIL; - sprintf(mess,"Executing Command failed\n"); + strcpy(mess, "Executing Command failed\n"); FILE_LOG(logERROR) << mess; + } else { + while (!feof(pipe.get())) { + if (fgets(temp.data(), tempsize, pipe.get()) != nullptr) + sresult += temp.data(); + } + strncpy(retval, sresult.c_str(), MAX_STR_LENGTH); + ret = OK; + FILE_LOG(logINFO) << "Result of cmd (" << cmd << "):\n" << retval; } } - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - mySock->SendDataOnly(mess,MAX_STR_LENGTH); - - // return ok/fail - return ret; + return interface->Server_SendResult(false, ret, retval, MAX_STR_LENGTH, mess); } int slsReceiverTCPIPInterface::exit_server() { - ret = GOODBYE; - strcpy(mess,"closing server"); - mySock->SendDataOnly(&ret,sizeof(ret)); - mySock->SendDataOnly(mess,sizeof(mess)); - cprintf(RED,"%s\n",mess); - return ret; + FILE_LOG(logINFO) << "Closing server"; + ret = OK; + memset(mess, 0, sizeof(mess)); + interface->Server_SendResult(false, ret, nullptr, 0); + return GOODBYE; } @@ -464,47 +367,31 @@ int slsReceiverTCPIPInterface::lock_receiver() { memset(mess, 0, sizeof(mess)); int lock = 0; - // receive arguments - if (mySock->ReceiveDataOnly(&lock,sizeof(lock)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed + if (interface->Server_ReceiveArg(ret, mess, &lock, sizeof(lock)) == FAIL) + return FAIL; + FILE_LOG(logDEBUG1) << "Locking Server to " << lock; // execute action if (lock >= 0) { - if (!lockStatus || (!strcmp(mySock->lastClientIP,mySock->thisClientIP)) || (!strcmp(mySock->lastClientIP,"none"))) { + if (!lockStatus || // if it was unlocked, anyone can lock + (!strcmp(mySock->lastClientIP,mySock->thisClientIP)) || // if it was locked, need same ip + (!strcmp(mySock->lastClientIP,"none"))) // if it was locked, must be by "none" + { lockStatus = lock; strcpy(mySock->lastClientIP,mySock->thisClientIP); } else - receiverlocked(); + interface->Server_LockedError(ret, mess); } - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - else - mySock->SendDataOnly(&lockStatus,sizeof(lockStatus)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &lockStatus,sizeof(lockStatus), mess); } int slsReceiverTCPIPInterface::get_last_client_ip() { ret = OK; - - if (mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - mySock->SendDataOnly(mySock->lastClientIP,sizeof(mySock->lastClientIP)); - - // return ok/fail - return ret; + memset(mess, 0, sizeof(mess)); + return interface->Server_SendResult(true, ret,mySock->lastClientIP, sizeof(mySock->lastClientIP)); } @@ -512,25 +399,17 @@ int slsReceiverTCPIPInterface::get_last_client_ip() { int slsReceiverTCPIPInterface::set_port() { ret = OK; memset(mess, 0, sizeof(mess)); - int p_type = 0; int p_number = -1; - MySocketTCP* mySocket = 0; - char oldLastClientIP[INET_ADDRSTRLEN]; - memset(oldLastClientIP, 0, sizeof(oldLastClientIP)); + MySocketTCP* mySocket = nullptr; + char oldLastClientIP[INET_ADDRSTRLEN] = {0}; - // receive arguments - if (mySock->ReceiveDataOnly(&p_type,sizeof(p_type)) < 0 ) - return printSocketReadError(); - if (mySock->ReceiveDataOnly(&p_number,sizeof(p_number)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed + if (interface->Server_ReceiveArg(ret, mess, &p_number, sizeof(p_number)) == FAIL) + return FAIL; - // execute action - if (mySock->differentClients && lockStatus) { - ret=FAIL; - sprintf(mess,"Detector locked by %s\n",mySock->lastClientIP); - FILE_LOG(logERROR) << mess; - } - else { + // verify if receiver is unlocked + if (interface->Server_VerifyLock(ret, mess, lockStatus) == OK) { + // port number too low if (p_number < 1024) { ret = FAIL; sprintf(mess,"Port Number (%d) too low\n", p_number); @@ -538,39 +417,31 @@ int slsReceiverTCPIPInterface::set_port() { } else { FILE_LOG(logINFO) << "set port to " << p_number <lastClientIP); - + // create new socket try { mySocket = new MySocketTCP(p_number); strcpy(mySock->lastClientIP,oldLastClientIP); - } catch(SamePortSocketException e) { + } catch(SocketError &e) { ret = FAIL; - sprintf(mess, "Could not bind port %d. It is already set\n", p_number); + // same socket, could not bind port + sprintf(mess, "%s", e.what()); FILE_LOG(logERROR) << mess; } catch (...) { ret = FAIL; - sprintf(mess, "Could not bind port %d.\n", p_number); + sprintf(mess, "Could not set port %d.\n", p_number); FILE_LOG(logERROR) << mess; } } } - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - else { - mySock->SendDataOnly(&p_number,sizeof(p_number)); - if(ret != FAIL){ - mySock->Disconnect(); - delete mySock; - mySock = mySocket; - } + interface->Server_SendResult(true, ret, &p_number,sizeof(p_number), mess); + // delete old socket + if(ret != FAIL){ + mySock->Disconnect(); + delete mySock; + mySock = mySocket; + interface->SetSocket(mySock); } - - // return ok/fail return ret; } @@ -579,17 +450,14 @@ int slsReceiverTCPIPInterface::set_port() { int slsReceiverTCPIPInterface::update_client() { ret = OK; memset(mess, 0, sizeof(mess)); - if (receiverBase == NULL) - invalidReceiverObject(); - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - //fail and force_update - if (ret != OK){ - mySock->SendDataOnly(mess,sizeof(mess)); - // return ok/fail + // no arg, check receiver is null + interface->Server_ReceiveArg(ret, mess, nullptr, 0, true, receiver); + + interface->Server_SendResult(false, ret, nullptr, 0, mess); + + if (ret == FAIL) return ret; - } // update return send_update(); @@ -598,138 +466,87 @@ int slsReceiverTCPIPInterface::update_client() { int slsReceiverTCPIPInterface::send_update() { - int ind = -1; - char defaultVal[MAX_STR_LENGTH]; - memset(defaultVal, 0, sizeof(defaultVal)); - char* path = NULL; int n = 0; + int i32 = -1; + char cstring[MAX_STR_LENGTH] = {0}; + n += mySock->SendDataOnly(mySock->lastClientIP,sizeof(mySock->lastClientIP)); // filepath -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - path = receiverBase->getFilePath(); -#endif - if (path == NULL) - n += mySock->SendDataOnly(defaultVal,MAX_STR_LENGTH); - else { - n += mySock->SendDataOnly(path,MAX_STR_LENGTH); - delete[] path; - } + strcpy(cstring, receiver->getFilePath().c_str()); + n += mySock->SendDataOnly(cstring, sizeof(cstring)); // filename -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - path = receiverBase->getFileName(); -#endif - if(path == NULL) - n += mySock->SendDataOnly(defaultVal,MAX_STR_LENGTH); - else { - n += mySock->SendDataOnly(path,MAX_STR_LENGTH); - delete[] path; - } + strcpy(cstring, receiver->getFileName().c_str()); + n += mySock->SendDataOnly(cstring, sizeof(cstring)); // index -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - ind=receiverBase->getFileIndex(); -#endif - n += mySock->SendDataOnly(&ind,sizeof(ind)); + i32=receiver->getFileIndex(); + n += mySock->SendDataOnly(&i32, sizeof(i32)); //file format -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - ind=(int)receiverBase->getFileFormat(); -#endif - n += mySock->SendDataOnly(&ind,sizeof(ind)); + i32=(int)receiver->getFileFormat(); + n += mySock->SendDataOnly(&i32, sizeof(i32)); //frames per file -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - ind=(int)receiverBase->getFramesPerFile(); -#endif - n += mySock->SendDataOnly(&ind,sizeof(ind)); + i32=(int)receiver->getFramesPerFile(); + n += mySock->SendDataOnly(&i32, sizeof(i32)); //frame discard policy -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - ind=(int)receiverBase->getFrameDiscardPolicy(); -#endif - n += mySock->SendDataOnly(&ind,sizeof(ind)); + i32=(int)receiver->getFrameDiscardPolicy(); + n += mySock->SendDataOnly(&i32, sizeof(i32)); //frame padding -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - ind=(int)receiverBase->getFramePaddingEnable(); -#endif - n += mySock->SendDataOnly(&ind,sizeof(ind)); + i32=(int)receiver->getFramePaddingEnable(); + n += mySock->SendDataOnly(&i32, sizeof(i32)); // file write enable -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - ind=(int)receiverBase->getFileWriteEnable(); -#endif - n += mySock->SendDataOnly(&ind,sizeof(ind)); + i32=(int)receiver->getFileWriteEnable(); + n += mySock->SendDataOnly(&i32, sizeof(i32)); // file overwrite enable -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - ind=(int)receiverBase->getOverwriteEnable(); -#endif - n += mySock->SendDataOnly(&ind,sizeof(ind)); + i32=(int)receiver->getOverwriteEnable(); + n += mySock->SendDataOnly(&i32, sizeof(i32)); // gap pixels -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - ind=(int)receiverBase->getGapPixelsEnable(); -#endif - n += mySock->SendDataOnly(&ind,sizeof(ind)); + i32=(int)receiver->getGapPixelsEnable(); + n += mySock->SendDataOnly(&i32, sizeof(i32)); - // receiver read frequency -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - ind=(int)receiverBase->getFrameToGuiFrequency(); -#endif - n += mySock->SendDataOnly(&ind,sizeof(ind)); + // streaming frequency + i32=(int)receiver->getStreamingFrequency(); + n += mySock->SendDataOnly(&i32, sizeof(i32)); // streaming port -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - ind=(int)receiverBase->getStreamingPort(); -#endif - n += mySock->SendDataOnly(&ind,sizeof(ind)); + i32=(int)receiver->getStreamingPort(); + n += mySock->SendDataOnly(&i32, sizeof(i32)); // streaming source ip -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - path = receiverBase->getStreamingSourceIP(); -#endif - mySock->SendDataOnly(path,MAX_STR_LENGTH); - if (path != NULL) - delete[] path; + strcpy(cstring, receiver->getStreamingSourceIP().c_str()); + n += mySock->SendDataOnly(cstring, sizeof(cstring)); // additional json header -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - path = receiverBase->getAdditionalJsonHeader(); -#endif - mySock->SendDataOnly(path,MAX_STR_LENGTH); - if (path != NULL) - delete[] path; + strcpy(cstring, receiver->getAdditionalJsonHeader().c_str()); + n += mySock->SendDataOnly(cstring, sizeof(cstring)); // data streaming enable -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - ind=(int)receiverBase->getDataStreamEnable(); -#endif - n += mySock->SendDataOnly(&ind,sizeof(ind)); + i32=(int)receiver->getDataStreamEnable(); + n += mySock->SendDataOnly(&i32, sizeof(i32)); // activate -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - ind=(int)receiverBase->getActivate(); -#endif - n += mySock->SendDataOnly(&ind,sizeof(ind)); + i32=(int)receiver->getActivate(); + n += mySock->SendDataOnly(&i32, sizeof(i32)); // deactivated padding enable -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - ind=(int)receiverBase->getDeactivatedPadding(); -#endif - n += mySock->SendDataOnly(&ind,sizeof(ind)); + i32=(int)receiver->getDeactivatedPadding(); + n += mySock->SendDataOnly(&i32, sizeof(i32)); // silent mode -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - ind=(int)receiverBase->getSilentMode(); -#endif - n += mySock->SendDataOnly(&ind,sizeof(ind)); + i32=(int)receiver->getSilentMode(); + n += mySock->SendDataOnly(&i32, sizeof(i32)); if (!lockStatus) - strcpy(mySock->lastClientIP,mySock->thisClientIP); + strcpy(mySock->lastClientIP, mySock->thisClientIP); return OK; } @@ -738,22 +555,9 @@ int slsReceiverTCPIPInterface::send_update() { int slsReceiverTCPIPInterface::get_id(){ ret = OK; - int64_t retval=-1; - - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - retval = getReceiverVersion(); -#endif - - if(mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + memset(mess, 0, sizeof(mess)); + int64_t retval = getReceiverVersion(); + return interface->Server_SendResult(true, ret, &retval, sizeof(retval)); } @@ -761,70 +565,63 @@ int slsReceiverTCPIPInterface::get_id(){ int slsReceiverTCPIPInterface::set_detector_type(){ ret = OK; memset(mess, 0, sizeof(mess)); - detectorType dr = GENERIC; + detectorType arg = GENERIC; detectorType retval = GENERIC; - // receive arguments - if (mySock->ReceiveDataOnly(&dr,sizeof(dr)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed + if (interface->Server_ReceiveArg(ret, mess, &arg, sizeof(arg)) == FAIL) + return FAIL; - // execute action - if (dr == GET_DETECTOR_TYPE) - retval = myDetectorType; -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - else if (mySock->differentClients && lockStatus) - receiverlocked(); - else if ((receiverBase) && (receiverBase->getStatus() != IDLE)) - receiverNotIdle(); - else { - switch(dr) { - case GOTTHARD: - case PROPIX: - case MOENCH: - case EIGER: - case JUNGFRAUCTB: - case JUNGFRAU: - break; - default: - ret = FAIL; - sprintf(mess,"Unknown detector type: %d\n", dr); - FILE_LOG(logERROR) << mess; - break; - } - if(ret == OK) { - if(receiverBase == NULL){ - receiverBase = UDPInterface::create(); - if(startAcquisitionCallBack) - receiverBase->registerCallBackStartAcquisition(startAcquisitionCallBack,pStartAcquisition); - if(acquisitionFinishedCallBack) - receiverBase->registerCallBackAcquisitionFinished(acquisitionFinishedCallBack,pAcquisitionFinished); - if(rawDataReadyCallBack) - receiverBase->registerCallBackRawDataReady(rawDataReadyCallBack,pRawDataReady); - if(rawDataModifyReadyCallBack) - receiverBase->registerCallBackRawDataModifyReady(rawDataModifyReadyCallBack,pRawDataReady); + // set + if (arg >= 0) { + // if object exists, verify unlocked and idle, else only verify lock (connecting first time) + if (receiver == nullptr) + interface->Server_VerifyLock(ret, mess, lockStatus); + else + interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum); + if (ret == OK) { + switch(arg) { + case GOTTHARD: + case EIGER: + case CHIPTESTBOARD: + case MOENCH: + case JUNGFRAU: + break; + default: + ret = FAIL; + sprintf(mess,"Unknown detector type: %d\n", arg); + FILE_LOG(logERROR) << mess; + break; } - myDetectorType = dr; - ret = receiverBase->setDetectorType(myDetectorType); - retval = myDetectorType; + if(ret == OK) { + if(receiver == nullptr){ + receiver = new slsReceiverImplementation(); + } + myDetectorType = arg; + ret = receiver->setDetectorType(myDetectorType); + retval = myDetectorType; + + // callbacks after (in setdetectortype, the object is reinitialized) + if(startAcquisitionCallBack) + receiver->registerCallBackStartAcquisition(startAcquisitionCallBack,pStartAcquisition); + if(acquisitionFinishedCallBack) + receiver->registerCallBackAcquisitionFinished(acquisitionFinishedCallBack,pAcquisitionFinished); + if(rawDataReadyCallBack) + receiver->registerCallBackRawDataReady(rawDataReadyCallBack,pRawDataReady); + if(rawDataModifyReadyCallBack) + receiver->registerCallBackRawDataModifyReady(rawDataModifyReadyCallBack,pRawDataReady); + + // client has started updating receiver, update ip + if (!lockStatus) + strcpy(mySock->lastClientIP, mySock->thisClientIP); + } + } } -#endif - // client has started updating receiver, update ip - if (!lockStatus) - strcpy(mySock->lastClientIP,mySock->thisClientIP); - - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + //get + retval = myDetectorType; + validate((int)arg, (int)retval, std::string("set detector type"), DEC); + return interface->Server_SendResult(false, ret, &retval, sizeof(retval), mess); } @@ -832,50 +629,32 @@ int slsReceiverTCPIPInterface::set_detector_type(){ int slsReceiverTCPIPInterface::set_detector_hostname() { ret = OK; memset(mess, 0, sizeof(mess)); - char hostname[MAX_STR_LENGTH]; - memset(hostname, 0, sizeof(hostname)); - char* retval = NULL; - char defaultVal[MAX_STR_LENGTH]; - memset(defaultVal, 0, sizeof(defaultVal)); + char hostname[MAX_STR_LENGTH] = {0}; + char retval[MAX_STR_LENGTH] = {0}; + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, hostname,MAX_STR_LENGTH, true, receiver) == FAIL) + return FAIL; - // receive arguments - if (mySock->ReceiveDataOnly(hostname,MAX_STR_LENGTH) < 0 ) - return printSocketReadError(); - - // execute action - // only a set, not a get -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase == NULL) - invalidReceiverObject(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->initialize(hostname); - retval = receiverBase->getDetectorHostname(); - if(retval == NULL) + // base object not null + if (ret == OK) { + // set + if (strlen(hostname)) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) + receiver->setDetectorHostname(hostname); + } + // get + std::string s = receiver->getDetectorHostname(); + strcpy(retval, s.c_str()); + if (!s.length()) { ret = FAIL; - } -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - if(retval == NULL) - mySock->SendDataOnly(defaultVal,MAX_STR_LENGTH); - else { - mySock->SendDataOnly(retval,MAX_STR_LENGTH); - delete[] retval; + sprintf(mess, "hostname not set\n"); + FILE_LOG(logERROR) << mess; + } } - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, retval, MAX_STR_LENGTH, mess); } @@ -883,136 +662,173 @@ int slsReceiverTCPIPInterface::set_detector_hostname() { int slsReceiverTCPIPInterface::set_roi() { ret = OK; memset(mess, 0, sizeof(mess)); - int nroi = 0; + int narg = -1; + std::vector arg; // receive arguments - if (mySock->ReceiveDataOnly(&nroi,sizeof(nroi)) < 0 ) - return printSocketReadError(); - - std::vector roiLimits; - int iloop = 0; - for (iloop = 0; iloop < nroi; iloop++) { + if (mySock->ReceiveDataOnly(&narg,sizeof(narg)) < 0 ) + return interface->Server_SocketCrash(); + for (int iloop = 0; iloop < narg; ++iloop) { ROI temp; - if ( mySock->ReceiveDataOnly(&temp,sizeof(ROI)) < 0 ) - return printSocketReadError(); - roiLimits.push_back(temp); + if ( mySock->ReceiveDataOnly(&temp.xmin, sizeof(int)) < 0 ) + return interface->Server_SocketCrash(); + if ( mySock->ReceiveDataOnly(&temp.xmax, sizeof(int)) < 0 ) + return interface->Server_SocketCrash(); + if ( mySock->ReceiveDataOnly(&temp.ymin, sizeof(int)) < 0 ) + return interface->Server_SocketCrash(); + if ( mySock->ReceiveDataOnly(&temp.ymax, sizeof(int)) < 0 ) + return interface->Server_SocketCrash(); + arg.push_back(temp); + } + FILE_LOG(logDEBUG1) << "Set ROI narg: " << narg; + for (int iloop = 0; iloop < narg; ++iloop) { + FILE_LOG(logDEBUG1) << "(" << arg[iloop].xmin << ", " << + arg[iloop].xmax << ", " << arg[iloop].ymin << ", " << + arg[iloop].ymax << ")"; } - //does not exist - if (myDetectorType != GOTTHARD) + if (myDetectorType == EIGER || myDetectorType == JUNGFRAU) functionNotImplemented(); - // execute action - // only a set, not a get + // base object not null + else if (receiver == nullptr) + interface->Server_NullObjectError(ret, mess); else { -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase == NULL) - invalidReceiverObject(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - ret = receiverBase->setROI(roiLimits); - //retval = receiverBase->getROI(); - } -#endif + // only set + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) + ret = receiver->setROI(arg); } - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - - roiLimits.clear(); - - // return ok/fail - return ret; + arg.clear(); + return interface->Server_SendResult(true, ret, nullptr, 0, mess); } int slsReceiverTCPIPInterface::setup_udp(){ ret = OK; - char args[3][MAX_STR_LENGTH]; - memset(args,0,sizeof(args)); - char retval[MAX_STR_LENGTH]; - memset(retval,0,sizeof(retval)); + memset(mess, 0, sizeof(mess)); + char args[6][MAX_STR_LENGTH] = {{""}, {""}, {""}, {""}, {""}, {""}}; + char retvals[2][MAX_STR_LENGTH] = {{""}, {""}}; + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, args, sizeof(args), true, receiver) == FAIL) + return FAIL; - // receive arguments - if (mySock->ReceiveDataOnly(args,sizeof(args)) < 0 ) - return printSocketReadError(); + // base object not null + if (ret == OK) { + // only set + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { - // execute action - // only a set, not a get -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase == NULL) - invalidReceiverObject(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - //set up udp port - int udpport=-1,udpport2=-1; - sscanf(args[1],"%d",&udpport); - sscanf(args[2],"%d",&udpport2); - receiverBase->setUDPPortNumber(udpport); - if (myDetectorType == EIGER) - receiverBase->setUDPPortNumber2(udpport2); + //setup interfaces count + int numInterfaces = atoi(args[0]) > 1 ? 2 : 1; + int selInterface = atoi(args[1]) > 1 ? 2 : 1; - //setup udpip - //get ethernet interface or IP to listen to - FILE_LOG(logINFO) << "Receiver UDP IP: " << args[0]; - std::string temp = genericSocket::ipToName(args[0]); - if (temp == "none"){ - ret = FAIL; - strcpy(mess, "Failed to get ethernet interface or IP\n"); - FILE_LOG(logERROR) << mess; - } - else { - char eth[MAX_STR_LENGTH]; - memset(eth,0,sizeof(eth)); - strcpy(eth,temp.c_str()); - if (strchr(eth,'.') != NULL) { - strcpy(eth,""); - ret = FAIL; - strcpy(mess, "Failed to get ethernet interface\n"); - FILE_LOG(logERROR) << mess; + char* ip1 = args[2]; + char* ip2 = args[3]; + uint32_t port1 = atoi(args[4]); + uint32_t port2 = atoi(args[5]); + + // using the 2nd interface only + if (myDetectorType == JUNGFRAU && numInterfaces == 1 && selInterface == 2) { + ip1 = ip2; + port1 = port2; } - receiverBase->setEthernetInterface(eth); - //get mac address from ethernet interface - if (ret != FAIL) - temp = genericSocket::nameToMac(eth); - - if ((temp=="00:00:00:00:00:00") || (ret == FAIL)){ - ret = FAIL; - strcpy(mess,"failed to get mac adddress to listen to\n"); - FILE_LOG(logERROR) << mess; + // 1st interface + receiver->setUDPPortNumber(port1); + if (myDetectorType == EIGER) { + receiver->setUDPPortNumber2(port2); } - else { - strcpy(retval,temp.c_str()); - FILE_LOG(logINFO) << "Reciever MAC Address: " << retval; + FILE_LOG(logINFO) << "Receiver UDP IP: " << ip1; + // get eth + std::string temp = genericSocket::ipToName(ip1); + if (temp == "none"){ + ret = FAIL; + strcpy(mess, "Failed to get ethernet interface or IP \n"); + FILE_LOG(logERROR) << mess; + } else { + char eth[MAX_STR_LENGTH] = {""}; + memset(eth, 0, MAX_STR_LENGTH); + strcpy(eth, temp.c_str()); + // if there is a dot in eth name + if (strchr(eth, '.') != nullptr) { + strcpy(eth, ""); + ret = FAIL; + sprintf(mess, "Failed to get ethernet interface from IP. Got %s\n", temp.c_str()); + FILE_LOG(logERROR) << mess; + } + receiver->setEthernetInterface(eth); + + //get mac address + if (ret != FAIL) { + temp = genericSocket::nameToMac(eth); + if (temp=="00:00:00:00:00:00") { + ret = FAIL; + strcpy(mess,"failed to get mac adddress to listen to\n"); + FILE_LOG(logERROR) << mess; + } else { + // using the 2nd interface only + if (myDetectorType == JUNGFRAU && numInterfaces == 1 && selInterface == 2) { + strcpy(retvals[1],temp.c_str()); + FILE_LOG(logINFO) << "Receiver MAC Address: " << retvals[1]; + } + else { + strcpy(retvals[0],temp.c_str()); + FILE_LOG(logINFO) << "Receiver MAC Address: " << retvals[0]; + } + } + } + } + + // 2nd interface + if (myDetectorType == JUNGFRAU && numInterfaces == 2) { + receiver->setUDPPortNumber2(port2); + FILE_LOG(logINFO) << "Receiver UDP IP 2: " << ip2; + // get eth + temp = genericSocket::ipToName(ip2); + if (temp == "none"){ + ret = FAIL; + strcpy(mess, "Failed to get 2nd ethernet interface or IP \n"); + FILE_LOG(logERROR) << mess; + } else { + char eth[MAX_STR_LENGTH] = {""}; + memset(eth, 0, MAX_STR_LENGTH); + strcpy(eth, temp.c_str()); + // if there is a dot in eth name + if (strchr(eth, '.') != nullptr) { + strcpy(eth, ""); + ret = FAIL; + sprintf(mess, "Failed to get 2nd ethernet interface from IP. Got %s\n", temp.c_str()); + FILE_LOG(logERROR) << mess; + } + receiver->setEthernetInterface2(eth); + + //get mac address + if (ret != FAIL) { + temp = genericSocket::nameToMac(eth); + if (temp=="00:00:00:00:00:00") { + ret = FAIL; + strcpy(mess,"failed to get 2nd mac adddress to listen to\n"); + FILE_LOG(logERROR) << mess; + } else { + strcpy(retvals[1],temp.c_str()); + FILE_LOG(logINFO) << "Receiver MAC Address 2: " << retvals[1]; + } + } + } + } + + // set the number of udp interfaces (changes number of threads and many others) + if (myDetectorType == JUNGFRAU && receiver->setNumberofUDPInterfaces(numInterfaces) == FAIL) { + ret = FAIL; + sprintf(mess, "Failed to set number of interfaces\n"); + FILE_LOG(logERROR) << mess; } } } -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(retval,MAX_STR_LENGTH); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, retvals, sizeof(retvals), mess); } @@ -1023,113 +839,85 @@ int slsReceiverTCPIPInterface::set_timer() { int64_t index[2] = {-1, -1}; int64_t retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(index,sizeof(index)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &index, sizeof(index), true, receiver) == FAIL) + return FAIL; + + // base object not null + if (ret == OK) { + FILE_LOG(logDEBUG1) << "Setting timer index " << index[0] << " to " << index[1]; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { // set if (index[1] >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - // else if (receiverBase->getStatus() != IDLE) - // receiverNotIdle(); - else { + // verify if receiver is unlocked + if (interface->Server_VerifyLock(ret, mess, lockStatus) == OK) { switch (index[0]) { case ACQUISITION_TIME: - ret = receiverBase->setAcquisitionTime(index[1]); + ret = receiver->setAcquisitionTime(index[1]); break; case FRAME_PERIOD: - ret = receiverBase->setAcquisitionPeriod(index[1]); + ret = receiver->setAcquisitionPeriod(index[1]); break; case FRAME_NUMBER: case CYCLES_NUMBER: case STORAGE_CELL_NUMBER: - receiverBase->setNumberOfFrames(index[1]); + receiver->setNumberOfFrames(index[1]); break; case SUBFRAME_ACQUISITION_TIME: - receiverBase->setSubExpTime(index[1]); + receiver->setSubExpTime(index[1]); break; case SUBFRAME_DEADTIME: - receiverBase->setSubPeriod(index[1] + receiverBase->getSubExpTime()); + receiver->setSubPeriod(index[1] + receiver->getSubExpTime()); break; - case SAMPLES_JCTB: - if (myDetectorType != JUNGFRAUCTB) { - ret = FAIL; - sprintf(mess,"This timer mode (%lld) does not exist for this receiver type\n", (long long int)index[0]); - FILE_LOG(logERROR) << "Warning: " << mess; + case SAMPLES: + if (myDetectorType != CHIPTESTBOARD && myDetectorType != MOENCH) { + modeNotImplemented("(Samples) Timer index", (int)index[0]); break; } - receiverBase->setNumberofSamples(index[1]); + receiver->setNumberofSamples(index[1]); break; default: - ret = FAIL; - sprintf(mess,"This timer mode (%lld) does not exist for receiver\n", (long long int)index[0]); - FILE_LOG(logERROR) << mess; + modeNotImplemented("Timer index", (int)index[0]); + break; } } } // get switch (index[0]) { case ACQUISITION_TIME: - retval=receiverBase->getAcquisitionTime(); + retval=receiver->getAcquisitionTime(); break; case FRAME_PERIOD: - retval=receiverBase->getAcquisitionPeriod(); + retval=receiver->getAcquisitionPeriod(); break; case FRAME_NUMBER: case CYCLES_NUMBER: case STORAGE_CELL_NUMBER: - retval=receiverBase->getNumberOfFrames(); + retval=receiver->getNumberOfFrames(); break; case SUBFRAME_ACQUISITION_TIME: - retval=receiverBase->getSubExpTime(); + retval=receiver->getSubExpTime(); break; case SUBFRAME_DEADTIME: - retval=(receiverBase->getSubPeriod() - receiverBase->getSubExpTime()); + retval=(receiver->getSubPeriod() - receiver->getSubExpTime()); break; - case SAMPLES_JCTB: - if (myDetectorType != JUNGFRAUCTB) { + case SAMPLES: + if (myDetectorType != CHIPTESTBOARD && myDetectorType != MOENCH) { ret = FAIL; sprintf(mess,"This timer mode (%lld) does not exist for this receiver type\n", (long long int)index[0]); FILE_LOG(logERROR) << "Warning: " << mess; break; } - retval=receiverBase->getNumberofSamples(); + retval=receiver->getNumberofSamples(); break; default: - ret = FAIL; - sprintf(mess,"This timer mode (%lld) does not exist for receiver\n", (long long int)index[0]); - FILE_LOG(logERROR) << mess; - } - - // check - if (ret == OK && index[1] >= 0 && retval != index[1]) { - ret = FAIL; - strcpy(mess,"Could not set timer\n"); - FILE_LOG(logERROR) << mess; + modeNotImplemented("Timer index", (int)index[0]); + break; } + validate((int)index[1], (int)retval, std::string("set timer"), DEC); + FILE_LOG(logDEBUG1) << slsDetectorDefs::getTimerType((timerIndex)(index[0])) << ":" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << getTimerType(index[0]) << ":" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1140,154 +928,102 @@ int slsReceiverTCPIPInterface::set_dynamic_range() { int dr = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&dr,sizeof(dr)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &dr, sizeof(dr), true, receiver) == FAIL) + return FAIL; - // execute action - bool exists = false; - switch (dr) { - case -1: - case 16: - exists = true; - break; - case 4: - case 8: - case 32: - if (myDetectorType == EIGER) - exists = true; - break; - default: - break; - } - if (!exists) { - ret = FAIL; - sprintf(mess,"This dynamic range %d does not exist for this detector\n",dr); - FILE_LOG(logERROR) << mess; - } - -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (ret == OK){ - if (receiverBase == NULL) - invalidReceiverObject(); - else { - // set - if (dr > 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); + // base object not null + if (ret == OK) { + // set + if (dr >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting dynamic range: " << dr; + bool exists = false; + switch (dr) { + case 16: + exists = true; + break; + case 4: + case 8: + case 32: + if (myDetectorType == EIGER) + exists = true; + break; + default: + break; + } + // invalid dr + if (!exists) { + modeNotImplemented("Dynamic range", dr); + } + // valid dr else { - ret = receiverBase->setDynamicRange(dr); + ret = receiver->setDynamicRange(dr); if(ret == FAIL) { strcpy(mess, "Could not allocate memory for fifo or could not start listening/writing threads\n"); FILE_LOG(logERROR) << mess; } } } - //get - retval = receiverBase->getDynamicRange(); - if(dr > 0 && retval != dr) { - ret = FAIL; - strcpy(mess, "Could not set dynamic range\n"); - FILE_LOG(logERROR) << mess; - } } + // get + retval = receiver->getDynamicRange(); + validate(dr, retval, std::string("set dynamic range"), DEC); + FILE_LOG(logDEBUG1) << "dynamic range: " << retval; } -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "dynamic range: " << retval; -#endif -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } -int slsReceiverTCPIPInterface::set_read_frequency(){ +int slsReceiverTCPIPInterface::set_streaming_frequency() { ret = OK; memset(mess, 0, sizeof(mess)); int index = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&index,sizeof(index)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &index, sizeof(index), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set if (index >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - ret = receiverBase->setFrameToGuiFrequency(index); + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting streaming frequency: " << index; + ret = receiver->setStreamingFrequency(index); if(ret == FAIL) { strcpy(mess, "Could not allocate memory for listening fifo\n"); FILE_LOG(logERROR) << mess; } } } - //get - retval=receiverBase->getFrameToGuiFrequency(); - if(index >= 0 && retval != index){ - ret = FAIL; - strcpy(mess,"Could not set frame to gui frequency"); - FILE_LOG(logERROR) << mess; - } + // get + retval = receiver->getStreamingFrequency(); + validate(index, retval, std::string("set streaming frequency"), DEC); } -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } int slsReceiverTCPIPInterface::get_status(){ ret = OK; + memset(mess, 0, sizeof(mess)); enum runStatus retval = ERROR; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else retval = receiverBase->getStatus(); -#endif + // no arg, check receiver is null + interface->Server_ReceiveArg(ret, mess, nullptr, 0, true, receiver); - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + if (ret == OK) { + FILE_LOG(logDEBUG1) << "Getting Status"; + retval = receiver->getStatus(); + FILE_LOG(logDEBUG1) << "Status:" << runStatusType(retval); + } + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1296,47 +1032,30 @@ int slsReceiverTCPIPInterface::start_receiver(){ ret = OK; memset(mess, 0, sizeof(mess)); - // execute action - // only a set, not a get -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else if (mySock->differentClients && lockStatus) - receiverlocked(); - /* - else if(!strlen(receiverBase->getFilePath())){ - strcpy(mess,SET_RECEIVER_ERR_MESSAGE"); - ret = FAIL; - } - */ - else { - enum runStatus s = receiverBase->getStatus(); - if (s != IDLE) { - ret=FAIL; - sprintf(mess,"Cannot start Receiver as it is in %s state\n",runStatusType(s).c_str()); - FILE_LOG(logERROR) << mess; - } - else { - ret=receiverBase->startReceiver(mess); - if (ret == FAIL) { + // no arg, and check receiver is null + interface->Server_ReceiveArg(ret, mess, nullptr, 0, true, receiver); + + // receiver is not null + if (ret == OK) { + // only set + // verify if receiver is unlocked + if (interface->Server_VerifyLock(ret, mess, lockStatus) == OK) { + // should not be idle + enum runStatus s = receiver->getStatus(); + if (s != IDLE) { + ret=FAIL; + sprintf(mess,"Cannot start Receiver as it is in %s state\n",runStatusType(s).c_str()); FILE_LOG(logERROR) << mess; + }else { + FILE_LOG(logDEBUG1) << "Starting Receiver"; + ret = receiver->startReceiver(mess); + if (ret == FAIL) { + FILE_LOG(logERROR) << mess; + } } } } -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - - // return ok/fail - return ret; - - + return interface->Server_SendResult(true, ret, nullptr, 0, mess); } @@ -1344,148 +1063,62 @@ int slsReceiverTCPIPInterface::start_receiver(){ int slsReceiverTCPIPInterface::stop_receiver(){ ret = OK; memset(mess, 0, sizeof(mess)); - enum runStatus s = ERROR; - // execute action - // only a set, not a get -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else if (mySock->differentClients && lockStatus) - receiverlocked(); - else { - if(receiverBase->getStatus() != IDLE) - receiverBase->stopReceiver(); - s = receiverBase->getStatus(); - if (s == IDLE) - ret = OK; - else { - ret = FAIL; - sprintf(mess,"Could not stop receiver. It is in %s state\n",runStatusType(s).c_str()); - FILE_LOG(logERROR) << mess; + // no arg, and check receiver is null + interface->Server_ReceiveArg(ret, mess, nullptr, 0, true, receiver); + + // receiver is not null + if (ret == OK) { + // only set + // verify if receiver is unlocked + if (interface->Server_VerifyLock(ret, mess, lockStatus) == OK) { + if(receiver->getStatus() != IDLE) { + FILE_LOG(logDEBUG1) << "Stopping Receiver"; + receiver->stopReceiver(); + } + enum runStatus s = receiver->getStatus(); + if (s == IDLE) + ret = OK; + else { + ret = FAIL; + sprintf(mess,"Could not stop receiver. It is in %s state\n",runStatusType(s).c_str()); + FILE_LOG(logERROR) << mess; + } } } -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, nullptr, 0, mess); } -int slsReceiverTCPIPInterface::start_readout(){ - ret = OK; - memset(mess, 0, sizeof(mess)); - enum runStatus retval; - - // execute action - // only a set, not a get - -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else if (mySock->differentClients && lockStatus) - receiverlocked(); - /*else if(receiverBase->getStatus() != IDLE){ - strcpy(mess,"Can not start receiver readout while receiver not idle\n"); - ret = FAIL; - }*/ - else { - receiverBase->startReadout(); - retval = receiverBase->getStatus(); - if ((retval == TRANSMITTING) || (retval == RUN_FINISHED) || (retval == IDLE)) - ret = OK; - else { - ret = FAIL; - strcpy(mess,"Could not start readout"); - FILE_LOG(logERROR) << mess; - } - } -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; -} - - - - - int slsReceiverTCPIPInterface::set_file_dir() { ret = OK; memset(mess, 0, sizeof(mess)); - char fPath[MAX_STR_LENGTH]; - memset(fPath, 0, sizeof(fPath)); - char* retval=NULL; - char defaultVal[MAX_STR_LENGTH]; - memset(defaultVal, 0, sizeof(defaultVal)); + char fPath[MAX_STR_LENGTH] = {0}; + char retval[MAX_STR_LENGTH] = {0}; - // receive arguments - if (mySock->ReceiveDataOnly(fPath,MAX_STR_LENGTH) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, fPath, sizeof(fPath), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set if (strlen(fPath)) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setFilePath(fPath); - } + FILE_LOG(logDEBUG1) << "Setting file path: " << fPath; + receiver->setFilePath(fPath); } - //get - retval = receiverBase->getFilePath(); - if (retval == NULL || (strlen(fPath) && strcasecmp(fPath, retval))) { + // get + std::string s = receiver->getFilePath(); + strcpy(retval, s.c_str()); + if ((!s.length()) || (strlen(fPath) && strcasecmp(fPath, retval))) { ret = FAIL; strcpy(mess,"receiver file path does not exist\n"); FILE_LOG(logERROR) << mess; - } + } else + FILE_LOG(logDEBUG1) << "file path:" << retval; } -#endif -#ifdef VERYVERBOSE - if (retval != NULL) - FILE_LOG(logDEBUG1) << "file path:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - if(retval == NULL) - mySock->SendDataOnly(defaultVal,MAX_STR_LENGTH); - else{ - mySock->SendDataOnly(retval,MAX_STR_LENGTH); - delete[] retval; - } - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, retval, MAX_STR_LENGTH, mess); } @@ -1493,60 +1126,31 @@ int slsReceiverTCPIPInterface::set_file_dir() { int slsReceiverTCPIPInterface::set_file_name() { ret = OK; memset(mess, 0, sizeof(mess)); - char fName[MAX_STR_LENGTH]; - memset(fName, 0, sizeof(fName)); - char* retval = NULL; - char defaultVal[MAX_STR_LENGTH]; - memset(defaultVal, 0, sizeof(defaultVal)); + char fName[MAX_STR_LENGTH] = {0}; + char retval[MAX_STR_LENGTH] = {0}; - // receive arguments - if (mySock->ReceiveDataOnly(fName,MAX_STR_LENGTH) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, fName, sizeof(fName), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set if (strlen(fName)) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setFileName(fName); - } + FILE_LOG(logDEBUG1) << "Setting file name: " << fName; + receiver->setFileName(fName); } - //get - retval = receiverBase->getFileName(); - if(retval == NULL) { + // get + std::string s = receiver->getFileName(); + strcpy(retval, s.c_str()); + if (!s.length()) { ret = FAIL; strcpy(mess, "file name is empty\n"); FILE_LOG(logERROR) << mess; - } + } else + FILE_LOG(logDEBUG1) << "file name:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "file name:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - if(retval == NULL) - mySock->SendDataOnly(defaultVal,MAX_STR_LENGTH); - else{ - mySock->SendDataOnly(retval,MAX_STR_LENGTH); - delete[] retval; - } - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, retval, MAX_STR_LENGTH, mess); } @@ -1557,101 +1161,62 @@ int slsReceiverTCPIPInterface::set_file_index() { int index = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&index,sizeof(index)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &index, sizeof(index), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set - if(index >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setFileIndex(index); + if (index >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting file index: " << index; + receiver->setFileIndex(index); } } - //get - retval=receiverBase->getFileIndex(); - if(index >= 0 && retval != index) { - ret = FAIL; - strcpy(mess, "Could not set file index\n"); - FILE_LOG(logERROR) << mess; - } + // get + retval=receiver->getFileIndex(); + validate(index, retval, std::string("set file index"), DEC); + FILE_LOG(logDEBUG1) << "file index:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "file index:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval,sizeof(retval), mess); } - - - int slsReceiverTCPIPInterface::get_frame_index(){ ret = OK; + memset(mess, 0, sizeof(mess)); int retval = -1; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else - retval=receiverBase->getAcquisitionIndex(); -#endif + // no arg, check receiver is null + interface->Server_ReceiveArg(ret, mess, nullptr, 0, true, receiver); - if (mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + if (ret == OK) { + FILE_LOG(logDEBUG1) << "Getting frame index"; + retval = receiver->getAcquisitionIndex(); + FILE_LOG(logDEBUG1) << "frame index:" << retval; + } + return interface->Server_SendResult(true, ret, &retval,sizeof(retval), mess); } int slsReceiverTCPIPInterface::get_frames_caught(){ ret = OK; + memset(mess, 0, sizeof(mess)); int retval = -1; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else retval=receiverBase->getTotalFramesCaught(); -#endif + // no arg, check receiver is null + interface->Server_ReceiveArg(ret, mess, nullptr, 0, true, receiver); - if (mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + if (ret == OK) { + FILE_LOG(logDEBUG1) << "Getting frames caught"; + retval = receiver->getTotalFramesCaught(); + FILE_LOG(logDEBUG1) << "frames caught:" << retval; + } + return interface->Server_SendResult(true, ret, &retval,sizeof(retval), mess); } @@ -1660,29 +1225,19 @@ int slsReceiverTCPIPInterface::reset_frames_caught(){ ret = OK; memset(mess, 0, sizeof(mess)); - // execute action - // only a set, not a get -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else - receiverBase->resetAcquisitionCount(); -#endif + // no arg, and check receiver is null + interface->Server_ReceiveArg(ret, mess, nullptr, 0, true, receiver); - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - - // return ok/fail - return ret; + // receiver is not null + if (ret == OK) { + // only set + // verify if receiver is unlocked + if (interface->Server_VerifyLock(ret, mess, lockStatus) == OK) { + FILE_LOG(logDEBUG1) << "Reset frames caught"; + receiver->resetAcquisitionCount(); + } + } + return interface->Server_SendResult(true, ret, nullptr, 0, mess); } @@ -1693,74 +1248,26 @@ int slsReceiverTCPIPInterface::enable_file_write(){ int enable = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&enable,sizeof(enable)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &enable, sizeof(enable), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set if (enable >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setFileWriteEnable(enable); + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting File write enable:" << enable; + receiver->setFileWriteEnable(enable); } } - //get - retval=receiverBase->getFileWriteEnable(); - if(enable >= 0 && enable != retval) { - ret=FAIL; - strcpy(mess,"Could not set file write enable"); - FILE_LOG(logERROR) << mess; - } + // get + retval = receiver->getFileWriteEnable(); + validate(enable, retval, std::string("set file write enable"), DEC); + FILE_LOG(logDEBUG1) << "file write enable:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "file write enable:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; -} - - - - - -int slsReceiverTCPIPInterface::enable_compression() { - ret = OK; - memset(mess, 0, sizeof(mess)); - int enable = -1; - - // receive arguments - if(mySock->ReceiveDataOnly(&enable,sizeof(enable)) < 0 ) - return printSocketReadError(); - - ret = FAIL; - sprintf(mess, "This function (%s) is not implemented yet\n", getFunctionName((enum recFuncs)fnum)); - FILE_LOG(logERROR) << mess; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - mySock->SendDataOnly(mess,sizeof(mess)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1771,49 +1278,26 @@ int slsReceiverTCPIPInterface::enable_overwrite() { int index = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&index,sizeof(index)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &index, sizeof(index), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set - if(index >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setOverwriteEnable(index); + if (index >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting File overwrite enable:" << index; + receiver->setOverwriteEnable(index); } } - //get - retval=receiverBase->getOverwriteEnable(); - if(index >=0 && retval != index) { - ret = FAIL; - strcpy(mess,"Could not set file over write enable\n"); - FILE_LOG(logERROR) << mess; - } + // get + retval = receiver->getOverwriteEnable(); + validate(index, retval, std::string("set file overwrite enable"), DEC); + FILE_LOG(logDEBUG1) << "file overwrite enable:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "file overwrite enable:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1824,114 +1308,63 @@ int slsReceiverTCPIPInterface::enable_tengiga() { int val = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&val,sizeof(val)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &val, sizeof(val), true, receiver) == FAIL) + return FAIL; - if (myDetectorType != EIGER) + if (myDetectorType != EIGER && myDetectorType != CHIPTESTBOARD && myDetectorType != MOENCH) functionNotImplemented(); - // execute action - - -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - else { - if (receiverBase == NULL) - invalidReceiverObject(); - else { - // set - if (val >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - ret = receiverBase->setTenGigaEnable(val); - } - } - //get - retval=receiverBase->getTenGigaEnable(); - if((val >= 0) && (val != retval)) { - ret = FAIL; - strcpy(mess,"Could not set ten giga enable"); - FILE_LOG(logERROR) << mess; + // base object not null + else if (ret == OK) { + // set + if (val >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting 10GbE:" << val; + ret = receiver->setTenGigaEnable(val); } } + // get + retval = receiver->getTenGigaEnable(); + validate(val, retval, std::string("set 10GbE"), DEC); + FILE_LOG(logDEBUG1) << "10Gbe:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "10Gbe:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } - int slsReceiverTCPIPInterface::set_fifo_depth() { ret = OK; memset(mess, 0, sizeof(mess)); int value = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&value,sizeof(value)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &value, sizeof(value), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set - if(value >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - ret = receiverBase->setFifoDepth(value); + if (value >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting fifo depth:" << value; + ret = receiver->setFifoDepth(value); if (ret == FAIL) { strcpy(mess,"Could not set fifo depth"); FILE_LOG(logERROR) << mess; } } } - //get - retval = receiverBase->getFifoDepth(); - if(value >= 0 && retval != value) { - ret = FAIL; - strcpy(mess, "Could not set fifo depth\n"); - FILE_LOG(logERROR) << mess; - } + // get + retval = receiver->getFifoDepth(); + validate(value, retval, std::string("set fifo depth"), DEC); + FILE_LOG(logDEBUG1) << "fifo depth:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "fifo depth:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -1942,54 +1375,29 @@ int slsReceiverTCPIPInterface::set_activate() { int enable = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&enable,sizeof(enable)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &enable, sizeof(enable), true, receiver) == FAIL) + return FAIL; if (myDetectorType != EIGER) functionNotImplemented(); - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - else { - if (receiverBase == NULL) - invalidReceiverObject(); - else { - // set - if(enable >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setActivate(enable > 0 ? true : false); - } - } - //get - retval = (int)receiverBase->getActivate(); - if(enable >= 0 && retval != enable){ - ret = FAIL; - sprintf(mess,"Could not set activate to %d, returned %d\n",enable,retval); - FILE_LOG(logERROR) << mess; + // base object not null + else if (ret == OK) { + // set + if (enable >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting activate:" << enable; + receiver->setActivate(enable > 0 ? true : false); } } + // get + retval = (int)receiver->getActivate(); + validate(enable, retval, std::string("set activate"), DEC); + FILE_LOG(logDEBUG1) << "Activate: " << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "Activate: " << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -2000,102 +1408,56 @@ int slsReceiverTCPIPInterface::set_data_stream_enable(){ int index = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&index,sizeof(index)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &index, sizeof(index), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set - if(index >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - ret = receiverBase->setDataStreamEnable(index); + if (index >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting data stream enable:" << index; + ret = receiver->setDataStreamEnable(index); } } - //get - retval = receiverBase->getDataStreamEnable(); - if(index >= 0 && retval != index){ - ret = FAIL; - strcpy(mess,"Could not set data stream enable"); - FILE_LOG(logERROR) << mess; - } + // get + retval = receiver->getDataStreamEnable(); + validate(index, retval, std::string("set data stream enable"), DEC); + FILE_LOG(logDEBUG1) << "data streaming enable:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "data streaming enable:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } -int slsReceiverTCPIPInterface::set_read_receiver_timer(){ +int slsReceiverTCPIPInterface::set_streaming_timer(){ ret = OK; memset(mess, 0, sizeof(mess)); int index = -1; int retval = -1; - // receive arguments - if(mySock->ReceiveDataOnly(&index,sizeof(index)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &index, sizeof(index), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set - if(index >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setFrameToGuiTimer(index); + if (index >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting streaming timer:" << index; + receiver->setStreamingTimer(index); } } - //get - retval=receiverBase->getFrameToGuiTimer(); - if(index >= 0 && retval != index){ - ret = FAIL; - strcpy(mess,"Could not set datastream timer"); - FILE_LOG(logERROR) << mess; - } + // get + retval=receiver->getStreamingTimer(); + validate(index, retval, std::string("set data stream timer"), DEC); + FILE_LOG(logDEBUG1) << "Streaming timer:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "receiver read timer:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -2106,108 +1468,59 @@ int slsReceiverTCPIPInterface::set_flipped_data(){ int args[2] = {0,-1}; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(args,sizeof(args)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, args, sizeof(args), true, receiver) == FAIL) + return FAIL; if (myDetectorType != EIGER) functionNotImplemented(); - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - else { - if (receiverBase == NULL) - invalidReceiverObject(); - else { - // set - if(args[1] >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setFlippedData(args[0],args[1]); - } - } - //get - retval=receiverBase->getFlippedData(args[0]); - if (args[1] > -1 && retval != args[1]) { - ret = FAIL; - strcpy(mess, "Could not set flipped data\n"); - FILE_LOG(logERROR) << mess; + // base object not null + else if (ret == OK) { + // set + if (args[1] >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting flipped data:" << args[1]; + receiver->setFlippedData(args[0],args[1]); } } + // get + retval=receiver->getFlippedData(args[0]); + validate(args[1], retval, std::string("set flipped data"), DEC); + FILE_LOG(logDEBUG1) << "Flipped Data:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "Flipped Data:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } - int slsReceiverTCPIPInterface::set_file_format() { ret = OK; memset(mess, 0, sizeof(mess)); fileFormat retval = GET_FILE_FORMAT; fileFormat f = GET_FILE_FORMAT; - // receive arguments - if (mySock->ReceiveDataOnly(&f,sizeof(f)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &f, sizeof(f), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set - if(f >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setFileFormat(f); + if (f >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting file format:" << f; + receiver->setFileFormat(f); } } - //get - retval = receiverBase->getFileFormat(); - if(f >= 0 && retval != f){ - ret = FAIL; - sprintf(mess,"Could not set file format to %s, returned %s\n",getFileFormatType(f).c_str(),getFileFormatType(retval).c_str()); - FILE_LOG(logERROR) << mess; - } + // get + retval = receiver->getFileFormat(); + validate(f, retval, std::string("set file format"), DEC); + FILE_LOG(logDEBUG1) << "File Format: " << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "File Format: " << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -2218,490 +1531,310 @@ int slsReceiverTCPIPInterface::set_detector_posid() { int arg = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&arg,sizeof(arg)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &arg, sizeof(arg), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set - if(arg >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setDetectorPositionId(arg); + if (arg >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting detector position id:" << arg; + receiver->setDetectorPositionId(arg); } } - //get - retval=receiverBase->getDetectorPositionId(); - if (arg >= 0 && retval != arg) { - ret = FAIL; - strcpy(mess,"Could not set detector position id"); - FILE_LOG(logERROR) << mess; - } + // get + retval = receiver->getDetectorPositionId(); + validate(arg, retval, std::string("set detector position id"), DEC); + FILE_LOG(logDEBUG1) << "Position Id:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "Position Id:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } - - - int slsReceiverTCPIPInterface::set_multi_detector_size() { ret = OK; memset(mess, 0, sizeof(mess)); int arg[2] = {-1, -1}; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(arg,sizeof(arg)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, arg, sizeof(arg), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set if((arg[0] > 0) && (arg[1] > 0)) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setMultiDetectorSize(arg); + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting multi detector size:" << arg[0] << "," << arg[1]; + receiver->setMultiDetectorSize(arg); } } - //get - int* temp = receiverBase->getMultiDetectorSize(); + // get + int* temp = receiver->getMultiDetectorSize(); for (int i = 0; i < MAX_DIMENSIONS; ++i) { if (!i) retval = temp[i]; else retval *= temp[i]; } + FILE_LOG(logDEBUG1) << "Multi Detector Size:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "Multi Detector Size:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } - int slsReceiverTCPIPInterface::set_streaming_port() { ret = OK; memset(mess, 0, sizeof(mess)); int port = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&port,sizeof(port)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &port, sizeof(port), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set - if(port >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setStreamingPort(port); + if (port >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting streaming port:" << port; + receiver->setStreamingPort(port); } } - //get - retval=receiverBase->getStreamingPort(); + // get + retval = receiver->getStreamingPort(); + validate(port, retval, std::string("set streaming port"), DEC); + FILE_LOG(logDEBUG1) << "streaming port:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "streaming port:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } - - int slsReceiverTCPIPInterface::set_streaming_source_ip() { ret = OK; memset(mess, 0, sizeof(mess)); - char arg[MAX_STR_LENGTH]; - memset(arg, 0, sizeof(arg)); - char* retval=NULL; + char arg[MAX_STR_LENGTH] = {0}; + char retval[MAX_STR_LENGTH] = {0}; - // receive arguments - if (mySock->ReceiveDataOnly(arg,MAX_STR_LENGTH) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, arg, MAX_STR_LENGTH, true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { - // set - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setStreamingSourceIP(arg); + // base object not null + if (ret == OK) { + // only set + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting streaming source ip:" << arg; + receiver->setStreamingSourceIP(arg); } - - //get - retval = receiverBase->getStreamingSourceIP(); + // get + strcpy(retval, receiver->getStreamingSourceIP().c_str()); + FILE_LOG(logDEBUG1) << "streaming source ip:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "streaming source ip:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(retval,MAX_STR_LENGTH); - delete[] retval; - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, retval, MAX_STR_LENGTH, mess); } - - - - int slsReceiverTCPIPInterface::set_silent_mode() { ret = OK; memset(mess, 0, sizeof(mess)); int value = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&value,sizeof(value)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &value, sizeof(value), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set - if(value >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setSilentMode(value); // no check required + if (value >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting silent mode:" << value; + receiver->setSilentMode(value); } } - //get - retval = (int)receiverBase->getSilentMode(); // no check required + // get + retval = (int)receiver->getSilentMode(); + validate(value, retval, std::string("set silent mode"), DEC); + FILE_LOG(logDEBUG1) << "silent mode:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "silent mode:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } - - - int slsReceiverTCPIPInterface::enable_gap_pixels() { ret = OK; memset(mess, 0, sizeof(mess)); int enable = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&enable,sizeof(enable)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &enable, sizeof(enable), true, receiver) == FAIL) + return FAIL; + if (myDetectorType != EIGER) + functionNotImplemented(); - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + else if (ret == OK) { // set - if(enable >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - if ((myDetectorType != EIGER) && (enable > 0)) - functionNotImplemented(); - else - receiverBase->setGapPixelsEnable(enable); + if (enable >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting gap pixels enable:" << enable; + receiver->setGapPixelsEnable(enable); } } - //get - retval = receiverBase->getGapPixelsEnable(); - if(enable >= 0 && retval != enable){ - ret = FAIL; - sprintf(mess,"Could not set gap pixels to %d, returned %d\n",enable,retval); - FILE_LOG(logERROR) << "Warning: " << mess; - } + // get + retval = receiver->getGapPixelsEnable(); + validate(enable, retval, std::string("set gap pixels enable"), DEC); + FILE_LOG(logDEBUG1) << "Gap Pixels Enable: " << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "Gap Pixels Enable: " << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } - int slsReceiverTCPIPInterface::restream_stop(){ ret = OK; memset(mess, 0, sizeof(mess)); - // execute action - // only a set, not a get -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else if (receiverBase->getDataStreamEnable() == false) { - ret = FAIL; - sprintf(mess,"Could not restream stop packet as data Streaming is disabled.\n"); - FILE_LOG(logERROR) << mess; - } else { - ret = receiverBase->restreamStop(); - if (ret == FAIL) { - sprintf(mess,"Could not restream stop packet.\n"); - FILE_LOG(logERROR) << mess; + // no arg, and check receiver is null + interface->Server_ReceiveArg(ret, mess, nullptr, 0, true, receiver); + + // receiver is not null + if (ret == OK) { + // only set + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + if (receiver->getDataStreamEnable() == false) { + ret = FAIL; + sprintf(mess,"Could not restream stop packet as data Streaming is disabled.\n"); + FILE_LOG(logERROR) << mess; + } else { + FILE_LOG(logDEBUG1) << "Restreaming stop"; + ret = receiver->restreamStop(); + if (ret == FAIL) { + sprintf(mess,"Could not restream stop packet.\n"); + FILE_LOG(logERROR) << mess; + } + } } } -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, nullptr, 0, mess); } int slsReceiverTCPIPInterface::set_additional_json_header() { - ret = OK; + ret = OK; memset(mess, 0, sizeof(mess)); - char arg[MAX_STR_LENGTH]; - memset(arg, 0, sizeof(arg)); - char* retval=NULL; - // std::cout << "set additional json header" << std::endl; - // receive arguments - if (mySock->ReceiveDataOnly(arg,MAX_STR_LENGTH) < 0 ) - return printSocketReadError(); - - // std::cout << arg << endl; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { - // set - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setAdditionalJsonHeader(arg); - } + char arg[MAX_STR_LENGTH] = {0}; + char retval[MAX_STR_LENGTH] = {0}; - //get - retval = receiverBase->getAdditionalJsonHeader(); - } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "additional json header:" << retval; -#endif + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, arg, sizeof(arg), true, receiver) == FAIL) + return FAIL; - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; + // base object not null + if (ret == OK) { + // only set + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting additional json header: " << arg; + receiver->setAdditionalJsonHeader(arg); + } + // get + strcpy(retval, receiver->getAdditionalJsonHeader().c_str()); + FILE_LOG(logDEBUG1) << "additional json header:" << retval; + } + return interface->Server_SendResult(true, ret, retval, MAX_STR_LENGTH, mess); +} - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(retval,MAX_STR_LENGTH); - delete[] retval; - // return ok/fail - return ret; + +int slsReceiverTCPIPInterface::get_additional_json_header() { + ret = OK; + memset(mess, 0, sizeof(mess)); + char retval[MAX_STR_LENGTH] = {0}; + + // no arg, check receiver is null + interface->Server_ReceiveArg(ret, mess, nullptr, 0, true, receiver); + + // base object not null + if (ret == OK) { + // get + strcpy(retval, receiver->getAdditionalJsonHeader().c_str()); + FILE_LOG(logDEBUG1) << "additional json header:" << retval; + } + return interface->Server_SendResult(true, ret, retval, MAX_STR_LENGTH, mess); } int slsReceiverTCPIPInterface::set_udp_socket_buffer_size() { - ret = OK; + ret = OK; memset(mess, 0, sizeof(mess)); - int index = -1; - int retval = -1; + int64_t index = -1; + int64_t retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&index,sizeof(index)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &index, sizeof(index), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { - // set - if(index >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - if (receiverBase->setUDPSocketBufferSize(index) == FAIL) { + // base object not null + if (ret == OK) { + // set + if (index >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting UDP Socket Buffer size: " << index; + if (receiver->setUDPSocketBufferSize(index) == FAIL) { ret = FAIL; strcpy(mess, "Could not create dummy UDP Socket to test buffer size\n"); FILE_LOG(logERROR) << mess; } - } - } - //get - retval=receiverBase->getUDPSocketBufferSize(); - if(index >= 0 && ((retval != index) || ((int)receiverBase->getActualUDPSocketBufferSize() != (index*2)))) { - ret = FAIL; - strcpy(mess, "Could not set UDP Socket buffer size (No CAP_NET_ADMIN privileges?)\n"); - FILE_LOG(logERROR) << mess; - } - } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "UDP Socket Buffer Size:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + } + } + // get + retval = receiver->getUDPSocketBufferSize(); + if (index != 0) + validate(index, retval, std::string("set udp socket buffer size (No CAP_NET_ADMIN privileges?)"), DEC); + FILE_LOG(logDEBUG1) << "UDP Socket Buffer Size:" << retval; + } + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } int slsReceiverTCPIPInterface::get_real_udp_socket_buffer_size(){ - ret = OK; - int retval = -1; + ret = OK; + memset(mess, 0, sizeof(mess)); + int64_t retval = -1; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else retval = receiverBase->getActualUDPSocketBufferSize(); -#endif + // no arg, check receiver is null + interface->Server_ReceiveArg(ret, mess, nullptr, 0, true, receiver); - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + if (ret == OK) { + FILE_LOG(logDEBUG1) << "Getting actual UDP buffer size"; + retval = receiver->getActualUDPSocketBufferSize(); + } + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } @@ -2712,70 +1845,39 @@ int slsReceiverTCPIPInterface::set_frames_per_file() { int index = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&index,sizeof(index)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &index, sizeof(index), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set - if(index >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setFramesPerFile(index); + if (index >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting frames per file: " << index; + receiver->setFramesPerFile(index); } } - //get - retval=receiverBase->getFramesPerFile(); - if(index >= 0 && retval != index) { - ret = FAIL; - strcpy(mess, "Could not set frames per file\n"); - FILE_LOG(logERROR) << mess; - } + // get + retval = receiver->getFramesPerFile(); + validate(index, retval, std::string("set frames per file"), DEC); + FILE_LOG(logDEBUG1) << "frames per file:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "frames per file:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } - - - int slsReceiverTCPIPInterface::check_version_compatibility() { ret = OK; memset(mess, 0, sizeof(mess)); int64_t arg = -1; - int64_t retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&arg,sizeof(arg)) < 0 ) - return printSocketReadError(); - - - // execute action + // get args, return if socket crashed + if (interface->Server_ReceiveArg(ret, mess, &arg, sizeof(arg)) == FAIL) + return FAIL; FILE_LOG(logDEBUG1) << "Checking versioning compatibility with value " << arg; - int64_t client_requiredVersion = arg; int64_t rx_apiVersion = APIRECEIVER; int64_t rx_version = getReceiverVersion(); @@ -2802,184 +1904,131 @@ int slsReceiverTCPIPInterface::check_version_compatibility() { FILE_LOG(logERROR) << mess; } else FILE_LOG(logINFO) << "Compatibility with Client: Successful"; - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); // sending crap (because of thisReceiver interface) - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, nullptr, 0, mess); } - int slsReceiverTCPIPInterface::set_discard_policy() { ret = OK; memset(mess, 0, sizeof(mess)); int index = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&index,sizeof(index)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &index, sizeof(index), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set - if(index >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setFrameDiscardPolicy((frameDiscardPolicy)index); + if (index >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting frames discard policy: " << index; + receiver->setFrameDiscardPolicy((frameDiscardPolicy)index); } } - //get - retval=receiverBase->getFrameDiscardPolicy(); - if(index >= 0 && retval != index) { - ret = FAIL; - strcpy(mess, "Could not set frame discard policy\n"); - FILE_LOG(logERROR) << mess; - } + // get + retval = receiver->getFrameDiscardPolicy(); + validate(index, retval, std::string("set discard policy"), DEC); + FILE_LOG(logDEBUG1) << "frame discard policy:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "frame discard policy:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } - int slsReceiverTCPIPInterface::set_padding_enable() { ret = OK; memset(mess, 0, sizeof(mess)); int index = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&index,sizeof(index)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &index, sizeof(index), true, receiver) == FAIL) + return FAIL; - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - if (receiverBase == NULL) - invalidReceiverObject(); - else { + // base object not null + if (ret == OK) { // set - if(index >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { + if (index >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { index = (index == 0) ? 0 : 1; - receiverBase->setFramePaddingEnable(index); + FILE_LOG(logDEBUG1) << "Setting frames padding enable: " << index; + receiver->setFramePaddingEnable(index); } } - //get - retval=(int)receiverBase->getFramePaddingEnable(); - if(index >= 0 && retval != index) { - ret = FAIL; - strcpy(mess, "Could not set frame padding enable\n"); - FILE_LOG(logERROR) << mess; - } + // get + retval = (int)receiver->getFramePaddingEnable(); + validate(index, retval, std::string("set frame padding enable"), DEC); + FILE_LOG(logDEBUG1) << "Frame Padding Enable:" << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "Frame Padding Enable:" << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } - int slsReceiverTCPIPInterface::set_deactivated_receiver_padding_enable() { ret = OK; memset(mess, 0, sizeof(mess)); int enable = -1; int retval = -1; - // receive arguments - if (mySock->ReceiveDataOnly(&enable,sizeof(enable)) < 0 ) - return printSocketReadError(); + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &enable, sizeof(enable), true, receiver) == FAIL) + return FAIL; if (myDetectorType != EIGER) functionNotImplemented(); - // execute action -#ifdef SLS_RECEIVER_UDP_FUNCTIONS - else { - if (receiverBase == NULL) - invalidReceiverObject(); - else { - // set - if(enable >= 0) { - if (mySock->differentClients && lockStatus) - receiverlocked(); - else if (receiverBase->getStatus() != IDLE) - receiverNotIdle(); - else { - receiverBase->setDeactivatedPadding(enable > 0 ? true : false); - } - } - //get - retval = (int)receiverBase->getDeactivatedPadding(); - if(enable >= 0 && retval != enable){ - ret = FAIL; - sprintf(mess,"Could not set deactivated padding enable to %d, returned %d\n",enable,retval); - FILE_LOG(logERROR) << mess; + // base object not null + else if (ret == OK) { + // set + if (enable >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting deactivated padding enable: " << enable; + receiver->setDeactivatedPadding(enable > 0 ? true : false); } } + // get + retval = (int)receiver->getDeactivatedPadding(); + validate(enable, retval, std::string("set deactivated padding enable"), DEC); + FILE_LOG(logDEBUG1) << "Deactivated Padding Enable: " << retval; } -#endif -#ifdef VERYVERBOSE - FILE_LOG(logDEBUG1) << "Deactivated Padding Enable: " << retval; -#endif - - if (ret == OK && mySock->differentClients) - ret = FORCE_UPDATE; - - // send answer - mySock->SendDataOnly(&ret,sizeof(ret)); - if (ret == FAIL) - mySock->SendDataOnly(mess,sizeof(mess)); - mySock->SendDataOnly(&retval,sizeof(retval)); - - // return ok/fail - return ret; + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); +} + + +int slsReceiverTCPIPInterface::set_readout_flags() { + ret = OK; + memset(mess, 0, sizeof(mess)); + readOutFlags arg = GET_READOUT_FLAGS; + readOutFlags retval = GET_READOUT_FLAGS; + + // get args, return if socket crashed, ret is fail if receiver is not null + if (interface->Server_ReceiveArg(ret, mess, &arg, sizeof(arg), true, receiver) == FAIL) + return FAIL; + + if (myDetectorType == JUNGFRAU || myDetectorType == GOTTHARD || myDetectorType == MOENCH) + functionNotImplemented(); + + // base object not null + else if (ret == OK) { + // set + if (arg >= 0) { + // verify if receiver is unlocked and idle + if (interface->Server_VerifyLockAndIdle(ret, mess, lockStatus, receiver->getStatus(), fnum) == OK) { + FILE_LOG(logDEBUG1) << "Setting readout flag: " << arg; + ret = receiver->setReadOutFlags(arg); + } + } + // get + retval = receiver->getReadOutFlags(); + validate((int)arg, (int)(retval & arg), std::string("set readout flags"), HEX); + FILE_LOG(logDEBUG1) << "Readout flags: " << retval; + } + return interface->Server_SendResult(true, ret, &retval, sizeof(retval), mess); } diff --git a/slsReceiverSoftware/src/slsReceiverUsers.cpp b/slsReceiverSoftware/src/slsReceiverUsers.cpp old mode 100644 new mode 100755 index f65751dbb..572f5fe22 --- a/slsReceiverSoftware/src/slsReceiverUsers.cpp +++ b/slsReceiverSoftware/src/slsReceiverUsers.cpp @@ -1,19 +1,19 @@ +#include "container_utils.h" // For sls::make_unique<> + #include "slsReceiverUsers.h" -#include "slsReceiver.h" slsReceiverUsers::slsReceiverUsers(int argc, char *argv[], int &success) { // catch the exception here to limit it to within the library (for current version) try { - slsReceiver* r = new slsReceiver(argc, argv); - receiver = r; - success = slsReceiverDefs::OK; + receiver = sls::make_unique(argc, argv); + success = slsDetectorDefs::OK; } catch (...) { - success = slsReceiverDefs::FAIL; + success = slsDetectorDefs::FAIL; } } -slsReceiverUsers::~slsReceiverUsers() { - delete receiver; +slsReceiverUsers::slsReceiverUsers(int tcpip_port_no) { + receiver = sls::make_unique(tcpip_port_no); } int slsReceiverUsers::start() { diff --git a/slsReceiverSoftware/src/utilities.cpp b/slsReceiverSoftware/src/utilities.cpp deleted file mode 100644 index 60215c96b..000000000 --- a/slsReceiverSoftware/src/utilities.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include - -#include "utilities.h" -#include "logger.h" - - - - -int read_config_file(std::string fname, int *tcpip_port_no, std::map * configuration_map ){ - - std::ifstream infile; - std::string sLine,sargname, sargvalue; - int iline = 0; - int success = slsReceiverDefs::OK; - - - FILE_LOG(logINFO) << "config file name " << fname; - try { - infile.open(fname.c_str(), std::ios_base::in); - } catch(...) { - FILE_LOG(logERROR) << "Could not open configuration file " << fname ; - success = slsReceiverDefs::FAIL; - } - - if (success == slsReceiverDefs::OK && infile.is_open()) { - while(infile.good()){ - getline(infile,sLine); - iline++; - - //VERBOSE_PRINT(sLine); - - if(sLine.find('#') != std::string::npos) - continue; - - else if(sLine.length()<2) - continue; - - else{ - std::istringstream sstr(sLine); - - //parameter name - if(sstr.good()){ - sstr >> sargname; - - if (! sstr.good()) - continue; - - sstr >> sargvalue; - (*configuration_map)[sargname] = sargvalue; - } - //tcp port - if(sargname=="rx_tcpport"){ - if(sstr.good()) { - sstr >> sargname; - if(sscanf(sargname.c_str(),"%d",tcpip_port_no)) - cprintf(RESET, "dataport: %d\n" , *tcpip_port_no); - else{ - cprintf(RED, "could not decode port in config file. Exiting.\n"); - success = slsReceiverDefs::FAIL; - } - } - } - } - } - infile.close(); - } - - return success; -} - - - - diff --git a/slsReceiverSoftware/tests/CMakeLists.txt b/slsReceiverSoftware/tests/CMakeLists.txt new file mode 100755 index 000000000..03e10f106 --- /dev/null +++ b/slsReceiverSoftware/tests/CMakeLists.txt @@ -0,0 +1,24 @@ +# include_directories( +# ${PROJECT_SOURCE_DIR}/catch +# ) + +# set(SOURCES +# test.cpp +# test-GeneralData.cpp +# ) + +target_sources(tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/test-GeneralData.cpp) + +# add_executable(testSlsReceiver ${SOURCES}) +# target_link_libraries(testSlsReceiver +# slsSupportLib +# slsDetectorShared +# slsReceiverShared +# pthread +# rt +# ) +# set_target_properties(testSlsReceiver PROPERTIES +# RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin +# ) +# #TODO! Move to automatic test discovery +# add_test(test-testSlsReceiver ${CMAKE_BINARY_DIR}/bin/testSlsReceiver) \ No newline at end of file diff --git a/slsReceiverSoftware/tests/test-GeneralData.cpp b/slsReceiverSoftware/tests/test-GeneralData.cpp new file mode 100755 index 000000000..996ad612f --- /dev/null +++ b/slsReceiverSoftware/tests/test-GeneralData.cpp @@ -0,0 +1,83 @@ + +#include "GeneralData.h" +#include "catch.hpp" + + +#include + + + +// using namespace sls; + +TEST_CASE("Parse jungfrauctb header", "[receiver]") { + + struct packet { + unsigned char emptyHeader[6]; + unsigned char reserved[4]; + unsigned char packetNumber[1]; + unsigned char frameNumber[3]; + unsigned char bunchid[8]; + unsigned char data[UDP_PACKET_DATA_BYTES]; + } __attribute__((packed)); + + MoenchData data; + + packet test_packet; + test_packet.packetNumber[0] = 53u; + test_packet.frameNumber[0] = 32u; + test_packet.frameNumber[1] = 15u; + test_packet.frameNumber[2] = 91u; + + test_packet.bunchid[0] = 91u; + test_packet.bunchid[1] = 25u; + test_packet.bunchid[2] = 15u; + test_packet.bunchid[3] = 1u; + test_packet.bunchid[4] = 32u; + test_packet.bunchid[5] = 251u; + test_packet.bunchid[6] = 18u; + test_packet.bunchid[7] = 240u; + + int index = 0; + char *packetData = reinterpret_cast(&test_packet); + uint32_t dynamicRange{0}; + bool oddStartingPacket{0}; + uint64_t frameNumber{0}; + uint32_t packetNumber{0}; + uint32_t subFrameNumber{0}; + uint64_t bunchId{0}; + + data.GetHeaderInfo(index, packetData, dynamicRange, oddStartingPacket, + frameNumber, packetNumber, subFrameNumber, bunchId); + + CHECK(packetNumber == 53); + CHECK(frameNumber == 0x5b0f20); + CHECK(bunchId == 0xf012fb20010f195b); + CHECK(subFrameNumber == -1); +} + +TEST_CASE("Parse header gotthard data", "[receiver]") { + GotthardData data; + struct packet { + uint32_t frameNumber; + unsigned char data[GOTTHARD_PACKET_SIZE]; + } __attribute__((packed)); + packet test_packet; + test_packet.frameNumber = 25698u; + + int index = 0; + char *packetData = reinterpret_cast(&test_packet); + uint32_t dynamicRange{0}; + bool oddStartingPacket{0}; + uint64_t frameNumber{0}; + uint32_t packetNumber{0}; + uint32_t subFrameNumber{0}; + uint64_t bunchId{0}; + + data.GetHeaderInfo(index, packetData, dynamicRange, oddStartingPacket, + frameNumber, packetNumber, subFrameNumber, bunchId); + + CHECK(frameNumber == test_packet.frameNumber/2); + CHECK(subFrameNumber == -1); + CHECK(bunchId == -1); + +} \ No newline at end of file diff --git a/slsReceiverSoftware/updateAPIVersion.sh b/slsReceiverSoftware/updateAPIVersion.sh deleted file mode 100755 index 389b2929e..000000000 --- a/slsReceiverSoftware/updateAPIVersion.sh +++ /dev/null @@ -1,7 +0,0 @@ -SRCFILE=include/gitInfoReceiver.h -DSTFILE=include/versionAPI.h - -SRCPATTERN=GITDATE -DSTPATTERN=APIRECEIVER - -awk -v a="$SRCFILE" -v b="$DSTFILE" -v c="$SRCPATTERN" -v d="$DSTPATTERN" 'FNR==NR&&$2==c{x=$3} NR!=FNR{if($2==d){$3="0x"substr(x,5)}print > b}' $SRCFILE $DSTFILE \ No newline at end of file diff --git a/slsReceiverSoftware/updateGitVersion.sh b/slsReceiverSoftware/updateGitVersion.sh deleted file mode 100755 index 83b9a65bb..000000000 --- a/slsReceiverSoftware/updateGitVersion.sh +++ /dev/null @@ -1,28 +0,0 @@ -MAINDIR=slsDetectorsPackage -SPECDIR=slsReceiverSoftware -TMPFILE=include/gitInfoReceiverTmp.h -INCLFILE=include/gitInfoReceiver.h -WD=$PWD - -#evaluate the variables -EVALFILE=../evalVersionVariables.sh -source $EVALFILE - -#get modified date -#RDATE1='git log --pretty=format:"%ci" -1' -RDATE1="find . -type f -exec stat --format '%Y :%y %n' '{}' \; | sort -nr | cut -d: -f2- | egrep -v 'gitInfo|build|.git|updateGitVersion' | head -n 1" -RDATE=`eval $RDATE1` -NEWDATE=$(sed "s/-//g" <<< $RDATE | awk '{print $1;}') -NEWDATE=${NEWDATE/#/0x} - -#get old date from INCLFILE -OLDDATE=$(more $INCLFILE | grep '#define GITDATE' | awk '{print $3}') - -#update INCLFILE if changes -if [ "$OLDDATE" != "$NEWDATE" ]; then - echo Path: ${MAINDIR}/${SPECDIR} $'\n'URL: ${GITREPO} $'\n'Repository Root: ${GITREPO} $'\n'Repsitory UUID: ${REPUID} $'\n'Revision: ${FOLDERREV} $'\n'Branch: ${BRANCH} $'\n'Last Changed Author: ${AUTH1}_${AUTH2} $'\n'Last Changed Rev: ${REV} $'\n'Last Changed Date: ${RDATE} > gitInfo.txt - cd .. - ./genVersionHeader.sh $SPECDIR/gitInfo.txt $SPECDIR/$TMPFILE $SPECDIR/$INCLFILE - cd $WD -fi - diff --git a/slsSupportLib/CMakeLists.txt b/slsSupportLib/CMakeLists.txt new file mode 100755 index 000000000..ae44b93c6 --- /dev/null +++ b/slsSupportLib/CMakeLists.txt @@ -0,0 +1,71 @@ +set(SOURCES + src/ClientInterface.cpp + src/CmdLineParser.cpp + src/string_utils.cpp + src/file_utils.cpp + src/ClientSocket.cpp + src/DataSocket.cpp + src/ServerSocket.cpp + src/ServerInterface.cpp + src/network_utils.cpp +) + +set(HEADERS +) + +set(PUBLICHEADERS + include/ansi.h + include/sls_detector_defs.h + include/sls_detector_funcs.h + include/error_defs.h + include/versionAPI.h + include/sls_detector_exceptions.h + include/file_utils.h + include/container_utils.h + include/string_utils.h + include/ClientInterface.h + include/MySocketTCP.h + include/genericSocket.h + include/logger.h + include/ClientSocket.h + include/DataSocket.h + include/ServerSocket.h + include/ServerInterface.h + include/network_utils.h +) + +add_library(slsSupportLib SHARED + ${SOURCES} + ${HEADERS} +) + +check_ipo_supported(RESULT result) +if(result) + set_property(TARGET slsSupportLib PROPERTY INTERPROCEDURAL_OPTIMIZATION True) +endif() + +target_include_directories(slsSupportLib PUBLIC + ${ZeroMQ_INCLUDE_DIRS} + "$" + "$" +) + +set_target_properties(slsSupportLib PROPERTIES + LIBRARY_OUTPUT_NAME SlsSupport + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin + PUBLIC_HEADER "${PUBLICHEADERS}" +) + +target_link_libraries(slsSupportLib slsProjectOptions slsProjectWarnings) + +if (SLS_USE_TESTS) + add_subdirectory(tests) +endif(SLS_USE_TESTS) + +# Install the library +install(TARGETS slsSupportLib + EXPORT "${TARGETS_EXPORT_NAME}" + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} +) diff --git a/slsSupportLib/include/ClientInterface.h b/slsSupportLib/include/ClientInterface.h new file mode 100755 index 000000000..379d10bd6 --- /dev/null +++ b/slsSupportLib/include/ClientInterface.h @@ -0,0 +1,71 @@ +#pragma once + + +#include "sls_detector_defs.h" +#include "MySocketTCP.h" +#include "ClientSocket.h" + + +/** + * @short the ClientInterface class is the interface between the client and the server + */ +// Do not overload to make it easier for manual comparison between client and server functions + +class ClientInterface: public virtual slsDetectorDefs{ + +public: + + /** + * (default) constructor + * @param socket tcp socket between client and receiver + * @param n for debugging purposes (useful only for client side) + * @param t string to identify type (Detector, Receiver) for printouts (useful only for client side) + */ + ClientInterface(sls::ClientSocket* socket, int n); + + /** + * destructor + */ + virtual ~ClientInterface() = default; + + void SetSocket(sls::ClientSocket *socket){ + socket_ = socket; + } + + /** + * Receive ret, mess or retval from Server + * @param ret result of operation + * @param mess pointer to message + * @param retval pointer to retval + * @param sizeOfRetval size of retval + */ + void Client_Receive(int& ret, char* mess, void* retval, int sizeOfRetval); + + /** + * Send Arguments to server and receives result back + * @param fnum function enum to determine what parameter + * @param args pointer to arguments + * @param sizeOfArgs argument size + * @param retval pointer to return value + * @param sizeOfRetval return value size + * @param mess pointer to message if message required externally + * @returns success of operation + */ + int Client_Send(int fnum, + void* args, int sizeOfArgs, + void* retval, int sizeOfRetval, + char* mess = 0); + + + + +private: + + /** + * socket for data acquisition + */ + sls::ClientSocket* socket_; + +}; + + diff --git a/slsSupportLib/include/ClientSocket.h b/slsSupportLib/include/ClientSocket.h new file mode 100755 index 000000000..14ec6e639 --- /dev/null +++ b/slsSupportLib/include/ClientSocket.h @@ -0,0 +1,44 @@ +#pragma once +#include "DataSocket.h" +#include +#include +#include +#include + +namespace sls { + +class ClientSocket : public DataSocket { + public: + ClientSocket(std::string stype, const std::string &hostname, uint16_t port_number); + ClientSocket(std::string stype, struct sockaddr_in addr); + int sendCommandThenRead(int fnum, void *args, size_t args_size, void *retval, + size_t retval_size); + + private: + void readReply(int &ret, void *retval, size_t retval_size); + struct sockaddr_in serverAddr {}; + std::string socketType; +}; + +class ReceiverSocket : public ClientSocket { + public: + ReceiverSocket(const std::string &hostname, uint16_t port_number) + : ClientSocket("Receiver", hostname, port_number){}; + ReceiverSocket(struct sockaddr_in addr) : ClientSocket("Receiver", addr){}; +}; + +class DetectorSocket : public ClientSocket { + public: + DetectorSocket(const std::string &hostname, uint16_t port_number) + : ClientSocket("Detector", hostname, port_number){}; + DetectorSocket(struct sockaddr_in addr) : ClientSocket("Detector", addr){}; +}; + +class GuiSocket : public ClientSocket { + public: + GuiSocket(const std::string &hostname, uint16_t port_number) + : ClientSocket("Gui", hostname, port_number){}; + GuiSocket(struct sockaddr_in addr) : ClientSocket("Gui", addr){}; +}; + +}; // namespace sls diff --git a/slsSupportLib/include/CmdLineParser.h b/slsSupportLib/include/CmdLineParser.h new file mode 100755 index 000000000..8066438d3 --- /dev/null +++ b/slsSupportLib/include/CmdLineParser.h @@ -0,0 +1,31 @@ +#ifndef CMD_LINE_PARSER_H +#define CMD_LINE_PARSER_H +#include +#include +#include + +class CmdLineParser { + public: + void Parse(int argc, char *argv[]); + void Parse(const std::string &s); + void Print(); + + //getters + int multi_id() const { return multi_id_; }; + int detector_id() const { return detector_id_; }; + int n_arguments() const { return arguments_.size(); } + const std::string &command() const { return command_; } + const std::string &executable() const { return executable_; } + const std::vector &arguments() const { return arguments_; }; + std::vector argv(); + + private: + void DecodeIdAndPosition(const char *c); + int multi_id_ = 0; + int detector_id_ = -1; + std::string command_; + std::string executable_; + std::vector arguments_; +}; + +#endif // CMD_LINE_PARSER_H \ No newline at end of file diff --git a/slsSupportLib/include/DataSocket.h b/slsSupportLib/include/DataSocket.h new file mode 100755 index 000000000..5b455b6dc --- /dev/null +++ b/slsSupportLib/include/DataSocket.h @@ -0,0 +1,36 @@ +#pragma once + +#include +#include +#include +#include +namespace sls { + +class DataSocket { + public: + DataSocket(int socketId); + DataSocket(DataSocket &&move) noexcept; + virtual ~DataSocket(); + DataSocket &operator=(DataSocket &&move) noexcept; + void swap(DataSocket &other) noexcept; + DataSocket(const DataSocket &) = delete; + DataSocket &operator=(DataSocket const &) = delete; + int getSocketId() const { + return socketId_; + } + size_t sendData(void *buffer, size_t size); + size_t receiveData(void *buffer, size_t size); + int setTimeOut(int t_seconds); + void close(); + void shutDownSocket(); + + private: + int socketId_ = -1; +}; + +int ConvertHostnameToInternetAddress(const char *const hostname, struct ::addrinfo **res); +int ConvertInternetAddresstoIpString(struct ::addrinfo *res, char *ip, const int ipsize); + +struct ::sockaddr_in ConvertHostnameToInternetAddress(const std::string &hostname); + +}; // namespace sls diff --git a/slsReceiverSoftware/include/MySocketTCP.h b/slsSupportLib/include/MySocketTCP.h old mode 100644 new mode 100755 similarity index 51% rename from slsReceiverSoftware/include/MySocketTCP.h rename to slsSupportLib/include/MySocketTCP.h index a3f6ea285..ff8de1bb5 --- a/slsReceiverSoftware/include/MySocketTCP.h +++ b/slsSupportLib/include/MySocketTCP.h @@ -12,56 +12,31 @@ /* canceled SetupParameters() and varaibles intialized in the constructors' headers; defined SEND_REC_MAX_SIZE (for compatibilty with mythen (and possibly other) pure C servers (i would move it to the common header file) - added #ifndef C_ONLY... to cutout class definition when including in pure C servers (can be removed if SEND_REC_MAX_SIZE is moved to the common header file) - defined private variables char hostname[1000] and int portno to store connection informations; - defined public functions int getHostname(char *name) and int getPortNumber() to retrieve connection informations - added public function int getErrorStatus() returning 1 if socketDescriptor<0 - remove exits in the constructors and replace them with socketDescriptor=-1 - replaced the argument of send/receive data with void (to avoid too much casting or compiler errors/warnings) - added a function which really does not close the socket between send/receive (senddataonly, receivedataonly) -*/ -/* Modified by Anna on 31.10.2012 - -developed and - -*/ - + Modified by Anna on 31.10.2012 developed and + */ #include "genericSocket.h" #define TCP_PACKET_SIZE 4096 -class MySocketTCP: public genericSocket { - - public: - MySocketTCP(const char* const host_ip_or_name, unsigned short int const port_number): genericSocket(host_ip_or_name, port_number,TCP), last_keep_connection_open_action_was_a_send(0){setPacketSize(TCP_PACKET_SIZE);}; // sender (client): where to? ip - MySocketTCP(unsigned short int const port_number):genericSocket(port_number,TCP), last_keep_connection_open_action_was_a_send(0) {setPacketSize(TCP_PACKET_SIZE);}; // receiver (server) local no need for ip +class MySocketTCP : public genericSocket { + public: + // sender (client): where to? ip + MySocketTCP(const char *const host_ip_or_name, uint16_t port_number) + : genericSocket(host_ip_or_name, port_number, TCP) { + setPacketSize(TCP_PACKET_SIZE); + } + // receiver (server) local no need for ip + MySocketTCP(uint16_t port_number) + : genericSocket(port_number, TCP) { + setPacketSize(TCP_PACKET_SIZE); + } virtual ~MySocketTCP(){}; - - //The following two functions will connectioned->send/receive->disconnect - int SendData(void* buf,int length);//length in characters - int ReceiveData(void* buf,int length); - - - //The following two functions stay connected, blocking other connections, and must be manually disconnected, - // when the last call is a SendData() or ReceiveData() the disconnection will be done automatically - //These function will also automatically disconnect->reconnect if - // two reads (or two writes) are called in a row to preserve the data send/receive structure - int SendDataAndKeepConnection(void* buf,int length); - int ReceiveDataAndKeepConnection(void* buf,int length); - - private: - - - bool last_keep_connection_open_action_was_a_send; - - }; - diff --git a/slsSupportLib/include/ServerInterface.h b/slsSupportLib/include/ServerInterface.h new file mode 100755 index 000000000..223efa3a2 --- /dev/null +++ b/slsSupportLib/include/ServerInterface.h @@ -0,0 +1,152 @@ +#pragma once + + +#include "sls_detector_defs.h" +#include "MySocketTCP.h" + + +/** + * @short the ServerInterface class is the interface between the client and the server + */ +// Do not overload to make it easier for manual comparison between client and server functions + +class ServerInterface: public virtual slsDetectorDefs{ + +public: + + /** + * (default) constructor + * @param socket tcp socket between client and receiver + * @param n for debugging purposes (useful only for client side) + * @param t string to identify type (Detector, Receiver) for printouts (useful only for client side) + */ + ServerInterface(MySocketTCP *socket, int n=-1, std::string t=""); + + /** + * destructor + */ + virtual ~ServerInterface() = default; + + /** + * Set the datasocket + * @param socket the data socket + */ + void SetSocket(MySocketTCP *socket); + + /** + * Receive ret, mess or retval from Server + * @param ret result of operation + * @param mess pointer to message + * @param retval pointer to retval + * @param sizeOfRetval size of retval + */ + void Client_Receive(int& ret, char* mess, void* retval, int sizeOfRetval); + + /** + * Send Arguments to server and receives result back + * @param fnum function enum to determine what parameter + * @param args pointer to arguments + * @param sizeOfArgs argument size + * @param retval pointer to return value + * @param sizeOfRetval return value size + * @param mess pointer to message if message required externally + * @returns success of operation + */ + int Client_Send(int fnum, + void* args, int sizeOfArgs, + void* retval, int sizeOfRetval, + char* mess = 0); + + + /** only Receiver + * Server sends result to client (also set ret to force_update if different clients) + * @param update true if one must update if different clients, else false + * @param ret success of operation + * @param retval pointer to result + * @param retvalSize size of result + * @param mess message + * @returns success of operation + */ + int Server_SendResult(bool update, int ret, void* retval, int retvalSize, char* mess = 0); + + /** only Receiver + * Server receives arguments and checks if base object is null (if checkbase is true) + * checking base object is null (for receiver only when it has not been configured yet) + * @param ret pointer to success of operation + * @param mess message + * @param arg pointer to argument + * @param sizeofArg size of argument + * @param checkbase if true, checks if base object is null and sets ret and mess accordingly + * @param base pointer to base object + * @returns fail if socket crashes while reading arguments, else fail + */ + int Server_ReceiveArg(int& ret, char* mess, void* arg, int sizeofArg,bool checkbase=false, void* base=NULL); + + /** only Receiver + * Server verifies if it is unlocked, + * sets and prints appropriate message if it is locked and different clients + * @param ret pointer to success + * @param mess message + * @param lockstatus status of lock + * @returns success of operaton + */ + int Server_VerifyLock(int& ret, char* mess, int lockstatus); + + /** only Receiver + * Server verifies if it is unlocked and idle, + * sets and prints appropriate message if it is locked and different clients + * @param ret pointer to success + * @param mess message + * @param lockstatus status of lock + * @param status status of server + * @param fnum function number for error message + * @returns success of operaton + */ + int Server_VerifyLockAndIdle(int& ret, char* mess, int lockstatus, slsDetectorDefs::runStatus status, int fnum); + + /** only Receiver + * Server sets and prints error message for null object error (receiver only) + * @param ret pointer to success that will be set to FAIL + * @param mess message + */ + void Server_NullObjectError(int& ret, char* mess); + + /** only Receiver + * Servers prints error message for socket crash when reading + * @returns always FAIL + */ + int Server_SocketCrash(); + + /** only Receiver + * Servers sets and prints error message for locked server + * @param ret pointer to success that will be set to FAIL + * @param mess message + * @returns success of operaton + */ + int Server_LockedError(int& ret, char* mess); + + /** only Receiver + * Servers sets and prints error message for server not being idle + * @param ret pointer to success that will be set to FAIL + * @param mess message + * @param fnum function number for error message + * @returns success of operaton + */ + int Server_NotIdleError(int& ret, char* mess, int fnum); + +private: + + /** + * socket for data acquisition + */ + MySocketTCP *mySocket; + + /** index for client debugging purposes */ + int index; + + /** string for type to differentiate between Detector & Receiver in printouts */ + std::string type; + +}; + + diff --git a/slsSupportLib/include/ServerSocket.h b/slsSupportLib/include/ServerSocket.h new file mode 100755 index 000000000..4e15a820a --- /dev/null +++ b/slsSupportLib/include/ServerSocket.h @@ -0,0 +1,28 @@ +#pragma once + +#include "DataSocket.h" + +#include +#include +#include +#include +#include + +namespace sls { + +class ServerSocket : public DataSocket { + public: + ServerSocket(int port); + DataSocket accept(); + const std::string &getLastClient(); + int getPort() const; + void SendResult(int &ret, void *retval, int retvalSize, char* mess); + + private: + std::string lastClient_ = std::string(INET_ADDRSTRLEN, '\0'); + std::string thisClient_ = std::string(INET_ADDRSTRLEN, '\0'); + int serverPort; + // char lastClient_[INET_ADDRSTRLEN]{}; +}; + +}; // namespace sls \ No newline at end of file diff --git a/slsSupportLib/include/Timer.h b/slsSupportLib/include/Timer.h new file mode 100755 index 000000000..4d03860e2 --- /dev/null +++ b/slsSupportLib/include/Timer.h @@ -0,0 +1,38 @@ +#ifndef TIMER_H +#define TIMER_H +#include +#include +#include + +namespace sls{ + +class Timer { + using clock = std::chrono::high_resolution_clock; + using time_point = std::chrono::time_point; + + public: + Timer(std::string name = "0") + : t0(clock::now()), name_(name) { + } + + double elapsed_ms() { + return std::chrono::duration(clock::now() - t0).count(); + } + double elapsed_s() { + return std::chrono::duration(clock::now() - t0).count(); + } + void print_elapsed() { + std::cout << "Timer \"" << name_ << "\": Elapsed time " << elapsed_ms() << " ms\n"; + } + void restart() { + t0 = clock::now(); + } + + private: + time_point t0; + std::string name_; +}; + + +}; //namespace sls +#endif // TIMER_H diff --git a/slsReceiverSoftware/include/ZmqSocket.h b/slsSupportLib/include/ZmqSocket.h old mode 100644 new mode 100755 similarity index 94% rename from slsReceiverSoftware/include/ZmqSocket.h rename to slsSupportLib/include/ZmqSocket.h index e58419a1e..6c7e1680f --- a/slsReceiverSoftware/include/ZmqSocket.h +++ b/slsSupportLib/include/ZmqSocket.h @@ -8,7 +8,7 @@ */ #include "ansi.h" - +#include "sls_detector_exceptions.h" #include #include @@ -27,6 +27,8 @@ using namespace rapidjson; // #define ZMQ_DETAIL #define ROIVERBOSITY + + class ZmqSocket { public: @@ -54,7 +56,7 @@ public: struct addrinfo *result; if ((ConvertHostnameToInternetAddress(hostname_or_ip, &result)) || (ConvertInternetAddresstoIpString(result, ip, MAX_STR_LENGTH))) - throw std::exception(); + throw sls::ZmqSocketError("Could convert IP to string"); // construct address sprintf (sockfd.serverAddress, "tcp://%s:%d", ip, portno); @@ -65,14 +67,14 @@ public: // create context sockfd.contextDescriptor = zmq_ctx_new(); if (sockfd.contextDescriptor == 0) - throw std::exception(); + throw sls::ZmqSocketError("Could not create contextDescriptor"); // create publisher sockfd.socketDescriptor = zmq_socket (sockfd.contextDescriptor, ZMQ_SUB); if (sockfd.socketDescriptor == 0) { PrintError (); Close (); - throw std::exception(); + throw sls::ZmqSocketError("Could not create socket"); } //Socket Options provided above @@ -80,7 +82,7 @@ public: if ( zmq_setsockopt(sockfd.socketDescriptor, ZMQ_SUBSCRIBE, "", 0)) { PrintError (); Close(); - throw std::exception(); + throw sls::ZmqSocketError("Could set socket opt"); } //ZMQ_LINGER default is already -1 means no messages discarded. use this options if optimizing required //ZMQ_SNDHWM default is 0 means no limit. use this to optimize if optimizing required @@ -89,7 +91,7 @@ public: if (zmq_setsockopt(sockfd.socketDescriptor, ZMQ_LINGER, &value,sizeof(value))) { PrintError (); Close(); - throw std::exception(); + throw sls::ZmqSocketError("Could not set ZMQ_LINGER"); } }; @@ -110,13 +112,13 @@ public: // create context sockfd.contextDescriptor = zmq_ctx_new(); if (sockfd.contextDescriptor == 0) - throw std::exception(); + throw sls::ZmqSocketError("Could not create contextDescriptor"); // create publisher sockfd.socketDescriptor = zmq_socket (sockfd.contextDescriptor, ZMQ_PUB); if (sockfd.socketDescriptor == 0) { PrintError (); Close (); - throw std::exception(); + throw sls::ZmqSocketError("Could not create socket"); } //Socket Options provided above @@ -130,7 +132,7 @@ public: if (zmq_bind (sockfd.socketDescriptor, sockfd.serverAddress) < 0) { PrintError (); Close (); - throw std::exception(); + throw sls::ZmqSocketError("Could not bind socket"); } //sleep for a few milliseconds to allow a slow-joiner @@ -245,7 +247,7 @@ public: */ int SendHeaderData ( int index, bool dummy, uint32_t jsonversion, uint32_t dynamicrange = 0, uint64_t fileIndex = 0, uint32_t npixelsx = 0, uint32_t npixelsy = 0, uint32_t imageSize = 0, - uint64_t acqIndex = 0, uint64_t fIndex = 0, char* fname = NULL, + uint64_t acqIndex = 0, uint64_t fIndex = 0, const char* fname = NULL, uint64_t frameNumber = 0, uint32_t expLength = 0, uint32_t packetNumber = 0, uint64_t bunchId = 0, uint64_t timestamp = 0, uint16_t modId = 0, uint16_t row = 0, uint16_t column = 0, uint16_t reserved = 0, @@ -254,25 +256,25 @@ public: char* additionalJsonHeader = 0) { - char buf[MAX_STR_LENGTH] = ""; + /** Json Header Format */ - const char* jsonHeaderFormat = + const char jsonHeaderFormat[] = "{" "\"jsonversion\":%u, " "\"bitmode\":%u, " - "\"fileIndex\":%llu, " + "\"fileIndex\":%lu, " "\"shape\":[%u, %u], " "\"size\":%u, " - "\"acqIndex\":%llu, " - "\"fIndex\":%llu, " + "\"acqIndex\":%lu, " + "\"fIndex\":%lu, " "\"fname\":\"%s\", " "\"data\": %d, " - "\"frameNumber\":%llu, " + "\"frameNumber\":%lu, " "\"expLength\":%u, " "\"packetNumber\":%u, " - "\"bunchId\":%llu, " - "\"timestamp\":%llu, " + "\"bunchId\":%lu, " + "\"timestamp\":%lu, " "\"modId\":%u, " "\"row\":%u, " "\"column\":%u, " @@ -286,7 +288,8 @@ public: "\"flippedDataX\":%u" ;//"}\n"; - int length = sprintf(buf, jsonHeaderFormat, + char buf[MAX_STR_LENGTH] = ""; + sprintf(buf, jsonHeaderFormat, jsonversion, dynamicrange, fileIndex, npixelsx, npixelsy, imageSize, acqIndex, fIndex, (fname == NULL)? "":fname, dummy?0:1, @@ -297,11 +300,13 @@ public: //additional stuff ((flippedData == 0 ) ? 0 :flippedData[0]) ); + if (additionalJsonHeader && strlen(additionalJsonHeader)) { - length = sprintf(buf, "%s, %s}\n", buf, additionalJsonHeader); - } else { - length = sprintf(buf, "%s}\n", buf); - } + strcat(buf, ", "); + strcat(buf, additionalJsonHeader); + } + strcat(buf, "}\n"); + int length = strlen(buf); #ifdef VERBOSE //if(!index) diff --git a/slsReceiverSoftware/include/ansi.h b/slsSupportLib/include/ansi.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/ansi.h rename to slsSupportLib/include/ansi.h diff --git a/slsSupportLib/include/container_utils.h b/slsSupportLib/include/container_utils.h new file mode 100755 index 000000000..ede320f4e --- /dev/null +++ b/slsSupportLib/include/container_utils.h @@ -0,0 +1,114 @@ +#ifndef CONTAINER_UTILS_H +#define CONTAINER_UTILS_H + +#include +#include +#include +#include +#include +#include +#include + +namespace sls { + +// C++11 make_unique implementation for exception safety +// already available as std::make_unique in C++14 +template +typename std::enable_if::value, std::unique_ptr>::type +make_unique(Args &&... args) { + return std::unique_ptr(new T(std::forward(args)...)); +} + +template +typename std::enable_if::value, std::unique_ptr>::type +make_unique(std::size_t n) { + typedef typename std::remove_extent::type RT; + return std::unique_ptr(new RT[n]); +} + +template bool allEqual(const std::vector &container) { + if (container.empty()) + return false; + const auto &first = container[0]; + return std::all_of(container.cbegin(), container.cend(), + [first](const T &element) { return element == first; }); +} + +template +typename std::enable_if::value, bool>::type +allEqualWithTol(const std::vector &container, const T tol) { + if (container.empty()) + return false; + + const auto &first = container[0]; + return std::all_of(container.cbegin(), container.cend(), + [first, tol](const T &element) { + return (std::abs(element - first) < tol); + }); +} + +template +bool allEqualTo(const std::vector &container, const T value) { + if (container.empty()) + return false; + + return std::all_of(container.cbegin(), container.cend(), + [value](const T &element) { return element == value; }); +} + +template +bool allEqualToWithTol(const std::vector &container, const T value, + const T tol) { + if (container.empty()) + return false; + + return std::all_of(container.cbegin(), container.cend(), + [value, tol](const T &element) { + return (std::abs(element - value) < tol); + }); +} + +template +bool anyEqualTo(const std::vector &container, const T value) { + return std::any_of(container.cbegin(), container.cend(), + [value](const T &element) { return element == value; }); +} + +template +bool anyEqualToWithTol(const std::vector &container, const T value, + const T tol) { + return std::any_of(container.cbegin(), container.cend(), + [value, tol](const T &element) { + return (std::abs(element - value) < tol); + }); +} + +template +typename std::enable_if::value, T>::type +sum(const std::vector &container) { + return std::accumulate(container.cbegin(), container.cend(), T{0}); +} + +template T minusOneIfDifferent(const std::vector &container) { + if (allEqual(container)) + return container.front(); + return static_cast(-1); +} + +inline int minusOneIfDifferent(const std::vector &container) { + if (allEqual(container)) + return static_cast(container.front()); + return -1; +} + +template +std::vector +minusOneIfDifferent(const std::vector> &container) { + if (allEqual(container)) + return container.front(); + return std::vector{-1}; +} + +} // namespace sls + +#endif // CONTAINER_UTILS_H diff --git a/slsDetectorSoftware/commonFiles/error_defs.h b/slsSupportLib/include/error_defs.h old mode 100644 new mode 100755 similarity index 76% rename from slsDetectorSoftware/commonFiles/error_defs.h rename to slsSupportLib/include/error_defs.h index dc733c2d7..6b521689c --- a/slsDetectorSoftware/commonFiles/error_defs.h +++ b/slsSupportLib/include/error_defs.h @@ -25,6 +25,9 @@ #define MULTI_DETECTORS_NOT_ADDED 0x8000000000000000ULL #define MULTI_HAVE_DIFFERENT_VALUES 0x4000000000000000ULL #define MULTI_CONFIG_FILE_ERROR 0x2000000000000000ULL +#define MULTI_POS_EXCEEDS_LIST 0x1000000000000000ULL +#define MUST_BE_MULTI_CMD 0x0800000000000000ULL +#define MULTI_OTHER_ERROR 0x0400000000000000ULL // sls errors #define CRITICAL_ERROR_MASK 0xFFFFFFF @@ -38,26 +41,24 @@ #define FILE_PATH_DOES_NOT_EXIST 0x0200000000000000ULL #define COULDNOT_CREATE_UDP_SOCKET 0x0100000000000000ULL #define COULDNOT_CREATE_FILE 0x0080000000000000ULL -#define COULDNOT_ENABLE_COMPRESSION 0x0040000000000000ULL -#define RECEIVER_DET_HOSTNAME_NOT_SET 0x0020000000000000ULL -#define RECEIVER_DET_HOSTTYPE_NOT_SET 0x0010000000000000ULL -#define DETECTOR_TEN_GIGA 0x0008000000000000ULL -#define DETECTOR_ACTIVATE 0x0004000000000000ULL -#define COULD_NOT_CONFIGURE_MAC 0x0002000000000000ULL -#define COULDNOT_START_RECEIVER 0x0001000000000000ULL // default error like starting threads -#define COULDNOT_STOP_RECEIVER 0x0000800000000000ULL -#define RECEIVER_DET_POSID_NOT_SET 0x0000400000000000ULL -#define RECEIVER_MULTI_DET_SIZE_NOT_SET 0x0000200000000000ULL -#define PREPARE_ACQUISITION 0x0000100000000000ULL -#define CLEANUP_ACQUISITION 0x0000080000000000ULL -#define REGISER_WRITE_READ 0x0000040000000000ULL -#define VERSION_COMPATIBILITY 0x0000020000000000ULL +#define RECEIVER_DET_HOSTNAME_NOT_SET 0x0040000000000000ULL +#define RECEIVER_DET_HOSTTYPE_NOT_SET 0x0020000000000000ULL +#define DETECTOR_TEN_GIGA 0x0010000000000000ULL +#define DETECTOR_ACTIVATE 0x0008000000000000ULL +#define COULD_NOT_CONFIGURE_MAC 0x0004000000000000ULL +#define COULDNOT_START_RECEIVER 0x0002000000000000ULL // default error like starting threads +#define COULDNOT_STOP_RECEIVER 0x0001000000000000ULL +#define RECEIVER_DET_POSID_NOT_SET 0x0000800000000000ULL +#define RECEIVER_MULTI_DET_SIZE_NOT_SET 0x0000400000000000ULL +#define PREPARE_ACQUISITION 0x0000200000000000ULL +#define REGISER_WRITE_READ 0x0000100000000000ULL +#define VERSION_COMPATIBILITY 0x0000080000000000ULL // 0xFFFFFF0000000000ULL // 0x000000FFFFFFFFFFULL #define COULDNOT_SET_NETWORK_PARAMETER 0x0000000000000001ULL #define COULDNOT_SET_ROI 0x0000000000000002ULL -#define RECEIVER_READ_FREQUENCY 0x0000000000000004ULL +#define RECEIVER_STREAMING_FREQUENCY 0x0000000000000004ULL #define SETTINGS_NOT_SET 0x0000000000000008ULL #define SETTINGS_FILE_NOT_OPEN 0x0000000000000010ULL #define DETECTOR_TIMER_VALUE_NOT_SET 0x0000000000000020ULL @@ -70,31 +71,30 @@ #define COULD_NOT_SET_READOUT_FLAGS 0x0000000000001000ULL #define COULD_NOT_SET_FIFO_DEPTH 0x0000000000002000ULL #define COULD_NOT_SET_COUNTER_BIT 0x0000000000004000ULL -#define COULD_NOT_PULSE_PIXEL 0x0000000000008000ULL -#define COULD_NOT_PULSE_PIXEL_NMOVE 0x0000000000010000ULL -#define COULD_NOT_PULSE_CHIP 0x0000000000020000ULL -#define COULD_NOT_SET_RATE_CORRECTION 0x0000000000040000ULL -#define DETECTOR_NETWORK_PARAMETER 0x0000000000080000ULL -#define RATE_CORRECTION_NOT_32or16BIT 0x0000000000100000ULL -#define RATE_CORRECTION_NO_TAU_PROVIDED 0x0000000000200000ULL -#define PROGRAMMING_ERROR 0x0000000000400000ULL -#define RECEIVER_ACTIVATE 0x0000000000800000ULL -#define DATA_STREAMING 0x0000000001000000ULL -#define RESET_ERROR 0x0000000002000000ULL -#define POWER_CHIP 0x0000000004000000ULL -#define RECEIVER_READ_TIMER 0x0000000008000000ULL -#define RECEIVER_ACQ_TIME_NOT_SET 0x0000000010000000ULL -#define RECEIVER_FLIPPED_DATA_NOT_SET 0x0000000020000000ULL -#define THRESHOLD_NOT_SET 0x0000000040000000ULL -#define RECEIVER_FILE_FORMAT 0x0000000080000000ULL -#define RECEIVER_PARAMETER_NOT_SET 0x0000000100000000ULL -#define RECEIVER_TIMER_NOT_SET 0x0000000200000000ULL -#define RECEIVER_ENABLE_GAPPIXELS_NOT_SET 0x0000000400000000ULL -#define RESTREAM_STOP_FROM_RECEIVER 0x0000000800000000ULL -#define TEMPERATURE_CONTROL 0x0000001000000000ULL -#define AUTO_COMP_DISABLE 0x0000002000000000ULL -#define CONFIG_FILE 0x0000004000000000ULL -#define STORAGE_CELL_START 0x0000008000000000ULL +#define COULD_NOT_PULSE 0x0000000000008000ULL +#define COULD_NOT_SET_RATE_CORRECTION 0x0000000000010000ULL +#define DETECTOR_NETWORK_PARAMETER 0x0000000000020000ULL +#define RATE_CORRECTION_NOT_32or16BIT 0x0000000000040000ULL +#define RATE_CORRECTION_NO_TAU_PROVIDED 0x0000000000080000ULL +#define PROGRAMMING_ERROR 0x0000000000100000ULL +#define RECEIVER_ACTIVATE 0x0000000000200000ULL +#define DATA_STREAMING 0x0000000000400000ULL +#define RESET_ERROR 0x0000000000800000ULL +#define POWER_CHIP 0x0000000001000000ULL +#define RECEIVER_STREAMING_TIMER 0x0000000002000000ULL +#define RECEIVER_ACQ_TIME_NOT_SET 0x0000000004000000ULL +#define RECEIVER_FLIPPED_DATA_NOT_SET 0x0000000008000000ULL +#define THRESHOLD_NOT_SET 0x0000000010000000ULL +#define RECEIVER_FILE_FORMAT 0x0000000020000000ULL +#define RECEIVER_PARAMETER_NOT_SET 0x0000000040000000ULL +#define RECEIVER_TIMER_NOT_SET 0x0000000080000000ULL +#define RECEIVER_ENABLE_GAPPIXELS_NOT_SET 0x0000000100000000ULL +#define RESTREAM_STOP_FROM_RECEIVER 0x0000000200000000ULL +#define TEMPERATURE_CONTROL 0x0000000400000000ULL +#define AUTO_COMP_DISABLE 0x0000000800000000ULL +#define CONFIG_FILE 0x0000001000000000ULL +#define STORAGE_CELL_START 0x0000002000000000ULL +#define OTHER_ERROR_CODE 0x0000004000000000ULL // 0x000000FFFFFFFFFFULL @@ -141,9 +141,6 @@ public: if(slsErrorMask&COULDNOT_CREATE_FILE) retval.append("Could not create file to start receiver.\nCheck permissions of output directory or the overwrite flag\n"); - if(slsErrorMask&COULDNOT_ENABLE_COMPRESSION) - retval.append("Could not enable/disable data compression in receiver.\nThread creation failed or recompile code with MYROOT1 flag.\n"); - if(slsErrorMask&RECEIVER_DET_HOSTNAME_NOT_SET) retval.append("Could not send the detector hostname to the receiver.\n"); @@ -165,9 +162,6 @@ public: if(slsErrorMask&PREPARE_ACQUISITION) retval.append("Could not prepare acquisition in detector\n"); - if(slsErrorMask&CLEANUP_ACQUISITION) - retval.append("Could not clean up after acquisition in detector\n"); - if(slsErrorMask®ISER_WRITE_READ) retval.append("Could not read/write register in detector\n"); @@ -185,7 +179,7 @@ public: if(slsErrorMask&COULDNOT_SET_ROI) retval.append("Could not set the exact region of interest. Verify ROI set by detector.\n"); - if(slsErrorMask&RECEIVER_READ_FREQUENCY) + if(slsErrorMask&RECEIVER_STREAMING_FREQUENCY) retval.append("Could not set receiver read frequency.\n"); if(slsErrorMask&SETTINGS_NOT_SET) @@ -230,14 +224,8 @@ public: if(slsErrorMask&COULD_NOT_SET_COUNTER_BIT) retval.append("Could not set/reset counter bit\n"); - if(slsErrorMask&COULD_NOT_PULSE_PIXEL) - retval.append("Could not pulse pixel\n"); - - if(slsErrorMask&COULD_NOT_PULSE_PIXEL_NMOVE) - retval.append("Could not pulse pixel and move\n"); - - if(slsErrorMask&COULD_NOT_PULSE_CHIP) - retval.append("Could not pulse chip\n"); + if(slsErrorMask&COULD_NOT_PULSE) + retval.append("Could not pulse pixel or chip\n"); if(slsErrorMask&COULD_NOT_SET_RATE_CORRECTION) retval.append("Could not set rate correction\n"); @@ -266,7 +254,7 @@ public: if(slsErrorMask&POWER_CHIP) retval.append("Could not power on/off/get the chip\n"); - if(slsErrorMask&RECEIVER_READ_TIMER) + if(slsErrorMask&RECEIVER_STREAMING_TIMER) retval.append("Could not set receiver read timer\n"); if(slsErrorMask&RECEIVER_FLIPPED_DATA_NOT_SET) @@ -299,6 +287,9 @@ public: if(slsErrorMask&CONFIG_FILE) retval.append("Could not load/write config file\n"); + if(slsErrorMask&OTHER_ERROR_CODE) + retval.append("Some error occured.\n"); + //------------------------------------------------------ length of message diff --git a/slsSupportLib/include/file_utils.h b/slsSupportLib/include/file_utils.h new file mode 100755 index 000000000..9be439e77 --- /dev/null +++ b/slsSupportLib/include/file_utils.h @@ -0,0 +1,56 @@ +#pragma once + + +#include "sls_detector_defs.h" + +#include +#include +#include + + +/** (used by multi and sls) + * reads a short int raw data file + * @param infile input file stream + * @param data array of data values + * @param nch number of channels + * @param offset start channel value + * @returns OK or FAIL if it could not read the file or data=NULL + */ +int readDataFile(std::ifstream &infile, short int *data, int nch, int offset=0); + + +/** (used by multi and sls) + * reads a short int rawdata file + * @param name of the file to be read + * @param data array of data value + * @param nch number of channels + * @returns OK or FAIL if it could not read the file or data=NULL + */ +int readDataFile(std::string fname, short int *data, int nch); + + +/** (used by multi and sls) + * writes a short int raw data file + * @param outfile output file stream + * @param nch number of channels + * @param data array of data values + * @param offset start channel number + * @returns OK or FAIL if it could not write the file or data=NULL + */ +int writeDataFile(std::ofstream &outfile,int nch, short int *data, int offset=0); + + + +/** (used by multi and sls) + * writes a short int raw data file + * @param fname of the file to be written + * @param nch number of channels + * @param data array of data values + * @returns OK or FAIL if it could not write the file or data=NULL + */ +int writeDataFile(std::string fname,int nch, short int *data); + + + + + diff --git a/slsReceiverSoftware/include/genericSocket.h b/slsSupportLib/include/genericSocket.h old mode 100644 new mode 100755 similarity index 86% rename from slsReceiverSoftware/include/genericSocket.h rename to slsSupportLib/include/genericSocket.h index 819e68cbc..431dcf604 --- a/slsReceiverSoftware/include/genericSocket.h +++ b/slsSupportLib/include/genericSocket.h @@ -9,7 +9,7 @@ */ #include "ansi.h" -#include "sls_receiver_exceptions.h" +#include "sls_detector_exceptions.h" #ifdef __CINT__ //class sockaddr_in; @@ -49,6 +49,7 @@ class sockaddr_in; #define SOCKET_BUFFER_SIZE (100*1024*1024) //100 MB #define DEFAULT_BACKLOG 5 +using sls::SocketError; class genericSocket{ @@ -90,7 +91,7 @@ public: struct addrinfo *result; if (ConvertHostnameToInternetAddress(host_ip_or_name, &result)) { sockfd.fd = -1; - throw SocketException(); + throw SocketError("Could convert hostname to address"); } sockfd.fd = 0; @@ -112,7 +113,7 @@ public: */ genericSocket(unsigned short int const port_number, communicationProtocol p, int ps = DEFAULT_PACKET_SIZE, const char *eth=NULL, int hsize=0, - uint32_t buf_size=SOCKET_BUFFER_SIZE): + uint64_t buf_size=SOCKET_BUFFER_SIZE): portno(port_number), protocol(p), is_a_server(1), @@ -134,7 +135,7 @@ public: // same port if(serverAddress.sin_port == htons(port_number)){ sockfd.fd = -10; - throw SamePortSocketException(); + throw SocketError("Cannot create socket on same port"); } char ip[20]; @@ -150,9 +151,9 @@ public: sockfd.fd = socket(AF_INET, getProtocol(),0); //tcp if (sockfd.fd < 0) { - cprintf(RED, "Can not create socket\n"); + FILE_LOG(logERROR) << "Can not create socket"; sockfd.fd =-1; - throw SocketException(); + throw SocketError("Can not create socket"); } // Set some fields in the serverAddress structure. @@ -173,18 +174,18 @@ public: int val=1; if (setsockopt(sockfd.fd,SOL_SOCKET,SO_REUSEADDR, &val,sizeof(int)) == -1) { - cprintf(RED, "setsockopt REUSEADDR failed\n"); + FILE_LOG(logERROR) << "setsockopt REUSEADDR failed"; sockfd.fd =-1; - throw SocketException(); + throw SocketError("setsockopt REUSEADDR failed"); } } //increase socket buffer size if its udp if (p == UDP) { - uint32_t desired_size = buf_size; - uint32_t real_size = desired_size * 2; // kernel doubles this value for bookkeeping overhead - uint32_t ret_size = -1; - socklen_t optlen = sizeof(int); + uint64_t desired_size = buf_size; + uint64_t real_size = desired_size * 2; // kernel doubles this value for bookkeeping overhead + uint64_t ret_size = -1; + socklen_t optlen = sizeof(uint64_t); // confirm if sufficient if (getsockopt(sockfd.fd, SOL_SOCKET, SO_RCVBUF, &ret_size, &optlen) == -1) { @@ -192,10 +193,8 @@ public: "Could not get rx socket receive buffer size"; } else if (ret_size >= real_size) { actual_udp_socket_buffer_size = ret_size; -#ifdef VEBOSE - FILE_LOG(logINFO) << "[Port " << port_number << "] " + FILE_LOG(logDEBUG1) << "[Port " << port_number << "] " "UDP rx socket buffer size is sufficient (" << ret_size << ")"; -#endif } // not sufficient, enhance size @@ -244,9 +243,9 @@ public: if(bind(sockfd.fd,(struct sockaddr *) &serverAddress,sizeof(serverAddress))<0){ - cprintf(RED, "Can not bind socket\n"); + FILE_LOG(logERROR) << "Can not bind socket"; sockfd.fd =-1; - throw SocketException(); + throw SocketError("Can not bind socket"); } @@ -268,7 +267,7 @@ public: * Halving is because of kernel book keeping * @returns actual udp socket buffer size/2 */ - int getActualUDPSocketBufferSize(){return actual_udp_socket_buffer_size;}; + uint64_t getActualUDPSocketBufferSize(){return actual_udp_socket_buffer_size;}; /** * Get protocol TCP or UDP @@ -313,7 +312,7 @@ public: case UDP: return SOCK_DGRAM; default: - cprintf(RED, "unknown protocol %d\n", p); + FILE_LOG(logERROR) << "unknown protocol: " << p; return -1; } }; @@ -365,74 +364,70 @@ public: if(is_a_server && protocol==TCP){ //server tcp; the server will wait for the clients connection if (sockfd.fd>0) { if ((sockfd.newfd = accept(sockfd.fd,(struct sockaddr *) &clientAddress, &clientAddress_length)) < 0) { - cprintf(RED, "Error: with server accept, connection refused\n"); + FILE_LOG(logERROR) << "with server accept, connection refused"; switch(errno) { case EWOULDBLOCK: - printf("ewouldblock eagain\n"); + FILE_LOG(logERROR) << "ewouldblock eagain"; break; case EBADF: - printf("ebadf\n"); + FILE_LOG(logERROR) << "ebadf"; break; case ECONNABORTED: - printf("econnaborted\n"); + FILE_LOG(logERROR) << "econnaborted"; break; case EFAULT: - printf("efault\n"); + FILE_LOG(logERROR) << "efault"; break; case EINTR: - printf("eintr\n"); + FILE_LOG(logERROR) << "eintr"; break; case EINVAL: - printf("einval\n"); + FILE_LOG(logERROR) << "einval"; break; case EMFILE: - printf("emfile\n"); + FILE_LOG(logERROR) << "emfile"; break; case ENFILE: - printf("enfile\n"); + FILE_LOG(logERROR) << "enfile"; break; case ENOTSOCK: - printf("enotsock\n"); + FILE_LOG(logERROR) << "enotsock"; break; case EOPNOTSUPP: - printf("eOPNOTSUPP\n"); + FILE_LOG(logERROR) << "eOPNOTSUPP"; break; case ENOBUFS: - printf("ENOBUFS\n"); + FILE_LOG(logERROR) << "ENOBUFS"; break; case ENOMEM: - printf("ENOMEM\n"); + FILE_LOG(logERROR) << "ENOMEM"; break; case ENOSR: - printf("ENOSR\n"); + FILE_LOG(logERROR) << "ENOSR"; break; case EPROTO: - printf("EPROTO\n"); + FILE_LOG(logERROR) << "EPROTO"; break; default: - printf("unknown error\n"); + FILE_LOG(logERROR) << "unknown error"; } } else{ inet_ntop(AF_INET, &(clientAddress.sin_addr), dummyClientIP, INET_ADDRSTRLEN); -#ifdef VERY_VERBOSE - cout << "client connected "<< sockfd.newfd << endl; -#endif + FILE_LOG(logDEBUG1) << "client connected " << sockfd.newfd; } } -#ifdef VERY_VERBOSE - cout << "fd " << sockfd.newfd << endl; -#endif + FILE_LOG(logDEBUG1) << "fd " << sockfd.newfd; return sockfd.newfd; } else { if (sockfd.fd<=0) sockfd.fd = socket(AF_INET, getProtocol(),0); // SetTimeOut(10); if (sockfd.fd < 0){ - cprintf(RED, "Can not create socket\n"); + FILE_LOG(logERROR) << "Can not create socket"; } else { if(connect(sockfd.fd,(struct sockaddr *) &serverAddress,sizeof(serverAddress))<0){ - cprintf(RED, "Can not connect to socket\n"); + FILE_LOG(logERROR) << "Can not connect to socket"; return -1; } } @@ -470,13 +465,13 @@ public: tout.tv_usec = 0; if(::setsockopt(sockfd.fd, SOL_SOCKET, SO_RCVTIMEO, &tout, sizeof(struct timeval)) <0) { - cprintf(RED, "Error in setsockopt SO_RCVTIMEO %d\n", 0); + FILE_LOG(logERROR) << "setsockopt SO_RCVTIMEO " << 0; } tout.tv_sec = ts; tout.tv_usec = 0; if(::setsockopt(sockfd.fd, SOL_SOCKET, SO_SNDTIMEO, &tout, sizeof(struct timeval)) < 0) { - cprintf(RED, "Error in setsockopt SO_SNDTIMEO %d\n", ts); + FILE_LOG(logERROR) << "setsockopt SO_SNDTIMEO " << ts; } return 0; }; @@ -508,7 +503,6 @@ public: sa = (struct sockaddr_in *)(iap->ifa_addr); inet_ntop(iap->ifa_addr->sa_family, (void *)&(sa->sin_addr), buf, buf_len); if (ip==std::string(buf)) { - //printf("%s\n", iap->ifa_name); strcpy(buf,iap->ifa_name); break; } @@ -615,17 +609,17 @@ public: // get host info into res int errcode = getaddrinfo (hostname, NULL, &hints, res); if (errcode != 0) { - cprintf (RED,"Error: Could not convert %s hostname to internet address (zmq):" - "%s\n", hostname, gai_strerror(errcode)); + FILE_LOG(logERROR) << "Could not convert hostname (" << hostname << ") to internet address (zmq):" << + gai_strerror(errcode); } else { if (*res == NULL) { - cprintf (RED,"Error: Could not convert %s hostname to internet address (zmq): " - "gettaddrinfo returned null\n", hostname); + FILE_LOG(logERROR) << "Could not converthostname (" << hostname << ") to internet address (zmq):" + "gettaddrinfo returned null"; } else{ return 0; } } - cprintf(RED, "Error: Could not convert hostname to internet address\n"); + FILE_LOG(logERROR) << "Could not convert hostname to internet address"; return 1; }; @@ -643,7 +637,7 @@ public: freeaddrinfo(res); return 0; } - cprintf(RED, "Error: Could not convert internet address to ip string\n"); + FILE_LOG(logERROR) << "Could not convert internet address to ip string"; return 1; } @@ -666,9 +660,7 @@ public: if (tcpfd<0) return -1; while(length>0){ nsending = (length>packet_size) ? packet_size:length; - // std::cout << "*"<0) @@ -699,8 +690,9 @@ public: if(nsent == header_packet_size) continue; if(nsent != nsending){ - if(nsent && (nsent != -1)) - cprintf(RED,"Incomplete Packet size %d\n",nsent); + if(nsent && (nsent != -1)) { + FILE_LOG(logERROR) << "Incomplete Packet size " << nsent; + } break; } length-=nsent; @@ -712,16 +704,14 @@ public: //normal nsending=packet_size; while(1){ -#ifdef VERYVERBOSE - cprintf(BLUE,"%d gonna listen\n", portno); fflush(stdout); -#endif nsent = recvfrom(sockfd.fd,(char*)buf+total_sent,nsending, 0, (struct sockaddr *) &clientAddress, &clientAddress_length); //break out of loop only if read one packets size or read didnt work (cuz of shutdown) if(nsent<=0 || nsent == packet_size) break; //incomplete packets or header packets ignored and read buffer again - if(nsent != packet_size && nsent != header_packet_size) - cprintf(RED,"%d Incomplete Packet size %d\n", portno, nsent); + if(nsent != packet_size && nsent != header_packet_size) { + FILE_LOG(logERROR) << portno << ": Incomplete Packet size " << nsent; + } } //nsent = 1040; if(nsent > 0)total_sent+=nsent; @@ -730,9 +720,7 @@ public: default: ; } -#ifdef VERY_VERBOSE - cout << "sent "<< total_sent << " Bytes" << endl; -#endif + FILE_LOG(logDEBUG1) << "sent " << total_sent << " Bytes"; return total_sent; } @@ -743,9 +731,7 @@ public: * @returns size of data sent */ int SendDataOnly(void *buf, int length) { -#ifdef VERY_VERBOSE - cout << "want to send "<< length << " Bytes" << endl; -#endif + FILE_LOG(logDEBUG1) << "want to send " << length << " Bytes"; if (buf==NULL) return -1; total_sent=0; @@ -760,7 +746,7 @@ public: nsending = (length>packet_size) ? packet_size:length; nsent = write(tcpfd,(char*)buf+total_sent,nsending); if(is_a_server && nsent < 0) { - cprintf(BG_RED, "Error writing to socket. Possible client socket crash\n"); + FILE_LOG(logERROR) << "Could not write to socket. Possible client socket crash"; break; } if(!nsent) break; @@ -782,9 +768,7 @@ public: default: ; } -#ifdef VERY_VERBOSE - cout << "sent "<< total_sent << " Bytes" << endl; -#endif + FILE_LOG(logDEBUG1) << "sent "<< total_sent << " Bytes"; return total_sent; } @@ -834,5 +818,5 @@ private: int nsent; int total_sent; int header_packet_size; - int actual_udp_socket_buffer_size; + uint64_t actual_udp_socket_buffer_size; }; diff --git a/slsReceiverSoftware/include/logger.h b/slsSupportLib/include/logger.h old mode 100644 new mode 100755 similarity index 71% rename from slsReceiverSoftware/include/logger.h rename to slsSupportLib/include/logger.h index 32370605c..1a7dae07a --- a/slsReceiverSoftware/include/logger.h +++ b/slsSupportLib/include/logger.h @@ -18,6 +18,7 @@ #ifndef FILELOG_MAX_LEVEL #define FILELOG_MAX_LEVEL logINFO +//#define FILELOG_MAX_LEVEL logDEBUG5 #endif @@ -36,8 +37,9 @@ inline std::string NowTime(); - -enum TLogLevel {logERROR, logWARNING, logINFO, logDEBUG, logDEBUG1, logDEBUG2, logDEBUG3, logDEBUG4, logDEBUG5}; +// 1 normal debug, 3 function names, 5 fifodebug +enum TLogLevel {logERROR, logWARNING, logINFOBLUE, logINFOGREEN, logINFORED, logINFO, + logDEBUG, logDEBUG1, logDEBUG2, logDEBUG3, logDEBUG4, logDEBUG5}; template class Log{ public: @@ -63,20 +65,11 @@ public: static void Output(const std::string& msg, TLogLevel level); }; -#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) -# if defined (BUILDING_FILELOG_DLL) -# define FILELOG_DECLSPEC __declspec (dllexport) -# elif defined (USING_FILELOG_DLL) -# define FILELOG_DECLSPEC __declspec (dllimport) -# else -# define FILELOG_DECLSPEC -# endif // BUILDING_DBSIMPLE_DLL -#else -# define FILELOG_DECLSPEC -#endif // _WIN32 + +#define FILELOG_DECLSPEC class FILELOG_DECLSPEC FILELog : public Log {}; -//typedef Log FILELog; + #define FILE_LOG(level) \ if (level > FILELOG_MAX_LEVEL) ; \ @@ -84,34 +77,11 @@ class FILELOG_DECLSPEC FILELog : public Log {}; else FILELog().Get(level) -#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) - -#include - - - -inline std::string NowTime() - -{ - const int MAX_LEN = 200; - char buffer[MAX_LEN]; - if (GetTimeFormatA(LOCALE_USER_DEFAULT, 0, 0, - "HH':'mm':'ss", buffer, MAX_LEN) == 0) - return "Error in NowTime()"; - - char result[100] = {0}; - static DWORD first = GetTickCount(); - sprintf(result, "%s.%03ld", buffer, (long)(GetTickCount() - first) % 1000); - return result; -} - -#else - #include inline std::string NowTime() { - char buffer[11]; + char buffer[12]; const int buffer_len = sizeof(buffer); time_t t; time(&t); @@ -127,8 +97,6 @@ inline std::string NowTime() return result; } -#endif //WIN32 - template Log::Log():lev(logDEBUG){} @@ -138,7 +106,7 @@ template std::ostringstream& Log::Get(TLogLevel level) os << "- " << NowTime(); os << " " << ToString(level) << ": "; if (level > logDEBUG) - os << std::string(level - logDEBUG, '\t'); + os << std::string(level - logDEBUG, ' '); return os; } @@ -156,7 +124,9 @@ template TLogLevel& Log::ReportingLevel() template std::string Log::ToString(TLogLevel level) { - static const char* const buffer[] = {"ERROR", "WARNING", "INFO", "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4","DEBUG5"}; + static const char* const buffer[] = { + "ERROR", "WARNING", "INFO", "INFO", "INFO", "INFO", + "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4","DEBUG5"}; return buffer[level]; } @@ -211,21 +181,10 @@ inline void Output2FILE::Output(const std::string& msg, TLogLevel level) case logERROR: cprintf(RED BOLD,"%s",msg.c_str()); break; case logWARNING: cprintf(YELLOW BOLD,"%s",msg.c_str()); break; case logINFO: cprintf(RESET,"%s",msg.c_str()); break; + case logINFOBLUE: cprintf(BLUE,"%s",msg.c_str()); break; + case logINFORED: cprintf(RED,"%s",msg.c_str()); break; + case logINFOGREEN: cprintf(GREEN,"%s",msg.c_str()); break; default: fprintf(pStream,"%s",msg.c_str()); out = false; break; } fflush(out ? stdout : pStream); } - -#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) -# if defined (BUILDING_FILELOG_DLL) -# define FILELOG_DECLSPEC __declspec (dllexport) -# elif defined (USING_FILELOG_DLL) -# define FILELOG_DECLSPEC __declspec (dllimport) -# else -# define FILELOG_DECLSPEC -# endif // BUILDING_DBSIMPLE_DLL -#else -# define FILELOG_DECLSPEC -#endif // _WIN32 - - diff --git a/slsSupportLib/include/network_utils.h b/slsSupportLib/include/network_utils.h new file mode 100755 index 000000000..59a7432a1 --- /dev/null +++ b/slsSupportLib/include/network_utils.h @@ -0,0 +1,63 @@ +#pragma once +#include +#include + +namespace sls { + +uint32_t HostnameToIp(const char *hostname); + +class IpAddr { + private: + uint32_t addr_{0}; + + public: + constexpr IpAddr(uint32_t address) noexcept : addr_{address} {} + IpAddr(const std::string &address); + IpAddr(const char *address); + std::string str() const; + std::string hex() const; + constexpr bool operator==(const IpAddr &other) const noexcept { + return addr_ == other.addr_; + } + constexpr bool operator!=(const IpAddr &other) const noexcept { + return addr_ != other.addr_; + } + constexpr bool operator==(const uint32_t other) const noexcept { + return addr_ == other; + } + constexpr bool operator!=(const uint32_t other) const noexcept { + return addr_ != other; + } + constexpr uint32_t uint32() const noexcept { return addr_; } +}; + +class MacAddr { + private: + uint64_t addr_{0}; + std::string to_hex(const char delimiter = 0) const; + + public: + constexpr MacAddr(uint64_t mac) noexcept : addr_{mac} {} + MacAddr(std::string mac); + MacAddr(const char *address); + std::string str() const; + std::string hex() const; + constexpr bool operator==(const MacAddr &other) const noexcept { + return addr_ == other.addr_; + } + constexpr bool operator!=(const MacAddr &other) const noexcept { + return addr_ != other.addr_; + } + constexpr bool operator==(const uint64_t other) const noexcept { + return addr_ == other; + } + constexpr bool operator!=(const uint64_t other) const noexcept { + return addr_ != other; + } + constexpr uint64_t uint64() const noexcept { return addr_; } +}; + +std::ostream &operator<<(std::ostream &out, const IpAddr &addr); +std::ostream &operator<<(std::ostream &out, const MacAddr &addr); + +} // namespace sls diff --git a/slsReceiverSoftware/include/rapidjson/allocators.h b/slsSupportLib/include/rapidjson/allocators.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/allocators.h rename to slsSupportLib/include/rapidjson/allocators.h diff --git a/slsReceiverSoftware/include/rapidjson/document.h b/slsSupportLib/include/rapidjson/document.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/document.h rename to slsSupportLib/include/rapidjson/document.h diff --git a/slsReceiverSoftware/include/rapidjson/encodedstream.h b/slsSupportLib/include/rapidjson/encodedstream.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/encodedstream.h rename to slsSupportLib/include/rapidjson/encodedstream.h diff --git a/slsReceiverSoftware/include/rapidjson/encodings.h b/slsSupportLib/include/rapidjson/encodings.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/encodings.h rename to slsSupportLib/include/rapidjson/encodings.h diff --git a/slsReceiverSoftware/include/rapidjson/error/en.h b/slsSupportLib/include/rapidjson/error/en.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/error/en.h rename to slsSupportLib/include/rapidjson/error/en.h diff --git a/slsReceiverSoftware/include/rapidjson/error/error.h b/slsSupportLib/include/rapidjson/error/error.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/error/error.h rename to slsSupportLib/include/rapidjson/error/error.h diff --git a/slsReceiverSoftware/include/rapidjson/filereadstream.h b/slsSupportLib/include/rapidjson/filereadstream.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/filereadstream.h rename to slsSupportLib/include/rapidjson/filereadstream.h diff --git a/slsReceiverSoftware/include/rapidjson/filewritestream.h b/slsSupportLib/include/rapidjson/filewritestream.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/filewritestream.h rename to slsSupportLib/include/rapidjson/filewritestream.h diff --git a/slsReceiverSoftware/include/rapidjson/fwd.h b/slsSupportLib/include/rapidjson/fwd.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/fwd.h rename to slsSupportLib/include/rapidjson/fwd.h diff --git a/slsReceiverSoftware/include/rapidjson/internal/biginteger.h b/slsSupportLib/include/rapidjson/internal/biginteger.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/internal/biginteger.h rename to slsSupportLib/include/rapidjson/internal/biginteger.h diff --git a/slsReceiverSoftware/include/rapidjson/internal/diyfp.h b/slsSupportLib/include/rapidjson/internal/diyfp.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/internal/diyfp.h rename to slsSupportLib/include/rapidjson/internal/diyfp.h diff --git a/slsReceiverSoftware/include/rapidjson/internal/dtoa.h b/slsSupportLib/include/rapidjson/internal/dtoa.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/internal/dtoa.h rename to slsSupportLib/include/rapidjson/internal/dtoa.h diff --git a/slsReceiverSoftware/include/rapidjson/internal/ieee754.h b/slsSupportLib/include/rapidjson/internal/ieee754.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/internal/ieee754.h rename to slsSupportLib/include/rapidjson/internal/ieee754.h diff --git a/slsReceiverSoftware/include/rapidjson/internal/itoa.h b/slsSupportLib/include/rapidjson/internal/itoa.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/internal/itoa.h rename to slsSupportLib/include/rapidjson/internal/itoa.h diff --git a/slsReceiverSoftware/include/rapidjson/internal/meta.h b/slsSupportLib/include/rapidjson/internal/meta.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/internal/meta.h rename to slsSupportLib/include/rapidjson/internal/meta.h diff --git a/slsReceiverSoftware/include/rapidjson/internal/pow10.h b/slsSupportLib/include/rapidjson/internal/pow10.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/internal/pow10.h rename to slsSupportLib/include/rapidjson/internal/pow10.h diff --git a/slsReceiverSoftware/include/rapidjson/internal/regex.h b/slsSupportLib/include/rapidjson/internal/regex.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/internal/regex.h rename to slsSupportLib/include/rapidjson/internal/regex.h diff --git a/slsReceiverSoftware/include/rapidjson/internal/stack.h b/slsSupportLib/include/rapidjson/internal/stack.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/internal/stack.h rename to slsSupportLib/include/rapidjson/internal/stack.h diff --git a/slsReceiverSoftware/include/rapidjson/internal/strfunc.h b/slsSupportLib/include/rapidjson/internal/strfunc.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/internal/strfunc.h rename to slsSupportLib/include/rapidjson/internal/strfunc.h diff --git a/slsReceiverSoftware/include/rapidjson/internal/strtod.h b/slsSupportLib/include/rapidjson/internal/strtod.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/internal/strtod.h rename to slsSupportLib/include/rapidjson/internal/strtod.h diff --git a/slsReceiverSoftware/include/rapidjson/internal/swap.h b/slsSupportLib/include/rapidjson/internal/swap.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/internal/swap.h rename to slsSupportLib/include/rapidjson/internal/swap.h diff --git a/slsReceiverSoftware/include/rapidjson/istreamwrapper.h b/slsSupportLib/include/rapidjson/istreamwrapper.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/istreamwrapper.h rename to slsSupportLib/include/rapidjson/istreamwrapper.h diff --git a/slsReceiverSoftware/include/rapidjson/memorybuffer.h b/slsSupportLib/include/rapidjson/memorybuffer.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/memorybuffer.h rename to slsSupportLib/include/rapidjson/memorybuffer.h diff --git a/slsReceiverSoftware/include/rapidjson/memorystream.h b/slsSupportLib/include/rapidjson/memorystream.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/memorystream.h rename to slsSupportLib/include/rapidjson/memorystream.h diff --git a/slsReceiverSoftware/include/rapidjson/msinttypes/inttypes.h b/slsSupportLib/include/rapidjson/msinttypes/inttypes.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/msinttypes/inttypes.h rename to slsSupportLib/include/rapidjson/msinttypes/inttypes.h diff --git a/slsReceiverSoftware/include/rapidjson/msinttypes/stdint.h b/slsSupportLib/include/rapidjson/msinttypes/stdint.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/msinttypes/stdint.h rename to slsSupportLib/include/rapidjson/msinttypes/stdint.h diff --git a/slsReceiverSoftware/include/rapidjson/ostreamwrapper.h b/slsSupportLib/include/rapidjson/ostreamwrapper.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/ostreamwrapper.h rename to slsSupportLib/include/rapidjson/ostreamwrapper.h diff --git a/slsReceiverSoftware/include/rapidjson/pointer.h b/slsSupportLib/include/rapidjson/pointer.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/pointer.h rename to slsSupportLib/include/rapidjson/pointer.h diff --git a/slsReceiverSoftware/include/rapidjson/prettywriter.h b/slsSupportLib/include/rapidjson/prettywriter.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/prettywriter.h rename to slsSupportLib/include/rapidjson/prettywriter.h diff --git a/slsReceiverSoftware/include/rapidjson/rapidjson.h b/slsSupportLib/include/rapidjson/rapidjson.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/rapidjson.h rename to slsSupportLib/include/rapidjson/rapidjson.h diff --git a/slsReceiverSoftware/include/rapidjson/reader.h b/slsSupportLib/include/rapidjson/reader.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/reader.h rename to slsSupportLib/include/rapidjson/reader.h diff --git a/slsReceiverSoftware/include/rapidjson/schema.h b/slsSupportLib/include/rapidjson/schema.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/schema.h rename to slsSupportLib/include/rapidjson/schema.h diff --git a/slsReceiverSoftware/include/rapidjson/stream.h b/slsSupportLib/include/rapidjson/stream.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/stream.h rename to slsSupportLib/include/rapidjson/stream.h diff --git a/slsReceiverSoftware/include/rapidjson/stringbuffer.h b/slsSupportLib/include/rapidjson/stringbuffer.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/stringbuffer.h rename to slsSupportLib/include/rapidjson/stringbuffer.h diff --git a/slsReceiverSoftware/include/rapidjson/writer.h b/slsSupportLib/include/rapidjson/writer.h old mode 100644 new mode 100755 similarity index 100% rename from slsReceiverSoftware/include/rapidjson/writer.h rename to slsSupportLib/include/rapidjson/writer.h diff --git a/slsSupportLib/include/sls_detector_defs.h b/slsSupportLib/include/sls_detector_defs.h new file mode 100755 index 000000000..4db2091ff --- /dev/null +++ b/slsSupportLib/include/sls_detector_defs.h @@ -0,0 +1,961 @@ +#pragma once +/************************************************ + * @file sls_detector_defs.h + * @short contains all the constants, enum definitions and enum-string conversions + ***********************************************/ +/** + *@short contains all the constants, enum definitions and enum-string conversions + */ + + +#ifdef __CINT__ +#define MYROOT +#define __cplusplus +#endif + +#include +#ifdef __cplusplus +#include +#include +#endif +#include "ansi.h" + + +/** default ports */ +#define DEFAULT_PORTNO 1952 +#define DEFAULT_UDP_PORTNO 50001 +#define DEFAULT_GUI_PORTNO 65001 +#define DEFAULT_ZMQ_CL_PORTNO 30001 +#define DEFAULT_ZMQ_RX_PORTNO 30001 + +#define SLS_DETECTOR_HEADER_VERSION 0x2 +#define SLS_DETECTOR_JSON_HEADER_VERSION 0x3 + +// ctb/ moench 1g udp (read from fifo) +#define UDP_PACKET_DATA_BYTES (1344) + +/** maximum rois */ +#define MAX_ROIS 100 + +/** maximum trim en */ +#define MAX_TRIMEN 100 + +/** maximum unit size of program sent to detector */ +#define MAX_FPGAPROGRAMSIZE (2 * 1024 *1024) + +/** get flag form most functions */ +#define GET_FLAG -1 + +#define DEFAULT_DET_MAC "00:aa:bb:cc:dd:ee" +#define DEFAULT_DET_IP "129.129.202.45" +#define DEFAULT_DET_MAC2 "00:aa:bb:cc:dd:ff" +#define DEFAULT_DET_IP2 "129.129.202.46" + +/** default maximum string length */ +#define MAX_STR_LENGTH 1000 +#define MAX_FRAMES_PER_FILE 20000 +#define SHORT_MAX_FRAMES_PER_FILE 100000 +#define MOENCH_MAX_FRAMES_PER_FILE 100000 +#define EIGER_MAX_FRAMES_PER_FILE 10000 +#define JFRAU_MAX_FRAMES_PER_FILE 10000 +#define CTB_MAX_FRAMES_PER_FILE 20000 + +#define DEFAULT_STREAMING_TIMER_IN_MS 200 + + + +typedef char mystring[MAX_STR_LENGTH]; + + +#ifdef __cplusplus +class slsDetectorDefs { +public: + slsDetectorDefs(){}; +#endif + + /** + Type of the detector + */ + enum detectorType { + GET_DETECTOR_TYPE=-1, /**< the detector will return its type */ + GENERIC, /**< generic sls detector */ + EIGER, /**< eiger */ + GOTTHARD, /**< gotthard */ + JUNGFRAU, /**< jungfrau */ + CHIPTESTBOARD, /**< CTB */ + MOENCH /**< moench */ + }; + + + /** + return values + */ + enum { + OK, /**< function succeeded */ + FAIL, /**< function failed */ + FORCE_UPDATE + }; + + + /** + indexes for the acquisition timers + */ + enum timerIndex { + FRAME_NUMBER, /**< number of real time frames: total number of acquisitions is number or frames*number of cycles */ + ACQUISITION_TIME, /**< exposure time */ + FRAME_PERIOD, /**< period between exposures */ + DELAY_AFTER_TRIGGER, /**< delay between trigger and start of exposure or readout (in triggered mode) */ + GATES_NUMBER, /**< number of gates per frame (in gated mode) */ + CYCLES_NUMBER, /**< number of cycles: total number of acquisitions is number or frames*number of cycles */ + ACTUAL_TIME, /**< Actual time of the detector's internal timer */ + MEASUREMENT_TIME, /**< Time of the measurement from the detector (fifo) */ + + PROGRESS, /**< fraction of measurement elapsed - only get! */ + MEASUREMENTS_NUMBER, + FRAMES_FROM_START, + FRAMES_FROM_START_PG, + SAMPLES, + SUBFRAME_ACQUISITION_TIME, /**< subframe exposure time */ + STORAGE_CELL_NUMBER, /** sls_bitset; + + typedef struct { + sls_detector_header detHeader; /**< is the detector header */ + sls_bitset packetsMask; /**< is the packets caught bit mask */ + } sls_receiver_header; + + typedef uint8_t bitset_storage[MAX_NUM_PACKETS/8]; + +#endif + /** + * frameDiscardPolicy + */ + enum frameDiscardPolicy { + GET_FRAME_DISCARD_POLICY = -1, /**< to get the missing packet mode */ + NO_DISCARD, /**< pad incomplete packets with -1, default mode */ + DISCARD_EMPTY_FRAMES, /**< discard incomplete frames, fastest mode, save space, not suitable for multiple modules */ + DISCARD_PARTIAL_FRAMES, /**< ignore missing packets, must check with packetsMask for data integrity, fast mode and suitable for multiple modules */ + NUM_DISCARD_POLICIES + }; + + + /** + format + */ + enum fileFormat { + GET_FILE_FORMAT=-1,/**< the receiver will return its file format */ + BINARY, /**< binary format */ + HDF5, /**< hdf5 format */ + NUM_FILE_FORMATS + }; + + + /** + @short structure for a region of interest + xmin,xmax,ymin,ymax define the limits of the region + */ + typedef struct { + int xmin; /**< is the roi xmin (in channel number) */ + int xmax; /**< is the roi xmax (in channel number)*/ + int ymin; /**< is the roi ymin (in channel number)*/ + int ymax; /**< is the roi ymax (in channel number)*/ + } ROI ; + + /** + @short structure for a detector module + + should not be used by unexperienced users + + \see :: moduleRegisterBit ::chipRegisterBit :channelRegisterBit + + @li reg is the module register (e.g. dynamic range? see moduleRegisterBit) + @li dacs is the pointer to the array of dac values (in V) + @li adcs is the pointer to the array of adc values (in V) + @li chipregs is the pointer to the array of chip registers + @li chanregs is the pointer to the array of channel registers + @li gain is the module gain + @li offset is the module offset + */ + typedef struct { + int serialnumber; /**< is the module serial number */ + int nchan; /**< is the number of channels on the module*/ + int nchip; /**< is the number of chips on the module */ + int ndac; /**< is the number of dacs on the module */ + int reg; /**< is the module register settings (gain level) */ + int iodelay; /**< iodelay */ + int tau; /**< tau */ + int eV; /**< threshold energy */ + int *dacs; /**< is the pointer to the array of the dac values (in V) */ + int *chanregs; /**< is the pointer to the array of the channel registers */ + } sls_detector_module; + + + /** + network parameters + */ + + enum networkParameter { + DETECTOR_MAC, /**< detector MAC */ + DETECTOR_IP, /**< detector IP */ + RECEIVER_HOSTNAME, /**< receiver IP/hostname */ + RECEIVER_UDP_IP, /**< receiever UDP IP */ + RECEIVER_UDP_PORT, /**< receiever UDP Port */ + RECEIVER_UDP_MAC, /**< receiever UDP MAC */ + RECEIVER_UDP_PORT2, /**< receiever UDP Port of second half module for eiger */ + DETECTOR_TXN_DELAY_LEFT, /**< transmission delay on the (left) port for next frame */ + DETECTOR_TXN_DELAY_RIGHT, /**< transmission delay on the right port for next frame */ + DETECTOR_TXN_DELAY_FRAME, /**< transmission delay of a whole frame for all the ports */ + FLOW_CONTROL_10G, /**< flow control for 10GbE */ + FLOW_CONTROL_WR_PTR, /**< memory write pointer for flow control */ + FLOW_CONTROL_RD_PTR, /**< memory read pointer for flow control */ + RECEIVER_STREAMING_PORT, /**< receiever streaming TCP(ZMQ) port */ + CLIENT_STREAMING_PORT, /**< client streaming TCP(ZMQ) port */ + RECEIVER_STREAMING_SRC_IP,/**< receiever streaming TCP(ZMQ) ip */ + CLIENT_STREAMING_SRC_IP, /**< client streaming TCP(ZMQ) ip */ + ADDITIONAL_JSON_HEADER, /**< additional json header (ZMQ) */ + RECEIVER_UDP_SCKT_BUF_SIZE, /**< UDP socket buffer size */ + RECEIVER_REAL_UDP_SCKT_BUF_SIZE /**< real UDP socket buffer size */ + }; + + /** + type of action performed (for text client) + */ + enum {GET_ACTION, PUT_ACTION, READOUT_ACTION, HELP_ACTION}; + + /** online flags enum \sa setOnline*/ + enum {GET_ONLINE_FLAG=-1, /**< returns wether the detector is in online or offline state */ + OFFLINE_FLAG=0, /**< detector in offline state (i.e. no communication to the detector - using only local structure - no data acquisition possible!) */ + ONLINE_FLAG =1/**< detector in online state (i.e. communication to the detector updating the local structure) */ + }; + + /** + flags to get (or set) the size of the detector + */ + enum numberOf { + MAXMODX, /***/ + M_vIbias, /**< mythen 3 >*/ + M_vIinSh, /**< mythen 3 >*/ + M_VdcSh, /**< mythen 3 >*/ + M_Vth2, /**< mythen 3 >*/ + M_VPL, /**< mythen 3 >*/ + M_Vth3, /**< mythen 3 >*/ + M_casSh, /**< mythen 3 >*/ + M_cas, /**< mythen 3 >*/ + M_vIbiasSh, /**< mythen 3 >*/ + M_vIcin, /**< mythen 3 >*/ + M_vIpreOut, /**< mythen 3 >*/ + V_POWER_A = 100, /**new chiptest board */ + V_POWER_B = 101, /**new chiptest board */ + V_POWER_C = 102, /**new chiptest board */ + V_POWER_D = 103, /**new chiptest board */ + V_POWER_IO =104, /**new chiptest board */ + V_POWER_CHIP=105 ,/**new chiptest board */ + I_POWER_A=106 , /**new chiptest board */ + I_POWER_B=107 , /**new chiptest board */ + I_POWER_C=108 , /**new chiptest board */ + I_POWER_D=109 , /**new chiptest board */ + I_POWER_IO=110 , /**new chiptest board */ + V_LIMIT=111, /**new chiptest board */ + SLOW_ADC0=1000, + SLOW_ADC1, + SLOW_ADC2, + SLOW_ADC3, + SLOW_ADC4, + SLOW_ADC5, + SLOW_ADC6, + SLOW_ADC7, + SLOW_ADC_TEMP + }; + + /** + detector settings indexes + */ + enum detectorSettings{ + GET_SETTINGS=-1, /**< return current detector settings */ + STANDARD, /**< standard settings */ + FAST, /**< fast settings */ + HIGHGAIN, /**< highgain settings */ + DYNAMICGAIN, /**< dynamic gain settings */ + LOWGAIN, /**< low gain settings */ + MEDIUMGAIN, /**< medium gain settings */ + VERYHIGHGAIN, /**< very high gain settings */ + LOWNOISE, /**< low noise settings */ + DYNAMICHG0, /**< dynamic high gain 0 */ + FIXGAIN1, /**< fix gain 1 */ + FIXGAIN2, /**< fix gain 2 */ + FORCESWITCHG1, /**< force switch gain 1 */ + FORCESWITCHG2, /**< force switch gain 2 */ + VERYLOWGAIN, /**< very low gain settings */ + UNDEFINED=200, /**< undefined or custom settings */ + UNINITIALIZED /**< uninitialiazed (status at startup) */ + }; + + + #define TRIMBITMASK 0x3f + + + /** + important speed parameters + */ + enum speedVariable { + CLOCK_DIVIDER, /**< readout clock divider */ + ADC_CLOCK, /**< adc clock divider */ + ADC_PHASE, /**< adc clock phase */ + ADC_PIPELINE, /**< adc pipeline */ + DBIT_CLOCK, /**< adc clock divider */ + DBIT_PHASE, /**< adc clock phase */ + DBIT_PIPELINE, /**< adc pipeline */ + MAX_ADC_PHASE_SHIFT, /** max adc phase shift */ + MAX_DBIT_PHASE_SHIFT, /** max adc phase shift */ + }; + + + /** + readout flags + */ + enum readOutFlags { + GET_READOUT_FLAGS=-1, /**< return readout flags */ + NORMAL_READOUT=0, /**< no flag */ + STORE_IN_RAM=0x1, /**< data are stored in ram and sent only after end of acquisition for faster frame rate */ + READ_HITS=0x2, /**< return only the number of the channel which counted ate least one */ + ZERO_COMPRESSION=0x4,/**< returned data are 0-compressed */ + PUMP_PROBE_MODE=0x8,/** +#include + +namespace sls{ + +struct RuntimeError : public std::runtime_error { +public: + RuntimeError(): runtime_error("SLS Detector Package Failed") { + FILE_LOG(logERROR) << "SLS Detector Package Failed"; + } + RuntimeError(std::string msg): runtime_error(msg) { + FILE_LOG(logERROR) << msg; + } + RuntimeError(const char* msg): runtime_error(msg) { + FILE_LOG(logERROR) << msg; + } +}; + +struct CriticalError : public RuntimeError { +public: + CriticalError(std::string msg):RuntimeError(msg) {} +}; + +struct SharedMemoryError : public CriticalError { +public: + SharedMemoryError(std::string msg):CriticalError(msg) {} +}; + +struct SocketError : public CriticalError { +public: + SocketError(std::string msg):CriticalError(msg) {} +}; + +struct ZmqSocketError : public CriticalError { +public: + ZmqSocketError(std::string msg):CriticalError(msg) {} +}; + +struct NonCriticalError : public RuntimeError { +public: + NonCriticalError(std::string msg):RuntimeError(msg) {} +}; + +struct NotImplementedError : public NonCriticalError { +public: + NotImplementedError(std::string msg):NonCriticalError(msg) {} +}; + +struct DetectorError : public NonCriticalError { +public: + DetectorError(std::string msg):NonCriticalError(msg) {} +}; + +struct ReceiverError : public NonCriticalError { +public: + ReceiverError(std::string msg):NonCriticalError(msg) {} +}; + +struct GuiError : public NonCriticalError { +public: + GuiError(std::string msg):NonCriticalError(msg) {} +}; + +} + + + diff --git a/slsSupportLib/include/sls_detector_funcs.h b/slsSupportLib/include/sls_detector_funcs.h new file mode 100755 index 000000000..4179a1536 --- /dev/null +++ b/slsSupportLib/include/sls_detector_funcs.h @@ -0,0 +1,258 @@ +#pragma once + +/************************************************ + * @file sls_detector_funcs.h + * @short functions indices to call on server (detector/receiver) + ***********************************************/ +/** + *@short functions indices to call on server (detector/receiver) + */ + + +enum detFuncs{ + F_EXEC_COMMAND=0, /**< command is executed */ + F_GET_DETECTOR_TYPE, /**< return detector type */ + F_SET_EXTERNAL_SIGNAL_FLAG, /**< set/get flag for external signal */ + F_SET_EXTERNAL_COMMUNICATION_MODE, /**< set/get external communication mode (obsolete) */ + F_GET_ID, /**< get detector id of version */ + F_DIGITAL_TEST, /**< digital test of the detector */ + F_SET_DAC, /**< set DAC value */ + F_GET_ADC, /**< get ADC value */ + F_WRITE_REGISTER, /**< write to register */ + F_READ_REGISTER, /**< read register */ + F_SET_MODULE, /**< initialize module */ + F_GET_MODULE, /**< get module status */ + F_SET_SETTINGS, /**< set detector settings */ + F_GET_THRESHOLD_ENERGY, /**< get detector threshold (in eV) */ + F_START_ACQUISITION, /**< start acquisition */ + F_STOP_ACQUISITION, /**< stop acquisition */ + F_START_READOUT, /**< start readout */ + F_GET_RUN_STATUS, /**< get acquisition status */ + F_START_AND_READ_ALL, /**< start acquisition and read all frames*/ + F_READ_ALL, /**< read alla frames */ + F_SET_TIMER, /**< set/get timer value */ + F_GET_TIME_LEFT, /**< get current value of the timer (time left) */ + F_SET_DYNAMIC_RANGE, /**< set/get detector dynamic range */ + F_SET_READOUT_FLAGS, /**< set/get readout flags */ + F_SET_ROI, /**< set/get region of interest */ + F_SET_SPEED, /**< set/get readout speed parameters */ + F_EXIT_SERVER, /**< turn off detector server */ + F_LOCK_SERVER, /**< Locks/Unlocks server communication to the given client */ + F_GET_LAST_CLIENT_IP, /**< returns the IP of the client last connected to the detector */ + F_SET_PORT, /**< Changes communication port of the server */ + F_UPDATE_CLIENT, /**< Returns all the important parameters to update the shared memory of the client */ + F_CONFIGURE_MAC, /**< Configures MAC for Gotthard readout */ + F_LOAD_IMAGE, /**< Loads Dark/Gain image to the Gotthard detector */ + F_READ_COUNTER_BLOCK, /**< reads the counter block memory for gotthard */ + F_RESET_COUNTER_BLOCK, /**< resets the counter block memory for gotthard */ + F_ENABLE_TEN_GIGA, /**< enable 10Gbe */ + F_SET_ALL_TRIMBITS, /** < set all trimbits to this value */ + F_SET_PATTERN, /** < loads a pattern */ + F_SET_PATTERN_MASK, /** < loads a pattern mask */ + F_GET_PATTERN_MASK, /** < retrieves pattern mask */ + F_SET_PATTERN_BIT_MASK, /** < loads bitmask for the pattern */ + F_GET_PATTERN_BIT_MASK, /** < retrieves bitmask for the pattern */ + F_WRITE_ADC_REG, /** < writes an ADC register */ + F_SET_COUNTER_BIT, /** < set/reset counter bit in detector for eiger */ + F_PULSE_PIXEL,/** < pulse pixel n number of times in eiger at (x,y) */ + F_PULSE_PIXEL_AND_MOVE,/** < pulse pixel n number of times and move relatively by x and y */ + F_PULSE_CHIP, /** < pulse chip n number of times */ + F_SET_RATE_CORRECT,/** < set/reset rate correction tau */ + F_GET_RATE_CORRECT,/** < get rate correction tau */ + F_SET_NETWORK_PARAMETER,/**< set network parameters such as transmission delay, flow control */ + F_PROGRAM_FPGA,/**< program FPGA */ + F_RESET_FPGA, /**< reset FPGA */ + F_POWER_CHIP, /**< power chip */ + F_ACTIVATE,/** < activate */ + F_PREPARE_ACQUISITION,/** < prepare acquisition */ + F_THRESHOLD_TEMP, /** < set threshold temperature */ + F_TEMP_CONTROL, /** < set temperature control */ + F_TEMP_EVENT, /** < set temperature event */ + F_AUTO_COMP_DISABLE, /** < auto comp disable mode */ + F_STORAGE_CELL_START, /** < storage cell start */ + F_CHECK_VERSION,/** < check version compatibility */ + F_SOFTWARE_TRIGGER,/** < software trigger */ + F_LED, /** < switch on/off led */ + F_DIGITAL_IO_DELAY, /** < digital IO delay */ + F_COPY_DET_SERVER, /** < copy detector server & respawn */ + F_REBOOT_CONTROLLER, /** < reboot detector controller (blackfin/ powerpc) */ + NUM_DET_FUNCTIONS, + + RECEIVER_ENUM_START = 128, /**< detector function should not exceed this (detector server should not compile anyway) */ + F_EXEC_RECEIVER_COMMAND,/**< command is executed */ + F_EXIT_RECEIVER,/**< turn off receiver server */ + F_LOCK_RECEIVER,/**< Locks/Unlocks server communication to the given client */ + F_GET_LAST_RECEIVER_CLIENT_IP,/**< returns the IP of the client last connected to the receiver */ + F_SET_RECEIVER_PORT, /**< Changes communication port of the receiver */ + F_UPDATE_RECEIVER_CLIENT, /**< Returns all the important parameters to update the shared memory of the client */ + F_GET_RECEIVER_ID, /**< get receiver id of version */ + F_GET_RECEIVER_TYPE, /**< return receiver type */ + F_SEND_RECEIVER_DETHOSTNAME, /**< set detector hostname to receiver */ + F_RECEIVER_SET_ROI, /**< Sets receiver ROI */ + F_SETUP_RECEIVER_UDP, /**< sets the receiver udp connection and returns receiver mac address */ + F_SET_RECEIVER_TIMER, /**< set/get timer value */ + F_SET_RECEIVER_DYNAMIC_RANGE, /**< set/get detector dynamic range */ + F_RECEIVER_STREAMING_FREQUENCY, /**< sets the frequency of receiver sending frames to gui */ + F_GET_RECEIVER_STATUS, /**< gets the status of receiver listening mode */ + F_START_RECEIVER, /**< starts the receiver listening mode */ + F_STOP_RECEIVER, /**< stops the receiver listening mode */ + F_SET_RECEIVER_FILE_PATH, /**< sets receiver file directory */ + F_SET_RECEIVER_FILE_NAME, /**< sets receiver file name */ + F_SET_RECEIVER_FILE_INDEX, /**< sets receiver file index */ + F_GET_RECEIVER_FRAME_INDEX, /**< gets the receiver frame index */ + F_GET_RECEIVER_FRAMES_CAUGHT, /**< gets the number of frames caught by receiver */ + F_RESET_RECEIVER_FRAMES_CAUGHT, /**< resets the frames caught by receiver */ + F_ENABLE_RECEIVER_FILE_WRITE, /**< sets the receiver file write */ + F_ENABLE_RECEIVER_OVERWRITE, /**< set overwrite flag in receiver */ + F_ENABLE_RECEIVER_TEN_GIGA, /**< enable 10Gbe in receiver */ + F_SET_RECEIVER_FIFO_DEPTH, /**< set receiver fifo depth */ + F_RECEIVER_ACTIVATE, /** < activate/deactivate readout */ + F_STREAM_DATA_FROM_RECEIVER, /**< stream data from receiver to client */ + F_RECEIVER_STREAMING_TIMER, /** < sets the timer between each data stream in receiver */ + F_SET_FLIPPED_DATA_RECEIVER, /** < sets the enable to flip data across x/y axis (bottom/top) */ + F_SET_RECEIVER_FILE_FORMAT, /** < sets the receiver file format */ + F_SEND_RECEIVER_DETPOSID, /** < sets the detector position id in the reveiver */ + F_SEND_RECEIVER_MULTIDETSIZE, /** < sets the multi detector size to the receiver */ + F_SET_RECEIVER_STREAMING_PORT, /** < sets the receiver streaming port */ + F_RECEIVER_STREAMING_SRC_IP, /** < sets the receiver streaming source IP */ + F_SET_RECEIVER_SILENT_MODE, /** < sets the receiver silent mode */ + F_ENABLE_GAPPIXELS_IN_RECEIVER, /** < sets gap pixels in the receiver */ + F_RESTREAM_STOP_FROM_RECEIVER, /** < restream stop from receiver */ + F_ADDITIONAL_JSON_HEADER, /** < additional json header */ + F_GET_ADDITIONAL_JSON_HEADER,/** < get additional json header */ + F_RECEIVER_UDP_SOCK_BUF_SIZE, /** < UDP socket buffer size */ + F_RECEIVER_REAL_UDP_SOCK_BUF_SIZE, /** < real UDP socket buffer size */ + F_SET_RECEIVER_FRAMES_PER_FILE, /** < receiver frames per file */ + F_RECEIVER_CHECK_VERSION, /** < check receiver version compatibility */ + F_RECEIVER_DISCARD_POLICY, /** < frames discard policy */ + F_RECEIVER_PADDING_ENABLE, /** < partial frames padding enable */ + F_RECEIVER_DEACTIVATED_PADDING_ENABLE, /** < deactivated receiver padding enable */ + F_RECEIVER_SET_READOUT_FLAGS, /**< set/get receiver readout flags */ + NUM_REC_FUNCTIONS +}; + +#ifdef __cplusplus +static const char* getFunctionNameFromEnum(enum detFuncs func) { + switch (func) { + case F_EXEC_COMMAND: return "F_EXEC_COMMAND"; + case F_GET_DETECTOR_TYPE: return "F_GET_DETECTOR_TYPE"; + case F_SET_EXTERNAL_SIGNAL_FLAG: return "F_SET_EXTERNAL_SIGNAL_FLAG"; + case F_SET_EXTERNAL_COMMUNICATION_MODE: return "F_SET_EXTERNAL_COMMUNICATION_MODE"; + case F_GET_ID: return "F_GET_ID"; + case F_DIGITAL_TEST: return "F_DIGITAL_TEST"; + case F_SET_DAC: return "F_SET_DAC"; + case F_GET_ADC: return "F_GET_ADC"; + case F_WRITE_REGISTER: return "F_WRITE_REGISTER"; + case F_READ_REGISTER: return "F_READ_REGISTER"; + case F_SET_MODULE: return "F_SET_MODULE"; + case F_GET_MODULE: return "F_GET_MODULE"; + case F_SET_SETTINGS: return "F_SET_SETTINGS"; + case F_GET_THRESHOLD_ENERGY: return "F_GET_THRESHOLD_ENERGY"; + case F_START_ACQUISITION: return "F_START_ACQUISITION"; + case F_STOP_ACQUISITION: return "F_STOP_ACQUISITION"; + case F_START_READOUT: return "F_START_READOUT"; + case F_GET_RUN_STATUS: return "F_GET_RUN_STATUS"; + case F_START_AND_READ_ALL: return "F_START_AND_READ_ALL"; + case F_READ_ALL: return "F_READ_ALL"; + case F_SET_TIMER: return "F_SET_TIMER"; + case F_GET_TIME_LEFT: return "F_GET_TIME_LEFT"; + case F_SET_DYNAMIC_RANGE: return "F_SET_DYNAMIC_RANGE"; + case F_SET_READOUT_FLAGS: return "F_SET_READOUT_FLAGS"; + case F_SET_ROI: return "F_SET_ROI"; + case F_SET_SPEED: return "F_SET_SPEED"; + case F_EXIT_SERVER: return "F_EXIT_SERVER"; + case F_LOCK_SERVER: return "F_LOCK_SERVER"; + case F_GET_LAST_CLIENT_IP: return "F_GET_LAST_CLIENT_IP"; + case F_SET_PORT: return "F_SET_PORT"; + case F_UPDATE_CLIENT: return "F_UPDATE_CLIENT"; + case F_CONFIGURE_MAC: return "F_CONFIGURE_MAC"; + case F_LOAD_IMAGE: return "F_LOAD_IMAGE"; + case F_READ_COUNTER_BLOCK: return "F_READ_COUNTER_BLOCK"; + case F_RESET_COUNTER_BLOCK: return "F_RESET_COUNTER_BLOCK"; + case F_ENABLE_TEN_GIGA: return "F_ENABLE_TEN_GIGA"; + case F_SET_ALL_TRIMBITS: return "F_SET_ALL_TRIMBITS"; + case F_SET_PATTERN: return "F_SET_PATTERN"; + case F_SET_PATTERN_MASK: return "F_SET_PATTERN_MASK"; + case F_GET_PATTERN_MASK: return "F_GET_PATTERN_MASK"; + case F_SET_PATTERN_BIT_MASK: return "F_SET_PATTERN_BIT_MASK"; + case F_GET_PATTERN_BIT_MASK: return "F_GET_PATTERN_BIT_MASK"; + case F_WRITE_ADC_REG: return "F_WRITE_ADC_REG"; + case F_SET_COUNTER_BIT: return "F_SET_COUNTER_BIT"; + case F_PULSE_PIXEL: return "F_PULSE_PIXEL"; + case F_PULSE_PIXEL_AND_MOVE: return "F_PULSE_PIXEL_AND_MOVE"; + case F_PULSE_CHIP: return "F_PULSE_CHIP"; + case F_SET_RATE_CORRECT: return "F_SET_RATE_CORRECT"; + case F_GET_RATE_CORRECT: return "F_GET_RATE_CORRECT"; + case F_SET_NETWORK_PARAMETER: return "F_SET_NETWORK_PARAMETER"; + case F_PROGRAM_FPGA: return "F_PROGRAM_FPGA"; + case F_RESET_FPGA: return "F_RESET_FPGA"; + case F_POWER_CHIP: return "F_POWER_CHIP"; + case F_ACTIVATE: return "F_ACTIVATE"; + case F_PREPARE_ACQUISITION: return "F_PREPARE_ACQUISITION"; + case F_THRESHOLD_TEMP: return "F_THRESHOLD_TEMP"; + case F_TEMP_CONTROL: return "F_TEMP_CONTROL"; + case F_TEMP_EVENT: return "F_TEMP_EVENT"; + case F_AUTO_COMP_DISABLE: return "F_AUTO_COMP_DISABLE"; + case F_STORAGE_CELL_START: return "F_STORAGE_CELL_START"; + case F_CHECK_VERSION: return "F_CHECK_VERSION"; + case F_SOFTWARE_TRIGGER: return "F_SOFTWARE_TRIGGER"; + case F_LED: return "F_LED"; + + case NUM_DET_FUNCTIONS: return "NUM_DET_FUNCTIONS"; + case RECEIVER_ENUM_START: return "RECEIVER_ENUM_START"; + + case F_EXEC_RECEIVER_COMMAND: return "F_EXEC_RECEIVER_COMMAND"; + case F_EXIT_RECEIVER: return "F_EXIT_RECEIVER"; + case F_LOCK_RECEIVER: return "F_LOCK_RECEIVER"; + case F_GET_LAST_RECEIVER_CLIENT_IP: return "F_GET_LAST_RECEIVER_CLIENT_IP"; + case F_SET_RECEIVER_PORT: return "F_SET_RECEIVER_PORT"; + case F_UPDATE_RECEIVER_CLIENT: return "F_UPDATE_RECEIVER_CLIENT"; + case F_GET_RECEIVER_ID: return "F_GET_RECEIVER_ID"; + case F_GET_RECEIVER_TYPE: return "F_GET_RECEIVER_TYPE"; + case F_SEND_RECEIVER_DETHOSTNAME: return "F_SEND_RECEIVER_DETHOSTNAME"; + case F_RECEIVER_SET_ROI: return "F_RECEIVER_SET_ROI"; + case F_SETUP_RECEIVER_UDP: return "F_SETUP_RECEIVER_UDP"; + case F_SET_RECEIVER_TIMER: return "F_SET_RECEIVER_TIMER"; + case F_SET_RECEIVER_DYNAMIC_RANGE: return "F_SET_RECEIVER_DYNAMIC_RANGE"; + case F_RECEIVER_STREAMING_FREQUENCY: return "F_RECEIVER_STREAMING_FREQUENCY"; + case F_GET_RECEIVER_STATUS: return "F_GET_RECEIVER_STATUS"; + case F_START_RECEIVER: return "F_START_RECEIVER"; + case F_STOP_RECEIVER: return "F_STOP_RECEIVER"; + case F_SET_RECEIVER_FILE_PATH: return "F_SET_RECEIVER_FILE_PATH"; + case F_SET_RECEIVER_FILE_NAME: return "F_SET_RECEIVER_FILE_NAME"; + case F_SET_RECEIVER_FILE_INDEX: return "F_SET_RECEIVER_FILE_INDEX"; + case F_GET_RECEIVER_FRAME_INDEX: return "F_GET_RECEIVER_FRAME_INDEX"; + case F_GET_RECEIVER_FRAMES_CAUGHT: return "F_GET_RECEIVER_FRAMES_CAUGHT"; + case F_RESET_RECEIVER_FRAMES_CAUGHT: return "F_RESET_RECEIVER_FRAMES_CAUGHT"; + case F_ENABLE_RECEIVER_FILE_WRITE: return "F_ENABLE_RECEIVER_FILE_WRITE"; + case F_ENABLE_RECEIVER_OVERWRITE: return "F_ENABLE_RECEIVER_OVERWRITE"; + case F_ENABLE_RECEIVER_TEN_GIGA: return "F_ENABLE_RECEIVER_TEN_GIGA"; + case F_SET_RECEIVER_FIFO_DEPTH: return "F_SET_RECEIVER_FIFO_DEPTH"; + case F_RECEIVER_ACTIVATE: return "F_RECEIVER_ACTIVATE"; + case F_STREAM_DATA_FROM_RECEIVER: return "F_STREAM_DATA_FROM_RECEIVER"; + case F_RECEIVER_STREAMING_TIMER: return "F_RECEIVER_STREAMING_TIMER"; + case F_SET_FLIPPED_DATA_RECEIVER: return "F_SET_FLIPPED_DATA_RECEIVER"; + case F_SET_RECEIVER_FILE_FORMAT: return "F_SET_RECEIVER_FILE_FORMAT"; + case F_SEND_RECEIVER_DETPOSID: return "F_SEND_RECEIVER_DETPOSID"; + case F_SEND_RECEIVER_MULTIDETSIZE: return "F_SEND_RECEIVER_MULTIDETSIZE"; + case F_SET_RECEIVER_STREAMING_PORT: return "F_SET_RECEIVER_STREAMING_PORT"; + case F_RECEIVER_STREAMING_SRC_IP: return "F_RECEIVER_STREAMING_SRC_IP"; + case F_SET_RECEIVER_SILENT_MODE: return "F_SET_RECEIVER_SILENT_MODE"; + case F_ENABLE_GAPPIXELS_IN_RECEIVER: return "F_ENABLE_GAPPIXELS_IN_RECEIVER"; + case F_RESTREAM_STOP_FROM_RECEIVER: return "F_RESTREAM_STOP_FROM_RECEIVER"; + case F_ADDITIONAL_JSON_HEADER: return "F_ADDITIONAL_JSON_HEADER"; + case F_GET_ADDITIONAL_JSON_HEADER: return "F_GET_ADDITIONAL_JSON_HEADER"; + case F_RECEIVER_UDP_SOCK_BUF_SIZE: return "F_RECEIVER_UDP_SOCK_BUF_SIZE"; + case F_RECEIVER_REAL_UDP_SOCK_BUF_SIZE: return "F_RECEIVER_REAL_UDP_SOCK_BUF_SIZE"; + case F_SET_RECEIVER_FRAMES_PER_FILE: return "F_SET_RECEIVER_FRAMES_PER_FILE"; + case F_RECEIVER_CHECK_VERSION: return "F_RECEIVER_CHECK_VERSION"; + case F_RECEIVER_DISCARD_POLICY: return "F_RECEIVER_DISCARD_POLICY"; + case F_RECEIVER_PADDING_ENABLE: return "F_RECEIVER_PADDING_ENABLE"; + case F_RECEIVER_DEACTIVATED_PADDING_ENABLE: return "F_RECEIVER_DEACTIVATED_PADDING_ENABLE"; + case F_RECEIVER_SET_READOUT_FLAGS: return "F_RECEIVER_SET_READOUT_FLAGS"; + case NUM_REC_FUNCTIONS: return "NUM_REC_FUNCTIONS"; + default: return "Unknown Function"; + } +}; +#endif + diff --git a/slsSupportLib/include/string_utils.h b/slsSupportLib/include/string_utils.h new file mode 100755 index 000000000..293af39d4 --- /dev/null +++ b/slsSupportLib/include/string_utils.h @@ -0,0 +1,75 @@ +#pragma once + +#include +#include +#include +#include + +namespace sls { + +/* Implementation of a safe string copy function for setting fields in +for example the multi sls detector. It tries to copy the size of the +destination from the source, stopping on '\0'. + +Warning this will truncate the source string and should be used with care. +Still this is better than strcpy and a buffer overflow... +*/ +template +void strcpy_safe(char (&destination)[array_size], const char *source) { + assert(array_size > strlen(source)); + strncpy(destination, source, array_size-1); + destination[array_size - 1] = '\0'; +} + +template +void strcpy_safe(char (&destination)[array_size], const std::string& source) { + assert(array_size > source.size()); + strncpy(destination, source.c_str(), array_size-1); + destination[array_size - 1] = '\0'; +} + +/* +Removes all occurrences of the specified char from a c string +Templated on array size to ensure no access after buffer limits. +*/ +template +void removeChar(char (&str)[array_size], char ch) { + int count = 0; + for (int i = 0; str[i]; i++) { + if (str[i] != ch) + str[count++] = str[i]; + if (i == array_size - 1) + break; + } + str[count] = '\0'; +} + +/* +Split a string using the specified delimeter and return a vector of strings. +TODO! Look into switching to absl or a string_view based implementation. Current +implementation should not be used in a performance critical place. +*/ +std::vector split(const std::string &strToSplit, char delimeter); + +/* +Concatenate the non empty strings in the vector using + +*/ +std::string concatenateNonEmptyStrings(const std::vector &vec); + +/* +Concatenate strings using + if the strings are different +*/ +std::string concatenateIfDifferent(const std::vector &container); + +/* +Concatenate vector of things with str method using + if the strings are different +*/ +template +std::string concatenateIfDifferent(const std::vector &container); + +/* +Convert an ip address string to a string in hex format. (removing dots) +*/ +std::string stringIpToHex(const std::string &ip); + +}; // namespace sls diff --git a/slsSupportLib/include/versionAPI.h b/slsSupportLib/include/versionAPI.h new file mode 100644 index 000000000..f21f00794 --- /dev/null +++ b/slsSupportLib/include/versionAPI.h @@ -0,0 +1,10 @@ +/** API versions */ +#define GITBRANCH "refgui" +#define APIGOTTHARD 0x190108 +#define APIMOENCH 0x181108 +#define APIEIGER 0x190405 +#define APIJUNGFRAU 0x190405 +#define APILIB 0x190405 +#define APIRECEIVER 0x190405 +#define APIGUI 0x190405 +#define APICTB 0x190405 diff --git a/slsSupportLib/src/ClientInterface.cpp b/slsSupportLib/src/ClientInterface.cpp new file mode 100755 index 000000000..a09ff6002 --- /dev/null +++ b/slsSupportLib/src/ClientInterface.cpp @@ -0,0 +1,42 @@ +#include "ClientInterface.h" +#include "ClientSocket.h" + +ClientInterface::ClientInterface(sls::ClientSocket *socket, int n) : socket_(socket){} + +void ClientInterface::Client_Receive(int &ret, char *mess, void *retval, int sizeOfRetval) { + // get result of operation + socket_->receiveData(reinterpret_cast(&ret), sizeof(ret)); + + bool unrecognizedFunction = false; + if (ret == FAIL) { + bool created = false; + // allocate mess if null + if (!mess) { + created = true; + mess = new char[MAX_STR_LENGTH]; + memset(mess, 0, MAX_STR_LENGTH); + } + // get error message + socket_->receiveData(mess, MAX_STR_LENGTH); + // cprintf(RED, "%s %d returned error: %s", type.c_str(), index, mess); + + // unrecognized function, do not ask for retval + if (strstr(mess, "Unrecognized Function") != nullptr) + unrecognizedFunction = true; + // delete allocated mess + if (created) + delete[] mess; + } + // get retval + if (!unrecognizedFunction) + socket_->receiveData(reinterpret_cast(retval), sizeOfRetval); +} + +int ClientInterface::Client_Send(int fnum, void *args, int sizeOfArgs, void *retval, + int sizeOfRetval, char *mess) { + int ret = FAIL; + socket_->sendData(reinterpret_cast(&fnum), sizeof(fnum)); + socket_->sendData(reinterpret_cast(args), sizeOfArgs); + Client_Receive(ret, mess, retval, sizeOfRetval); + return ret; +} \ No newline at end of file diff --git a/slsSupportLib/src/ClientSocket.cpp b/slsSupportLib/src/ClientSocket.cpp new file mode 100755 index 000000000..9db998dde --- /dev/null +++ b/slsSupportLib/src/ClientSocket.cpp @@ -0,0 +1,89 @@ +#include "ClientSocket.h" +#include "logger.h" +#include "sls_detector_defs.h" +#include "sls_detector_exceptions.h" +#include +#include +#include +#include +#include +#include +namespace sls { + +ClientSocket::ClientSocket(std::string stype, const std::string &host, uint16_t port) + : DataSocket(socket(AF_INET, SOCK_STREAM, 0)), socketType(stype) { + + struct addrinfo hints, *result; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags |= AI_CANONNAME; + + if (getaddrinfo(host.c_str(), NULL, &hints, &result) != 0) { + std::string msg = + "ClientSocket cannot decode host:" + host + " on port " + std::to_string(port) + "\n"; + throw SocketError(msg); + } + + // TODO! Erik, results could have multiple entries do we need to loop through them? + // struct sockaddr_in serverAddr {}; + serverAddr.sin_family = AF_INET; + serverAddr.sin_port = htons(port); + memcpy((char *)&serverAddr.sin_addr.s_addr, &((struct sockaddr_in *)result->ai_addr)->sin_addr, + sizeof(in_addr_t)); + + if (::connect(getSocketId(), (struct sockaddr *)&serverAddr, sizeof(serverAddr)) != 0) { + freeaddrinfo(result); + std::string msg = "ClientSocket: Cannot connect to " + socketType + ":" + + host + " on port " + std::to_string(port) + "\n"; + throw SocketError(msg); + } + freeaddrinfo(result); +} + +ClientSocket::ClientSocket(std::string sType, struct sockaddr_in addr) + : DataSocket(socket(AF_INET, SOCK_STREAM, 0)), socketType(sType) { + + if (::connect(getSocketId(), (struct sockaddr *)&addr, sizeof(addr)) != 0) { + char address[INET_ADDRSTRLEN]; + inet_ntop(AF_INET, &addr.sin_addr, address, INET_ADDRSTRLEN); + std::string msg = "ClientSocket: Cannot connect to " + socketType + ":" + address + " on port " + + std::to_string(addr.sin_port) + "\n"; + throw SocketError(msg); + } +} + +int ClientSocket::sendCommandThenRead(int fnum, void *args, size_t args_size, void *retval, + size_t retval_size) { + int ret = slsDetectorDefs::FAIL; + sendData(&fnum, sizeof(fnum)); + sendData(args, args_size); + readReply(ret, retval, retval_size); + return ret; +} + +void ClientSocket::readReply(int &ret, void *retval, size_t retval_size) { + + receiveData(&ret, sizeof(ret)); + if (ret == slsDetectorDefs::FAIL) { + char mess[MAX_STR_LENGTH]{}; + // get error message + receiveData(mess, sizeof(mess)); + FILE_LOG(logERROR) << socketType << " returned error: " << mess; + std::cout << "\n"; // needed to reset the color. + + // Do we need to know hostname here? + // In that case save it??? + if (socketType == "Receiver") { + throw ReceiverError(mess); + } else if (socketType == "Detector") { + throw DetectorError(mess); + } else { + throw GuiError(mess); + } + } + // get retval + receiveData(retval, retval_size); +} + +}; // namespace sls diff --git a/slsSupportLib/src/CmdLineParser.cpp b/slsSupportLib/src/CmdLineParser.cpp new file mode 100755 index 000000000..9ede50612 --- /dev/null +++ b/slsSupportLib/src/CmdLineParser.cpp @@ -0,0 +1,84 @@ + +#include "CmdLineParser.h" +#include +#include +#include +#include +#include +//printing function for debugging +void CmdLineParser::Print() { + std::cout << "\nCmdLineParser::Print()\n"; + std::cout << "\tmulti_id: " << multi_id_ << ", detector_id: " << detector_id_ << std::endl; + std::cout << "\texecutable: " << executable_ << '\n'; + std::cout << "\tcommand: " << command_ << '\n'; + std::cout << "\tn_arguments: " << n_arguments() << '\n'; + std::cout << "\targuments: "; + for (const auto &argument : arguments_) { + std::cout << argument << " "; + } + std::cout << "\n\n"; +}; + +void CmdLineParser::Parse(int argc, char *argv[]) { + //first element of argv is the command used to call the executable ->skipping + //and if this is the only command skip all + executable_ = argv[0]; + if (argc > 1) { + //second element is cmd string that needs to be decoded + DecodeIdAndPosition(argv[1]); + //The rest of the arguments goes into a vector for later processing + for (int i = 2; i < argc; ++i) { + arguments_.emplace_back(std::string(argv[i])); + } + } +}; + +void CmdLineParser::Parse(const std::string &s) { + std::istringstream iss(s); + auto it = std::istream_iterator(iss); + //read the first element and increment + command_ = *it++; + arguments_ = std::vector(it, std::istream_iterator()); + ; + DecodeIdAndPosition(command_.c_str()); +} + +void CmdLineParser::DecodeIdAndPosition(const char *c) { + bool contains_id = std::strchr(c, '-') != nullptr; + bool contains_pos = std::strchr(c, ':') != nullptr; + char tmp[100]; + + if (contains_id && contains_pos) { + int r = sscanf(c, "%d-%d:%s", &multi_id_, &detector_id_, tmp); + if (r != 3) { + throw(std::invalid_argument("Cannot decode client or detector id from: \"" + std::string(c) + "\"\n")); + } + command_ = tmp; + } else if (contains_id && !contains_pos) { + int r = sscanf(c, "%d-%s", &multi_id_, tmp); + if (r != 2) { + throw(std::invalid_argument("Cannot decode client id from: \"" + std::string(c) + "\"\n")); + } + command_ = tmp; + } else if (!contains_id && contains_pos) { + int r = sscanf(c, "%d:%s", &detector_id_, tmp); + if (r != 2) { + throw(std::invalid_argument("Cannot decode detector id from: \"" + std::string(c) + "\"\n")); + } + command_ = tmp; + } else { + command_ = c; + } +} + +std::vector CmdLineParser::argv() { + std::vector vec; + if (command_.empty()!=true){ + vec.push_back(&command_.front()); + } + + for (auto &arg : arguments_) { + vec.push_back(&arg.front()); + } + return vec; +} diff --git a/slsSupportLib/src/DataSocket.cpp b/slsSupportLib/src/DataSocket.cpp new file mode 100755 index 000000000..b64b9fda8 --- /dev/null +++ b/slsSupportLib/src/DataSocket.cpp @@ -0,0 +1,159 @@ +#include "DataSocket.h" +#include "logger.h" +#include "sls_detector_exceptions.h" +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace sls { + +DataSocket::DataSocket(int socketId) : socketId_(socketId) {} + +DataSocket::~DataSocket() { + if (socketId_ <= 0) { + return; + } else { + try { + close(); + } catch (...) { + // pass + } + } +} + +void DataSocket::swap(DataSocket &other) noexcept { std::swap(socketId_, other.socketId_); } + +DataSocket::DataSocket(DataSocket &&move) noexcept { move.swap(*this); } +DataSocket &DataSocket::operator=(DataSocket &&move) noexcept { + move.swap(*this); + return *this; +} + +size_t DataSocket::receiveData(void *buffer, size_t size) { + // std::cout << "Sending\n"; + size_t dataRead = 0; + while (dataRead < size) { + dataRead += + read(getSocketId(), reinterpret_cast(buffer) + dataRead, size - dataRead); + } + return dataRead; +} + +size_t DataSocket::sendData(void *buffer, size_t size) { + // std::cout << "Receiving\n"; + size_t dataSent = 0; + while (dataSent < size) { + dataSent += + write(getSocketId(), reinterpret_cast(buffer) + dataSent, size - dataSent); + } + return dataSent; +} + +int DataSocket::setTimeOut(int t_seconds) { + if (t_seconds <= 0) + return -1; + + struct timeval t; + t.tv_sec = 0; + t.tv_usec = 0; + // Receive timeout indefinet + if (::setsockopt(getSocketId(), SOL_SOCKET, SO_RCVTIMEO, &t, sizeof(struct timeval)) < 0) { + FILE_LOG(logERROR) << "setsockopt SO_RCVTIMEO " << 0; + } + + t.tv_sec = t_seconds; + t.tv_usec = 0; + // Sending timeout in seconds + if (::setsockopt(getSocketId(), SOL_SOCKET, SO_SNDTIMEO, &t, sizeof(struct timeval)) < 0) { + FILE_LOG(logERROR) << "setsockopt SO_SNDTIMEO " << t_seconds; + } + return 0; +} + +void DataSocket::close() { + if (socketId_ > 0) { + if(::close(socketId_)){ + throw SocketError("could not close socket"); + } + socketId_ = -1; + + } else { + throw std::runtime_error("Socket ERROR: close called on bad socket\n"); + } +} + +void DataSocket::shutDownSocket() { + shutdown(getSocketId(), SHUT_RDWR); + close(); +} + +struct sockaddr_in ConvertHostnameToInternetAddress(const std::string &hostname) { + struct addrinfo hints, *result; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags |= AI_CANONNAME; + + struct sockaddr_in serverAddr {}; + if (getaddrinfo(hostname.c_str(), NULL, &hints, &result) != 0) { + freeaddrinfo(result); + std::string msg = "ClientSocket cannot decode host:" + hostname + "\n"; + throw SocketError(msg); + } + serverAddr.sin_family = AF_INET; + memcpy((char *)&serverAddr.sin_addr.s_addr, &((struct sockaddr_in *)result->ai_addr)->sin_addr, + sizeof(in_addr_t)); + freeaddrinfo(result); + return serverAddr; +} + +int ConvertHostnameToInternetAddress(const char *const hostname, struct ::addrinfo **res) { + // criteria in selecting socket address structures returned by res + struct ::addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + // get host info into res + int errcode = getaddrinfo(hostname, NULL, &hints, res); + if (errcode != 0) { + FILE_LOG(logERROR) << "Could not convert hostname (" << hostname + << ") to internet address (zmq):" << gai_strerror(errcode); + } else { + if (*res == NULL) { + FILE_LOG(logERROR) << "Could not converthostname (" << hostname + << ") to internet address (zmq):" + "gettaddrinfo returned null"; + } else { + return 0; + } + } + FILE_LOG(logERROR) << "Could not convert hostname to internet address"; + return 1; +}; + +/** + * Convert Internet Address structure pointer to ip string (char*) + * Clears the internet address structure as well + * @param res pointer to internet address structure + * @param ip pointer to char array to store result in + * @param ipsize size available in ip buffer + * @return 1 for fail, 0 for success + */ +// Do not make this static (for multi threading environment) +int ConvertInternetAddresstoIpString(struct ::addrinfo *res, char *ip, const int ipsize) { + if (inet_ntop(res->ai_family, &((struct sockaddr_in *)res->ai_addr)->sin_addr, ip, ipsize) != + NULL) { + ::freeaddrinfo(res); + return 0; + } + FILE_LOG(logERROR) << "Could not convert internet address to ip string"; + return 1; +} + +} // namespace sls diff --git a/slsSupportLib/src/ServerInterface.cpp b/slsSupportLib/src/ServerInterface.cpp new file mode 100755 index 000000000..6be49a37e --- /dev/null +++ b/slsSupportLib/src/ServerInterface.cpp @@ -0,0 +1,143 @@ +#include "ServerInterface.h" + +ServerInterface::ServerInterface(MySocketTCP *socket, int n, std::string t): mySocket(socket), + index(n), + type(t){} + +void ServerInterface::SetSocket(MySocketTCP *socket) { + mySocket = socket; +} + + +void ServerInterface::Client_Receive(int& ret, char* mess, void* retval, int sizeOfRetval) { + // get result of operation + mySocket->ReceiveDataOnly(&ret,sizeof(ret)); + + bool unrecognizedFunction = false; + if (ret == FAIL) { + bool created = false; + // allocate mess if null + if (!mess){ + created = true; + mess = new char[MAX_STR_LENGTH]; + memset(mess, 0, MAX_STR_LENGTH); + } + // get error message + mySocket->ReceiveDataOnly(mess,MAX_STR_LENGTH); + cprintf(RED, "%s %d returned error: %s", type.c_str(), index, mess); + + // unrecognized function, do not ask for retval + if(strstr(mess,"Unrecognized Function") != nullptr) + unrecognizedFunction = true; + // delete allocated mess + if (created) + delete [] mess; + } + // get retval + if (!unrecognizedFunction) + mySocket->ReceiveDataOnly(retval, sizeOfRetval); +} + + +int ServerInterface::Client_Send(int fnum, + void* args, int sizeOfArgs, + void* retval, int sizeOfRetval, + char* mess) { + int ret = FAIL; + mySocket->SendDataOnly(&fnum,sizeof(fnum)); + mySocket->SendDataOnly(args, sizeOfArgs); + Client_Receive(ret, mess, retval, sizeOfRetval); + return ret; +} + + +int ServerInterface::Server_SendResult(bool update, int ret, + void* retval, int retvalSize, char* mess) { + + // update if different clients + if (update && ret == OK && mySocket->differentClients) + ret = FORCE_UPDATE; + + // send success of operation + mySocket->SendDataOnly(&ret,sizeof(ret)); + if(ret == FAIL) { + // send error message + if (mess) + mySocket->SendDataOnly(mess, MAX_STR_LENGTH); + // debugging feature. should not happen. + else + FILE_LOG(logERROR) << "No error message provided for this failure. Will mess up TCP\n"; + } + // send return value + mySocket->SendDataOnly(retval, retvalSize); + + return ret; +} + + +int ServerInterface::Server_ReceiveArg(int& ret, char* mess, void* arg, int sizeofArg, bool checkbase, void* base) { + // client socket crash, cannot receive arguments + if (sizeofArg && mySocket->ReceiveDataOnly(arg, sizeofArg) < 0) + return Server_SocketCrash(); + + // check if server object created + if (checkbase && base == nullptr) + Server_NullObjectError(ret, mess); + + // no crash + return OK; +} + + +int ServerInterface::Server_VerifyLock(int& ret, char* mess, int lockstatus) { + // server locked + if (mySocket->differentClients && lockstatus) + return Server_LockedError(ret, mess); + return ret; +} + + +int ServerInterface::Server_VerifyLockAndIdle(int& ret, char* mess, int lockstatus, slsDetectorDefs::runStatus status, int fnum) { + // server locked + if (mySocket->differentClients && lockstatus) + return Server_LockedError(ret, mess); + + // server not idle for this command + if (status != slsDetectorDefs::IDLE) + return Server_NotIdleError(ret, mess, fnum); + return ret; +} + + +void ServerInterface::Server_NullObjectError(int& ret, char* mess) { + ret=FAIL; + strcpy(mess,"Receiver not set up. Please use rx_hostname first.\n"); + FILE_LOG(logERROR) << mess; +} + + +int ServerInterface::Server_SocketCrash() { + FILE_LOG(logERROR) << "Reading from socket failed. Possible socket crash"; + return FAIL; +} + + +int ServerInterface::Server_LockedError(int& ret, char* mess) { + ret = FAIL; + sprintf(mess,"Receiver locked by %s\n", mySocket->lastClientIP); + FILE_LOG(logERROR) << mess; + return ret; +} + + +int ServerInterface::Server_NotIdleError(int& ret, char* mess, int fnum) { + ret = FAIL; + sprintf(mess,"Can not execute %s when receiver is not idle\n", + getFunctionNameFromEnum((enum detFuncs)fnum)); + FILE_LOG(logERROR) << mess; + return ret; +} + + + + diff --git a/slsSupportLib/src/ServerSocket.cpp b/slsSupportLib/src/ServerSocket.cpp new file mode 100755 index 000000000..54943cc79 --- /dev/null +++ b/slsSupportLib/src/ServerSocket.cpp @@ -0,0 +1,79 @@ +#include "ServerSocket.h" +#include "DataSocket.h" +#include "logger.h" +#include "sls_detector_defs.h" +#include "sls_detector_exceptions.h" +#include "string_utils.h" + +#include +#include +#include +#include +#include +#define DEFAULT_PACKET_SIZE 1286 +#define SOCKET_BUFFER_SIZE (100 * 1024 * 1024) // 100 MB +#define DEFAULT_BACKLOG 5 + +namespace sls { + +ServerSocket::ServerSocket(int port) + : DataSocket(socket(AF_INET, SOCK_STREAM, 0)), serverPort(port) { + + struct sockaddr_in serverAddr; + serverAddr.sin_family = AF_INET; + serverAddr.sin_port = htons(port); + serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); + + if (bind(getSocketId(), (struct sockaddr *)&serverAddr, + sizeof(serverAddr)) != 0) { + close(); + throw std::runtime_error("Server ERROR: cannot bind socket"); + } + if (listen(getSocketId(), DEFAULT_BACKLOG) != 0) { + close(); + throw std::runtime_error("Server ERROR: cannot listen to socket"); + } +} + +DataSocket ServerSocket::accept() { + struct sockaddr_in clientAddr; + socklen_t addr_size = sizeof clientAddr; + int newSocket = + ::accept(getSocketId(), (struct sockaddr *)&clientAddr, &addr_size); + if (newSocket == -1) { + throw std::runtime_error("Server ERROR: socket accept failed\n"); + } + inet_ntop(AF_INET, &(clientAddr.sin_addr), &thisClient_.front(), + INET_ADDRSTRLEN); + std::cout << "lastClient: " << lastClient_ << " thisClient: " << thisClient_ + << '\n'; + // Here goes any check for locks etc + lastClient_ = thisClient_; + + return DataSocket(newSocket); +} + +const std::string &ServerSocket::getLastClient() { return lastClient_; } + +int ServerSocket::getPort() const { return serverPort; } + +void ServerSocket::SendResult(int &ret, void* retval, int retvalSize, char* mess) { + + // send success of operation + sendData(&ret, sizeof(ret)); + + if (ret == slsDetectorDefs::FAIL) { + // create error message if empty + if (!strlen(mess)) { + strcpy(mess, "No error message provided for this failure in server. Will mess up TCP."); + } + + sendData(mess, MAX_STR_LENGTH); + throw sls::RuntimeError(mess); + } + // send return value + sendData(retval, retvalSize); +} + + +}; // namespace sls diff --git a/slsSupportLib/src/file_utils.cpp b/slsSupportLib/src/file_utils.cpp new file mode 100755 index 000000000..71897e5c0 --- /dev/null +++ b/slsSupportLib/src/file_utils.cpp @@ -0,0 +1,81 @@ +#include "file_utils.h" +#include "logger.h" + +#include +#include + + +int readDataFile(std::ifstream &infile, short int *data, int nch, int offset) { + int ichan, iline=0; + short int idata; + int interrupt=0; + std::string str; + while (infile.good() and interrupt==0) { + getline(infile,str); + std::istringstream ssstr(str); + ssstr >> ichan >> idata; + if (ssstr.fail() || ssstr.bad()) { + interrupt=1; + break; + } + if (iline=offset) { + data[iline]=idata; + iline++; + } + } else { + interrupt=1; + break; + } + return iline; + }; + return iline; +} + + + +int readDataFile(std::string fname, short int *data, int nch) { + std::ifstream infile; + int iline=0; + std::string str; + infile.open(fname.c_str(), std::ios_base::in); + if (infile.is_open()) { + iline=readDataFile(infile, data, nch, 0); + infile.close(); + } else { + FILE_LOG(logERROR) << "Could not read file " << fname; + return -1; + } + return iline; +} + + + +int writeDataFile(std::ofstream &outfile,int nch, short int *data, int offset) { + if (data==nullptr) + return slsDetectorDefs::FAIL; + for (int ichan=0; ichan +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "network_utils.h" + +namespace sls { + +IpAddr::IpAddr(const std::string &address) { + inet_pton(AF_INET, address.c_str(), &addr_); +} + +IpAddr::IpAddr(const char *address) { + inet_pton(AF_INET, address, &addr_); +} + +std::string IpAddr::str() const { + char ipstring[INET_ADDRSTRLEN]{}; + inet_ntop(AF_INET, &addr_, ipstring, INET_ADDRSTRLEN); + return ipstring; +} +std::string IpAddr::hex() const { + std::ostringstream ss; + ss << std::hex << std::setfill('0') << std::setw(2); + for (int i = 0; i != 4; ++i) { + ss << ((addr_ >> i * 8) & 0xFF); + } + return ss.str(); +} + +MacAddr::MacAddr(std::string mac) { + if ((mac.length() != 17) || (mac[2] != ':') || (mac[5] != ':') || + (mac[8] != ':') || (mac[11] != ':') || (mac[14] != ':')) { + addr_ = 0; + } else { + mac.erase(std::remove(mac.begin(), mac.end(), ':'), mac.end()); + addr_ = std::strtoul(mac.c_str(), nullptr, 16); + } +} +MacAddr::MacAddr(const char *address) : MacAddr(std::string(address)) {} + +std::string MacAddr::to_hex(const char delimiter) const { + std::ostringstream ss; + ss << std::hex << std::setfill('0') << std::setw(2); + ss << ((addr_ >> 40) & 0xFF); + for (int i = 32; i >= 0; i -= 8) { + if (delimiter) + ss << delimiter; + ss << ((addr_ >> i) & 0xFF); + } + return ss.str(); +} + +std::string MacAddr::str() const { + return to_hex(':'); +} + +std::string MacAddr::hex() const { + return to_hex(); +} + +std::ostream &operator<<(std::ostream &out, const IpAddr &addr) { + return out << addr.str(); +} + +std::ostream &operator<<(std::ostream &out, const MacAddr &addr) { + return out << addr.str(); +} + +uint32_t HostnameToIp(const char *hostname) { + addrinfo hints; + addrinfo *result = nullptr; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + if (getaddrinfo(hostname, NULL, &hints, &result)) { + freeaddrinfo(result); + throw RuntimeError("Could not convert hostname to ip"); + } + uint32_t ip = ((sockaddr_in *)result->ai_addr)->sin_addr.s_addr; + freeaddrinfo(result); + return ip; +} + +} // namespace sls diff --git a/slsSupportLib/src/string_utils.cpp b/slsSupportLib/src/string_utils.cpp new file mode 100755 index 000000000..2ddfe6785 --- /dev/null +++ b/slsSupportLib/src/string_utils.cpp @@ -0,0 +1,54 @@ + +#include "string_utils.h" +#include "container_utils.h" +#include "network_utils.h" +#include +#include +#include +namespace sls { + +std::vector split(const std::string &strToSplit, char delimeter) { + std::stringstream ss(strToSplit); + std::string item; + std::vector splittedStrings; + while (std::getline(ss, item, delimeter)) { + splittedStrings.push_back(item); + } + return splittedStrings; +} + +std::string concatenateNonEmptyStrings(const std::vector &vec) { + std::string ret; + for (const auto &s : vec) + if (!s.empty()) + ret += s + '+'; + return ret; +} + +std::string concatenateIfDifferent(const std::vector &container) { + if (allEqual(container)) { + return container.front(); + } else { + std::string result; + for (const auto &s : container) + result += s + '+'; + return result; + } +} +template +std::string concatenateIfDifferent(const std::vector &container) { + if (allEqual(container)) { + return container.front().str(); + } else { + std::string result; + for (const auto &s : container) + result += s.str() + '+'; + return result; + } +} + + +template std::string concatenateIfDifferent(const std::vector &); +template std::string concatenateIfDifferent(const std::vector &); + +}; // namespace sls \ No newline at end of file diff --git a/slsSupportLib/tests/CMakeLists.txt b/slsSupportLib/tests/CMakeLists.txt new file mode 100755 index 000000000..6164cc13d --- /dev/null +++ b/slsSupportLib/tests/CMakeLists.txt @@ -0,0 +1,8 @@ +target_sources(tests PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/test-ClientInterface.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test-CmdLineParser.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test-container_utils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test-network_utils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test-string_utils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/test-Timer.cpp + ) \ No newline at end of file diff --git a/slsSupportLib/tests/test-ClientInterface.cpp b/slsSupportLib/tests/test-ClientInterface.cpp new file mode 100755 index 000000000..633e8a0f9 --- /dev/null +++ b/slsSupportLib/tests/test-ClientInterface.cpp @@ -0,0 +1,12 @@ +#include "ClientInterface.h" +#include "MySocketTCP.h" +#include "catch.hpp" + +//tests to add +//help for all docs +//command for all depreciated commands + +TEST_CASE("hopp") { + REQUIRE(true); + +} \ No newline at end of file diff --git a/slsSupportLib/tests/test-CmdLineParser.cpp b/slsSupportLib/tests/test-CmdLineParser.cpp new file mode 100755 index 000000000..df4c3e27a --- /dev/null +++ b/slsSupportLib/tests/test-CmdLineParser.cpp @@ -0,0 +1,266 @@ +#include "CmdLineParser.h" +#include "catch.hpp" +#include +#include +//tests to add +//help for all docs +//command for all depreciated commands + +TEST_CASE("Parse with no arguments results in no command and default id") { + //build up argc and argv + //first argument is the command used to call the binary + int argc = 1; + char *argv[argc]; + char a0[] = "call"; + argv[0] = static_cast(a0); + + CmdLineParser p; + p.Parse(argc, argv); + + REQUIRE(p.detector_id() == -1); + REQUIRE(p.multi_id() == 0); + REQUIRE(p.command().empty()); + REQUIRE(p.arguments().empty()); +} + +TEST_CASE("Parse empty string") { + std::string s; + CmdLineParser p; + p.Parse(s); + + REQUIRE(p.detector_id() == -1); + REQUIRE(p.multi_id() == 0); + REQUIRE(p.command().empty()); + REQUIRE(p.arguments().empty()); +} + +TEST_CASE("Parse a command without client id and detector id results in default") { + int argc = 2; + char *argv[argc]; + char a0[] = "call"; + char a1[] = "vrf"; + argv[0] = static_cast(a0); + argv[1] = static_cast(a1); + + CmdLineParser p; + p.Parse(argc, argv); + + REQUIRE(p.detector_id() == -1); + REQUIRE(p.multi_id() == 0); + REQUIRE(p.command() == "vrf"); + REQUIRE(p.arguments().empty()); +} + +TEST_CASE("Parse a string without client id and detector id results in default") { + std::string s = "vrf"; + CmdLineParser p; + p.Parse(s); + + REQUIRE(p.detector_id() == -1); + REQUIRE(p.multi_id() == 0); + REQUIRE(p.command() == "vrf"); + REQUIRE(p.arguments().empty()); +} + +TEST_CASE("Parse a command with value but without client or detector id") { + int argc = 3; + char *argv[argc]; + char a0[] = "call"; + char a1[] = "vrf"; + char a2[] = "3000"; + argv[0] = static_cast(a0); + argv[1] = static_cast(a1); + argv[2] = static_cast(a2); + + CmdLineParser p; + p.Parse(argc, argv); + + REQUIRE(p.detector_id() == -1); + REQUIRE(p.multi_id() == 0); + REQUIRE(p.command() == "vrf"); + REQUIRE(p.arguments().size() == 1); + REQUIRE(p.arguments()[0] == "3000"); +} +TEST_CASE("Parse a string with value but without client or detector id") { + std::string s = "vrf 3000\n"; + + CmdLineParser p; + p.Parse(s); + + REQUIRE(p.detector_id() == -1); + REQUIRE(p.multi_id() == 0); + REQUIRE(p.command() == "vrf"); + REQUIRE(p.arguments().size() == 1); + REQUIRE(p.arguments()[0] == "3000"); +} + +TEST_CASE("Decodes position") { + int argc = 2; + char *argv[argc]; + char a0[] = "call"; + char a1[] = "7:vrf"; + argv[0] = static_cast(a0); + argv[1] = static_cast(a1); + + CmdLineParser p; + p.Parse(argc, argv); + + REQUIRE(p.detector_id() == 7); + REQUIRE(p.multi_id() == 0); + REQUIRE(p.command() == "vrf"); + REQUIRE(p.arguments().empty()); +} +TEST_CASE("Decodes position from string") { + std::string s = "7:vrf\n"; + + CmdLineParser p; + p.Parse(s); + + REQUIRE(p.detector_id() == 7); + REQUIRE(p.multi_id() == 0); + REQUIRE(p.command() == "vrf"); + REQUIRE(p.arguments().empty()); +} + +TEST_CASE("Decodes double digit position") { + int argc = 2; + char *argv[argc]; + char a0[] = "call"; + char a1[] = "73:vcmp"; + argv[0] = static_cast(a0); + argv[1] = static_cast(a1); + + CmdLineParser p; + p.Parse(argc, argv); + + REQUIRE(p.detector_id() == 73); + REQUIRE(p.multi_id() == 0); + REQUIRE(p.command() == "vcmp"); + REQUIRE(p.arguments().empty()); +} + +TEST_CASE("Decodes double digit position from string") { + + std::string s = "73:vcmp"; + CmdLineParser p; + p.Parse(s); + + REQUIRE(p.detector_id() == 73); + REQUIRE(p.multi_id() == 0); + REQUIRE(p.command() == "vcmp"); + REQUIRE(p.arguments().empty()); +} + +TEST_CASE("Decodes position and id") { + int argc = 2; + char *argv[argc]; + char a0[] = "call"; + char a1[] = "5-8:vrf"; + argv[0] = static_cast(a0); + argv[1] = static_cast(a1); + + CmdLineParser p; + p.Parse(argc, argv); + + REQUIRE(p.detector_id() == 8); + REQUIRE(p.multi_id() == 5); + REQUIRE(p.command() == "vrf"); + REQUIRE(p.arguments().empty()); +} +TEST_CASE("Decodes position and id from string") { + std::string s = "5-8:vrf"; + CmdLineParser p; + p.Parse(s); + + REQUIRE(p.detector_id() == 8); + REQUIRE(p.multi_id() == 5); + REQUIRE(p.command() == "vrf"); + REQUIRE(p.arguments().empty()); +} + +TEST_CASE("Double digit id") { + int argc = 2; + char *argv[argc]; + char a0[] = "call"; + char a1[] = "56-8:vrf"; + argv[0] = static_cast(a0); + argv[1] = static_cast(a1); + + CmdLineParser p; + p.Parse(argc, argv); + + REQUIRE(p.detector_id() == 8); + REQUIRE(p.multi_id() == 56); + REQUIRE(p.command() == "vrf"); + REQUIRE(p.arguments().empty()); +} + +TEST_CASE("Double digit id from string") { + std::string s = "56-8:vrf"; + CmdLineParser p; + p.Parse(s); + + REQUIRE(p.detector_id() == 8); + REQUIRE(p.multi_id() == 56); + REQUIRE(p.command() == std::string("vrf")); + REQUIRE(p.arguments().empty()); +} + +TEST_CASE("Calling with wrong id throws invalid_argument") { + + int argc = 2; + char *argv[argc]; + char a0[] = "call"; + char a1[] = "asvldkn:vrf"; + argv[0] = static_cast(a0); + argv[1] = static_cast(a1); + + CmdLineParser p; + CHECK_THROWS(p.Parse(argc, argv)); +} +TEST_CASE("Calling with string with wrong id throws invalid_argument") { + std::string s = "asvldkn:vrf"; + CmdLineParser p; + CHECK_THROWS(p.Parse(s)); +} + +TEST_CASE("Calling with wrong client throws invalid_argument") { + int argc = 2; + char *argv[argc]; + char a0[] = "call"; + char a1[] = "lki-3:vrf"; + argv[0] = static_cast(a0); + argv[1] = static_cast(a1); + + CmdLineParser p; + CHECK_THROWS(p.Parse(argc, argv)); +} +TEST_CASE("Calling with string with wrong client throws invalid_argument") { + std::string s = "lki-3:vrf"; + CmdLineParser p; + CHECK_THROWS(p.Parse(s)); +} + +TEST_CASE("Parses string with two arguments") { + std::string s = "trimen 3000 4000\n"; + CmdLineParser p; + p.Parse(s); + + REQUIRE("trimen" == p.command()); + REQUIRE("3000" == p.arguments()[0]); + REQUIRE("4000" == p.arguments()[1]); + REQUIRE(p.arguments().size() == 2); +} + +TEST_CASE("Build up argv"){ + CmdLineParser p; + // p.argv(); + REQUIRE(p.argv().empty()); + REQUIRE(p.argv().data() == nullptr); + + std::string s = "trimen 3000 4000\n"; + p.Parse(s); + REQUIRE(p.argv().data() != nullptr); + REQUIRE(p.argv().size() == 3); + +} \ No newline at end of file diff --git a/slsSupportLib/tests/test-Timer.cpp b/slsSupportLib/tests/test-Timer.cpp new file mode 100755 index 000000000..e382cc340 --- /dev/null +++ b/slsSupportLib/tests/test-Timer.cpp @@ -0,0 +1,23 @@ +#include "Timer.h" +#include "catch.hpp" + +#include +#include + +TEST_CASE("Time 1s restart then time 2s") { + auto sleep_duration = std::chrono::seconds(1); + auto t = sls::Timer(); + std::this_thread::sleep_for(sleep_duration); + REQUIRE(t.elapsed_s() == Approx(1).epsilon(0.01)); + + t.restart(); + std::this_thread::sleep_for(sleep_duration * 2); + REQUIRE(t.elapsed_s() == Approx(2).epsilon(0.01)); +} + +TEST_CASE("Return ms") { + auto sleep_duration = std::chrono::milliseconds(1300); + auto t = sls::Timer(); + std::this_thread::sleep_for(sleep_duration); + REQUIRE(t.elapsed_ms() == Approx(1300).epsilon(0.5)); +} \ No newline at end of file diff --git a/slsSupportLib/tests/test-container_utils.cpp b/slsSupportLib/tests/test-container_utils.cpp new file mode 100755 index 000000000..b2403d551 --- /dev/null +++ b/slsSupportLib/tests/test-container_utils.cpp @@ -0,0 +1,125 @@ +#include "catch.hpp" +#include "container_utils.h" +#include +#include +#include + +using namespace sls; + +TEST_CASE("Equality of an empty vector", "[support]") { + std::vector v; + REQUIRE(v.empty()); + REQUIRE_FALSE(allEqual(v)); + REQUIRE_FALSE(allEqualWithTol(v, 2)); + REQUIRE_FALSE(allEqualTo(v, 5)); + REQUIRE_FALSE(anyEqualTo(v, 5)); + REQUIRE_FALSE(anyEqualToWithTol(v, 5, 1)); +} + +TEST_CASE("Equality of a vector with one element", "[support]") { + std::vector v{5}; + REQUIRE(v.size() == 1); + REQUIRE(allEqual(v)); + REQUIRE(allEqualWithTol(v, 1)); + REQUIRE(allEqualTo(v, 5)); + REQUIRE(allEqualToWithTol(v, 5, 2)); + REQUIRE(anyEqualTo(v, 5)); + REQUIRE(anyEqualToWithTol(v, 5, 1)); +} + +TEST_CASE("A larger vector of the same elements", "[support]") { + std::vector v(101, 5); + REQUIRE(v.size() == 101); + REQUIRE(allEqual(v)); + REQUIRE(allEqualWithTol(v, 1)); + REQUIRE(allEqualTo(v, 5)); + REQUIRE(anyEqualTo(v, 5)); + + SECTION("Push back another element to create a vector where not all are " + "equal") { + v.push_back(7); + REQUIRE(v.size() == 102); + REQUIRE_FALSE(allEqual(v)); + + REQUIRE_FALSE(allEqualWithTol(v, 1)); + REQUIRE(allEqualWithTol(v, 3)); + + REQUIRE_FALSE(allEqualTo(v, 5)); + + REQUIRE_FALSE(allEqualToWithTol(v, 5, 1)); + REQUIRE(allEqualToWithTol(v, 5, 3)); + REQUIRE(anyEqualTo(v, 5)); + } +} + +TEST_CASE("A vector of double with different values", "[support]") { + std::vector v{1.2, 2., 4.2, 4, 1.1}; + + REQUIRE(allEqual(v) == false); + REQUIRE(allEqualWithTol(v, 0.3) == false); + REQUIRE(allEqualWithTol(v, 3.2)); +} + +TEST_CASE("Sum of empty vector", "[support]") { + std::vector v; + REQUIRE(sls::sum(v) == Approx(0)); +} + +TEST_CASE("Sum of vector", "[support]") { + std::vector v{1.2, 2., 4.2, 4, 1.13}; + REQUIRE(sls::sum(v) == Approx(12.53)); +} + +TEST_CASE("Minus one if different", "[support]") { + std::vector v; + REQUIRE(v.empty()); + double d = -1; + REQUIRE(sls::minusOneIfDifferent(v) == d); + + SECTION("single element") { + v.push_back(7.3); + REQUIRE(v.size() == 1); + REQUIRE(sls::minusOneIfDifferent(v) == Approx(7.3)); + } + SECTION("different elements") { + v.push_back(7.3); + v.push_back(1.0); + v.push_back(62.1); + REQUIRE(sls::minusOneIfDifferent(v) == Approx(-1.0)); + } +} + +TEST_CASE("minus one does not have side effects", "[support]") { + std::vector v{1, 1, 1}; + int i = sls::minusOneIfDifferent(v); + REQUIRE(i == 1); + i = 5; + REQUIRE(v[0] == 1); +} + +TEST_CASE("Compare a vector containing two vectors", "[support]") { + + std::vector> a{{0, 1, 2, 3, 4, 5}, {0, 1, 2, 3, 4, 5}}; + std::vector> b{{0, 1, 2, 3, 4, 5}, {0, 1, 2, 3, 3, 5}}; + std::vector> c{{0, 1, 2, 3, 4}, {0, 1, 2, 3, 3, 5}}; + std::vector> d{ + {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4}, {0, 1, 2, 3, 4}}; + std::vector e{0, 1, 2, 3, 4, 5}; + + CHECK(minusOneIfDifferent(a) == a[0]); + CHECK(minusOneIfDifferent(a) == e); + CHECK(minusOneIfDifferent(b) == std::vector{-1}); + CHECK(minusOneIfDifferent(c) == std::vector{-1}); + CHECK(minusOneIfDifferent(d) == d[2]); +} + + +TEST_CASE("vector of bool", "[support]"){ + std::vector a{true, true, true}; + std::vector b{false, false, false}; + std::vector c{true, false, true}; + + CHECK(minusOneIfDifferent(a) == 1); + CHECK(minusOneIfDifferent(b) == 0); + CHECK(minusOneIfDifferent(c) == -1); +} \ No newline at end of file diff --git a/slsSupportLib/tests/test-network_utils.cpp b/slsSupportLib/tests/test-network_utils.cpp new file mode 100755 index 000000000..41e422812 --- /dev/null +++ b/slsSupportLib/tests/test-network_utils.cpp @@ -0,0 +1,99 @@ + +#include "catch.hpp" +#include "network_utils.h" +#include +#include + +#include "string_utils.h" +#include "sls_detector_exceptions.h" + +using namespace sls; + +TEST_CASE("Convert mac address using classes", "[support]") { + + std::vector vec_addr{346856806822, 346856806852, 262027939863028}; + std::vector vec_ans{"00:50:c2:46:d9:a6", "00:50:c2:46:d9:c4", + "ee:50:22:46:d9:f4"}; + for (size_t i = 0; i != vec_addr.size(); ++i) { + auto mac0 = MacAddr(vec_addr[i]); + auto mac1 = MacAddr(vec_ans[i]); + + CHECK(mac0 == vec_addr[i]); + CHECK(mac1 == vec_addr[i]); + CHECK(mac0 == vec_ans[i]); + CHECK(mac1 == vec_ans[i]); + CHECK(mac0.str() == vec_ans[i]); + CHECK(mac1.str() == vec_ans[i]); + } +} + +TEST_CASE("Hex representation of MAC", "[support]") { + MacAddr m{346856806822}; + CHECK(m.hex() == "0050c246d9a6"); + CHECK(m.str() == "00:50:c2:46:d9:a6"); + CHECK_FALSE(m == 7); + + MacAddr m2{"00:50:c2:46:d9:c4"}; + CHECK(m2 == 346856806852); + CHECK(m2.hex() == "0050c246d9c4"); + CHECK(m2.str() == "00:50:c2:46:d9:c4"); + + CHECK_FALSE(m2 == 3); +} + +TEST_CASE("Convert IP using classes ", "[support]") { + std::vector vec_addr{4073554305, 2747957633, 2697625985}; + std::vector vec_ans{"129.129.205.242", "129.129.202.163", + "129.129.202.160"}; + + for (size_t i = 0; i != vec_addr.size(); ++i) { + auto ip0 = IpAddr(vec_addr[i]); + auto ip1 = IpAddr(vec_ans[i]); + + CHECK(ip0 == ip1); + CHECK(ip0 == vec_addr[i]); + CHECK(ip1 == vec_addr[i]); + CHECK(ip0 == vec_ans[i]); + CHECK(ip1 == vec_ans[i]); + CHECK(ip0.str() == vec_ans[i]); + CHECK(ip1.str() == vec_ans[i]); + } +} + +TEST_CASE("Strange input gives 0", "[support]") { + CHECK(IpAddr("hej") == 0); + CHECK(MacAddr("hej") == 0); +} + +TEST_CASE("Convert to uint for sending over network", "[support]") { + MacAddr addr{346856806822}; + uint64_t a = addr.uint64(); + CHECK(a == 346856806822); + + IpAddr addr2{"129.129.205.242"}; + uint32_t b = addr2.uint32(); + CHECK(b == 4073554305); +} + +TEST_CASE("Hostname lookup failed throws", "[support]"){ + CHECK_THROWS_AS(HostnameToIp("pippifax"), RuntimeError); +} + +TEST_CASE("IP Output operator gives same result as string", "[support]") { + IpAddr addr{"129.129.205.242"}; + std::ostringstream os; + os << addr; + CHECK(os.str() == "129.129.205.242"); + CHECK(os.str() == addr.str()); + +} + +TEST_CASE("MAC Output operator gives same result as string", "[support]") { + MacAddr addr{"00:50:c2:46:d9:a6"}; + std::ostringstream os; + os << addr; + CHECK(os.str() == "00:50:c2:46:d9:a6"); + CHECK(os.str() == addr.str()); +} + +//TODO!(Erik) Look up a real hostname and verify the IP \ No newline at end of file diff --git a/slsSupportLib/tests/test-string_utils.cpp b/slsSupportLib/tests/test-string_utils.cpp new file mode 100755 index 000000000..efbf99b76 --- /dev/null +++ b/slsSupportLib/tests/test-string_utils.cpp @@ -0,0 +1,112 @@ +#include "MySocketTCP.h" +#include "catch.hpp" +#include "logger.h" +#include +#include + +#include "string_utils.h" + + +TEST_CASE("copy a string") { + + char src[10] = "hej"; + REQUIRE(src[3]=='\0'); + + char dst[20]; + + sls::strcpy_safe(dst, src); + REQUIRE(dst[0]=='h'); + REQUIRE(dst[1]=='e'); + REQUIRE(dst[2]=='j'); + REQUIRE(dst[3]=='\0'); + +} + + +#ifdef NDEBUG +//This test can only run in release since we assert on the length of the string +TEST_CASE("copy a long string"){ + auto src = "some very very long sting that does not fit"; + char dst[3]; + sls::strcpy_safe(dst, src); + REQUIRE(dst[0]=='s'); + REQUIRE(dst[1]=='o'); + REQUIRE(dst[2]=='\0'); + +} +#endif +TEST_CASE("Concat") { + std::vector v{"one", "one", "one"}; + std::vector v2{"one", "one", "one"}; + auto r = sls::concatenateIfDifferent(v); + REQUIRE(r == std::string("one")); + r.clear(); + + // make sure we didn't modify the string + REQUIRE(v == v2); + + SECTION("add a different value"){ + v.emplace_back("two"); + REQUIRE(v!=v2); + REQUIRE( sls::concatenateIfDifferent(v) == "one+one+one+two+"); + } +} + +TEST_CASE("split a string with end delimiter"){ + std::string s("abra+kadabra+"); + auto r =sls::split(s, '+'); + REQUIRE(r.size()==2); + REQUIRE(r[0]=="abra"); + REQUIRE(r[1]=="kadabra"); +} + +TEST_CASE("split a string without end delimiter"){ + std::string s("abra+kadabra+filibom"); + auto r =sls::split(s, '+'); + REQUIRE(r.size()==3); + REQUIRE(r[0]=="abra"); + REQUIRE(r[1]=="kadabra"); + REQUIRE(r[2]=="filibom"); +} + +TEST_CASE("concatenate non empty strings"){ + std::vector vec{"hej", "kalas", "", "foto"}; + REQUIRE(vec.size()==4); + auto ret = sls::concatenateNonEmptyStrings(vec); + REQUIRE(ret == "hej+kalas+foto+"); +} + +TEST_CASE("concatenate non empty strings with only emty"){ + std::vector vec{"", "", ""}; + REQUIRE(vec.size()==3); + auto ret = sls::concatenateNonEmptyStrings(vec); + REQUIRE(ret.empty()); +} + +TEST_CASE("concatenate non empty strings with one element"){ + std::vector vec{"", "hej", "", "", ""}; + REQUIRE(vec.size()==5); + auto ret = sls::concatenateNonEmptyStrings(vec); + REQUIRE(ret=="hej+"); +} + + +TEST_CASE("Remove char from string"){ + char str[] = "sometest"; + sls::removeChar(str, 'e'); + REQUIRE(std::string(str) == "somtst"); +} + +TEST_CASE("Remove char from empty string"){ + char str[50] = {}; + sls::removeChar(str, 'e'); + REQUIRE(std::string(str) == ""); +} + +TEST_CASE("Many characters in a row"){ + char str[] = "someeequitellll::ongstring"; + sls::removeChar(str, 'l'); + REQUIRE(std::string(str) == "someeequite::ongstring"); +} + +// TEST_CASE("concat things not being strings") \ No newline at end of file diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100755 index 000000000..61415ddc3 --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,26 @@ +include_directories( + ${PROJECT_SOURCE_DIR}/catch +) + +set(SLS_TEST_SOURCES + test.cpp +) + +add_executable(tests ${SLS_TEST_SOURCES}) +target_link_libraries(tests + slsProjectOptions + slsProjectWarnings + slsSupportLib + slsDetectorShared + slsReceiverShared + pthread + rt +) +set_target_properties(tests PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin + ) +include(CTest) +include(Catch) +catch_discover_tests(tests) +# #TODO! Move to automatic test discovery +# add_test(test ${CMAKE_BINARY_DIR}/bin/testSlsReceiver) \ No newline at end of file diff --git a/tests/test.cpp b/tests/test.cpp new file mode 100755 index 000000000..8daed99c4 --- /dev/null +++ b/tests/test.cpp @@ -0,0 +1,3 @@ +// tests-main.cpp +#define CATCH_CONFIG_MAIN +#include "catch.hpp" \ No newline at end of file diff --git a/updateAPIVersion.sh b/updateAPIVersion.sh new file mode 100755 index 000000000..6f4cb119f --- /dev/null +++ b/updateAPIVersion.sh @@ -0,0 +1,37 @@ +#require 2 arguments, API_NAME API_DIR (relative to package) +if [ $# -lt 2 ]; then + echo "wrong usage of updateVersion.sh" + exit -1 +fi + +API_NAME=$1 +PACKAGE_DIR=$PWD +API_DIR=$PACKAGE_DIR/$2 +API_FILE=$PACKAGE_DIR/slsSupportLib/include/versionAPI.h +CURR_DIR=$PWD + +#go to directory +cd $API_DIR + +#deleting line from file +NUM=$(sed -n '/'$API_NAME'/=' $API_FILE) +#echo $NUM + +if [ "$NUM" -gt 0 ]; then + sed -i ${NUM}d $API_FILE +fi + +#find new API date +API_DATE="find . -printf \"%T@ %CY-%Cm-%CdT%CH:%CM:%CS %p\n\"| sort -nr | cut -d' ' -f2- | egrep -v build | egrep -v '(\.)o'| egrep -v 'versionAPI.h' | head -n 1" +API_DATE=`eval $API_DATE` +API_DATE=$(sed "s/-//g" <<< $API_DATE | awk '{print $1;}' ) +#extracting only date +API_DATE=${API_DATE:2:6} +#prefix of 0x +API_DATE=${API_DATE/#/0x} + +#copy it to versionAPI.h +echo "#define "$API_NAME $API_DATE >> $API_FILE + +#go back to original directory +cd $CURR_DIR diff --git a/updateClientAPI.sh b/updateClientAPI.sh new file mode 100755 index 000000000..49e8be65a --- /dev/null +++ b/updateClientAPI.sh @@ -0,0 +1,24 @@ +API_FILE=$PWD/slsSupportLib/include/versionAPI.h +arraylength=3 + +LIB_DIR=slsDetectorSoftware +RXR_DIR=slsReceiverSoftware +GUI_DIR=slsDetectorGui + +declare -a arraydirs=($LIB_DIR $RXR_DIR $GUI_DIR) +declare -a arraynames=("APILIB" "APIRECEIVER" "APIGUI") + +for (( i=0; i<${arraylength}; ++i )); +do + ./updateAPIVersion.sh ${arraynames[$i]} ${arraydirs[$i]} +done + +#find branch +CURR_BRANCH=$(git branch | grep \* | cut -d ' ' -f2) + +#update branch +BRANCH=$(cat $API_FILE | grep GITBRANCH | cut -d' ' -f3) +sed -i s/$BRANCH/\"$CURR_BRANCH\"/g $API_FILE + + +